views:

381

answers:

2

When running a macro that changes the selected text, tags are automatically closed and the text formatted. How can I prevent that from happening?

For example, wrapping text in a tag:

DTE.ActiveDocument.Selection.Text = String.Format("<tag>{0}</tag>", DTE.ActiveDocument.Selection.Text)

Ends up with two closing tags:

<tag>Text</tag></tag>

Even stranger, multiple lines fails:

<li>One</li>
<li>Two</li>
<li>Three</li>

An ends up as

<ul>            <li>One</li>
            <li>Two</li>
                        <li>Three</li></li></ul>

How can I prevent that? As can be seen by the last example, the formatting is wrong and there is an extra </li>

A: 

I think the only way to do this is to open a undo transaction for your edit. This should suspend all formatting operations until the transaction is complete. This will allow you to do several edit operations before a format.

Here is the documentation OpenLinkedUndo method

JaredPar
No example code there... would want to undo the macro action (if this stops that from happening that is)
Sam
+2  A: 

You'll need to insert the text rather than assigning it:

Try
    DTE.UndoContext.Open("InsertSomeCode")
    Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
    ts.Insert(String.Format("<tag>{0}</tag>", ts.Text))
Finally
    DTE.UndoContext.Close()
End Try
Brian Schmitt