Auto-indent existing file using EnvDTE

194 views Asked by At

I'm using T4 Text templates for automatic code generation, but must of this code is not properly formatted, specially because of the TT files.

i would like to use EnvDTE to apply the smartformat, but all the examples that i've found needs to have the file open on the application.

Is there any way to apply the smartformat to an existing file without openning it?

Does some one have an example?

2

There are 2 answers

0
Carlos Quintero On

The document must be opened, but that doesn't mean that the document is visible to the user.

Given an EnvDTE.ProjectItem, you can .Open(view) it with the desired view (code) and you get an EnvDTE.Window, which is not visible (you would need to set .Visible = true). However, you can get its .Document property, and then cast its .Object property to EnvDTE.TextDocument and then you get the .StartPoint and .EndPoint text points, you .CreateEditPoint from them to get edit points and you .SmartFormat() between them.

0
Andrey On

This code worked for me:

 Window window = projectItem.Open();
 EnvDTE.TextDocument textDocument = window.Document.Object() as EnvDTE.TextDocument;

 textDocument.Selection.SelectAll();
 textDocument.Selection.SmartFormat();

 window.ProjectItem.Save();