|
| 1 | +;;; inotify-revert.el --- Auto-revert using inotify -*- lexical-binding: t; -*- |
| 2 | + |
| 3 | +;; Copyright (c) 2019 fmdkdd |
| 4 | +;; |
| 5 | +;; Author: fmdkdd |
| 6 | + |
| 7 | +;; This file is not part of GNU Emacs. |
| 8 | + |
| 9 | +;;; Commentary: |
| 10 | + |
| 11 | +;; Like auto-revert-mode, but without the weird lag. |
| 12 | +;; |
| 13 | +;; auto-revert-mode supposedly uses inotify thourgh filenotify, and reverts to |
| 14 | +;; polling when inotify fails. On my machine, auto-revert can take up to 1sec |
| 15 | +;; to revert a file that has changed, while using this mode is instantaneous. |
| 16 | + |
| 17 | +;; From: https://github.com/fmdkdd/dotfiles/blob/master/emacs/.emacs.d/elisp/inotify-revert.el |
| 18 | + |
| 19 | +;;; Code: |
| 20 | + |
| 21 | +(require 'filenotify) |
| 22 | + |
| 23 | +(defvar-local inotify-revert--descriptor nil |
| 24 | + "The filenotify descriptor for the current buffer.") |
| 25 | + |
| 26 | +(defun inotify-revert-activate () |
| 27 | + "Start watching the current buffer's file for changes." |
| 28 | + (when buffer-file-name |
| 29 | + (let ((buffer (current-buffer))) |
| 30 | + (setq inotify-revert--descriptor |
| 31 | + (file-notify-add-watch |
| 32 | + buffer-file-name '(change) |
| 33 | + ;; Using a lambda to capture the buffer, instead of a handler in a |
| 34 | + ;; separate defun |
| 35 | + (lambda (event) |
| 36 | + (when (eq (nth 1 event) 'changed) |
| 37 | + (with-current-buffer buffer |
| 38 | + (revert-buffer 'ignore-auto 'noconfirm))))))))) |
| 39 | + |
| 40 | +(defun inotify-revert-deactivate () |
| 41 | + "Unsubscribe to the current buffer's file changes." |
| 42 | + (when inotify-revert--descriptor |
| 43 | + (file-notify-rm-watch inotify-revert--descriptor) |
| 44 | + (kill-local-variable inotify-revert--descriptor))) |
| 45 | + |
| 46 | +;;;###autoload |
| 47 | +(define-minor-mode inotify-revert-mode |
| 48 | + "Like `auto-revert-mode', but faster." |
| 49 | + :lighter " revert" |
| 50 | + (cond |
| 51 | + (inotify-revert-mode |
| 52 | + (inotify-revert-activate)) |
| 53 | + ((not inotify-revert-mode) |
| 54 | + (inotify-revert-deactivate)))) |
| 55 | + |
| 56 | +(provide 'inotify-revert) |
| 57 | + |
| 58 | +;;; inotify-revert.el ends here |
0 commit comments