Click here to Skip to main content
Click here to Skip to main content
Go to top

Code Template Add-In for Visual Studio .NET

, 6 May 2004
Rate this:
Please Sign up or sign in to vote.
A Visual Studio .NET addin that provides a mechanism for inserting commonly used code snippets.

Version 1.9 - RC3 What's New?

Introduction

Code<Template>.NET is an add-in for Visual Studio .NET, that provides a mechanism for inserting commonly used text fragments into your source code. It is based on the ideas presented in my additions to Michael Taylor's extension to Darren Richard's original CodeTmpl addin.

The main differences with the original CodeTmpl addin are:

  • Support for Visual Studio .NET.
  • Rewritten from scratch in C#.
  • Cleaner file format.
  • Keyword, environment and prompted replaceable values.
  • Predefined and .NET standard formatters.

The text fragments used by Code<Template>.NET are contained in files called CodeTmpl.* (where * is a per-language extension) which are located in the user's roaming profile. These files are originally copied from sample files which are located on the same directory as the addin's executable. The format of these text files is very simple: named blocks contain the text fragments that will be inserted in your source code. Besides the directly inserted text, these fragments can also contain tags which represent replaceable keywords and prompted values. These named blocks will show up as menus and submenus in Code<Template>.NET's toolbar button. When you click on one of these menu items, the corresponding text fragment will be inserted in the active window's insertion point.

Configuration

The template files are completely configurable so you can replace or change the default text fragments to suit your own needs. The format of the template files is extremely simple. Basically you paste your block of code into the file and surround it with the open menu (#{) and close menu (}#) tags. The open menu tag should be followed by the name that will appear on the popup menu. The open menu tag can also include a Menu ID that is separated from the display name by a vertical bar (|); this Menu ID is used to directly insert a template into the editor by pressing Ctrl+Enter. Whatever text is placed between the open and close menu tags will be copied verbatim into the text editor. Menu items can be nested, creating a hierarchical view of templates. You can also specify an access key by placing an '&' character before the character to be used as the access key. For example, to specify the "F" in "File" as an access key, you would specify the caption for the menu name as "&File". You can use this feature to provide keyboard navigation for your templates. A separator (##) tag can be used to separate menu items and an exclamation mark (!) at the start of a line is used for single line comments.

Additional template files can be included by adding a line starting with "#include" followed by the file name. If the file name does not have an absolute path, the file will be searched for relative to the base template file in the user's roaming profile. Include statements can only be inserted between menu and submenu definitions.

For example:

#{Hello World - &Console|hwc 
#include <iostream> 
int main()
{
   std::cout << "Hello, new world!\n";
}
#}

##########################

#{Hello World - &GUI|hwg
#include <WinUser.h>

int PASCAL WinMain(HANDLE hInstance,
                   HANDLE hPrevInstance,
                   LPSTR lpszCommandLine,
                   int cmdShow)
{
    MessageBox(NULL, "Hello, World", 
                       "Example", MB_OK);
}
#}

If your template file contained the above text then clicking the CodeTmpl toolbar button would display a popup menu containing the options Hello World - Console and Hello World - GUI, with a separator between them. Selecting Hello World - Console would paste the text shown between the '#{' and '#}' tags into your source; a speedier way to insert this template would be to type hwc and then press ctrl+<space>.

Keywords

The replaceable text between the menu open and menu close tags can contain replaceable keywords. These keywords are surrounded by the keyword open (<% ) and keyword close (%>) tags and are case-insensitive. To insert these tags verbatim in the text (in ASP templates for example) escape the percent ('%') symbol by preceding it with a backslash ('\'). The less than ('<') and the greater than ('>') characters are escapable too.

Currently, the following keywords are predefined:

  • SOLUTION

    Returns the solution name.

  • PROJECT

    Returns the current project name.

  • FILE

    Returns the current file name.

  • NOW

    Returns the current date and time.

  • TODAY

    Returns the current date.

  • GUID

    Returns a GUID.

  • TEMPLATE

    Inserts the text from another template.

For example:

#{Sample
  The solution's name is <%SOLUTION%>
  and the current project is <%PROJECT%>

}#

will be expanded to:

  The solution's name is CodeTemplateNET
  and the current project is CodeTemplateNET

If an undefined keyword is used, then its value is searched for in the system's environment; if the environment variable is not found the keyword is replaced with the empty string. For example:

#{User name
   Logged-in user name: <%USERNAME%>
}#

will be expanded to:

   Logged-in user name: velasqueze

When using nested templates using the template keyword, the template that is being referenced must have a MenuID. For example:

