Skip to main content

Quit Current Context

This is just a short post sharing one of those commands I use every day and would immediately miss in an uncustomized Emacs session. Have you ever tried to quit the minibuffer when point was in another window? Naturally you would try hammering C-g but in stock Emacs the minibuffer stays active and all you get are grumpy "Quit" messages.

Emacs comes with the keyboard-escape-quit command which allows more sensible quits in certain contexts. One thing I do not like about this command is that one clause deletes other windows if there are any. I have written my own version combining keyboard-quit and keyboard-escape-quit in a way that fits my needs:

(defun keyboard-quit-context+ ()
  "Quit current context.

This function is a combination of `keyboard-quit' and
`keyboard-escape-quit' with some parts omitted and some custom
behavior added."
  (cond ((region-active-p)
         ;; Avoid adding the region to the window selection.
         (setq saved-region-selection nil)
         (let (select-active-regions)
        ((eq last-command 'mode-exited) nil)
            "Quit is ignored during macro defintion, use \\[kmacro-end-macro] if you want to stop macro definition"))
         (when (get-buffer-window "*Completions*")
           ;; hide completions first so point stays in active window when
           ;; outside the minibuffer
         ;; if we got this far just use the default so we don't miss
         ;; any upstream changes

(global-set-key [remap keyboard-quit] #'keyboard-quit-context+)

Most notably you can use this command to quit the minibuffer from any other window. Another thing I added recently is to ignore quits when defining macros.