Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .