Recently I'm using this function which is given bellow, to compile and run C++ program. Everything works fine with this function.

I just want to delete pop-up window (generated by this function) after compilation and running procedure is finished.

enter image description here

And want the window to give me a message asking :

press <return> key to delete current window and go-back.

I'm new to Emacs and have zero knowledge of elisp. So it would be very kind of you guys if you let me know how to done this work.

 (defun compile-and-run()
  (compile (concat "g++ " (file-name-nondirectory (buffer-file-name)) " -o " 
  (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) " && ./" 
  (file-name-sans-extension (file-name-nondirectory (buffer-file-name)))) t ) 
  (other-window 1)
 (goto-char (point-max))) 

(define-key c++-mode-map [f5] #'compile-and-run) 
  • emacs.stackexchange.com/tags/elisp/info
    – Drew
    Nov 7, 2022 at 20:37
  • In the *compilation* buffer q is bound to quit-window, which by default will close the window and bury the buffer. See the quit-window docs to see how to kill the buffer
    – nega
    Nov 11, 2022 at 15:03
  • quit-window doesn't work on *compilation*, I think that's because I run the program in *compilation* buffer. Nov 11, 2022 at 17:17

1 Answer 1


The compile mode actually exposes a hook that runs after compilation finishes, called compilation-finish-functions. You can add your own hook to the compilation, and in that, just call the quit-window function that others have mentioned in the comments.

(defun exit-after-compile-hook (cur-buffer msg)
  ;; nil: Don't kill the window.
  ;; 0: Affect visible and iconified frames.
  (quit-window nil (get-buffer-window cur-buffer 0)))

(add-hook 'compilation-finish-functions #'exit-after-compile-hook)

You can certainly combine these lines with a lambda. You also may wish to not close the window in the event that compilation failed. If you noticed, I passed nil to quit-window, which at least, keeps the buffer around.

  • great, I just add this (when (y-or-n-p "Quit window? ") before (quit-window nil (get-buffer-window cur-buffer 0)) so that I could hold that window open until I want to kill it. Is it good what i just added that way? And I wish, I could turn that y-or-n into in any key(e.g. <return>) this will close window on pressing the <return> key. Nov 13, 2022 at 10:13
  • It does look like you could potentially wrap y-or-n-p (in a let expression) to remap the y-or-no-p-map key binding for return to invoke y-or-n-p-insert-y. I haven't tried this, though. For those mechanisms, check subr.el... Nov 13, 2022 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.