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

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 modelo 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 siguientes ejemplos de complementos 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 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 la macro de ortografía y otros ejemplos en Automation Samples for Visual Studio (https://www.microsoft.com/downloads/details.aspx?familyid=3ff9c915-30e5-430e-95b3-621dccd25150&displaylang=en) (en inglés).

[!NOTA]

Los cuadros de diálogo y comandos de menú que se ven pueden diferir de los descritos en la Ayuda, dependiendo de los valores de configuración activos. Estos procedimientos se desarrollaron 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 Valores de configuración de 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

Este ejemplo de complemento muestra cómo utilizar 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.

// 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."); 
}

Este ejemplo de complemento muestra cómo utilizar 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.

// 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); 
        } 
}

Este ejemplo de complemento muestra cómo utilizar 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 agregue texto.

// 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 ) ); 
    }
}

Este ejemplo de complemento muestra cómo utilizar FindPattern.También muestra el uso de SelectLine.Antes de ejecutar este ejemplo, abra un archivo de código o un documento de texto en Visual Studio y agregue la palabra "sub", precedida y seguida de un espacio en blanco.

// 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(); 
    } 
}

Este ejemplo de complemento muestra cómo utilizar 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.

// 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 ); 
        } 
    } 
}

Este ejemplo de complemento abre un documento de texto y genera una lista de todos los comandos disponibles en él.

[!NOTA]

Este complemento muestra todos los comandos del entorno de desarrollo integrado (IDE) de Visual Studio y, dependiendo de la configuración del equipo, podría tardar varios minutos en ejecutarse.

// 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(); 
        } 
    }
}

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