I'm trying to create a function that inserts text into an arbitrary file without switching to that file's buffer.

I know this could be done with echo, but is there a way to do it using only elisp?

  • 1
    For appending to files, check the functions append-to-file and write-region on the elisp reference (info - Elisp - Writing to files)
    – Juancho
    Jun 16, 2011 at 0:08

2 Answers 2


Try this function:

(defun append-string-to-file (string filename)
  "Appends STRING to FILENAME."
  (append-to-file string nil filename))
  • How is this expected to work interactively? (And why not just use append-to-file, which does?) Nov 6, 2017 at 17:17

You need to make a buffer current to do pretty much anything with its content. Making a buffer current is related to the Lisp interpreter, it doesn't involve displaying the buffer in a window. The basic primitives are set-buffer to set the buffer for subsequent operations and save-excursion to execute a piece of code and restore the current buffer afterwards.

There are a number of macros called with-SOMETHING to execute code with different settings (such as the current buffer) and restore the settings when the code exits (for any reason, whether it's normal exit or an exception).

(with-current-buffer "name-of-file-that's-already-open"
  (goto-char 42)
  (insert "hello"))

If you want to open the file and close it when you're done, there's no with- macro in the standard library. (Warning: typed directly in the browser.)

  (let (buf)
        (setq buf (find-file-noselect "filename"))
        (when buf
          (goto-char 42)
          (insert "hello")))
      (if buf (kill-buffer buf))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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