From 827f6aa9fb616d9467dcccc011a5d3eb4dbac02d Mon Sep 17 00:00:00 2001 From: Gregory Heytings Date: Mon, 1 Nov 2021 00:53:05 +0000 Subject: [PATCH] Add a macro to execute body only when a file has changed. * lisp/subr.el (when-file-has-changed): New macro. (when-file-has-changed--hash-table): Internal variable used by the new macro. --- lisp/subr.el | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/lisp/subr.el b/lisp/subr.el index f6dbd00532..b29c56f8c6 100644 --- a/lisp/subr.el +++ b/lisp/subr.el @@ -3967,6 +3967,22 @@ function-get nil ;Re-try `get' on the same `f'. (setq f fundef)))) val)) + +(defvar when-file-has-changed--hash-table (make-hash-table) + "Internal variable used by `when-file-has-changed'.") + +(defmacro when-file-has-changed (file body) + "Execute BODY only if file has changed. +The modification time of the FILE is compared to the modification +time of FILE during a previous invocation of +`when-file-has-changed'. If they differ, BODY is executed." + `(let* ((attr (file-attributes ,file 'integer)) + (mtime (file-attribute-modification-time attr)) + (saved-mtime (gethash (intern ,file) + when-file-has-changed--hash-table))) + (when (not (equal mtime saved-mtime)) + (puthash (intern ,file) mtime when-file-has-changed--hash-table) + ,body))) ;;;; Support for yanking and text properties. ;; Why here in subr.el rather than in simple.el? --Stef -- 2.33.0