是否可以自动保存未访问文件的临时缓冲区?

时间:2012-01-13 11:11:23

标签: emacs elisp

假设我在一个没有访问文件的缓冲区中输入了一堆文本(它可能是一个新的org2blog帖子,或者只是一些临时缓冲区)。是否有可能将其自动保存在某处以防万一发生灾难并且Emacs死亡?

2 个答案:

答案 0 :(得分:12)

auto-save-mode实际上适用于非文件缓冲区。它默认情况下不会启用 - 通常发生在(after-find-file)

所以: M-x auto-save-mode RET

默认情况下,自动保存文件将写入缓冲区的default-directory(或/var/tmp~/,具体取决于写入权限;请参阅 Ch v buffer-auto-save-file-name RET )在崩溃后可能有点尴尬,因此将其设置为标准可能是一个好主意。

以下内容将确保将这些自动保存文件写入您的主目录(或 Mx customize-variable RET my-non-file-buffer-auto-save-dir 如果以交互方式调用auto-save-mode,则返回)。这有望避免与auto-save-mode与非文件缓冲区的任何其他用法冲突(例如,代码提到了邮件模式)。

(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)

答案 1 :(得分:5)

phils' answer为我解决了问题,但我最终采用了一种不同的方法。为了文档的缘故,我将它作为单独的答案发布。这是我的自动保存节:

;; 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)) "#"))))

在此上下文中,为非访问文件缓冲区创建单独的目录是可选的;他们也可以进入集中位置(在这种情况下,autosave-dir)。另请注意,如果临时缓冲区名称类似于“* foo / bar *”(带星号和/或斜杠),我必须执行一些基本文件名清理。

最后,可以使用类似

之类的东西自动打开某些模式的临时缓冲区中的自动保存
(add-hook 'org2blog/wp-mode-hook '(lambda () (auto-save-mode t)))
相关问题