Tuesday 11 April 2017

Close emacs buffer regardless of it being a server file

Emacs client

I use Emacs for text editing, which in my case means code, articles, web pages, notes, and short stories. Sometimes, I open files directly from emacs using \C-x \C-f, sometimes I use emacsclient from the command line. It opens the given file in an already running emacs window, avoiding the dreaded long startup time.

What bothered me for years was the way how to close a buffer. A file opened via file-find or through emacs filename can be closed by kill-buffer or \C-x k, but a server file complains about an existing client and needs a confirmation to be closed. One can use server-edit mapped to \C-x #, but the problem was I usually didn't remember how I opened a file - I just wanted to close its damned buffer.

The key to the solution was the server-buffer-clients variable which is buffer-local and defined only in server buffers. So, the solution was to bind a new function to  \C-x k:

(defun server-edit-or-close (buf)
  "Close the buffer regardless of whether it's a server file or not."
  (interactive "bKill/finish buffer: ")
  (if server-buffer-clients
      (progn
        (switch-to-buffer buf)
        (server-edit))
    (kill-buffer)))

No comments:

Post a Comment