[PATCH] D12407: [clang-format-vs] Add an option to reformat source code when file is saved to disk

Jean-Sebastien Mouret via cfe-commits cfe-commits at lists.llvm.org
Sun Aug 28 04:38:28 PDT 2016


jsmouret added a comment.

A slightly improved version of @jasjuang code.
Restores current selection, and really saves if modified.

  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++")
      {
  	TextSelection selection = doc.Selection as TextSelection;
  	int begin = selection.TopPoint.AbsoluteCharOffset;
  	int end = selection.BottomPoint.AbsoluteCharOffset;
  
  	selection.SelectAll();
  	DTE.ExecuteCommand("Tools.ClangFormat");
  
  	selection.MoveToAbsoluteOffset(begin, false);
  	selection.MoveToAbsoluteOffset(end, true);
  
  	if (!doc.Saved)
  	{
  	  doc.Save();
  	}
  
      }
    }
  
    private EnvDTE80.DTE2 DTE;
    private EnvDTE.Events events;
    private EnvDTE.DocumentEvents documentEvents;
  }


https://reviews.llvm.org/D12407





More information about the cfe-commits mailing list