[Solved] Using clang-format in CLion

I’d like to format my code using clang-format in CLion. I’ve gone through the settings and haven’t found any setting that would allow me to run an external command to transform code. How are such things normally done in CLion?

Solution #1:

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.

Respondent: Allan Hasegawa

Solution #2:

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.

Respondent: frido

Solution #3:

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
    Creating a new file watcher in the clion settings panel
  • 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
    My clang-format file watcher settings

    • For example, if you wish to execute clang-format automatically whenever the file changes (without needing to save) you can enable Advanced Options->Auto-save edited files to trigger the watcher

Documentation for the File Watchers plugin: https://www.jetbrains.com/help/clion/using-file-watchers.html

Respondent: Chris Frank

Solution #4:

Since CLion 191 EAP ClangFormat is supported from the box.

Respondent: uta

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.