Bart Simpson
Bart Simpson

Reputation: 849

Emacs: How to kill (C-x 4 0) a buffer of a frame by using the GUI Close button?

I know it is a bad habit to use a mouse as an Emacs user. However, there are times when it is just convenient to close "some" of my multiple Emacs frames by clicking the red "x" Close button on the upper left corner of Finder rather than just repeatedly using C-x 4 0.

Is there is a way to rebind OS X GUI Close button to kill (C-x 4 0) the buffer of a frame - that is, kill the buffer and the frame at the same time? And if the buffer has no filename, Emacs will ask me to save or discard the buffer.

My Emacs is 24.3.1 on OS X.

Upvotes: 1

Views: 722

Answers (1)

Drew
Drew

Reputation: 30701

First, it is not a bad idea to use a mouse with Emacs. Quite the contrary. But it can be a bad habit, as you say: anything overdone can be a bad habit. Emacs works especially well with a mouse (the Emacs mouse is more powerful than usual), and it works fine without a mouse. Use a mouse for what it is good for: direct access to any position, just by pointing.

And yes, you can make Emacs perform a command (such as delete-frame) when you click the window-manager X icon (or whatever icon your window manager uses to delete windows). You do this:

(define-key special-event-map [delete-frame] 'delete-frame)

See (elisp) Special Events.

(In library thumb-frm.el I use the Minimize icon (optionally) to thumbify frames, as another example of this.)


To answer your comment question more specifically. This code prompts for the buffer to kill (default: current buffer). If there is only one frame, then it quits Emacs. Otherwise, it deletes only the selected frame.

(defun foo (&optional buffer)
  (interactive (list (read-buffer "Buffer: " (current-buffer))))
  (if (not (cadr (frame-list)))
      (save-buffers-kill-terminal) ; Kill Emacs, if last frame
    (kill-buffer buffer)
    (delete-frame (selected-frame) 'FORCE)))

(define-key special-event-map [delete-frame] 'foo)

Upvotes: 1

Related Questions