Share via


Controlling the Code Editor

The Visual Studio .NET Code Editor is a text editor that accommodates language services such as Visual Basic .NET, Visual C++ .NET, and Visual C# .NET. Text is written to a buffer that displays in a text document. Using the Visual Studio .NET 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 Object Used to manipulate text in the view. The TextSelection object represents the insertion point (or caret) or selected text in the visible document.
TextPoint Object A fixed position in the text buffer.
EditPoint Object Similar to the TextPoint object, but can be moved around and can modify text in the buffer.
VirtualPoint Object 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 EditPoint objects. The main differences between them are:

  • TextSelection represents the visible text selection. Changing its position changes the selection in the view. An EditPoint is not tied to any 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 EditPoint objects as you want, and they can all have different positions.
  • TextSelection's methods are designed to have a one-to-one correspondence to user actions while EditPoint's are not. As a result, some EditPoint methods do things that no single TextSelection method can do, while other EditPoint methods are more granular in function than TextSelection methods. This is also the reason that TextSelection is richer in properties and methods than EditPoint.

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 any 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.

Code Editor Examples

The following VSMacro examples demonstrate how to reference and use the various members of the Editor automation model. For additional code demonstrating use of the Editor automation model, see the VSSpellCheck macro in the .../Automation/Samples directory on the Visual Studio .NET CDs or DVD.

' Example for TextSelection.ActivePoint
'
' Also shows usage of these methods and properties:
'   TextSelection.StartOfLine
'   VirtualPoint.DisplayColumn
'   TextSelection.EndOfLine
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 TextSelection.AnchorPoint
'
' Also shows usage of these methods and properties:
'   VirtualPoint.DisplayColumn
'   VirtualPoint.Line
'   TextSelection.StartOfDocument
'   TextSelection.EndOfDocument
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 any 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 TextSelection.Insert
'
' Also shows usage of these methods and properties:
'   TextSelection.IsEmpty
'   TextSelection.WordLeft
'   TextSelection.WordRight
'   TextSelection.Text
'   TextSelection.Delete
'   TextSelection.MoveToPoint
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 TextSelection.FindPattern
'
' Also shows usage of these methods and properties:
'   TextSelection.SelectLine
Sub FindPatternExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection

    ' Advance to the next Visual Basic .NET 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 TextSelection.OutlineSection
'
' Also shows usage of these methods and properties:
'   TextSelection.StartOfDocument
'   VirtualPoint.Line
'   VirtualPoint.LineCharOffset
'   TextSelection.FindPattern
'   TextSelection.SwapAnchor
'   TextSelection.MoveToLineAndOffset
'   TextSelection.LineDown
Sub OutlineSectionExample()
    ' Before running this example, open a text document.
    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

Sub CommandNamesCollapseExample()
  ' This generates a text document listing all available command names.
  Dim Cmd As Command
  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.  Demonstrates the following methods and 
' properties:
'   DTE.ActiveDocument, Document.ActiveWindow, Window.Object, 
'   HTMLWindow.CurrentTab, HTMLWindow.CurrentTabObject
'   TextWindow.ActivePane, TextPane.StartPoint, 
'   TextPoint.CreateEditPoint, EditPoint.FindPattern and
'   EditPoint.InsertFromFile
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 find out 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

Changing Window Characteristics | Creating and Controlling Environment Windows | Creating Add-Ins and Wizards | Creating an Add-In | Creating a Wizard | Automation and Extensibility Reference | Automation Object Model Chart