In Eclipse, I can hit CTRL + SHIFT + F
which not only corrects the indentation but also whitespace (for example: c=a +b ;
is corrected to c = a + b;
) and the line length. I am looking for a similar tool for Emacs. All I know is C-x h TAB
that corrects the indentation, but nothing more. Do you know any automatic way how to completely format a (espacially C/C++) source file in Emacs?
Asked
Active
Viewed 3,611 times
7

Monkey Supersonic
- 183
- 1
- 6
-
Nope. However, it shouldn't be too hard to write an integration for an external tool, such as AStyle or ClangFormat. Here's a relevant question: http://stackoverflow.com/questions/841075/best-c-code-formatter-beautifier – Dmitry Dec 06 '14 at 23:55
-
For indenting, you can do it faster with the command [prelude-cleanup-buffer-or-region](https://github.com/bbatsov/prelude/blob/cba761c21283b45f8228877773da9527607b8db1/core/prelude-core.el#L278). Copy the function definition and [prelude-indent-sensitive-modes](https://github.com/bbatsov/prelude/blob/37101cb867b81a61ccb7b216a3c053bc465cee06/core/prelude-custom.el#L79) in your `init.el`. Then bind the command to a key like `C-c i` and use it whenever you want to indent without cursor moved elsewhere. – Tu Do Dec 07 '14 at 07:17
1 Answers
8
You can use ClangFormat to achieve this. After installing the clang-format
tool, you can use clang-format.el
to perform the appropriate actions from emacs. clang-format.el
is also available from MELPA. The emacs commands provided are clang-format-buffer
and clang-format-region
which you can bind as you need. Note that you can customize formatting options by using a .clang-format
file located in an ancestor directory.

Pradhan
- 2,330
- 14
- 28
-
Ah, so the integration already exists. Note, however, that MELPA distributes a different (apparently newer) version than the one you linked to. – Dmitry Dec 07 '14 at 05:20
-
Clang-Format is indeed a great tool, well integrated into Emacs. To have the same binding as in Eclipse you can use the following in a your C/C++ mode hook `(define-key c-mode-base-map (kbd "C-S-f") 'clang-format-region)`. In recent versions `clang-format` supports also some other languages such as Javascript and Java, see LanguageKind in this page: http://clang.llvm.org/docs/ClangFormatStyleOptions.html – Guillaume Papin Dec 07 '14 at 16:13
-
Okay, this works nearly well, has only one weakness: spaces in closing angles in nested template arguments are removed: `List
>` -> `List – Monkey Supersonic Dec 10 '14 at 20:33> //Error!` -
@user3000316 Check the options for the config value "Standard" [here](http://clang.llvm.org/docs/ClangFormatStyleOptions.html). You can set it to `Cpp03` to fix this issue. – Pradhan Dec 10 '14 at 21:02