Is it possible to autosave temporary buffers that do not visit the file?

Suppose I enter a bunch of text in a buffer that does not visit the file (this could be a new org2blog post or just some buffer with a buffer). Is it possible to autosave it somewhere in case of disaster and Emacs dies?

+6
source share
2 answers

auto-save-mode works with non-file buffers. It just doesn't turn on by default - this usually happens in (after-find-file) .

So: Mx auto-save-mode RET

By default, the autosave file will be written to the default-directory buffer (or /var/tmp or ~/ , depending on write permissions, see Ch v buffer-auto-save-file-name RET ) which may be a little inconvenient to find out after a crash, so installing on something standard is probably a good idea.

The following ensures that these autosave files are written to your home directory (or Mx customize-variable RET my-non-file-buffer-auto-save-dir RET ) if auto-save-mode is invoked interactively. This, I hope, will avoid the conflict associated with any other use of auto-save-mode with non-file buffers (for example, Mail mode is mentioned in the code).

 (defcustom my-non-file-buffer-auto-save-dir (expand-file-name "~/") "Directory in which to store auto-save files for non-file buffers, when `auto-save-mode' is invoked manually.") (defadvice auto-save-mode (around use-my-non-file-buffer-auto-save-dir) "Use a standard location for auto-save files for non-file buffers" (if (and (not buffer-file-name) (called-interactively-p 'any)) (let ((default-directory my-non-file-buffer-auto-save-dir)) ad-do-it) ad-do-it)) (ad-activate 'auto-save-mode) 
+12
source

phils answer cleared me up but in the end I used a slightly different approach. I am posting it as a separate answer for documentation. Here is my car factory stanza:

 ;; Put autosave files (ie #foo#) in one place (defvar autosave-dir (concat "~/.emacs.d/autosave.1")) (defvar autosave-dir-nonfile (concat "~/.emacs.d/autosave.nonfile")) (make-directory autosave-dir t) (make-directory autosave-dir-nonfile t) (defun auto-save-file-name-p (filename) (string-match "^#.*#$" (file-name-nondirectory filename))) (defun make-auto-save-file-name () (if buffer-file-name (concat autosave-dir "/" "#" (file-name-nondirectory buffer-file-name) "#") (expand-file-name (concat autosave-dir-nonfile "/" "#%" (replace-regexp-in-string "[*]\\|/" "" (buffer-name)) "#")))) 

Creating a separate directory for unvisited file buffers is optional in this context; they could also go in a centralized place (in this case autosave-dir ). Please also note that I should do a basic cleanup of the file name if the temporary buffer name is something like "* foo / bar *" (with stars and / or slashes).

Finally, you can automatically enable autosave in the buffers of temporary buffers of certain modes, using something like

 (add-hook 'org2blog/wp-mode-hook '(lambda () (auto-save-mode t))) 
+5
source

Source: https://habr.com/ru/post/905901/


All Articles