I want to insert a default block of text when hitting a hotkey or when entering a special string in Visual Studio 2010 (either way would be fine).
Is there a fast and easy way to achieve this?
(Preferably without the use of third party extensions. )
Background / further explanation:
I want to use a special trigger-word to insert a default doxygen-commentblock, like "///" or "'''" for XML-commentblocks.
Other than the XML-functionality my inserted text does not have to be intelligent, it would suffice to just insert a default textblock.
My suggested trigger-string would be "---" as it would not collide with any program language I know. My suggested hotkey would be Alt+V.
Thanks for the help
Janis
Just write your own Code Snippet:
Code snippets are small blocks of reusable code that can be inserted in a code file using a context menu command or a combination of hotkeys. They typically contain commonly-used code blocks such as try-finally or if-else blocks, but they can be used to insert entire classes or methods.
Snippets are simply XML files that contain instructions to the Code Editor. For instance, here's the one that VS 2012 supplies for the C# if snippet:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>if</Title>
<Shortcut>if</Shortcut>
<Description>Code snippet for if statement</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>expression</ID>
<ToolTip>Expression to evaluate</ToolTip>
<Default>true</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[if ($expression$)
{
$selected$ $end$
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
You add new snippets to the IDE using the Code Snippet Manager, available from the Tools menu item from the main menu.
Related
I've trawled through the code snippet documentation and can't find anything that says you can do this but thought I would ask anyway.
Consider the following snippet that adds a context menu TagHelper to a page:
<CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>Context Menu</Title>
<Author>UX</Author>
<Shortcut>c:contextmenu</Shortcut>
<Description>Markup snippet for a context menu</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="html">
<![CDATA[<component:context-menu id="contextMenu">
<context-menu-trigger>$end$</context-menu-trigger>
<context-menu-content></context-menu-content>
</component:context-menu>]]>
</Code>
</Snippet>
</CodeSnippet>
I've tried multiple shortcut tags:
<Shortcut>c:contextmenu</Shortcut>
<Shortcut>c:context-menu</Shortcut>
I've tried separating them with a comma:
<Shortcut>c:contextmenu,c:context-menu</Shortcut>
No joy, I assume it can't be done and that I would have to create two snippets; one for each shortcut?
I created a code snippet (the first of many, hopefully) using mainly this article as guidance.
It seemed to work. Here are the steps I took:
First, I created this file with the code snippet (HtmlTableRowWithTwoCells.snippet):
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/CodeSnippet">
<CodeSnippet Format="1.0.0">
<!-- The Title of the snippet, this will be shown in the snippets manager. -->
<Title>Create a 2-Cell HTML Table Row</Title>
<!-- The description of the snippet. -->
<Description>Creates a 2-Cell Row to be added to an HtmlTable</Description>
<!-- The author of the snippet. -->
<Author>Warble P. McGorkle for Platypi R Us (Duckbills Unlimited)</Author>
<!-- The set of characters that must be keyed in to insert the snippet. -->
<Shortcut>row2</Shortcut>
<!-- The set of snippet types we're dealing with - either Expansion or -->
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<!-- Now we have the snippet itself. -->
<Snippet>
<Declarations>
<Literal>
<ID>RowName</ID>
<ToolTip>Enter the Row instance name</ToolTip>
<Default>RowName</Default>
</Literal>
<Literal>
<ID>Cell1Name</ID>
<ToolTip>Enter the name for Cell 1</ToolTip>
<Default>Cell1Name</Default>
</Literal>
<Literal>
<ID>Cell2Name</ID>
<ToolTip>Enter the name for Cell 2</ToolTip>
<Default>Cell2Name</Default>
</Literal>
</Declarations>
<!-- Sepecify the code language and the actual snippet content. -->
<Code Language="CSharp" Kind="any">
<![CDATA[
var $RowName$ = new HtmlTableRow();
var $Cell1Name$ = new HtmlTableCell();
var $Cell2Name$ = new HtmlTableCell();
$RowName$.Cells.Add($Cell1Name$);
$RowName$.Cells.Add($Cell2Name$);
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Then, I created this "manifest" file (.vscontent):
<?xml version="1.0" encoding="utf-8" ?>
<VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005" >
<Content>
<FileName>HtmlTableRowWithTwoCells.snippet</FileName>
<DisplayName>Inserts a 2-Cell HTML Table Row</DisplayName>
<Description>Inserts a 2-Cell Row to be added to an HtmlTable</Description>
<FileContentType>Code Snippet</FileContentType>
<ContentVersion>2.0</ContentVersion>
<Attributes>
<Attribute name="lang" value="csharp"/>
</Attributes>
</Content>
</VSContent>
I zipped those two files together, renamed the extension from .zip to .vsi, 2-clicked it, and installed it into the "My Code Snippets" folder here with these steps:
And it indicates the snippet was installed in a reasonable location:
Yet, when I attempt to add a Code Snippet in VS, the only categories I see are these (no "My Code Snippets"):
When I select Tools > Code Snippets Manager..., I can navigate to Visual C# > My Code Snippets, but it is empty.
When I use the Code Snippets Manager's "Import" button and navigate to the location of the snippet and attempt to add the snippet file, I get, "The snippet files chosen were not valid."
Why does it tell me it installed successfully, when it apparently didn't (or where is it hiding)? What flaming hoop did I neglect to catapult myself through?
Is the "weird" name of the "manifest" file possibly the problem? ".vscontent" seems odd to me, but that's what the article referenced above says to name it. Perhaps that was just on oversight, and it should really be [snippetName].vscontent?
UPDATE
Apparently, naming the "manifest" file *.vscontent" is not the problem. Maybe it's a problem, but it's not the problem, because I named it the same as the .snippets file (except for the extension), went through the installation process again, and got the same exact results: seeming success, actual demoralization.
BTW, by default, when choosing a category into which to place the snippet, the Code Snipeets Manager puts a checkbox in "Microsoft Visual Studio Tools for Applications 2005 > My Code Snippets". I had previously unticked that and ticked the topmost "My Code Snippets"; this time I retained the default selection, PLUS my preferred location/category PLUS "Visual C#"
But alas and anon, the only category of those that seems to dispaly via Ctrl+K, X in VS is C#, and the expected shortcut ("row2") does not appear in the snippet dropdown.
Here's an easier way (and, as a bonus, it works):
Download the Snippets Designer:
Write the code directly in Visual Studio:
var RowName = new HtmlTableRow();
var Cell1Name = new HtmlTableCell();
var Cell2Name = new HtmlTableCell();
RowName.Cells.Add(Cell1Name);
RowName.Cells.Add(Cell2Name);
Right-click and select "Export as Snippet"
This puts the code in the Snippet Designer. Here's what it looks like after setting a few properties, and electing which parts of the code would be replaceable:
This is quite easy - sure beats the "olde-fashioned" way I was trying (which would have been okay, had it worked).
All I had to do was right-click the elements of code I wanted to replace on adding a new snippet, set the snippet's shortcut and description properties in Solution Explorer, save it, and voila!
Now mashing Ctrl+K, X in VS shows the snippet in "My Code Snippets" along with its description and shortcut:
Selecting it adds the snippet with the replacement strings highlighted:
I'm looking for a way to quickly and routinely add my signature and the date to the top of new code files in Visual Studio.
There are some tutorials on using Macros to do this, but apparently Macros are no longer supported in VS2012.
I can define the header as a code snippet and insert the snippet, but snippets don't support getting the current date.
I can generate the correct text with the following T4 template:
<## template debug="false" hostspecific="false" language="C#" #>
// <author>Pieter Müller</author>
// <date><#=DateTime.Now.ToString("yyyy-MM-dd")#></date>
<## output extension=".cs" #>
This gives me the following result, which is perfect:
// <author>Pieter Müller</author>
// <date>2012-10-30</date>
The question is, is there a way for me to quickly and routinely insert this code into new code files, either automatically or manually using something similiar to Insert Snippet or a shortcut key?
If you don't have an answer, but you do have a good idea on generating the signature headers I need, please leave a comment. Thanks!
I hate to be answering my own question, but I did come up with a way to have T4 templates as snippets, although its Hack Level is over 9000. It works by writing a T4 template that generates a snippet, which it then automatically copies to the Visual Studio snippet folder.
Add a Text Template item to your project.
Set it up to build a snippet, that in turn builds the code you want to insert. For the example in my question, the snippet XML that you want to generate with the T4 template looks like this:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>DateHeaderSnippet</Title>
<Author>user</Author>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[// <author>Pieter Muller</author>
// <date>{Today's Date}</date>]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
To generate the above XML with a T4 template, we can insert the XML almost verbatim, with two changes. Firstly, this line:
<?xml version="1.0" encoding="utf-8"?>
must be inside a manual WriteLine statement, or the <?xml tag will confuse the T4 template processor:
<# WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); #>
And secondly, we want to use the T4 processing to inject today's date into the snippet XML, so we change:
<![CDATA[// <author>Pieter Muller</author>
// <date>{Today's Date}</date>]]>
to:
<![CDATA[// <author>Pieter Muller2</author>
// <date><#=DateTime.Now.ToString("yyyy-MM-dd")#></date>]]>
We also add some very hacky code to the end of the T4 template, that mannually reads the output file and writes it to a snippet file. The hacky part of this is that we have to specify absolute paths. The complete T4 code looks like this:
<## template debug="false" hostspecific="false" language="C#" #>
<## output extension=".txt" #>
<# WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); #>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>DateHeaderSnippet</Title>
<Author>user</Author>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[// <author>Pieter Muller2</author>
// <date><#=DateTime.Now.ToString("yyyy-MM-dd")#></date>]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
<#
System.IO.StreamReader sr = new System.IO.StreamReader(#"C:\Users\Pieter\Documents\Visual Studio 2010\Projects\tmp\tmp\TextTemplateToWriteHeaderTemplate.txt");
string sourceText = sr.ReadToEnd();
sr.Close();
System.IO.StreamWriter sw = new System.IO.StreamWriter(#"C:\Users\Pieter\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets\tryout.snippet");
sw.WriteLine(sourceText);
sw.Close();
#>
You'll have to compile the T4 template twice - the first run generates the snippet code, and the second run writes the previous run's output to the snippet folder. To do this, right click on the template in the Solution Explorer and click Run Custom Tool.
Now you can right click anywhere in code, select Insert Snippet... and select the generated snippet from the My Code Snippets group. The result:
// <author>Pieter Muller2</author>
// <date>2012-11-09</date>
I know this is way too much trouble to go through just to insert a simple author and date header, but hopefully someone else can use this technique for something more grandiose. You can put pretty much generate any kind of dynamic snippet this way.
Hope you are using ReSharper, which has powerful templates. I've implemented your example using very simple configuration for template variables
Now if I enter 'hd' and press tab this macro I will receive next result:
This may sound like a stupid question but I can't seem to find an answer. For example, take a look at the default div snippet that ships with Visual Studio 2010:
<CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>div</Title>
<Author>Microsoft Corporation</Author>
<Shortcut>div</Shortcut>
<AlternativeShortcuts>
<Shortcut>p</Shortcut>
<Shortcut>h1</Shortcut>
<Shortcut>h2</Shortcut>
<Shortcut>h3</Shortcut>
<Shortcut>h4</Shortcut>
<Shortcut>h5</Shortcut>
<Shortcut>h6</Shortcut>
<Shortcut>blockquote</Shortcut>
<Shortcut>pre</Shortcut>
<Shortcut>address</Shortcut>
<Shortcut>center</Shortcut>
<Shortcut>noscript</Shortcut>
</AlternativeShortcuts>
<Description>Markup snippet for a block element</Description>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="html"><![CDATA[<$shortcut$>$selected$$end$</$shortcut$>]]></Code>
</Snippet>
</CodeSnippet>
How would I use the alternative p shortcut? In IntelliSense, none of the alternatives are available. First of all, I've tried Surround With > HTML > p but since that's not a valid IntelliSense option, it defaults to surrounding with an a tag.
Additionally, I've tried Surround With > HTML > divp, div p, div-p, div:p among others and nothing works, it just defaults to div (and note the first option I wanted to try was div > p but the snippet selector won't allow > as input).
Does anyone know how to use this feature?
Accepting Hans' comment as the answer.
It's now documented. AlternativeShortcuts is used for intellisense when you start typing tags. Still no use with 'Surround With' even in VS 2013.
Quote from the link above:
Notice that the Alternative Shortcuts list includes other HTML elements such as p, h1, h2, and so on. This tells you that the same snippet is invoked by using the shortcuts <div, <p, <h1, and so on, because the corresponding HTML elements all use a similar pattern. Therefore, these elements are grouped together in the Code Snippets Manager.
I've created a code snippet in VS2010. It isn't showing as a shortcut when I start typing. I've called it propnch.
It is available when I use Ctrl-K, Ctrk-X but when I just start typing prop... it isn't showing as an option.
Have I missed some kind of setting somewhere?
I had screen shots, but I don't think SO lets you upload any.
Edit: Screen Shots
I can see my snippet with Ctrl-K, Ctrl-X (its gone grey when I ctrl-PrtScn to take the screenshot)
But It doesn't appear with the other snippet shortcuts.
The snippet code is here (taken from this tutorial) and is in the "Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets" folder.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propnch</Title>
<Shortcut>propnch</Shortcut>
<Description>Code snippet for property and backing field and ensure
that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
<Author>Abhishek</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[
private $type$ $field$;
public $type$ $property$
{
get
{
return $field$;
}
set
{
this.OnPropertyChanging("$property$");
$field$ = value;
this.OnPropertyChanged("$property$");
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
It turns out this is a design flaw for the xml editor in VS2010. In the C# editor, you just type the shortcut and press 'tab'. IN the xml editor, it requires two more keystrokes.
To quote from the documentation:
To insert snippets using the shortcut name
1. Position the cursor where you want to insert the XML snippet.
2. Type < in the editor pane.
3. Press ESC to close the IntelliSense complete word list.
4. Type the shortcut name of the snippet, and press TAB to invoke the XML snippet.
According to screenshots, you have ReSharper installed and it overrides VS's IntelliSense behavior. You can either turn off Resharper's overriding or just add right in it a new LiveTemplate. More details here:
http://www.jetbrains.com/resharper/webhelp/Templates__Applying_Templates__Inserting_Imported_Code_Snippets.html
In my case I just added a new ReSharper template:
private $type$ _$loweredProperty$;
public $type$ $property$
{
get { return _$loweredProperty$;}
set
{
if (_$loweredProperty$ == value) return;
_$loweredProperty$ = value;
OnPropertyChanged("$property$");
}
}
adn it works even better: you have to type only two words - type and property name. The backing field will appear with lowered first letter. You must set "$loweredProperty$" to non-editable macros and point it to $property$. That's just a couple of clicks in Template editor.
Too a sec to realize, but it's simple: you were missing the </CodeSnippets> at the end.
CTRL +K+ X
or
Right click on code page will show you the snippet
right click and start intellisense in Visualstudio
Go in Extensions and Updates of Visual Studio and then click on Online Tab and then in search type Bootstrap.
Install following Packs to enable intellisense
Bootstrap Bundle
Bootstrap Snippet Pack
If it is snippets for XML language it must be placed in next directory
C:\Users\%user%\Documents\Visual Studio 2015\Code Snippets\XML\My Xml Snippets\
For adding one of them to your document you must call snippet context menu by
ctrl+K, ctrl+X.
Your snippets will be in "My Xml Snippets"
This may come a little bit late but if you are debugging a program CTRL K + CTRL X will not work. Stop debugging your program and try it again. it worked for me in VS 2013 and without Resharper.