问题
i wrote a little addin, which does some formatting of my C# code. in the addins Exec method i do the following
try {
TextSelection selection = (EnvDTE.TextSelection)_applicationObject.ActiveDocument.Selection;
String foo = String.Empty;
if (!text.IsEmpty) {
foo = someCoolObjectThatFormatsText.Format(selection.Text);
selection.Text = foo; // here everything gets painfully slow :-(
}
}
catch (Exception) {
throw;
}
when the line with the code "SelectedText.Text = foobar;" is call, VS rebuilds each line of the selection step by step. You can easily watch it doing this step. But i don't get, why it is that slow.
Any hints? TIA
回答1:
JFTR: I had to use TextSelection.Insert(...), but to also get visual studios depth of indention, i also had to mess with the selected text to span the selection also over the full first and last line:
TextSelection text = (EnvDTE.TextSelection)_applicationObject.ActiveDocument.Selection;
text.SmartFormat(); // sets the correct indention als studio
/* the following lines will expand the selection to whole lines: */
int lineSpan = text.BottomPoint.Line - text.TopPoint.Line;
text.MoveToPoint(text.TopPoint,false);
text.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn,false);
text.LineDown(true,lineSpan);
text.EndOfLine(true);
/* and now my custom textformatting */
text.Insert(someCoolObjectThatFormatsText.Format(text.Text),(int)vsInsertFlags.vsInsertFlagsContainNewText);
text.Collapse();
I don't really know wether this is a good way to alter textselections but it works fine and is way faster than the original addin code
回答2:
I haven't worked with addins but since you only asked for a 'hint', here is mine.
Try disabling screen update before you make the assignment.
Also the help file says,
"When the Text property is set, the value of Text is inserted in front of the selected text, and then collapsed, similar to what happens when text is pasted into a document. Note that this property behaves just as when typing when the editor is in insert (that is, non-overtype) mode. Any text after the 128th character is truncated."
That seems to imply that the variable is not ovewritten as expected, but appended instead and then the previous text is removed. Try to empty the variable first and see if it changes anything.
Also, consider using the PasteMethod to substitute the text instead of assigning.
来源:https://stackoverflow.com/questions/1063719/my-vs2008-addin-for-textformatting-is-awfully-slow