pygabriel
pygabriel

Reputation: 10008

Emacs Lisp, how to monitor changes of a file/directory

I'm looking for a way to check periodically if a files under a certain directory were changed from the last check (a functionality symilar to FAM daemon or to gio.monitor_directory). In emacs lisp.

Upvotes: 5

Views: 2153

Answers (3)

Resigned June 2023
Resigned June 2023

Reputation: 4937

Emacs links with various filesystem watcher libraries and presents a unified interface in filenotify.el.

Upvotes: 2

huaiyuan
huaiyuan

Reputation: 26539

(defun install-monitor (file secs)
  (run-with-timer
   0 secs
   (lambda (f p)
     (unless (< p (second (time-since (elt (file-attributes f) 5))))
       (message "File %s changed!" f)))
   file secs))

(defvar monitor-timer (install-monitor "/tmp" 5)
  "Check if /tmp is changed every 5s.")

To cancel,

(cancel-timer monitor-timer)

Edit:

As mentioned by mankoff, the above code snippet monitors file modification in the last 5 seconds, instead of since last check. To achieve the latter, we will need to save the attributes each time we do the checking. Hope this works:

(defvar monitor-attributes nil
  "Cached file attributes to be monitored.")

(defun install-monitor (file secs)
  (run-with-timer
   0 secs
   (lambda (f p)
     (let ((att (file-attributes f)))
       (unless (or (null monitor-attributes) (equalp monitor-attributes att))
         (message "File %s changed!" f))
       (setq monitor-attributes att)))
   file secs))

(defvar monitor-timer (install-monitor "/tmp" 5)
  "Check if /tmp is changed every 5s.")

Upvotes: 6

Chmouel Boudjnah
Chmouel Boudjnah

Reputation: 2559

I don't have a proper solution but maybe a couple of pointer to get you on the right direction.

According to some quick googling it seems that dbus has an inotify interface built-ins. Since latest version of emacs you can access to dbus interface via Emacs lisp (under Linux at least) maybe you can plug all of this together to make it works. See an example here about using dbus with Emacs :

http://emacs-fu.blogspot.com/2009/01/using-d-bus-example.html

Upvotes: 1

Related Questions