Setting up clang-format to format on save in VisualStudio 2017
Step 1
- Install the ClangFormat and Visual Commander Extensions for Visual Studio
- Go to Tools -> Extensions and Updates and search for the Extensions under the Online tab.
An already existing Clang-Format Installation outside of Visual Studio is not sufficient; Visual Studio still needs the Extension.
Step 2
Visual Commander allows the user to create Extensions for Visual Studio.
- Go to the new VCmd tab in Visual Studio and select Extensions.
- Select Add in the Extensions area and Edit on the newly created extension.
- You can give the Extension a name like "clang_on_save", but what's important is making sure the language is set to C#.
- Copy the following code into the extension:
using EnvDTE;
using EnvDTE80;
public class E : VisualCommanderExt.IExtension
{
public void SetSite(EnvDTE80.DTE2 DTE_, Microsoft.VisualStudio.Shell.Package package)
{
DTE = DTE_;
events = DTE.Events;
documentEvents = events.DocumentEvents;
documentEvents.DocumentSaved += OnDocumentSaved;
}
public void Close()
{
documentEvents.DocumentSaved -= OnDocumentSaved;
}
private void OnDocumentSaved(EnvDTE.Document doc)
{
if(doc.Language == "C/C++")
{
DTE.ExecuteCommand("Tools.ClangFormatDocument");
}
}
private EnvDTE80.DTE2 DTE;
private EnvDTE.Events events;
private EnvDTE.DocumentEvents documentEvents;
}
- Then hit Save, Compile and Install.
Visual Studio should now apply Clang Format to any C and C++ documents upon saving them. You can also manually run Clang Format without saving by hitting Ctrl+R then Ctrl+D.
Below is a picture guide to make finding everything easier.