Cómo: Controlar el Editor de código (Visual Basic)

Los complementos de Visual Studio están desusados en Visual Studio 2013. Debe actualizar los complementos a las extensiones de VSPackage. Para obtener más información sobre la actualización, vea Preguntas más frecuentes: Convertir complementos en extensiones de VSPackage.

El editor de código de Visual Studio es un editor de texto que incluye servicios de lenguaje como Visual Basic, Visual C++ y Visual C#. El texto se escribe en un búfer que se muestra en un documento de texto. Mediante los objetos del modelo de automatización del editor de Visual Studio, se puede manipular el texto en segundo plano, ya sea en el búfer de texto o en la vista.

Los cuatro objetos principales utilizados para el control de texto en el editor de código son:

Nombre de objeto

Descripción

TextSelection

Se utiliza para manipular texto en la vista. El objeto TextSelection representa el punto de inserción (o símbolo de intercalación) o el texto seleccionado en el documento visible.

TextPoint

Una posición fija en el búfer de texto.

EditPoint2

Similar al objeto TextPoint, pero se puede mover y modificar texto en el búfer.

VirtualPoint

Similar al objeto TextPoint, pero contiene funciones adicionales para buscar posiciones de texto en el espacio virtual.

Los dos objetos más utilizados para manipular el editor de código son TextSelection y EditPoint2. Las principales diferencias entre ambos son:

  • TextSelection representa la selección de texto visible. Cambiar su posición cambia también la selección en la vista. Un objeto EditPoint2 no está asociado a ningún componente de la interfaz de usuario, por lo que no cambia la vista al cambiar su posición.

  • Puesto que TextSelection representa la selección visible, sólo hay un objeto TextSelection por documento. Aunque es posible tener varios objetos TextSelection en un documento, todos ellos hacen referencia a la misma selección visible y todos tienen la misma posición. Se pueden tener tantos objetos EditPoint2 como se desee y todos pueden tener posiciones distintas.

  • Los métodos del objeto TextSelection están diseñados para tener una correspondencia uno-a-uno con las acciones del usuario, pero no ocurre lo mismo con los métodos de EditPoint2. La consecuencia es que algunos métodos de EditPoint2 pueden efectuar operaciones que no puede efectuar ninguno de los métodos de TextSelection, mientras que otros métodos de EditPoint2 tienen una función más detallada que los métodos de TextSelection. Por esta misma razón, TextSelection incorpora más propiedades y métodos que EditPoint2.

Mediante estos objetos se puede:

  • Seleccionar, agregar, eliminar y mover texto en el búfer o en la vista.

  • Mover el punto de inserción en el búfer o en la vista.

  • Aplicar sangría a texto en el búfer o en la vista.

  • Insertar y quitar favoritos, y navegar por la lista de favoritos.

  • Agregar o quitar texto, incluidos espacios en blanco.

  • Buscar o reemplazar texto según un patrón determinado.

  • Crear una sección de esquematización en código y en texto.

  • Consultar información acerca del texto, como por ejemplo la posición en el texto, los extremos superior e inferior del documento, los rangos de texto seleccionados, etc.

Los ejemplos siguientes muestran cómo hacer referencia y utilizar los diversos miembros del modelo de automatización del editor. Para obtener más información sobre cómo ejecutar el código de ejemplo, vea Cómo: Compilar y ejecutar los ejemplos de código del modelo de objetos de automatización.

Para obtener ejemplos adicionales que muestren el uso del modelo de automatización del editor, vea los ejemplos del sitio web de ejemplos de automatización para Visual Studio (https://msdn2.microsoft.com/vstudio/aa718336.aspx).

Nota

Los cuadros de diálogo y comandos de menú que se ven pueden diferir de los descritos en la Ayuda, en función de los valores de configuración o de edición activos.Estos procedimientos se han desarrollado con la Configuración de desarrollo general activa.Para cambiar la configuración, elija la opción Importar y exportarconfiguraciones del menú Herramientas.Para obtener más información, vea Personalizar la configuración de desarrollo en Visual Studio.

HTMLWindow3, vsHTMLPanes y vsHTMLViews se agregaron con la introducción de la Vista dividida del editor HTML de Visual Studio 2008. La Vista dividida separa la ficha y los elementos de vista de la ventana de edición HTML. Cambiar de vista (Diseño o Código fuente) no implica necesariamente cambiar de ficha (Diseño, Dividir o Código fuente). Por ejemplo, al hacer clic en la ficha Dividir, cuando se alterna entre las vistas Diseño y Código fuente, la ficha no cambia, sino que simplemente se activan o desactivan las partes Diseño y Código fuente de la Vista dividida.

Ejemplo

Ejemplo para ActivePoint. También muestra el uso de StartOfLine, DisplayColumn y EndOfLine. Antes de ejecutar este ejemplo, abra un archivo de código o un documento de texto en Visual Studio, agregue texto y seleccione parte del mismo.

' 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

Ejemplo para AnchorPoint. También muestra el uso de DisplayColumn, Line, StartOfDocument y EndOfDocument. Antes de ejecutar este ejemplo, abra un archivo de código o un documento de texto en Visual Studio, agregue texto y seleccione parte del mismo.

' 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

Ejemplo para Insert. También muestra el uso de IsEmpty, WordLeft, WordRight, Text, Delete y MoveToPoint. Antes de ejecutar este ejemplo, abra un archivo de código o un documento de texto en Visual Studio y agréguele texto.

' 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

Ejemplo para FindPattern. Este ejemplo también muestra el uso de SelectLine. Antes de ejecutar este ejemplo, es necesario abrir un documento de texto o un archivo de código en Visual Studio y agregarle texto.

' 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

Ejemplo para OutlineSection. También muestra el uso de StartOfDocument, Line, LineCharOffset, FindPattern, SwapAnchor, MoveToLineAndOffset y LineDown. Antes de ejecutar este ejemplo, abra un documento de código en Visual Studio que contenga un bloque #if _DEBUG…#endif.

' 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

El ejemplo abre un documento de texto y genera una lista de todos los comandos disponibles en ese documento.

  ' 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

Ejemplo para el objeto HTMLWindow. Este ejemplo también muestra el uso de ActiveDocument, ActiveWindow, Window, CurrentTab, CurrentTabObject, ActivePane, StartPoint, CreateEditPoint, FindPattern e InsertFromFile. Antes de ejecutar este ejemplo, abra un documento HTML en 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

Vea también

Tareas

Cómo: Cambiar las características de las ventanas

Cómo: Crear un complemento

Tutorial: Crear un asistente

Conceptos

Gráfico del modelo de objetos de automatización

Otros recursos

Crear y controlar las ventanas del entorno

Crear complementos y asistentes

Referencia de automatización y extensibilidad