Created
March 30, 2017 11:01
-
-
Save apathyboy/8dad1b4b00393929c9a63f94c85c5b9e to your computer and use it in GitHub Desktop.
ClangFormat on Save via a C# Visual Commander extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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