clang-formatter is a function for formatting buffer using clang-format
.
You can install by cloning this repo to your emacs directory. For example:
git clone https://github.com/qxxt/clang-formatter.el ~/.emacs.d/clang-formatter-el
And then adding that directory to your load-path
:
(add-to-list 'load-path (expand-file-name "clang-formatter-el" user-emacs-directory))
(require ’clang-formatter)
You can simply call the function by M-x clang-format-buffer
. You can bind that to a key in c-mode
by:
(define-key c-mode-map (kbd "C-c C-b") 'clang-format-buffer)
To format before-save-hook on c-mode
you can:
(add-hook 'c-mode-hook #'(lambda ()
(add-hook 'before-save-hook 'clang-format-buffer nil 'local)))
Or you can adds before-save-hook to all supported mode by:
(add-hook 'prog-mode-hook #'(lambda ()
(if (cl-find major-mode '(c-mode c++-mode java-mode javascript-mode objc-mode csharp-mode protobuf-mode))
(add-hook ’before-save-hook 'clang-format-buffer nil 'local))))
variable | description | default |
clang-format-command | command for clang-format, can be absolute path to clang-format binary. (eg, “/usr/bin/clang-format-16”) | “clang-format” |
clang-format-style | style passed to clang-format | “google” |
clang-format-c-style | c-mode style for clang-format | nil |
clang-format-c++-style | c++-mode style for clang-format | nil |
clang-format-java-style | java-mode style for clang-format | nil |
clang-format-javascript-style | javascript-mode style for clang-format | nil |
clang-format-objc-style | objc-mode style for clang-format | nil |
clang-format-csharp-style | csharp-mode style for clang-format | nil |
clang-format-protobuf-style | protobuf-mode style for clang-format | nil |
You can customize style passed to clang-format
by modifying clang-format-style
.
clang-format-style
will be overriden by specific mode style if they are not nil.
You can configure styles from .dir-locals.el
:
((c-mode . ((clang-format-c-style . "{BasedOnStyle: GNU,AlignAfterOpenBracket: Align,SortIncludes: Never}"))))
If you have clang-configuration file in root directory of your project, you can use “%R” and it will be replaced with your project root. For example, if project root is “~/project/abc”:
((nil . ((clang-format-style . "file:%R/.clang-format" ;; => --style=file:~/project/abc/.clang-format
))))