Prevent Emacs Compilation Window From Displaying Other Content

By accident I found a setting for emacs windows that prevents a window from displaying any other content than what it currently is showing. It is not locking the textual contents but the buffer. That means you cannot show the contents of another file, or change the currently visible help page, or whatever.

And, just what I needed: you can prevent the small compilation results window from changing contents. Sometimes I have the compilation window focused and want to look at a code listing; now the code listing would open inside the tiny compilation window!

To prevent this, you can lock a window to its current buffer by making it “dedicated”. Call the non-interactive function (set-window-dedicated-p WINDOW t) to enable this, and (set-window-dedicated-p WINDOW nil) to disable this again.

I added it to the code where I create the compilation window to limit its height to 10 lines of text, and enable the flag after the window’s buffer is configured:

(setq compilation-window-height 10)

(defun ct/create-proper-compilation-window ()
  "Setup the *compilation* window with custom settings."
  (when (not (get-buffer-window "*compilation*"))
    (save-selected-window
      (save-excursion
        (let* ((w (split-window-vertically))
               (h (window-height w)))
          (select-window w)
          (switch-to-buffer "*compilation*")

          ;; Reduce window height
          (shrink-window (- h compilation-window-height))

          ;; Prevent other buffers from displaying inside
          (set-window-dedicated-p w t) 
  )))))
(add-hook 'compilation-mode-hook 'ct/create-proper-compilation-window)

That does the job. Now the tiny compilation window contents are locked and the madness of displaying anything anywhere is over!