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.

1 Answer 1

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.
4
  • Is this way efficient? I am calling this when Emacs starts. I don't want to add to the start-up time.
    – scribe
    Commented Oct 19, 2021 at 0:41
  • 1
    @scribe: Yes, using a buffer is very efficient. It's typically much more efficient that operating on strings, in Emacs.
    – Drew
    Commented Oct 19, 2021 at 1: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
    Commented Oct 19, 2021 at 12:50
  • Coincidentally, another question came up whose answer also uses this technique. Maybe a generic answer describing the technique is needed.
    – NickD
    Commented Oct 20, 2021 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.