#{Template A|tpla
// This is template A


}#
#{Template B|tplb
// <%template:tpla%>
// This is template B

}#

Ah, and by the way... recursive template nesting is a Bad thing... don't do it!

If the keyword's name starts with a question mark (?) then the keyword represents a prompt value and its name is used as the prompt string in the input dialog. The prompt keyword name can contain spaces. For example:

#{Ask me something
  <%?Please answer the prompt%>
}#

will be expanded to: (Supposing you typed "I just answered!" in the input boxSmile | :)

  I just answered!

The cursor position tag (%$%) will reposition the caret after the text has been formatted and inserted in the editor window.

Formatters

The value of a keyword can be modified by one or more formatters. Formatters follow the keyword name and are separated by colons (:) and can have parameters.

Currently, the following formatters are predefined:

U U[=start[,length]] Returns the key's value in uppercase. Start is zero-based.
L L[=start[,length]] Returns the key's value in lowercase. Start is zero-based.
W W=width Returns the key's value truncated to the parameter's width.
R R=str1[,str2] If only str1 is present, returns the key's value replacing the first character with the second character in the parameter string. If str2 is also present, returns the key's value replacing str1 with str2.

FMT

FMT=str

Returns the key's value formatted applying the parameter to System.String.Format(). e.g. String.Format("{0:str }", key)

VALUES VALUES=v1{, vn}* Forces the prompt keyword to show up as a ComboBox with a predefined list of values. Other values can be typed in.
FIXEDVALUES FIXEDVALUES=v1{, vn}* Forces the prompt keyword to show up as a ComboBox with a predefined list of values. Only the values in the list can be used.
MULTILINE MULTILINE=int Forces the prompt keyword to show up as a multi-line textbox. The provided value indicates the height (in lines) of the control.
DRIVE DRIVE Returns the drive part of the key's value.
DIR DIR Returns the directory part of the key's value.
FNAME FNAME Returns the file name part of the key's value.
EXT EXT Returns the file extension part of the key's value.
PATH PATH Returns the drive and directory parts of the key's value.
BASENAME BASENAME Returns the file name and extension parts of the key's value.

For example:

#{Sample
  User name: <%USERNAME:U%> // User name uppercased
  GUID: <%GUID:R=-_:U%>     // GUID replacing all the '-' with '_' and uppercased
  File's base name: <%FILE:BASENAME%>
  m_a is a <%?Access:values= public,protected,private%> variable. 
}#

will expand to:

  User name: VELASQUEZE // User name uppercased
  // GUID replacing all the '-' with '_' and uppercased
  GUID: 33784DF9_4EF5_49AE_8E8B_2F8FAAC8B1A2     
  File's base name: connect.cs
  m_a is a protected variable.

Updates

Version 1.9 - RC3 (05/07/04)

  • Extended characters "disappeared" from the inserted text. (Thanks to Frank Sandersen for spotting this.)
  • The menu was not accessible if there was a syntax error in the template file.
  • The syntax error message box now displays the file name and line number where the error occurred. (Thanks to Frank Sandersen for the suggestion.)
  • The template directory can now be explicitly specified by one of two registry values: "HKLM\Eddie Velasquez\CodeTemplate\TemplateDir" or "HKCU\Eddie Velasquez\CodeTemplate\TemplateDir" for a system-wide or per-user setting. If neither value is found the user's roaming profile directory will be used. Unfortunately there will be no UI in this version, so all changes have to be done via Regedit. (Thanks to Frank Sandersen for the suggestion.)
  • The parameter dialog is noe pre-populated with the previously used values. The values are stored in the registry on a per-user basis.

Known issues

  • The installer file is way too big. Visual Studio insists on adding a 204 K file named MSVBDPCA.DLL. I don't know where it came from and I don't know how to get rid of it.
  • The CommandBar is not removed after uninstalling. The darn toolbar just won't go away.
  • It has not been tested with Visual Studio .NET 2002.

Any suggestions on how to resolve these issues are greatly appreciated.

Version 1.9 - RC2 (04/12/04)

  • Autocomplete was deleting part of the text beyond the template ID.
  • Templates which started with whitespaces got misaligned when inserted. (Thanks to EnderJSC for reporting this.)

