Jun 04,
2018

Killing buffers in Emacs

Good day Interweb surfers!

I've used Emacs for several years but until today I've never realized that the kill-this-buffer function should be invoked only by menu:

This command can be reliably invoked only from the menu bar, otherwise it could decide to silently do nothing.

According to the Interwebs, around 10 years ago the function was made menu-bar specific, but originally could be invoked freely. I haven't investigated the rationale behind the change, but I'm pretty sure I've picked it up more than 10 years ago.

The observant reader would correctly guess that only this morning, amusingly enough, it decided to silently do nothing and I have no idea what I did differently1.

To not be surprised again in the future, at first I modified the binding like this:

(global-set-key (kbd "<f8>") 
                '(lambda ()
                   (interactive)
                   (kill-buffer (current-buffer))))

but immediately after I found out that the kill-current-buffer function, defined in simple.el, seems to do a slightly better job at killing buffers than my lambda above and it's probably the spiritual successor of the kill-this-buffer function.

A few days ago I also fixed the cursor position when correcting typos with Flyspell2 and when reopening a buffer as root, that always annoyed me but I continued forgetting about it:

;; flyspell
(eval-after-load 'flyspell
  '(define-key flyspell-mode-map (kbd "C-.")
     '(lambda ()
        (interactive)
        (let ((origin (point)))
          (flyspell-correct-at-point)
          (goto-char origin)))))

and

;; open the current buffer as a different user or root as default
(defun reopen-this-buffer-as-another-user (user)
  "Re-open the current buffer with tramp and sudo,
  using root as default"
  (interactive "sRe-open as user (default: root): ")
  (when (string= "" user)
    (setq user "root"))
  (let ((origin (point)))
    (find-alternate-file 
      (concat (format "/sudo:%s@localhost:" user)
              buffer-file-name))
    (goto-char origin)))

The only remarkable thing about the two definitions above is I couldn't use the save-excursion function because in both I hit two different corner cases: the first is related to the insertion of text adjacent to the saved position and the second is about changing buffers3.


  1. well, it should be related to the menu-bar's frame ↩︎

  2. an Emacs spell checker ↩︎

  3. the curious reader can find the details on the official documentation ↩︎