How to: Control the Code Editor (Visual C#)

The Visual Studio Code editor is a text editor that accommodates language services such as Visual Basic, Visual C++, and Visual C#. Text is written to a buffer that displays in a text document. By using the Visual Studio Editor Automation model objects, you can manipulate text behind the scenes either in the text buffer or in the view.

The four major objects used to control text in the Code editor are:

Object Name

Description

TextSelection

Used to manipulate text in the view. The TextSelection object represents the insertion point (or caret) or selected text in the visible document.

TextPoint

A fixed position in the text buffer.

EditPoint2

Similar to the TextPoint object, but it can be moved and can modify text in the buffer.

VirtualPoint

Similar to the TextPoint object, except that it contains additional functionality to locate text positions in virtual space.

The two major objects you use to manipulate the Code editor are the TextSelection and EditPoint2 objects. The main differences between them are:

  • TextSelection represents the visible text selection. Changing its position changes the selection in the view. An EditPoint2 is not tied to any user interface (UI) component, so changing its position changes nothing in the view.

  • Because TextSelection represents the visible selection, there is only one TextSelection object per document. While you can have multiple TextSelection objects in a document, they all refer to the same visible selection and they all have the same position. You can have as many EditPoint2 objects as you want, and they can all have different positions.

  • The methods of the TextSelection object are designed to have a one-to-one correspondence to user actions while the methods of EditPoint2 are not. As a result, some EditPoint2 methods do things that no single TextSelection method can do, while other EditPoint2 methods are more granular in function than TextSelection methods. This is also the reason that TextSelection is richer in properties and methods than EditPoint2.

Using these objects, you can:

  • Select, add, delete, and move text in the buffer or in the view.

  • Move the insertion point around the buffer or view.

  • Indent text in the buffer or the view.

  • Insert, remove, and navigate to bookmarks.

  • Add or remove text, including white space.

  • Find or replace text based on a specified pattern.

  • Create an outlining section in code and text.

  • Query information about the text, such as text position, top and bottom of document, selected text ranges, and so forth.

The following Add-in examples demonstrate how to reference and use the various members of the Editor Automation model. For more information about how to run the example, see How to: Compile and Run the Automation Object Model Code Examples.

For additional examples demonstrating the use of the Editor automation model, see the Spell Check macro and other examples on the Automation Samples for Visual Studio (https://www.microsoft.com/downloads/details.aspx?familyid=3ff9c915-30e5-430e-95b3-621dccd25150&displaylang=en) Web site.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. These procedures were developed with the General Development Settings active. To change your settings, choose Import and ExportSettings on the Tools menu. For more information, see Visual Studio Settings.

HTMLWindow3, vsHTMLPanes and vsHTMLViews were added with the introduction of Split view in the Visual Studio 2008 HTML editor. Split view separates the tab and view elements of the HTML edit window. Switching the view (to either Design or Source) does not necessarily mean switching the tab (Design/Split/Source). For example, when you click the Split tab, switching views between Design and Source does not change the tab, it only activates or deactivates the Design and Source parts in the Split view.

Example

This Add-in example demonstrates how to use ActivePoint. This example also illustrates the usage of StartOfLine, DisplayColumn, and EndOfLine. Before running this example open a code file or a text document in Visual Studio, add some text to it, and select some of the text.

// Add-in example.
using System.Windows.Forms;
public void OnConnection(object application, ext_ConnectMode
 connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;

// Pass the applicationObject member variable to the code example.
    ActivePointExample(_applicationObject); 
}

public void ActivePointExample( DTE2 dte ) 
{ 
    // Before running this example, open a text document.
    TextSelection objSel = (TextSelection )
(dte.ActiveDocument.Selection ); 
    VirtualPoint objActive = objSel.ActivePoint; 
    // Collapse the selection to the beginning of the line.
    objSel.StartOfLine( (EnvDTE.vsStartOfLineOptions)(0), false ); 
    // objActive is "live", tied to the position of the actual 
    // selection, so it reflects the new position.
    long iCol = objActive.DisplayColumn; 
    // Move the selection to the end of the line.
    objSel.EndOfLine( false );
            
    MessageBox.Show( "The length of the insertion point line is " + 
( objActive.DisplayColumn - iCol ) + " display characters."); 
}

This Add-in example demonstrates how to use AnchorPoint. This example also illustrates the use of DisplayColumn, Line, StartOfDocument and EndOfDocument. Before running this example, open a code file or a text document in Visual Studio, add some text to it, and select some of the text.

// Add-in example.
Using System.Windows.Formms;
public void OnConnection(object application, ext_ConnectMode
 connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;

// Pass the applicationObject member variable to the code example.
    AnchorPointExample(_applicationObject); 
}

public void AnchorPointExample( DTE2 dte ) 
{ 
// Before running this example, open a text document.
    TextSelection objSel = ( EnvDTE.TextSelection )(
 dte.ActiveDocument.Selection ); 
    VirtualPoint objAnchor = objSel.AnchorPoint; 
    // objAnchor is "live", tied to the position of the actual 
    // selection, so it reflects changes. iCol and iRow are 
    // created here to save a "snapshot" of the anchor point's 
    // position at this time.
    long iCol = objAnchor.DisplayColumn; 
    long iRow = objAnchor.Line; 
    // As the selection is extended, the active point moves but the 
    // anchor point remains in place.
    objSel.StartOfDocument( true ); 
    objSel.EndOfDocument( true ); 

    if ( ( iCol == objAnchor.DisplayColumn & iRow == objAnchor.Line ) ) 
        { 
           MessageBox.Show
( "The anchor point has remained in place at row "
 + iRow + ", display column " + iCol); 
        } 
}

This Add-in example that demonstrates how to use Insert. This example also illustrates the use of IsEmpty, WordLeft, WordRight, Text, Delete, and MoveToPoint. Before running this example, open a code file or a text document in Visual Studio and add some text to it.

// Add-in example.
using System.Windows.Forms;
public void OnConnection(object application, ext_ConnectMode
 connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;

// Pass the applicationObject member variable to the code example.
    InsertExample (_applicationObject); 
}
public void InsertExample( DTE2 dte ) 
{ 
// Before running this example, open a code file.
    TextSelection objSel = ( EnvDTE.TextSelection )(
 dte.ActiveDocument.Selection ); 
    if ( objSel.IsEmpty ) 
    { 
    // If there is no text selected, swap the words before and after 
    // the insertion point. Begin by selecting the word before 
    // the insertion point.
        objSel.WordLeft( true, 1 ); 
        if ( !( objSel.IsEmpty ) ) 
        { 
        // The example can continue only if the selection was not 
        // already at the beginning of the document.
            string strBefore = objSel.Text; 
                    
            // The text is saved in strBefore; now delete it and move 
            // past the following word.
            objSel.Delete( 1 ); 
            objSel.WordRight( true, 1 ); 
            if ( objSel.Text.StartsWith( " " )) 
                { 
                // The previous call to WordRight may have skipped 
                // some white space instead of an actual word. In that 
                // case, we should call it again.
                objSel.WordRight( true, 1 ); 
            } 

        // Insert the new text at the end of the selection.
        objSel.Insert( strBefore, System.Convert.ToInt32(
 vsInsertFlags.vsInsertFlagsInsertAtEnd ) ); 
        } 
    } 
    else 
    { 
    // If some text is selected, replace the following word with the 
    // selected text.
    string strSelected = objSel.Text; 

        objSel.MoveToPoint( objSel.BottomPoint, false ); 
        objSel.WordRight( true, 1 ); 
        if ( objSel.Text.StartsWith( " " )) 
        { 
             // The previous call to WordRight may have skipped some 
             // white space instead of an actual word. In that case, 
            // we should call it again.
            objSel.WordRight( true, 1 ); 
        } 

        // Insert the text, overwriting the existing text and leaving 
        // the selection containing the inserted text.
    objSel.Insert( strSelected, System.Convert.ToInt32( vsInsertFlags.vsInsertFlagsContainNewText ) ); 
    }
}

This Add-in example demonstrates how to use FindPattern. This example also illustrates the use of SelectLine. Before running this example, open a code file or a text document in Visual Studio and add the word "sub" into it, preceded and followed by white space.

// Add-in example.
using System.Windows.Forms;
public void OnConnection(object application, ext_ConnectMode
 connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;

// Pass the applicationObject member variable to the code example.
    FindPatternExample (_applicationObject); 
}

public void FindPatternExample( DTE2 dte ) 
{ 
// Before running this example, open a text document
// with the text " Sub ".
    TextSelection objSel = (EnvDTE.TextSelection)(dte.ActiveDocument.Selection ); 

    string srchPattern1 = " Sub ";
    EnvDTE.TextRanges textRanges = null;

    // Advance to the next Visual Basic function beginning or end by 
    // searching for  "Sub" with white space before and after it.
    objSel.FindPattern( srchPattern1, 0, ref textRanges );
    { 
        //  Select the entire line.
        objSel.SelectLine(); 
    } 
}

This Add-in example demonstrates how to use OutlineSection. This example also illustrates the use of StartOfDocument, Line, LineCharOffset, FindPattern, SwapAnchor, MoveToLineAndOffset and LineDown. Before running this example, open a code document in Visual Studio containing a #if _DEBUG…#endif block.

// Add-in example for.
public void OnConnection(object application,
 Extensibility.ext_ConnectMode connectMode, object addInInst,
 ref System.Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    //  Pass the applicationObject member variable to the code example.
    OutlineSectionExample(_applicationObject ); 
}

public void OutlineSectionExample( DTE2 dte ) 
{ 
    // Before running this example, open a code document
    // containing a #if _DEBUG…#endif block.
    TextSelection objSel = ( EnvDTE.TextSelection )(
 dte.ActiveDocument.Selection ); 
    string srchPattern1 = "#if _DEBUG";
    string srchPattern2 = "#endif";
    EnvDTE.TextRanges textRanges = null;

    //Move to the beginning of the document so we can iterate 
    // over the whole thing.
    objSel.StartOfDocument( false ); 
 
    while ( objSel.FindPattern( srchPattern1, 0, ref textRanges) ) 
    { 
        //  If it's the beginning of a debug-only section, 
        // save the position.
        long lStartLine = objSel.TopPoint.Line; 
        long lStartColumn = objSel.TopPoint.LineCharOffset; 

        //  Look for the end.
        if ( objSel.FindPattern(srchPattern2 , 0,ref textRanges) ) 
        { 
            //  Select the entire section and outline it.
            objSel.SwapAnchor(); 
            objSel.MoveToLineAndOffset( System.Convert.ToInt32
( lStartLine ), System.Convert.ToInt32( lStartColumn ), true ); 
            objSel.OutlineSection(); 
            objSel.LineDown( false, 1 ); 
        } 
    } 
}

This Add-in example opens a text document and generates a list of all available commands in that document.

Note

This add-in lists all the commands in the Visual Studio IDE, and depending on your machine configurations, might take several minutes to run.

// Add-in example.
// This generates a text document listing all available command names.

public void OnConnection(object application,
 Extensibility.ext_ConnectMode connectMode, object addInInst,
 ref System.Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
//  Pass the applicationObject member variable to the code example.
CommandNamesCollapseExample(_applicationObject ); 
}
public void CommandNamesCollapseExample( DTE2 dte ) 
{ 
    Command Cmd = null; 
    Commands Commands = dte.Commands; 
    ProjectItem PrjItem = null; 
    Document Doc = null; 
    TextDocument TxtDoc = null; 
    dte.ItemOperations.NewFile( @"General\Text File", "", 
"{00000000-0000-0000-0000-000000000000}" ); 
    Doc = dte.ActiveDocument; 
    TxtDoc = (EnvDTE.TextDocument )(Doc.Object( "TextDocument" )); 
    foreach ( EnvDTE.Command tempCmd in Commands ) 
    { 
        Cmd = tempCmd; 
        if ( ( Cmd.Name != "" ) ) 
        { 
            TxtDoc.Selection.Text = Cmd.Name +"\n"; 
            TxtDoc.Selection.Collapse(); 
        } 
    }
}

See Also

Tasks

How to: Change Window Characteristics

How to: Create an Add-In

Walkthrough: Creating a Wizard

Concepts

Automation Object Model Chart

Other Resources

Creating and Controlling Environment Windows

Creating Add-ins and Wizards

Automation and Extensibility Reference