Version 1.9 - RC1 (04/08/04)

  • Added support for include template files. Lines between template definitions that start with "#include" indicate the template file to be included. If the filename does not include an absolute path, Code<Template> will try to locate the file in the current user's roaming profile. (Thanks to Ken Blood for the suggestion.)
  • Added support for per-language template files. For example, the "CodeTmpl.cs" template file will be used for C# files, "CodeTmpl.cpp" will be used for C++ files, etc.
  • Added support for multi-line prompt tags using the "MULTILINE" formatter.
  • Added support for nested templates. (Thanks to Alex Kucherenko for the idea.)
  • Fixed a bug in which the tag would not be redisplayed if the user cleared the textbox in the prompts dialog. (Thanks to Jean-Claude Lanz for reporting this.)
  • The "Rebind Keyboard" was binding the keyboard to the wrong command.
  • The "Rebind Keyboard" menu item will now automatically create a copy of the default keyboard binding if necessary.
  • Fixed a bug when using the AutoComplete to insert a template, the contents of the clipboard got replaced by the template ID.
  • Added support for administrative installs.
  • The add-in commands are now removed while uninstalling.
  • Now using Visual Studio .NET 2003 for development.

Version 1.8.5 (08/10/03)

  • The '<', '>' and '%' characters can now be escaped by preceding them with a backslash. This allows to embed ASP tags in a template. (Thanks to popsy1111 for the suggestion.)
  • Menu separators could not be used in the root menu. (Thanks to rb126 for reporting this.)

Version 1.8.4 (04/03/03)

  • The "extra carriage return" bug rose back from the dead in version 1.8.3. (Thanks to matt310 for reporting this.)

Version 1.8.3 (04/01/03)

  • Due to a bug introduced in version 1.8.1, the template did not display as expected when previewed in the template parameter dialog. (Thanks to Kris Vandermotten for spotting this.)
  • Added support for comments. Lines between the template definitions that start with an exclamation mark (!) introduce a single line comment that will not be inserted in the editor. (Thanks to Kris Vandermotten for the suggestion.)
  • Added help menu item that opens the readme.htm file in the default browser. (Thanks to Kris Vandermotten for the suggestion.)
  • When a prompt tag was used several times in a template its value would not be inserted in places where the tag was used with different formatters from the first instance. (Thanks to Jason Buxton for reporting this.)

Version 1.8.2 (03/26/03)

  • The template ID was deleted after pressing ctrl+' even if it could not be found. (Thanks to M. Lansdaal and Stefano Del Furia's students for spotting this.)
  • Changed the default keyboard binding to Ctrl + Space. If the template ID cannot be found, then the default autocomplete function is invoked. (Thanks to David Hearn for the suggestion.)

Version 1.8.1 (03/12/03)

  • The add-in was inserting an extra linefeed at the end of the template. (Thanks to Stefano Del Furia for spotting this.)

Version 1.8 (02/30/03)

  • The data file is now kept in the roaming profile. If a local copy exists, it is moved to the roaming profile; if it doesn't, a copy from the sample file is made (Thanks to Stefano Del Furia for the suggestion.)
  • Fixed some formatting bugs in the inserted text, specially when using the cursor positioning token (%$%) (Thanks to Stefano Del Furia for spotting this.)
  • If the template file was malformed, the popup menu didn't allow the user to open the file inside Visual Studio for editing. (Thanks to Stefano Del Furia for spotting this.)
  • The Uppercase and Lowercase formatters where extended to allow an optional start position and length. (Thanks to Jason Buxton for the suggestion.)
  • The Replace formatter was extended to allow the replacement of substrings in addition to the replacement of single characters.

Version 1.7 (02/18/03)

  • Added named IDs for menu items. Typing the menuid and then pressing ctrl+' will insert the template without going through the menus. (Thanks to Stefano del Furia and jsimons007 for the suggestion.) Note that Visual Studio does not allow the default keyboard scheme to be modified, so a copy must be created manually to enable keyboard binding. After creating a copy of the default keyboard scheme, click "Rebind Keyboard" in the add-in's menu.
  • Reassigned the keyboard binding introduced in version 1.6 to the new template insertion method just described. The original method wasn't very useful.
  • Prompt fields that were never changed got inserted into the text editor with the raw tag text instead of an empty string.
  • Added support for Visual Studio .NET 2003 - Final Beta (also known as Everett).

