DEV Community

Discussion on: [Emacs] Auto runs clang-format when file save

Collapse
 
ricardoaiglesias profile image
Ricardo Iglesias • Edited

Thanks for this guide!

I found that this configuration essentially forces the "before-save-hook" to always run "clang-format-buffer" once you load a C/C++ file. This is fine if you're working on a project, but has the unintended consequence of formatting non-C/C++ files if you work on many different files. This is particularly cumbersome when editing something like a LaTeX file, where the position of the curly braces and whitespace tends to matter.

A much more robust way I've found is to do simply map the "C-x C-s" key (which is the default save key) to a function that formats then saves:

(defun format-and-save()
  (interactive)
  (clang-format-buffer)
  (save-buffer))


(define-key
  c-mode-base-map
  (kbd "C-x C-s")
  'format-and-save)
Collapse
 
thomas001 profile image
Thomas Weidner

I have the same problem. I solved it by doing

(add-hook 'c-common-mode-hook 
  (lambda ()
    (add-hook (make-local-variable 'before-save-hook)
              'clang-format-buffer)))
Collapse
 
yuu profile image
yuu

thank you both of them.
I will update for article and my init.el