4

I have the following code, which opens a file, inserts some text, saves the file and closes it.

(defun batch (file)
  (find-file file)
  (end-of-buffer)
  (insert "nix")
  (save-buffer)
  (kill-buffer))

If the file is already visited the buffer gets closed. How to prevent that? How to keep the buffer, if find-file does not created a new buffer? How to know, if a file has already been opened in a buffer?

  • What should be the behavior if the buffer's content is different from the file's content? – T. Verron Nov 29 '16 at 15:42
  • The buffer should be used. The function should not revert. – ceving Nov 29 '16 at 15:44
6

(get-file-buffer filename) returns the buffer visiting filename, or nil if there is none.

https://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html

Edit: justbur proposes using (find-buffer-visiting file) instead, as it also works when the buffer has a different name than the file.

So one solution would be sth in the lines of

(defun batch (file)
  (let ((keep (find-buffer-visiting file)))
    (find-file file)
    (end-of-buffer)
    (insert "nix")
    (save-buffer)
    (unless keep (kill-buffer)))

but there may be more elegant solutions.

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.