reddit / emacs

clang-format-buffer hook in wrong file format.

larg1979 · 2022-12-07 15:36
Hello all, I have in my init.el configured the clang-format-buffer call as a hook on the event before-save-hook for c and c++ modes. I don't understand why the .cmake files are processed too. Any hint? The problem is that the cmake files are parsed (corrupted) by the clang-format tool (add-hook 'c++-mode-hook (lamda() ( add-hook 'before-save-hook 'clang-format-buffer())) Thanks
Lucius_Martius · 2022-12-07 16:41
>(add-hook 'c++-mode-hook (lamda() ( add-hook 'before-save-hook 'clang-format-buffer())) What's happening here is that every time you open a c++ file, the (global) before-save-hook is (re)added. But that before-save-hook hook itself is then called unconditionally from that point forward when saving any file (including cmake files). What you want is likely something like this (without testing): (add-hook 'before-save-hook (lambda () (when (memq major-mode '(c-mode c++-mode)) (clang-format-buffer)))) Edit: I just found out that you can in fact make local hooks. So alternatively, this might work (again, untested): (add-hook 'c++-hook (lambda () (add-hook 'before-save-hook 'clang-format-buffer nil t))) Note the last two parameters that tell the hook added to c++-mode to be local to that buffer only. Thanks for making me look this up and learning something today.