locked
How to insert a code snippet into a string in MSVS? RRS feed

  • Question

  • I want to insert a code snippet from a code snippet library in Visual Studio into a string instead of a code editor window using C#. Into a code editor window a snippet is inserted like this:

    IVsTextLines textLines;
    m_vsTextView.GetBuffer(out textLines);
    IVsExpansion bufferExpansion = (IVsExpansion)textLines;
    bufferExpansion.InsertNamedExpansion(...);

    The problem is that I can't find out how to get an IVsExpansion (or IVsTextLines) compatible text buffer from a anything but a text editor window. The code like this:

    string s = "";
    IVsExpansion bufferExpansion = (IVsExpansion)s;

    doesn't work because string is not convertible to IVsExpansion. Can someone advise how to create a text buffer with which the IVsExpansion interface can be connected?

    • Edited by nbdspcl Sunday, March 23, 2014 2:59 PM readability
    Sunday, March 23, 2014 2:58 PM

Answers

  • Hi,

    According to your description, you want to implement code snippet.

    The implementation of code snippet expansion uses legacy Microsoft.VisualStudio.TextManager.Interop interfaces. When you translate from the current editor classes to the legacy code, remember that the legacy interfaces use a combination of line numbers and column numbers to specify locations in a text buffer, but the current classes use one index. Therefore, if a buffer has three lines each of which has ten characters (plus a newline, which counts as 1 character), the fourth character on the third line is at position 27 in the current implementation, but it is at line 2, position 3 in the old implementation.

    Please refer to the code snippet below.

    IVsTextLines textLines;
    m_vsTextView.GetBuffer(out textLines);
    IVsExpansion bufferExpansion = (IVsExpansion)textLines;
    
    if (bufferExpansion != null)
    {
      int hr = bufferExpansion.InsertNamedExpansion(
               title,
               path,
               addSpan,
               this,
               new Guid(SnippetUtilities.LanguageServiceGuidStr),
                    0,
                   out m_exSession);
       if (VSConstants.S_OK == hr)
       {
          return true;
       }
    }
    

    More information, please read http://msdn.microsoft.com/en-us/library/vstudio/ff926100(v=vs.110)

    Best regards,

    Sunny

    • Marked as answer by Anna Cc Wednesday, April 2, 2014 9:25 AM
    Monday, March 24, 2014 9:04 AM