Whats the best way to clang-format a C/C++/GLSL a buffer on save, that does nothing in the case there is no clang-format file found for a project?
Asked
Active
Viewed 3,505 times
1 Answers
7
Install the clang-format
package and add the following hooks to your emacs init:
(defun clang-format-save-hook-for-this-buffer ()
"Create a buffer local save hook."
(add-hook 'before-save-hook
(lambda ()
(when (locate-dominating-file "." ".clang-format")
(clang-format-buffer))
;; Continue to save.
nil)
nil
;; Buffer local hook.
t))
;; Run this for each mode you want to use the hook.
(add-hook 'c-mode-hook (lambda () (clang-format-save-hook-for-this-buffer)))
(add-hook 'c++-mode-hook (lambda () (clang-format-save-hook-for-this-buffer)))
(add-hook 'glsl-mode-hook (lambda () (clang-format-save-hook-for-this-buffer)))

ideasman42
- 8,375
- 1
- 28
- 105
-
For some reason this cases my file to be impossible to save even though it gets formatted. – Martin May 21 '19 at 04:15
-
Fixed, the function needed to evaluate to `nil`, also only run when `.clang-format` file is found. – ideasman42 Jun 24 '19 at 02:36
-
Thanks for showing us `locate-dominating-file`. Would be helpful with `flycheck`, `lsp-mode`, etc. where the notion of a project is needed. – legends2k Dec 12 '19 at 11:01
-
this answer is excellent, but is missing ')' on each of the last three lines. – optimus_prime Jul 28 '21 at 18:19
-
1@optimus_prime corrected (feel free to delete these comments to remove noise). – ideasman42 Apr 05 '22 at 05:59