Share via


How to: Control the Code Editor (Visual Basic)

Visual Studio add-ins are deprecated in Visual Studio 2013. You should upgrade your add-ins to VSPackage extensions. For more information about upgrading, see FAQ: Converting Add-ins to VSPackage Extensions.

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 examples demonstrate how to reference and use the various members of the Editor Automation model. For more information on how to run the sample code, 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 examples on the Automation Samples for Visual Studio (https://msdn2.microsoft.com/vstudio/aa718336.aspx) 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 Customizing Development Settings in Visual Studio.

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

Example for 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.

' Example for TextSelection.ActivePoint.
'
Sub ActivePointExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    Dim objActive As VirtualPoint = objSel.ActivePoint
     ' Collapse the selection to the beginning of the line.
    objSel.StartOfLine()
     ' objActive is "live", tied to the position of the actual 
     ' selection, so it will reflect the new position.
    Dim iCol As Long = objActive.DisplayColumn
     ' Move the selection to the end of the line.
        objSel.EndOfLine()

    MsgBox("The length of the insertion point line is " & _
    (objActive.DisplayColumn - iCol) & " display characters.")
End Sub

Example for 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.

' Example for TextSelection.AnchorPoint.
'
Sub AnchorPointExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    Dim objAnchor As VirtualPoint = objSel.AnchorPoint
    ' objAnchor is "live", tied to the position of the actual 
    ' selection, so it will reflect changes. iCol and iRow are created 
    ' here to save a "snapshot" of the anchor point's position at this 
    ' time.
    Dim iCol As Long = objAnchor.DisplayColumn
    Dim iRow As Long = 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 And iRow = objAnchor.Line) Then
        MsgBox("The anchor point has remained in place at row " & _
        iRow & ", display column " & iCol)
    End If
End Sub

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

' Example for TextSelection.Insert.
'
Sub InsertExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    If objSel.IsEmpty Then
        ' If there is no text selected, swap the words before and after 
        ' the insertion point. We begin by selecting the word before 
        ' the insertion point.
        objSel.WordLeft(True)
        If Not objSel.IsEmpty Then
            ' We can continue only if the selection was not already at 
            ' the beginning of the document.
            Dim strBefore As String = objSel.Text

            ' The text is saved in strBefore; now delete it and move 
            ' past the following word.
            objSel.Delete()
            objSel.WordRight(True)
            If objSel.Text.StartsWith(" ") Or _
            objSel.Text.StartsWith(Microsoft.VisualBasic. _
            ControlChars.Tab) Then
                ' 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)
            End If

            ' Insert the new text at the end of the selection.
            objSel.Insert(strBefore, _
            vsInsertFlags.vsInsertFlagsInsertAtEnd)
        End If
    Else
        ' If some text is selected, replace the following word with the 
        ' selected text.
        Dim strSelected As String = objSel.Text

        objSel.MoveToPoint(objSel.BottomPoint)
        objSel.WordRight(True)
        If objSel.Text.StartsWith(" ") Or _
        objSel.Text.StartsWith(Microsoft.VisualBasic. _
        ControlChars.Tab) Then
            ' 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)
        End If

        ' Insert the text, overwriting the existing text and leaving 
        ' the selection containing the inserted text.
        objSel.Insert(strSelected, _
        vsInsertFlags.vsInsertFlagsContainNewText)
    End If
End Sub

Example for FindPattern. This example also illustrates the use of SelectLine. Before running this example, you need to open a text document or a code file in Visual Studio and add some text to it.

' Example for TextSelection.FindPattern.
'
Sub FindPatternExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection

    ' Advance to the next Visual Basic function beginning or end by 
    ' searching for  "Sub" with white space before and after it.
    If objSel.FindPattern(":WhSub:Wh", _
    vsFindOptions.vsFindOptionsRegularExpression) Then
        ' Select the entire line.
        objSel.SelectLine()
    End If
End Sub

Example for 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.

' Example for TextSelection.OutlineSection.
'
Sub OutlineSectionExample()
    ' Before running this example, open a code document
    ' containing a #if _DEBUG…#endif block.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection

    ' Move to the beginning of the document so we can iterate over the 
    ' whole thing.
    objSel.StartOfDocument()
    While objSel.FindPattern("#if _DEBUG")
        ' If we found the beginning of a debug-only section, save the 
        ' position.
        Dim lStartLine As Long = objSel.TopPoint.Line
        Dim lStartColumn As Long = objSel.TopPoint.LineCharOffset

        ' Look for the end.
        If objSel.FindPattern("#endif") Then
            ' Select the entire section and outline it.
            objSel.SwapAnchor()
            objSel.MoveToLineAndOffset(lStartLine, lStartColumn, True)
            objSel.OutlineSection()
            objSel.LineDown()
        End If
    End While
End Sub

Example opens a text document and generates a list of all available commands into that document.

  ' This generates a text document listing all available command names.
Sub CommandNamesCollapseExample()
  Dim Cmd As Command
  Dim Commands As Commands = DTE.Commands 
  Dim PrjItem As ProjectItem
  Dim Doc As Document
  Dim TxtDoc As TextDocument
  DTE.ItemOperations.NewFile ("General\Text File")
  Set Doc = ActiveDocument
  Set TxtDoc = Doc.Object("TextDocument")
  For Each Cmd In Commands
  If (Cmd.Name <> "") Then
    TxtDoc.Selection.Text = Cmd.Name & vbLF
    TxtDoc.Selection.Collapse
  End If
  Next
End Sub

Example for HTMLWindow object. This example also illustrates the use of ActiveDocument, ActiveWindow, Window, CurrentTab, CurrentTabObject, ActivePane, StartPoint, CreateEditPoint, FindPattern and InsertFromFile. Before running this example, open an HTML document in Visual Studio.

' Example for HTMLWindow object

Sub HTMLWindowExample()
   ' Open an HTML document before running this sample.
   If TypeOf ActiveDocument.ActiveWindow.Object Is HTMLWindow Then
      ' Ask the user for a file to insert into the body of the HTML 
      ' document. This file should be an HTML fragment.
      Dim strFile As String = InputBox("Enter the name of a file to _
      insert at the end of the HTML document:")
      ' Get the HTMLWindow object and determin which tab is currently 
      ' active.
      Dim objHTMLWin As HTMLWindow = ActiveDocument.ActiveWindow.Object
      Dim Tab As vsHTMLTabs = objHTMLWin.CurrentTab

      ' Switch to the "source" tab.
      objHTMLWin.CurrentTab = vsHTMLTabs.vsHTMLTabsSource

      ' Get an EditPoint at the start of the text.
      Dim objTextWin As TextWindow = objHTMLWin.CurrentTabObject
      Dim objEP As EditPoint = _
      objTextWin.ActivePane.StartPoint.CreateEditPoint

      ' Look for the end of the document body.
      If objEP.FindPattern("</body>") Then
         ' Insert the contents of the file.
         objEP.InsertFromFile(strFile)
      End If

      ' Switch back to the original view of the HTML file.
       objHTMLWin.CurrentTab = Tab
   Else
      MsgBox("You must open an HTML document.")
   End If
End Sub

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