2

Here is what I want:

(fill-string ";; This is a long string to be inserted into a buffer somewhere. Okay that's it.")

This should insert line breaks according to the fill-column. Something like this should be returned,

;; This is a long string to
;; be inserted into a buffer
;; somewhere. Okay that's it.

This can be done interactively if the string is in the buffer and you select it and call M-x fill-region but I can't find a way of doing this programmatically.

Drew
  • 75,699
  • 9
  • 109
  • 225
scribe
  • 930
  • 4
  • 15

1 Answers1

3

You can insert the string into a temporary buffer, fill the region, and read the contents of the buffer as a string:

(defun fill-string (s)
  (with-temp-buffer
     (emacs-lisp-mode)
     (insert s)
     (fill-region (point-min) (point-max))
     (buffer-substring (point-min) (point-max))))

We put the temp buffer in emacs-lisp mode so that the filling will add the comment characters at the beginning of each line.

You can use the function like this:

(setq my-filled-comment
   (let ((fill-column 25)) 
      (fill-string ";; This is a long string to be inserted into a buffer somewhere. Okay that's it.")))

That binds fill-column to 25 for the duration of the fill-string call and sets the variable my-filled-comment to the result. You can then insert it wherever you want. The result looks like this:

;; This is a long string
;; to be inserted into a
;; buffer somewhere. Okay
;; that's it.
NickD
  • 27,023
  • 3
  • 23
  • 42
  • Is this way efficient? I am calling this when Emacs starts. I don't want to add to the start-up time. – scribe Oct 19 '21 at 00:41
  • 1
    @scribe: Yes, using a buffer is very efficient. It's typically much more efficient that operating on strings, in Emacs. – Drew Oct 19 '21 at 01:11
  • 1
    What @Drew said. In addition, Emacs provides many functions (like `fill-region` that operate on buffers (or regions within buffers), which provides much more flexibility to the programmer. If you look through the elisp code in Emacs, you'll see that the technique is pervasive. – NickD Oct 19 '21 at 12:50
  • Coincidentally, [another question came up whose answer also uses this technique](https://emacs.stackexchange.com/questions/69009/how-to-get-org-time-stamp-to-return-timestamp-rather-than-inserting). Maybe a generic answer describing the technique is needed. – NickD Oct 20 '21 at 02:26