Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically save files on lose focus in Emacs

Tags:

Is it possible to configure Emacs, so that it saves all files when the emacs window loses focus?

like image 298
Rockiger Avatar asked Aug 04 '09 22:08

Rockiger


2 Answers

I added focus hooks to Gnu Emacs 24.4.

They are called focus-in-hook and focus-out-hook.

You can add

(defun save-all ()   (interactive)   (save-some-buffers t))  (add-hook 'focus-out-hook 'save-all) 

to your .emacs file and it should save all files on loss of focus.

like image 199
bonkydog Avatar answered Sep 20 '22 04:09

bonkydog


I use this, it will only work if emacs is running under X (like it probably would in something like ubuntu).

(when    (and (featurep 'x) window-system)  (defvar on-blur--saved-window-id 0 "Last known focused window.")  (defvar on-blur--timer nil "Timer refreshing known focused window.")  (defun on-blur--refresh ()    "Runs on-blur-hook if emacs has lost focus."    (let* ((active-window (x-window-property                           "_NET_ACTIVE_WINDOW" nil "WINDOW" 0 nil t))           (active-window-id (if (numberp active-window)                                 active-window                               (string-to-number                                (format "%x00%x"                                        (car active-window)                                        (cdr active-window)) 16)))           (emacs-window-id (string-to-number                             (frame-parameter nil 'outer-window-id))))      (when (and             (= emacs-window-id on-blur--saved-window-id)             (not (= active-window-id on-blur--saved-window-id)))        (run-hooks 'on-blur-hook))      (setq on-blur--saved-window-id active-window-id)      (run-with-timer 1 nil 'on-blur--refresh)))  (add-hook 'on-blur-hook #'(lambda () (save-some-buffers t)))  (on-blur--refresh)) 
like image 21
Thomas Frössman Avatar answered Sep 19 '22 04:09

Thomas Frössman