当缓冲区文件名更改时,禁止缓冲区内容保存到旧文件

时间:2018-01-24 16:08:05

标签: emacs

我跟着用例烦恼了很多。

  1. 在emacs缓冲区中打开文件foo.rb
  2. foo.rb重命名为bar.rb使用外部工具。(例如从终端重命名)
  3. 在Emacs中选择foo.rb缓冲区,编辑它,保存C-x s时,此缓冲区 保存为旧文件名(foo.rb),不是预期的bar.rb
  4. 是否有任何emacs配置可以防止这种情况?

    我期待的是:

    1. 在Emacs缓冲区中打开文件foo.rb
    2. foo.rb重命名为bar.rb使用外部工具
    3. 编辑foo.rb缓冲区,保存时告诉我:文件被删除或提示, 另存为新文件名。

1 个答案:

答案 0 :(得分:0)

这是解决方案的开始。魔鬼的细节;可能存在许多此代码无法处理的极端情况。

(defvar do-not-save-list ())

(defun do-not-save-add-to-list (event)
  (when (eq 'renamed (cadr event))
    (add-to-list 'do-not-save-list
                 (caddr event))))

(defun do-not-save-add-watcher ()
  (setq do-not-save-list (remove (buffer-file-name) do-not-save-list))
  (file-notify-add-watch (buffer-file-name)
                         '(change)
                         #'do-not-save-add-to-list))
(add-hook 'find-file-hook #'do-not-save-add-watcher)

(defun do-not-save-check ()
  (let ((filename (buffer-file-name)))
    (when (member filename do-not-save-list)
      (message "not saving %s" filename)
      t ;; returns non-nil to prevent write
      )))
(add-hook 'write-file-functions #'do-not-save-check)

(defun do-not-save-kill-hook ()
  (setq do-not-save-list (remove (buffer-file-name) do-not-save-list)))
(add-hook 'kill-buffer-hook #'do-not-save-kill-hook)