Compartilhar via


ExpansionProvider Class

Definition

Important

This API is not CLS-compliant.

Provides support for inserting code snippets into source code.

public ref class ExpansionProvider : IDisposable, Microsoft::VisualStudio::TextManager::Interop::IVsExpansionClient
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public class ExpansionProvider : IDisposable, Microsoft.VisualStudio.TextManager.Interop.IVsExpansionClient
[System.Runtime.InteropServices.ComVisible(true)]
public class ExpansionProvider : IDisposable, Microsoft.VisualStudio.TextManager.Interop.IVsExpansionClient
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ExpansionProvider = class
    interface IDisposable
    interface IVsExpansionClient
[<System.Runtime.InteropServices.ComVisible(true)>]
type ExpansionProvider = class
    interface IDisposable
    interface IVsExpansionClient
Public Class ExpansionProvider
Implements IDisposable, IVsExpansionClient
Inheritance
ExpansionProvider
Attributes
Implements

Examples

Expansions are inserted in three ways:

  1. The code snippet browser,

  2. Selecting a snippet shortcut name from a completion list, or

  3. By typing a shortcut and entering a completion character such as a tab or space.

The following example shows one way to handle auto-expansion that is triggered by typing an expansion shortcut followed by the tab key. This method is called every time a tab key is typed.

using Microsoft.VisualStudio.Package;  
using Microsoft.VisualStudio;  

namespace MyLanguagePackage  
{  
    class MyViewFilter : ViewFilter  
    {  
        // This is called from our HandlePreExec when a tab key is pressed  
        bool HandleTabKey()  
        {  
            ExpansionProvider ep = GetExpansionProvider();  
            if (ep == null || ep.InTemplateEditingMode)  
            {  
                // No expansion provider or already editing a template,  
                // so nothing to do.  
                return false;  
            }  

            TokenInfo tokenInfo = Source.GetTokenInfo(TextView);  
            if (tokenInfo.StartLine != tokenInfo.EndLine ||  
                tokenInfo.StartIndex == tokenInfo.EndIndex)  
            {  
                // No shortcut found before caret, so nothing to do.  
                // Note that the above test does not allow for single  
                // character tokens to be shortcut names.  
                return false;  
            }  

            int line;  
            int col;  
            int hr;  
            hr = TextView.GetCaretPos(out line,out col);  
            if (hr != VsConstants.S_OK)  
            {  
                // Could not get current position, so nothing to do.  
                // GetCaretPos is used in Source.GetTokenInfo so if  
                // GetCaretPos fails, GetTokenInfo fails. However,  
                // better to be thorough and test again here.  
                return false;  
            }  

            // Get shortcut text that was just typed.  
            string shortcut = Source.GetText(line,  
                                             tokenInfo.StartIndex,  
                                             line,  
                                             tokenInfo.EndIndex);  
            if (shortcut == null || shortcut == "")  
            {  
                // No text was found at the position. This failure is  
                // is not likely if GetTokenInfo returned a valid token  
                // but better to be thorough.  
                return false;  
            }  

            string snippetTitle;  
            string snippetPath;  
            TextSpan pos = new TextSpan();  
            pos.iStartLine = line;  
            pos.iStartIndex = tokenInfo.StartIndex;  
            pos.iEndLine = line;  
            pos.iEndIndex = tokenInfo.EndIndex;  
            if (ep.FindExpansionByShortcut(TextView,  
                                            shortcut,  
                                            pos,  
                                            true,  
                                            out title,  
                                            out path) != VSConstants.S_OK)  
            {  
                // No snippet matched the shortcut, so nothing to do.  
                return false;  
            }  

            // If InsertNamedExpansion returns true, snippet was  
            // inserted and therefore the Tab key was handled.  
            // Otherwise, false is returned and the Tab key will be  
            // passed on to someone else.  
            return ep.InsertNamedExpansion(TextView,  
                                           title,  
                                           path,  
                                           pos,  
                                           false);  
        }  
    }  
}  

Remarks

A code snippet is a template that is expanded into full code when the user inserts the snippet. When the snippet is first expanded, the Visual Studio core editor enters a special template editing mode where the snippet can be modified in place. That is, certain parts of the snippet are designated as fields, and these fields can easily be changed by the user before the snippet is committed to the editor's buffer. The fields are highlighted and can feature drop-down boxes offering choices to the user.

A snippet has a name to identify it and a template file containing the snippet itself. The template file contains XML tags indicating specific elements of the template, from the code to substitution fields to functions (known as expansion functions). See Code Snippets for more details on code snippets.

