3

I want to use .dir-locals.el to append to the before-save-hook in a project for c++ files.

Currently I'm using:

(add-hook 'c++-mode-hook
          (lambda ()
            (add-hook 'before-save-hook 'clang-format-buffer nil t)))

This will set before-save-hook as a buffer local variable ignoring everything that I set globally.

How can I create a buffer-local variable of 'before-save-hook' that takes the value from the global version and then adds clang-format-buffer?

Another thing that is a little bit annoying is that this will only be applied after the second file I open in the project. In the first cpp file that I open the hook is not applied.

1
  • If it doesn't have to go to before-save-hook, you can add it to local-write-file-hooks which is buffer local by default. May 15, 2015 at 13:42

1 Answer 1

7
(add-hook 'before-save-hook #'clang-format-buffer nil t)

This is the right way to add a function locally to a hook.

This will set before-save-hook as a buffer local variable ignoring everything that I set globally.

No, it won't. The global value will still exist, and run-hooks will run both values. before-save-hook is no exception here, try it out and you will see. Nothing will get ignored.

Another thing that is a little bit annoying is that this will only be applied after the second file I open in the project. In the first cpp file that I open the hook is not applied.

This is what your .dir-locals.el should look like:

;;; Directory Local Variables
;;; For more information see (info "(emacs) Directory Variables")

((c++-mode
  (eval add-hook 'before-save-hook #'clang-format-buffer nil t)))
5
  • With some more looking around, from add-hook documentation: The optional fourth argument, LOCAL, if non-nil, says to modify the hook's buffer-local value rather than its global value. This makes the hook buffer-local, and it makes t a member of the buffer-local value. That acts as a flag to run the hook functions of the global value as well as in the local value. May 15, 2015 at 15:02
  • Thanks I wasn't aware that this will add a new before-save-hook that is independent from the global value.
    – kain88
    May 15, 2015 at 17:07
  • The difference between the line in the question and the answer seems to be the hash. Is the # important here?
    – user12190
    May 27, 2016 at 8:32
  • @JayeshBadwaik there's no difference. I just corrected the OP's understanding of what it does.
    – Malabarba
    May 27, 2016 at 8:56
  • Okay, cool. :-)
    – user12190
    May 27, 2016 at 8:56

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.