Version 1.6 (02/03/03)

  • Added simple keyboard binding (ctrl+') to the toolbar button. Note that Visual Studio does not allow the default keyboard scheme to be modified, so a copy must be created manually to enable keyboard binding. After creating a copy of the default keyboard scheme, click "Rebind Keyboard" in the add-in's menu.
  • The toolbar should always be visible after installation now. (This problem was reported by several users.) If the problem persists, run the development environment with the setup command line option (devenv.exe /setup). This will force all the addins to recreate their commands and toolbars.

Version 1.5 (01/07/03)

  • Changed the version numbering to x.x instead of x.x.x.x.
  • Code<Template>'s toolbar has a real bitmap instead of the smiley face.
  • Changes to the template file are now auto-detected. (Thanks to Oz Solomonovich for the suggestion.)
  • SmartFormat isn't applied to the inserted text anymore. (Thanks to Oz Solomonovich for the suggestion.)
  • The parameters dialog now has a template replacement preview. (Thanks to Alex Kucherenko for the suggestion.)
  • Prompt keywords now accept the values and fixedvalues formatters that show up in the parameters dialog as combo boxes instead of a textbox. (Thanks to Alex Kucherenko for the suggestion.)
  • The inserted text can be undone in one step.
  • Changed the way the template text is inserted into the editor. Now the text isn't modified by the editor in any way (for example, when the template starts a line with a single line comment, the "Smart Comment Editing" feature of the editor added more slash characters and messed up the template formatting).
  • The CodeTmpl.txt file is now saved in the user's directory (" C:\Documents and Settings\username\Local Settings\Application Data\Eddie Velasquez\CodeTemplate\codetmpl.txt ") This was changed to avoid loosing your changes when updating or uninstalling future versions of CodeTemplate. Make sure you manually save your modified CodeTmpl.txt before installing this update.

Version 1.0.0.4 (11/15/02)

  • Added the SELECTION keyword, that inserts the currently selected text. (Thanks to Alex Kucherenko for the suggestion.)
  • Occasionally, when the caret was in the last column of a line, an "Invalid parameter" message would pop up. (Thanks to rchecketts for spotting this.)

Version 1.0.0.1 (11/13/02)

  • Fixed installer problem where Visual Studio wasn't creating creating the add-in's commands. (Thanks to Paul Watson for spotting this.)
  • Removed code that tried to add a default key binding. (It always fails and I have no idea why.)

Version 1.0 (11/11/02)

  • Initial release.

To Do

  • Write better documentation.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Eddie Velasquez
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
QuestionSupport for VS 2008 and 2010? Pinmemberjtobler9-Mar-10 10:08 
QuestionVisual Studio 2008 support? Pinmemberrb12619-Mar-08 0:31 
AnswerLooks like my VS 2005 version works OK in VS 2008 as well, with a few minor tweaks Pinmemberrb12619-Mar-08 2:26 
QuestionTo use in Windows Vista? PinmemberbonaS6-Nov-07 8:15 
GeneralVisual Studio 2005 Version PinmemberjohnDoe4421-Oct-07 15:03 
GeneralRe: Visual Studio 2005 Version PinmemberSven Vranckx5-Nov-07 8:32 
GeneralRe: Visual Studio 2005 Version PinmemberSven Vranckx5-Nov-07 8:36 
GeneralRe: Visual Studio 2005 Version PinmemberDoom-Child19-Nov-07 5:13 
GeneralRequest Code Template for VS 2005 PinmemberAliasncnu9-Aug-07 23:48 
GeneralRe: Request Code Template for VS 2005 PinmemberSven Vranckx5-Nov-07 8:33 
GeneralAnybody help me !!!!!!! Pinmemberhienco24-Apr-06 17:03 
GeneralInstalling issues Pinmemberharryteck10-Feb-06 10:16 
GeneralIntellisence (Word completion) and MENU IDs integration Pinmemberahss14-Dec-05 7:40 
GeneralVisual Studio 2005 Support PinmemberSven Vranckx23-Nov-05 22:51 
GeneralRe: Visual Studio 2005 Support Pinmemberrb12617-Jan-06 22:48 
GeneralRe: Visual Studio 2005 Support PinmemberSven Vranckx19-Jan-06 0:33 
GeneralRe: Visual Studio 2005 Support Pinmemberrb12620-Jan-06 3:32 
GeneralCode Template User Input Pinmemberlundtech27-Oct-05 11:35 
GeneralDid I missing something obvious ... PinmemberAndy Bache21-Oct-05 7:16 
GeneralVery Nice PinmemberKevin James18-Oct-05 2:51 
GeneralNice Alternative: CodeWiz PlugIn PinsussMartin Schmidt29-Sep-05 1:09 
GeneralNice Alternative: CodeWiz PlugIn PinsussMartin Schmidt29-Sep-05 1:08 
GeneralPoll: Adding Visual Studio 2005 support PinmemberEddie Velasquez28-May-05 13:53 
GeneralRe: Poll: Adding Visual Studio 2005 support Pinmemberseazi5-Jul-05 20:04 
I vote YES.
 
Keep the wonderful job going, my buddy!
 

GeneralRe: Poll: Adding Visual Studio 2005 support PinmemberNathan Slingerland22-Nov-05 8:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 7 May 2004
Article Copyright 2002 by Eddie Velasquez
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid