次の方法で共有


方法 : コード エディターを制御する (Visual Basic)

Visual Studio アドインは、Visual Studio 2013 では使用されなくなりました。 アドインを VSPackage 拡張機能にアップグレードしてください。 アップグレードの詳細については、「FAQ: アドインを VSPackage 拡張に変換する」を参照してください。

Visual Studio コード エディターは、Visual Basic、Visual C++、Visual C# などの言語サービスに対応するテキスト エディターです。 テキストは、テキスト ドキュメントに表示されるバッファーに書き込まれます。 Visual Studio Editor オートメーション モデル オブジェクトを使用すると、テキスト バッファーまたはビューでは、テキストを背後で操作できます。

コード エディターのテキストを制御するために使用される主なオブジェクトには、次の 4 つがあります。

オブジェクト名

説明

TextSelection

ビューでテキストを操作します。 TextSelection オブジェクトは、表示しているドキュメント内のカーソル位置 (またはキャレット (^)) あるいは選択したテキストを表します。

TextPoint

テキスト バッファーの固定位置。

EditPoint2

TextPoint オブジェクトに似ていますが、このオブジェクトは移動したり、バッファー内のテキストを変更したりできます。

VirtualPoint

TextPoint オブジェクトに似ていますが、仮想空白におけるテキスト位置を特定するための追加機能がある点で異なります。

コード エディターの操作に使用する 2 つの主なオブジェクトは、TextSelection オブジェクトおよび EditPoint2 オブジェクトです。 TextSelection オブジェクトと EditPoint オブジェクトとの主な相違点は次のとおりです。

  • TextSelection は、表示されているテキスト選択内容を表します。 TextSelection の位置が変更すると、ビュー内の選択内容が変わります。 EditPoint2 はいずれのユーザー インターフェイス (UI: User Interface) コンポーネントにも結び付けられていないため、位置を変更してもビューの内容は変更されません。

  • TextSelection は表示されている選択内容を表すため、TextSelection オブジェクトはドキュメントごとに 1 つしか存在しません。 1 つのドキュメントで複数の TextSelection オブジェクトを保持できますが、すべてのオブジェクトは表示されている同一の選択内容を参照し、同じ位置を保持します。 EditPoint2 オブジェクトは、必要な数だけ保持でき、そのすべてが異なる位置を保持できます。

  • TextSelection オブジェクトのメソッドは、ユーザーによる操作に対して一対一で対応するようにデザインされていますが、EditPoint2 のメソッドはこのようにデザインされていません。 このため、単一の TextSelection メソッドでは実行できない処理を実行する EditPoint2 メソッドもありますが、TextSelection メソッドよりも機能が限定されている EditPoint2 メソッドもあります。 つまり、TextSelection の方が EditPoint2 よりもプロパティおよびメソッドが豊富です。

これらのオブジェクトを使用して、次の操作を行うことができます。

  • バッファーやビューにおいてテキストを選択、追加、削除、および移動します。

  • バッファーやビューでカーソル位置を移動します。

  • バッファーやビューのテキストのインデントを設定します。

  • ブックマークを挿入および削除したり、ブックマークに移動したりします。

  • テキスト (空白を含む) を追加または削除します。

  • 指定したパターンに基づいて、テキストを検索または置換します。

  • コードやテキスト内に、アウトライン セクションを作成します。

  • テキスト位置、ドキュメントの上部や下部、選択したテキストの範囲など、テキストに関する情報を問い合わせます。

次の例では、Editor オートメーション モデルのさまざまなメンバーを参照および使用する方法を示します。 サンプル コードの実行方法の詳細については、「方法 : オートメーション オブジェクト モデルのコード例をコンパイルおよび実行する」を参照してください。

Editor オートメーション モデルの使用方法を説明するその他の例については、Automation Samples for Visual Studio Web サイト (https://msdn2.microsoft.com/vstudio/aa718336.aspx) にある例を参照してください。

注意

実際に画面に表示されるダイアログ ボックスとメニュー コマンドは、アクティブな設定またはエディションによっては、ヘルプの説明と異なる場合があります。ここに記載されている手順は、全般的な開発設定が適用されているものとして記述されています。設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。詳細については、「Visual Studio での開発設定のカスタマイズ」を参照してください。

Visual Studio 2008 HTML エディターに分割ビューが導入されたことに伴い、HTMLWindow3vsHTMLPanes、および vsHTMLViews が追加されました。 分割ビューでは、HTML 編集ウィンドウのタブ要素とビュー要素が分かれています。 デザイン ビューまたはソース ビューへの切り替えは、必ずしもタブの切り替え (デザイン/分割/ソース) を意味するわけではありません。 たとえば、[分割] タブをクリックしたとき、[デザイン] と [ソース] とのビューの切り替えではタブは変更されません。分割ビューの [デザイン] および [ソース] の部分がアクティブになったり非アクティブになったりするだけです。

使用例

ActivePoint の例。 この例では、StartOfLineDisplayColumn、および EndOfLine の各使用法も示しています。 この例を実行する前に、Visual Studio でコード ファイルまたはテキスト ドキュメントを開いて、テキストを追加し、そのテキストの一部を選択します。

' 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

AnchorPoint の例。 この例では、DisplayColumnLineStartOfDocument、および EndOfDocument の各使用法も示しています。 この例を実行する前に、Visual Studio でコード ファイルまたはテキスト ドキュメントを開いて、テキストを追加し、そのテキストの一部を選択します。

' 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

Insert の例。 この例では、IsEmptyWordLeftWordRightTextDelete、および MoveToPoint の各使用法も示しています。 この例を実行する前に、Visual Studio でコード ファイルまたはテキスト ドキュメントを開いて、テキストを追加します。

' 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

FindPattern の例。 この例では、SelectLine の使用法も示しています。 この例を実行する前に、Visual Studio でテキスト ドキュメントまたはコード ファイルを開いて、テキストを追加する必要があります。

' 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

OutlineSection の例。 この例では、StartOfDocumentLineLineCharOffsetFindPatternSwapAnchorMoveToLineAndOffset、および LineDown の各使用法も示しています。 この例を実行する前に、Visual Studio で、#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

例では、テキスト ドキュメントを開き、使用できるすべてのコマンドの一覧をそのドキュメントに生成します。

  ' 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

HTMLWindow オブジェクトの例。 この例では、ActiveDocumentActiveWindowWindowCurrentTabCurrentTabObjectActivePaneStartPointCreateEditPointFindPattern、および InsertFromFile の各使用法も示しています。 この例を実行する前に、Visual Studio で HTML ドキュメントを開きます。

' 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

参照

処理手順

方法 : ウィンドウの特性を変更する

方法 : アドインを作成する

チュートリアル : ウィザードの作成

概念

オートメーション オブジェクト モデルの階層図

その他の技術情報

環境ウィンドウの作成と制御

アドインおよびウィザードの作成

オートメーションと機能拡張のリファレンス