Notes to Inheritors

The ExpansionProvider class provides all the support for selecting and inserting a code snippet into a source file. The base class provides all the basic functionality; however, if you want to support context-sensitive snippet insertion (that is, a snippet with the same name might behave differently depending on the context into which it is inserted), then you must derive a class from the ExpansionProvider class and override the IsValidType(IVsTextLines, TextSpan[], String[], Int32, Int32) and IsValidKind(IVsTextLines, TextSpan[], String, Int32) methods to report the appropriate snippet type and kind that are allowed in a particular context. Be sure to override the CreateExpansionProvider(Source) method in your version of the LanguageService class to return your version of the ExpansionProvider class.

Notes to Callers

An instance of the ExpansionProvider class is returned from the CreateExpansionProvider(Source) method in the LanguageService class that is called from the GetExpansionProvider() method in the Source class. The ViewFilter class calls its own GetExpansionProvider() that in turn forwards the call to the GetExpansionProvider() method in the Source class. The ViewFilter class calls the GetExpansionProvider() method any time a command is executed to allow the ExpansionProvider class a chance to act.

Constructors

ExpansionProvider(Source)

Initializes a new instance of the ExpansionProvider class.

Properties

Expansion

Returns the IVsExpansion object used for inserting snippets into a buffer.

ExpansionSession

Returns the expansion session created to manage editing the code snippet.

InTemplateEditingMode

Indicates whether the code snippet is currently being edited.

Source

Returns the Source object associated with this expansion provider.

TextView

Returns the text view containing the source file being manipulated by the expansion provider.

Methods

BeginTemplateEditing(Int32, Int32)

Inserts the previously prepared code snippet and starts the snippet editing mode.

DisplayExpansionBrowser(IVsTextView, String, String[], Boolean, String[], Boolean)

Displays a list of expansion templates of the specified type and kind.

Dispose()

Cleans up allocated resource just before the ExpansionProvider object is destroyed.

EndExpansion()

Called when an expansion session has ended.

EndTemplateEditing(Boolean)

Ends the current snippet editing mode.

Finalize()

Cleans up all resources just before the ExpansionProvider object is destroyed.

FindExpansionByShortcut(IVsTextView, String, TextSpan, Boolean, String, String)

Returns S_OK if match found, S_FALSE if expansion UI is shown, and error otherwise

FormatSpan(IVsTextLines, TextSpan[])

Formats the specified text span.

GetExpansionFunction(IXMLDOMNode, String, IVsExpansionFunction)

Returns a IVsExpansionFunction object representing the expansion function described in the given XML template node (COM implementation).

GetExpansionFunction(XmlElement, String)

Returns an IVsExpansionFunction object representing the expansion function described in the given XML template node.

GetExpansionSpan()

Returns the span occupied by the snippet currently being edited.

GetFieldSpan(String, TextSpan)

Gets the field span of the specified field

GetFieldValue(String, String)

Returns the value of the specified field.

HandlePostExec(Guid, UInt32, UInt32, Boolean, IntPtr, IntPtr)

Called after a command has been executed.

HandlePreExec(Guid, UInt32, UInt32, IntPtr, IntPtr)

Called before a command is executed.

HandleQueryStatus(Guid, UInt32, Int32)

Determines if the specified command is handled by the ExpansionProvider class.

InsertNamedExpansion(IVsTextView, String, String, TextSpan, Boolean)

Inserts the specified snippet into the source at the given position.

InsertSpecificExpansion(IVsTextView, XmlElement, TextSpan, String)

Inserts the specific snippet into the source at the specified position.

IsValidKind(IVsTextLines, TextSpan[], String, Int32)

Determines whether this is valid text for expansion. This method should be overridden if you want to specify where in the source document the expansion can take place.

IsValidType(IVsTextLines, TextSpan[], String[], Int32, Int32)

Determines whether or not a given type is valid for expansion purposes. This method should be overridden if you want to specify where in the source document the expansion can take place.

OnAfterInsertion(IVsExpansionSession)

Called after a snippet has been inserted into the source.

OnBeforeInsertion(IVsExpansionSession)

Called just before the snippet has been inserted into the source.

OnItemChosen(String, String)

Called when an item is chosen in a snippet browser.

PositionCaretForEditing(IVsTextLines, TextSpan[])

Puts the caret in a position suitable for editing.

PrepareTemplate(String, String)

Prepares for insertion of the specified snippet.

Applies to