Call me lame, but I'm tired of my subconscious C-x C-s
nervous twitch. I am switching buffers often enough and I think I would like to save a certain buffer as soon as I switch to another. I have not had the time yet to learn Emacs-Lisp basics.
Any hints on how to do this, or better solutions?
(On a related note, I found an autosave workaround that can save the current buffer as soon as you are idle for a given amount of time.)
By default, Emacs automatically saves your changes to a file intermittently. If anything should happen, you can recover a file with 'M-x recover-file' . Auto-saving can be turned on globally or on a per-buffer basis with 'M-x auto-save-mode' (users of Emacs 26.1 and later may prefer 'M-x auto-save-visited-mode' ).
For conveniently switching between a few buffers, use the commands C-x <LEFT> and C-x <RIGHT> . C-x <RIGHT> ( previous-buffer ) selects the previous buffer (following the order of most recent selection in the current frame), while C-x <LEFT> ( next-buffer ) moves through buffers in the reverse direction.
Emacs periodically saves all files that you are visiting; this is called auto-saving. Auto-saving prevents you from losing more than a limited amount of work if the system crashes. By default, auto-saves happen every 300 keystrokes, or after around 30 seconds of idle time.
To save the file you are editing, type C-x C-s or select Save Buffer from the Files menu. Emacs writes the file. To let you know that the file was saved correctly, it puts the message Wrote filename in the minibuffer.
To expand on Seth's answer, I'd do this:
(defadvice switch-to-buffer (before save-buffer-now activate)
(when buffer-file-name (save-buffer)))
(defadvice other-window (before other-window-now activate)
(when buffer-file-name (save-buffer)))
(defadvice other-frame (before other-frame-now activate)
(when buffer-file-name (save-buffer)))
The check for buffer-file-name
avoids saving buffers w/out files. You need to figure out all the entry points you use for switching buffers that you care about (I'd also advise other-window
).
I'm kind of new to emacs lisp myself but this works in my testing:
(defadvice switch-to-buffer (before save-buffer-now)
(save-buffer))
(ad-activate 'switch-to-buffer)
It's kind of annoying though because it's called after EVERY buffer (like scratch). So, consider this answer a hint.
When you want to disable it, you'll need to call:
(ad-disable-advice 'switch-to-buffer 'before 'save-buffer-now)
(ad-activate 'switch-to-buffer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With