About     Search     Feed

Nilesh D Kapadia


Music     Twitter     Github

Prompt Before Closing Emacs

I developed a bad habit of quitting Emacs from my earlier days of using Emacs mostly in a terminal session (where even there quitting it is not the best idea). Using GUI versions of Emacs, I sometimes find myself hitting C-x C-c and wishing I didn’t because I really intended to kill the current buffer, not completely close Emacs. So what I have done to deal with this is, when running a GUI version (which can be detected by checking the window-system variable), I always prompt to ask if I really want to quit. Here is the code I use:

(defun ask-before-closing ()
  "Ask whether or not to close, and then close if y was pressed"
  (interactive)
  (if (y-or-n-p (format "Are you sure you want to exit Emacs? "))
      (if (< emacs-major-version 22)
          (save-buffers-kill-terminal)
        (save-buffers-kill-emacs))
    (message "Canceled exit")))

(when window-system
  (global-set-key (kbd "C-x C-c") 'ask-before-closing))

I do this only for the GUI version, but you could remove the check for window-system if you want it to work in the terminal version as well. I use when instead of if in this case, because I do other things if I am running the GUI version, like (server-start), which I have excluded from this code sample.

© 2017 Nilesh D Kapadia