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.

Drew
  • 75,699
  • 9
  • 109
  • 225
tejasvi88
  • 151
  • 5
  • 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 Mar 25 '21 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. – tejasvi88 Mar 26 '21 at 01:54
  • 1
    No problem. Just wanted to be sure you'd thought about it. BTW, you can accept your own answer. – Drew Mar 26 '21 at 02:02

1 Answers1

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)
tejasvi88
  • 151
  • 5