다음을 통해 공유


방법: 코드 편집기 제어(Visual Basic)

Visual Studio 코드 편집기는 Visual Basic, Visual C++ 및 Visual C# 같은 언어 서비스를 수용하는 텍스트 편집기입니다.텍스트 문서에서 표시되는 텍스트는 버퍼에 쓰여집니다.이면에 숨겨진 텍스트 버퍼 또는 뷰의 텍스트를 Visual Studio 편집기 자동화 모델 개체를 통해 조작할 수 있습니다.

코드 편집기에서 텍스트를 제어하는 데 주로 사용되는 네 가지 개체는 다음과 같습니다.

개체 이름

설명

TextSelection

뷰에서 텍스트를 조작하는 데 사용됩니다.TextSelection 개체는 표시된 문서의 삽입 지점(또는 캐럿)이나 선택된 텍스트를 나타냅니다.

TextPoint

텍스트 버퍼에서 고정된 위치를 나타냅니다.

EditPoint2

TextPoint 개체와 유사하지만 이동이 가능하고 버퍼의 텍스트를 수정할 수 있습니다.

VirtualPoint

가상 공간에서 텍스트 위치를 찾을 수 있는 기능을 추가로 제공한다는 점을 제외하고 TextPoint 개체와 유사합니다.

코드 편집기를 조작할 때에는 TextSelectionEditPoint2 개체를 주로 사용합니다.두 개체의 주요한 차이점은 다음과 같습니다.

  • TextSelection은 표시된 텍스트 선택 영역을 나타내며,해당 위치를 변경하면 뷰의 선택 영역이 변경됩니다.EditPoint2는 UI(사용자 인터페이스) 구성 요소와 밀접하게 연관되지 않으므로 위치를 변경해도 뷰는 달라지지 않습니다.

  • TextSelection은 표시된 선택 영역을 나타내므로 문서마다 TextSelection 개체가 하나씩만 있습니다.한 문서에 여러 개의 TextSelection 개체를 가질 수도 있지만, 이 경우 모든 개체는 동일한 표시된 선택 영역을 참조하고 동일한 위치를 가집니다.그러나 EditPoint2 개체는 원하는 수만큼 가질 수 있으며 위치도 모두 다릅니다.

  • TextSelection 개체의 메서드는 사용자의 동작에 일대일로 대응하도록 디자인되었으나 EditPoint2의 메서드는 그렇지 않습니다.따라서 단일 TextSelection 메서드로 수행할 수 없는 작업을 수행하는 EditPoint2 메서드도 있지만, 기능면에서 TextSelection 메서드보다 더 세밀화된 EditPoint2 메서드도 있습니다.TextSelectionEditPoint2보다 더 많은 속성과 메서드를 제공하는 것도 이러한 이유 때문입니다.

이러한 개체를 사용하여 다음 작업을 수행할 수 있습니다.

  • 버퍼나 뷰에서 텍스트를 선택, 추가, 삭제 및 이동

  • 버퍼 또는 뷰 주위에서 삽입 지점 이동

  • 버퍼 또는 뷰에서 텍스트 들여쓰기

  • 책갈피 삽입, 제거 및 탐색

  • 공백을 포함하여 텍스트 추가 또는 제거

  • 특정 패턴에 따라 텍스트를 찾거나 바꾸기

  • 코드와 텍스트로 개요 섹션 만들기

  • 텍스트 위치, 문서의 맨 위 및 맨 아래, 선택한 텍스트 범위 등 텍스트에 대한 정보 쿼리

다음 예제에서는 편집기 자동화 모델의 다양 한 멤버를 참조 하는 방법을 보여 줍니다.샘플 코드를 실행하는 방법에 대한 자세한 내용은 방법: 자동화 개체 모델 코드의 예제 컴파일 및 실행을 참조하십시오.

에 대 한 추가 예제 편집기 자동화 모델의 사용을 보여 주는 표시 예제 자동화 샘플을 Visual Studio 대 한 (https://msdn2.microsoft.com/en-us/vstudio/aa718336.aspx) 웹 사이트입니다.

[!참고]

표시되는 대화 상자와 메뉴 명령은 활성 설정이나 버전에 따라 도움말에서 설명하는 것과 다를 수 있습니다. 이러한 절차는 일반 개발 설정을 사용하여 개발되었습니다.설정을 변경하려면 도구 메뉴에서 설정 가져오기 및 내보내기를 선택합니다.자세한 내용은 Visual Studio 설정을 참조하십시오.

Visual Studio 2008 HTML 편집기에 분할 뷰가 도입되어 HTMLWindow3, vsHTMLPanesvsHTMLViews가 추가되었습니다.분할 뷰는 HTML 편집 창의 탭 및 뷰 요소를 구분합니다.뷰(디자인 또는 소스)를 전환하더라도 탭(디자인/분할/소스)이 반드시 전환되지는 않습니다.예를 들어 분할 탭을 클릭하면 디자인 및 소스 뷰 간에 전환해도 탭이 변경되지 않습니다. 단지 분할 뷰에서 디자인 및 소스 부분이 활성화되거나 비활성화됩니다.

예제

예를 들어 ActivePoint.또한 StartOfLine, DisplayColumnEndOfLine 사용 방법도 보여 줍니다.이 예제를 실행하려면 먼저 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.또한 DisplayColumn, Line, StartOfDocumentEndOfDocument 사용 방법도 보여 줍니다.이 예제를 실행하려면 먼저 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.또한 IsEmpty, WordLeft, WordRight, Text, DeleteMoveToPoint 사용 방법도 보여 줍니다.이 예제를 실행하려면 먼저 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.또한 StartOfDocument, Line, LineCharOffset, FindPattern, SwapAnchor, MoveToLineAndOffsetLineDown 사용 방법도 보여 줍니다.이 예제를 실행하려면 먼저 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 개체입니다.이 예제에서는 ActiveDocument, ActiveWindow, Window, CurrentTab, CurrentTabObject, ActivePane, StartPoint, CreateEditPoint, FindPatternInsertFromFile을 사용하는 방법도 보여 줍니다.이 예제를 실행하려면 먼저 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

참고 항목

작업

방법: 창 특성 변경

방법: 추가 기능 만들기

연습: 마법사 만들기

개념

자동화 개체 모델 차트

기타 리소스

환경 창 만들기 및 제어

추가 기능 및 마법사 만들기

자동화 및 확장성 참조