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). Now that I use 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.

Comments

also avoids accidentally quitting

Every once in a while I manage to hit C-x C-c while trying for C-x C-s or something like that. It just happened again, I got annoyed and I googled for "emacs prompt for c-x c-c" and your blog posting showed up. Thanks you! It's exactly what's needed.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.