0

Vim prompts to save the buffer before switching if no other window is holding it. In other words, it prompts to save the buffer before putting it in background. How can I get the same behavior in Emacs?

A related question is about automatically saving the buffer.

3
  • Your question is welcome. But FWIW, this is pretty unusual behavior for Emacs users, I think. Are you sure you want/need to do this? or is this perhaps just a holdover habit from using Vim?
    – Drew
    Commented Mar 25, 2021 at 15:51
  • @Drew I feel uncomfortable with the notion of hidden dirty state. Recently I lost some of my notes in hidden buffer after Emacs crashed (with X server). Though I had backup file, I wasn't aware of the loss and overwrote it with additional notes (I missed the brief message of file recovery) and realized too late.
    – tejasvi
    Commented Mar 26, 2021 at 1:54
  • 1
    No problem. Just wanted to be sure you'd thought about it. BTW, you can accept your own answer.
    – Drew
    Commented Mar 26, 2021 at 2:02

1 Answer 1

0
(defun tst-nohidden (&optional orig-fn buffer-or-name &rest _)
  (let ((to-buffer (if (eq (type-of buffer-or-name) 'string) buffer-or-name (buffer-name buffer-or-name))))
    ;; Check if switching to or from a non-file buffer
    (unless (or (equal (buffer-name) to-buffer)
                (string-prefix-p "*" (string-trim-left (buffer-name)))
                (if buffer-or-name (string-prefix-p "*" (string-trim-left to-buffer)) nil))
      (when (and
             (buffer-modified-p)
             (= 1 (length (get-buffer-window-list (buffer-name) nil t)))
             (y-or-n-p (format "Save %s?" (buffer-name)))
             (save-buffer))))))

;; Switching buffer in current window
(advice-add 'doom-run-switch-buffer-hooks-a :before 'tst-nohidden)

;; Closing current buffer
(advice-add '+workspace/close-window-or-workspace :before 'tst-nohidden)

(defun tst-nohidden-max (&optional arg)
  (dolist (buf  (buffer-list))
    (when (and (get-buffer-window buf 'visible) (not (eq buf (current-buffer))))
      (with-current-buffer buf (tst-nohidden)))))

;; While closing other buffers
(advice-add 'doom/window-maximize-buffer :before 'tst-nohidden-max)

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.