Take the 2-minute tour ×

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?

share|improve this question
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 '11 at 0:08

2 Answers 2

up vote 4 down vote accepted

Try this function:

(defun append-string-to-file (string filename)
  "Appends STRING to FILENAME."
  (append-to-file string nil filename))
share|improve this answer

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))))
share|improve this answer

Your Answer


