5

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 '11 at 0:08
4

Try this function:

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

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

(save-excursion
  (let (buf)
    (unwind-protect
      (progn
        (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.