When deleting current frame, Emacs always picks the last created frame to show. How can I tweak it to pick the last visited frame?

2 Answers 2


It turns out very easy.

(defun +amos/workspace-delete ()
  (let ((frame (window-frame (get-mru-window t nil t))))
    (select-frame frame)))

Here is a better solution which works when there are multiple windows in current frame.

(defun +amos/workspace-delete ()
  (let (best-window best-time time)
    (dolist (window (window-list-1 nil 'nomini 'visible))
      (setq time (window-use-time window))
      (when (and (not (eq (window-frame window) (selected-frame)))
                 (or (not best-time) (> time best-time)))
        (setq best-time time)
        (setq best-window window)))
    (select-frame (window-frame best-window))))
  • good answer with a built-in function
    – shynur
    Nov 24, 2023 at 15:49
;;; ~/.emacs.d/init.el  -*- lexical-binding: t; -*-
(let (visited-frames)
  (advice-add 'select-frame :after
              (lambda (frame &rest _)
                (setq visited-frames (delq frame visited-frames))
                (push frame visited-frames)))
  (add-hook 'delete-frame-functions
            (lambda (frame)
              (setq visited-frames (delq frame visited-frames))))
  (add-hook 'after-delete-frame-functions
            (lambda (_)
              (when visited-frames
                (select-frame (car visited-frames))))))

I tested it by

  1. C-x 5 2: F1 -> F2
  2. C-x 5 2: F2 -> F3
  3. C-x 5 o: F3 -> F2
  4. C-x 5 o: F2 -> F1
  5. M-x delete-frame: F1 -> F2
  • Thank you for the answer. I didn't notice it until coming up with my own solution)
    – Amos
    Nov 24, 2023 at 15:37

Your Answer

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

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