Quit and Close Emacs Special Windows Like Help and Compilation Results
Emacs can display interactive help windows (the content/buffer name is called “
*Apropos*”), and compilation results. I managed to limit the height of the compilation window to 10 lines already. But when I have the compilation results pane focused, I want to close and dismiss it quickly.
This kind of window (or panes) is in the so-called
special-mode. That’s one mode where you do not interactively enter text, but can move the caret around freely. These non-text “special” windows have dedicated key bindings as well. One key is q which closes the currently visible contents, but leaves the window pane on screen. (The function that’s called is named
quit-window.) When the content is closed, the next best content is displayed in its stead.
Update: Turns out the compilation window is not reacting to the
special-mode-hook, so I had to add a hook for it, too. The rest remains valid, though.
Update (2020-08-07): Turns out I forgot to add the
-hook part of
special-mode-hook. No wonder it didn’t work!
Let me explain how this works. When I compile a project in emacs, the compilation window is created by splitting my current window in two. The bottommost window is displaying the very same buffer (or in-memory contents that are related to the file I’m viewing) as my original window. That’s the default behavior of the split command at least. Then the newly created window is set to display the compilation results. That operation is similar to all other buffer display operations: it puts the compilation buffer on top of the window’s buffer stack, and the topmost item is going to be displayed. The rest of the stack can still be navigated to by switching buffers if you want. (C-x b is the fundamental command you learn early, corresponding to the
switch-buffer function. It changes what you see in the window.) You can also pop the stack’s tip from it and have the new tip become active automatically. That’s similar to when you close tabs in your browser: the adjacent tab becomes focused. But I don’t want this to happen when I compile a project. I don’t want a source file to become visible in the small bottom pane.
So I figured I want to overwrite the lowercase-q shortcut to a “quit and remove window” action.
(defun ct/quit-and-kill-auxiliary-windows () "Kill buffer and its window on quitting" (local-set-key (kbd "q") 'kill-buffer-and-window)) (add-hook 'special-mode-hook #'ct/quit-and-kill-auxiliary-windows) (add-hook 'compilation-mode-hook #'ct/quit-and-kill-auxiliary-windows)
Update (2020-08-07): I also changed the way I reference functions by their name to the sharp-quoted form, because that tells the Lisp compiler this is supposed to be a function. It will then perform static analysis and produce warnings during compialtion when the function doesn’t exist, as opposed to just producing runtime errors.