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?

ideasman42
  • 8,375
  • 1
  • 28
  • 105

1 Answers1

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