Partager via


Comment : contrôler l'éditeur de code (Visual Basic)

Mise à jour : novembre 2007

L'éditeur de code Visual Studio est un éditeur de texte qui inclut des services de langage tels que Visual Basic, Visual C++ et Visual C#. Le texte est écrit dans une mémoire tampon qui s'affiche dans un document texte. À l'aide des objets du modèle Automation Editor de Visual Studio, vous pouvez manipuler le texte en arrière-plan dans la mémoire tampon du texte ou dans la vue.

Les quatre principaux objets utilisés pour contrôler du texte dans l'éditeur de code sont les suivants :

Nom de l'objet

Description

TextSelection

Utilisé pour manipuler du texte dans une vue. L'objet TextSelection représente le point d'insertion (ou signe insertion) ou le texte sélectionné dans le document visible.

TextPoint

Position fixe dans la mémoire tampon du texte.

EditPoint2

Semblable à l'objet TextPoint, mais peut être déplacé et peut modifier du texte dans la mémoire tampon.

VirtualPoint

Semblable à l'objet TextPoint, si ce n'est qu'il contient une fonctionnalité supplémentaire permettant de localiser des positions de texte dans l'espace virtuel.

Les deux principaux objets que vous utilisez pour manipuler l'éditeur de code sont les objets TextSelection et EditPoint2. Les principales différences qui existent entre eux sont les suivantes :

  • TextSelection représente la sélection de texte visible. Lorsque sa position change, la sélection dans la vue change également. Un objet EditPoint2 n'est lié à aucun composant de l'interface utilisateur. Par conséquent, la modification de sa position n'a aucun effet dans la vue.

  • Étant donné que l'objet TextSelection représente la sélection visible, il n'existe qu'un seul objet TextSelection par document. S'il est tout à fait possible d'avoir plusieurs objets TextSelection dans un document, ils font tous référence à la même sélection visible et ont tous la même position. Vous pouvez avoir autant d'objets EditPoint2 que vous le souhaitez, et ils peuvent tous avoir des positions différentes.

  • Les méthodes de l'objet TextSelection sont conçues pour avoir une correspondance un à un avec les actions de l'utilisateur, contrairement aux méthodes de EditPoint2. Par conséquent, certaines méthodes de l'objet EditPoint2 effectuent des opérations qu'aucune méthode TextSelection ne peut effectuer seule, tandis que d'autres méthodes EditPoint2 ont un rôle plus complet que les méthodes de l'objet TextSelection. C'est également pourquoi l'objet TextSelection est plus riche en propriétés et méthodes que l'objet EditPoint2.

À l'aide de ces objets, vous pouvez :

  • sélectionner, ajouter, supprimer et déplacer du texte dans la mémoire tampon ou dans la vue ;

  • déplacer le point d'insertion dans la mémoire tampon ou dans la vue ;

  • mettre du texte en retrait dans la mémoire tampon ou dans la vue ;

  • insérer, supprimer et atteindre des signets ;

  • ajouter ou supprimer du texte, y compris un espace blanc ;

  • rechercher ou remplacer du texte correspondant à un modèle spécifié ;

  • créer une section en mode Plan dans le code et le texte ;

  • demander des informations sur le texte, telles que la position du texte, le début et la fin du document, les plages de texte sélectionnées, etc.

Les exemples de macros suivants illustrent la façon de référencer les différents membres du modèle Automation Editor et de les utiliser. Pour plus d'informations sur l'exécution de l'exemple de code, consultez Comment : compiler et exécuter les exemples de code du modèle objet Automation.

Pour obtenir d'autres exemples qui illustrent l'utilisation du modèle Automation Editor, consultez la macro du correcteur orthographique ainsi que d'autres exemples disponibles sur le site Web des exemples Automation de Visual Studio (https://msdn2.microsoft.com/en-us/vstudio/aa718336.aspx).

Remarque :

Les boîtes de dialogue et les commandes de menu qui s'affichent peuvent être différentes de celles qui sont décrites dans l'aide, en fonction de vos paramètres actifs ou de l'édition utilisée. Ces procédures ont été développées avec les paramètres de développement généraux actifs. Pour modifier vos paramètres, choisissez Importation et exportation deparamètres dans le menu Outils. Pour plus d'informations, consultez Paramètres Visual Studio.

HTMLWindow3, vsHTMLPanes et vsHTMLViews ont été ajoutés avec l'introduction du mode Fractionné dans l'éditeur HTML de Visual Studio 2008. Le mode Fractionné sépare les onglets des éléments d'affichage de la fenêtre d'édition HTML. Le changement de mode (Design ou Source) n'implique pas nécessairement un changement d'onglet (Design/Fractionné/Source). Par exemple, lorsque vous cliquez sur l'onglet Fractionné, le basculement entre les modes Design et Source n'entraîne pas de changement d'onglet mais active ou désactive simplement les volets Design et Source en mode Fractionné.

Exemple

Exemple de macro pour ActivePoint. Cet exemple illustre également l'utilisation de StartOfLine, DisplayColumn et EndOfLine. Avant d'exécuter cet exemple, ouvrez un fichier de code ou un document texte dans Visual Studio, ajoutez-y du texte, puis sélectionnez-en une partie.

' Macro 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

Exemple de macro pour AnchorPoint. Cet exemple illustre également l'utilisation de DisplayColumn, Line, StartOfDocument et EndOfDocument. Avant d'exécuter cet exemple, ouvrez un fichier de code ou un document texte dans Visual Studio, ajoutez-y du texte, puis sélectionnez-en une partie.

' Macro 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

Exemple de macro pour Insert. Cet exemple illustre également l'utilisation de IsEmpty, WordLeft, WordRight, Text, Delete et MoveToPoint. Avant d'exécuter cet exemple, ouvrez un fichier de code ou un document texte dans Visual Studio et ajoutez-y du texte.

' Macro 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

Exemple de macro pour FindPattern. Cet exemple illustre également l'utilisation de SelectLine. Avant d'exécuter cet exemple, ouvrez un document texte ou un fichier de code dans Visual Studio et ajoutez-y du texte.

' Macro 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

Exemple de macro pour OutlineSection. Cet exemple illustre également l'utilisation de StartOfDocument, Line, LineCharOffset, FindPattern, SwapAnchor, MoveToLineAndOffset et LineDown. Avant d'exécuter cet exemple, dans Visual Studio, ouvrez un document de code contenant un bloc #if _DEBUG…#endif.

' Macro 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

L'exemple de macro ouvre un document texte et génère une liste de toutes les commandes disponibles dans ce document.

' Macro example
  ' 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

Exemple de macro pour l'objet HTMLWindow. Cet exemple illustre également l'utilisation de ActiveDocument, ActiveWindow, Window, CurrentTab, CurrentTabObject, ActivePane, StartPoint, CreateEditPoint, FindPattern et InsertFromFile. Avant d'exécuter cet exemple, ouvrez un document HTML dans Visual Studio.

' Macro 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

Voir aussi

Tâches

Comment : modifier les caractéristiques d'une fenêtre

Comment : créer un complément

Procédure pas à pas : création d'un Assistant

Concepts

Graphique Modèle d'objet Automation

Autres ressources

Création et contrôle de fenêtres d'environnement

Création de compléments et d'Assistants

Guide de référence de l'extensibilité et de l'automation