0

I need to test if the buffer has been modified even if (save-buffer) has been called after the changes.

I thought to use add-variable-watcher but I found that buffer-modified-p is a function, not a variable.

I thought something like (add-hook 'before-save-hook 'myfunction) where myfunction should set a custom-variable on t and remove the hook at the same time. In this case I could test (or (buffer-modified-p) custom-variable)

I mean something like

(defun myfunction (VAR)
  (setq VAR t)
  (remove-hook 'before-save-hook 'myfunction)

(defmacro mymacro
   `(let ((VAR nil))

      (add-hook 'before-save-hook 'myfunction)

      ,@body

      (if (or (buffer-modified-p) VAR) ...)))

(This is not a MWE but only an idea of code...)

How can I add a function with one argument (custom-variable) to 'before-save-hook? Is it a bad idea? I need to avoid lambda function because of the need to remove it from the hook.

I'm open to other ideas.

10
  • Please clarify. You talk about variable watchers as if you were wanting to react to changes when they happen, but then also talk about before-save-hook as if you're not concerned about changes unless you're about to save the buffer to a file. What is it that you want to do? Describe the behaviour you're trying to achieve.
    – phils
    Commented May 10, 2022 at 0:45
  • You could use write-region instead of save-buffer, if that is an option for you. It would 'save' your buffer without setting it 'unmodified'. Commented May 10, 2022 at 1:12
  • @phils the reaction to the changes would be setting VAR on t. I'm just looking for a way to check if the buffer has been modified at the end of ,@body even if user (interactively) or functions saved the buffer.
    – Gabriele
    Commented May 10, 2022 at 6:08
  • @dalanicolai write-region is not an option, thanks.
    – Gabriele
    Commented May 10, 2022 at 6:09
  • @GabrieleNicolardi You call (buffer-modified-p) to check if the buffer has been modified. But I believe you already know that, and knew before you asked the question, so I still don't understand what the question is, or how hooks or variable watchers come into it.
    – phils
    Commented May 10, 2022 at 7:23

1 Answer 1

1

I think you just want:

(let ((modified (buffer-modified-p)))
  ...do things...
  (when modified
    ...do more things...))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.