Just wrote a quick macro for Visual Studio that would replace < with < and > with >, etc. I am probably the 1000th person to do that. Yet, it proved to be surprisingly hard.
DTE.ActiveDocument.Selection
is an Object
. No methods, no nothing. Need to cast to TextSelection
to do anything useful with it.TextSelection.ReplacePattern()
happily replaces one pattern, then loses selection. Attempts to artificially restore selection failed, as TopPoint
and BottomPoint
properties are read only. MoveToPoint()
did not do the trick either. I am still not sure how to tell the IDE to select the text from here to there.- If you attempt to do something like
Selection.Text = Selection.Text.Replace((...)
it works fine for one line, but for multiline selection it inserts lots of spaces and generally looks very weird. It also takes a lot of time and occasionally throws exceptions. A non starter. - Tried to use
DTE.Find
object, could not find a way to close programmatically the damn Find window. Fortunately DTE.Find.FindReplace()
works without opening the window.
Oh yeah, if you try Googling for it – forget about it. You are drowning in crap. Bing is slightly better, but still no help there.
Final solution:
Sub EscapeXmlChars()
Replace("&", "&")
Replace("<", "<")
Replace(">", ">")
End Sub
Sub UnescapeXmlChars()
Replace("<", "<")
Replace(">", ">")
Replace("&", "&")
End Sub
Private Sub Replace(ByVal find As String, ByVal replace As String)
DTE.ActiveDocument.Activate()
DTE.Find.FindReplace( _
vsFindAction.vsFindActionReplaceAll, _
find, _
vsFindOptions.vsFindOptionsMatchInHiddenText, _
replace, _
vsFindTarget.vsFindTargetCurrentDocumentSelection)
End Sub
CodeProject