2

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?

5

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 ()
      (progn
        (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))
3
  • For some reason this cases my file to be impossible to save even though it gets formatted. – Martin May 21 '19 at 4:15
  • Fixed, the function needed to evaluate to nil, also only run when .clang-format file is found. – ideasman42 Jun 24 '19 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 '19 at 11:01

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.