views:

490

answers:

2

I realize that I may be being a bit lazy, but does anyone know of a Visual Studio macro, where I can select some text inside of the Visual Studio IDE, click a button, and have it wrap the selected text with tags? It would generate something like:

<strong>My Selected Text</strong>

I would even be up for creating a macro, just not sure where to exactly start!

+6  A: 

The code to do so is rather simple:

Sub SurroundWithStrongTag()
    DTE.ActiveDocument.Selection.Text = "<strong>" + DTE.ActiveDocument.Selection.Text + "</strong>"
End Sub

Now, if you don't know much about macros here's how to add it:

  • First you need open the macros IDE, click Tools->Macros->Macros IDE...
  • Next, we will add a module for your custom macros. Right click on "MyMacros" in the Project Explorer, click Add->Add Module..., type in an appropriate name then click "Add".
  • Now paste the function inside the module, making copies for any other tags you want
  • Save and close the macros IDE

To hook the macro up to a button:

  • Click Tools->Customize...
  • Click New..., type in an appropriate name, click OK. An empty toolbar should be visible (you may have to move the window to see it)
  • Click the Commands tab, and select "Macros" in categories
  • Find the macros created before and drag them over to the toolbar
  • Right click the buttons to change settings (such as displaying an icon instead of text)
redwyre
Thanks! You saved me a bunch of time!
mattruma
Can you actually present a prompt for which tag to surround the text with?
Sam
I just tried this and if I select text and run the marco, I end up with two </strong> tags at the end. I think this is because VS.NET does a little autocomplete of tags.So, from the code, I just took out the + "</strong>" from the end and it works great.Anyone know how to turn off that autocomplete functionality in the macro, and then reenable?
slolife
Sam, I just found an article (backlinking here) at http://webdevel.blogspot.com/2009/07/visual-studio-macro-wrap-selected-text.html which describes how to further build upon redwyre's excellent answer to provide a prompt allowing you to supply different tag names if you'd like. Also note, I believe this is built into VS 2010 now? See http://stackoverflow.com/questions/191463/
Funka
Hmmm, wondering if "Sam" the author of the article I linked is the same Sam I posted this comment for!?
Funka
A: 

Dim HTMLprops As Properties = DTE.Properties("Texteditor", "HTML Specific")

Dim aProp As EnvDTE.Property = HTMLprops.Item("AutoInsertCloseTag")

aProp.Value = False

neil