7

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?

Drew
  • 75,699
  • 9
  • 109
  • 225
ceving
  • 1,308
  • 1
  • 14
  • 28

1 Answers1

10

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

Vera Johanna
  • 873
  • 6
  • 9