Skip to content

Instantly share code, notes, and snippets.

@apathyboy
Created March 30, 2017 11:01
Show Gist options
  • Select an option

  • Save apathyboy/8dad1b4b00393929c9a63f94c85c5b9e to your computer and use it in GitHub Desktop.

Select an option

Save apathyboy/8dad1b4b00393929c9a63f94c85c5b9e to your computer and use it in GitHub Desktop.
ClangFormat on Save via a C# Visual Commander 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++")
{
Document current = DTE.ActiveDocument;
doc.Activate();
TextSelection selection = doc.Selection as TextSelection;
int begin = selection.TopPoint.AbsoluteCharOffset;
int end = selection.BottomPoint.AbsoluteCharOffset;
selection.SelectAll();
DTE.ExecuteCommand("Tools.ClangFormatSelection");
if (!doc.Saved)
{
doc.Save();
}
// As the old selection may not be selectable, be cautious.
try { selection.MoveToAbsoluteOffset(begin, false); } catch {}
try { selection.MoveToAbsoluteOffset(end, true); } catch {}
current.Activate();
}
}
private EnvDTE80.DTE2 DTE;
private EnvDTE.Events events;
private EnvDTE.DocumentEvents documentEvents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment