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?
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
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))))