4

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?

1 Answer 1

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)))
5
  • For some reason this cases my file to be impossible to save even though it gets formatted.
    – Martin
    May 21, 2019 at 4:15
  • Fixed, the function needed to evaluate to nil, also only run when .clang-format file is found.
    – ideasman42
    Jun 24, 2019 at 2: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, 2019 at 11:01
  • this answer is excellent, but is missing ')' on each of the last three lines. Jul 28, 2021 at 18:19
  • 1
    @optimus_prime corrected (feel free to delete these comments to remove noise).
    – ideasman42
    Apr 5 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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