Using clang-format in CLion
You can use External Tools in CLion.
Go to File->Settings->Tools->External Tools
and click on the plus sign.
A window should pop up. Use a name of your choice.
For the Tool settings
tab I'm using this configuration:
Program:
clang-format-3.7
(you should use the name of your executable here)Parameters:
-i $FileName$
Working directory:
$FileDir$
Now, with your file open, you can go to Tools->External tools
and run the config above. It basically calls clang-format and does inplace formatting.
You can also set a custom keymap to it, just search the name of your external tool in "Keymap" of the Settings menu.
The lates version of CLion 2019.1 has native support for ClangFormat.
For previous version go to File->Preferences->Plugins
and search for ClangFormatIJ
. Install this plugin.
It installs the context menu to invoke locally installed clang-format
for a file or for a selection. It also set up the key shortcut for 'Reformat current Statement with clang-format' action.
This option works quite well for me in CLion 218.3 however, it might be included in an early version as well.
Since CLion 191 EAP ClangFormat is supported from the box.
The previous answers work well, but do not allow executing clang-format on save without the use of workarounds which don't work with the Vim emulation plugin I am using.
Here is a solution which executes clang-format on save and works well in every situation that I have encountered.
- First you need to install the
File Watchers
plugin. - From there you need to go to
File->Settings->Tools->File Watchers
And create a custom template I use the following settings to execute
clang-format
when one of the currently open files is saved. You can tweak these settings to match your needs- For example, if you wish to execute
clang-format
automatically whenever the file changes (without needing to save) you can enableAdvanced Options->Auto-save edited files to trigger the watcher
- For example, if you wish to execute
Documentation for the File Watchers plugin: https://www.jetbrains.com/help/clion/using-file-watchers.html