Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code Extensions: Find and replace a string in workspace

I googled a lot and did not find any working way to search inside a specific file inside the vscode.workspace and replace the found terms.

So basicly I want to search the vscode.workspace for a file named app.component.ts, and check if the file contains a // my-marker. If so this marker should be replaced by some other string.

Does anybody know if this is possible? And if so, how? This is my approach:

function createAppEnvironment(name: string)
{
  if(name != undefined)
  {
    // replace all blanks ' ' with dashes '-'
    name = name.replace(/\w/g, '-');

    vscode.workspace.findFiles('app/app.component.ts', '', 1).then(
        // all good
        (result: vscode.Uri[]) => {
            vscode.workspace.openTextDocument(result[0]);
            vscode.commands.executeCommand('edit.findAndReplace');
        },
        // rejected
        (reason: any) => {
            // output error
            vscode.window.showErrorMessage(reason);
        });

    // Display a message box to the user
    // vscode.window.showInformationMessage('Successfully created a new App!');
}
else
{
    vscode.window.showWarningMessage("Nothing was created, due to the fact that you haven't entered a name.");
}

}

like image 704
jlang Avatar asked Jun 04 '26 07:06

jlang


1 Answers

I haven't done this myself, so I'm kinda winging it here...

Instead of opening find/replace:

  1. Use TextDocument.getText() to get the text.
  2. Use a regular expression to find your marker.
  3. Use TextDocument.positionAt() to get a Position for building a Range in the document that you need to edit.
  4. Create a WorkspaceEdit object that represents your change, using WorkspaceEdit.replace() to indicate the actual edit.
  5. Use Workspace.applyEdit() to apply the edit.
like image 86
seairth Avatar answered Jun 07 '26 12:06

seairth