Emacs可以跟踪像BBEdit这样的文件吗?

时间:2014-03-16 20:07:26

标签: macos emacs

引用a feature request for Sublime Text

BBEdit在OS X上具有此功能:
- 在BBEdit中,打开" myfile.txt"
- 在Finder中,重命名" myfile.txt" to" myfile2.txt"
- 现在,在BBEdit中,文档显示为" myfile2.txt",并保存文件更新" myfile2.txt"

这比ST2用例要好得多:
- 在Sublime Text 2中,打开" myfile.txt"
- 在Finder中,重命名" myfile.txt" to" myfile2.txt"
- 现在,将文档保存在ST2中会静默创建一个重复的文件" myfile.txt"。这导致我的工作区中同一文件的两个略有不同的版本,导致后来的麻烦。

与Submaime Text一样,Emacs也会发生类似的事情。所以,我很想找到一种方法让Emacs做BBEdit正在做的事情。

我搜索了谷歌,但我真的不确定在这里搜索什么。这是否有特定的艺术术语?无论哪种方式,我都没有发现任何兴趣。

有没有现成的方法呢?还是会变得相当复杂? This post表示NSURL的“书签”功能正在此处使用。

1 个答案:

答案 0 :(得分:6)

来自最新emacs trunk的NEWS文件(未发布)

*** Support for filesystem notifications.
Emacs now supports notifications of filesystem changes, such as
creation, modification, and deletion of files.  This requires the
`glib' API, or the 'inotify' API (on GNU/Linux systems only).  On
MS-Windows systems, this is supported for Windows XP and newer
versions.

因此,对于GNU / Linux和Windows用户,您可能要求使用的功能很可能在OS X上生成的文件通知似乎不支持(在Emacs中)。

下面的代码应该做你想要的(尽管还没有经过全面测试),它需要最新的(未发布的)emacs

(require 'filenotify)
(require 'cl-lib)

(defvar my-file-to-fd-hash (make-hash-table))

(defun my-file-notify-add-rename-watch (&optional file)
  (let ((file-name (or file buffer-file-name)))
    (when file-name
      (puthash file-name
               (file-notify-add-watch file-name
                          '(change)
                          'my-handle-file-change)
               my-file-to-fd-hash))))

(defun my-file-notify-rm-rename-watch (&optional file)
  (let* ((file-name (or file
                buffer-file-name))
         (fd (gethash file-name my-file-to-fd-hash)))
    ;; Stop watching the file
    (when fd
      (file-notify-rm-watch fd)
      (remhash file-name my-file-to-fd-hash))))

(add-to-list 'find-file-hook 'my-file-notify-add-rename-watch)
(add-to-list 'kill-buffer-hook 'my-file-notify-rm-rename-watch)

(defun my-handle-file-change (event)
  (let* ((fd (cl-first event))
         (action (cl-second event))
         (file (cl-third event))
         (renamed-to (cl-fourth event))
         (visiting-buffer (get-file-buffer file)))
    ;; Ignore events other than `rename` and also the `rename` events
    ;; generated due to emacs backing up file
    (when (and (eq action 'renamed)
           (not (backup-file-name-p renamed-to)))
      (message (format "File %s was renamed" file))

      ;; If file is not open ignore the notification
      (when visiting-buffer
        (with-current-buffer visiting-buffer
          (set-visited-file-name renamed-to))
        (my-file-notify-rm-rename-watch file)
        (my-file-notify-add-rename-watch renamed-to)))))