How to: Automate Text Search and Replace

Visual Studio gives you the ability to search and replace text in documents that are open in the integrated development environment (IDE) and contained in files on the system. The primary way to accomplish this is by using the FindReplace and Execute methods of the Find object. The TextSelection and EditPoint objects also offer the FindPattern method. For more information, see the FindPattern method in How to: Control the Code Editor (Visual Basic).

Note

The vsFindOptionsMatchInHiddenText constant value does not apply to the FindPattern method because it searches all text, including hidden text.

The version of Find in the EnvDTE80 namespace is named Find2. It is the same as the Find object, but it offers a new property named WaitForFindToComplete. When this boolean property is set to True, the find operation does not conclude until all selected documents have been searched.

If, for example, you were to search for a word in 100 documents, you might receive incomplete results unless you either used the WaitForFindToComplete property or handled the FindDone event. Both methods work, but setting the WaitForFindToComplete property is a shorter and easier way to ensure that all documents are searched before displaying the search results.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. These procedures were developed with the General Development Settings active. To change your settings, choose Import and ExportSettings on the Tools menu. For more information, see Visual Studio Settings.

Example

The following examples demonstrate how to reference and use the various members of the Find automation model. This example creates a text document with some text, and then searches for and replaces text by using different methods. To run this example, replace the OnConnection method in a simple add-in with the code below. To run different sections of this example, uncomment the appropriate code.

Public Sub OnConnection(ByVal application As Object, ByVal _
connectMode As ext_ConnectMode, ByVal addInInst As Object, _
ByRef custom As Array) Implements IDTExtensibility2.OnConnection
    _applicationObject = CType(application, DTE2)
    _addInInstance = CType(addInInst, AddIn)
    searchReplace(_applicationObject)
End Sub

Public Sub searchReplace(ByVal dte As DTE2)
    Dim findWin As Find2
    Dim doc As Document
    Dim textDoc As TextDocument
    Dim textSel As TextSelection
    Dim iCtr As Integer

    ' Create a new text file.
    dte.ItemOperations.NewFile("General\Text File")

    ' Set up references for the text document, Find object, and
    ' TextSelection object.
    doc = dte.ActiveDocument
    textDoc = CType(doc.Object("TextDocument"), TextDocument)
    textSel = textDoc.Selection
    findWin = CType(dte.Find, Find2)
    ' Make sure all docs are searched before displaying results.
    findWin.WaitForFindToComplete = True

    ' Insert ten lines of text.
    For iCtr = 1 To 10
        textDoc.Selection.Text = "This is a test" & vbCr
    Next iCtr
    textDoc.Selection.Text = "This is a different word"

    ' Uses FindReplace to find all occurrences of the word, test, in 
    ' the document.
    MsgBox("Now changing all occurrences of 'test' to 'replacement'.")
    findWin.FindReplace(vsFindAction.vsFindActionReplaceAll, "test", _
      vsFindOptions.vsFindOptionsMatchCase, "replacement", _
      vsFindTarget.vsFindTargetCurrentDocument, , , _
      vsFindResultsLocation.vsFindResultsNone)

    ' Uses Find2.Execute to find the word, different, in the document.
    ' findWin.FindWhat = "different"
    ' findWin.MatchCase = True
    ' findWin.Execute()

    ' Uses Find2.Execute to replace all occurrences of the word, Test, 
    ' with the word, replacement.
    ' findWin.FindWhat = "test"
    ' findWin.ReplaceWith = "replacement"
    ' findWin.Action = vsFindAction.vsFindActionReplaceAll
    ' findWin.Execute()
End Sub
public void OnConnection(object application, ext_ConnectMode 
  connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    searchReplace(_applicationObject);
}

public void searchReplace(DTE2 dte)
{
    Find2 findWin;
    Document doc;
    TextDocument textDoc;
    TextSelection textSel;
    int iCtr;

    // Create a new text file.
    dte.ItemOperations.NewFile("General\\Text File","New 
      file",Constants.vsViewKindTextView);

    // Set up references for the text document, Find object, and
    // TextSelection object.
    doc = dte.ActiveDocument;
    textDoc = (TextDocument) doc.Object("TextDocument");
    textSel = textDoc.Selection;
    findWin = (Find2) dte.Find;
    // Make sure all docs are searched before displaying results.
    findWin.WaitForFindToComplete = true;

    // Insert ten lines of text.
    for(iCtr=1; iCtr<=10; iCtr+)
    {
        textDoc.Selection.Text = "This is a test"+Environment.NewLine;
    }
    textDoc.Selection.Text = "This is a different word";

    // Uses FindReplace to find all occurrences of the word, test, in 
    // the document.
   System.Windows.Forms.MessageBox.Show("Now changing all occurrences 
     of 'test' to 'replacement'.");
   findWin.FindReplace(vsFindAction.vsFindActionReplaceAll, "test", 
     vsFindOptions.vsFindOptionsFromStart, "replacement", 
     vsFindTarget.vsFindTargetCurrentDocument, "", 
     "",vsFindResultsLocation.vsFindResultsNone);

   // Uses Find2.Execute to find the word, different, in the document.
   // findWin.FindWhat = "different"
   // findWin.MatchCase = True
   // findWin.Execute()

   // Uses Find2.Execute to replace all occurrences of the word, Test, 
   // with the word, replacement.
   // findWin.FindWhat = "test"
   // findWin.ReplaceWith = "replacement"
   // findWin.Action = vsFindAction.vsFindActionReplaceAll
   // findWin.Execute()
}

See Also

Tasks

How to: Compile and Run the Automation Object Model Code Examples

How to: Control the Code Editor (Visual Basic)

How to: Create an Add-In

Walkthrough: Creating a Wizard

Concepts

Automation Object Model Chart

Other Resources

Creating and Controlling Environment Windows

Creating Add-ins and Wizards

Automation and Extensibility Reference