VS Code 扩展:在工作区中查找和替换字符串

jla*_*ang 3 visual-studio-code vscode-extensions

我用谷歌搜索了很多,并没有找到任何有效的方法来搜索内部特定文件vscode.workspace并替换找到的术语。

所以基本上我想搜索vscode.workspace一个名为 app.component.ts 的文件,并检查该文件是否包含 // my-marker。如果是这样,这个标记应该被其他一些字符串替换。

有谁知道这是否可能?如果是这样,如何?这是我的方法:

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.");
}
Run Code Online (Sandbox Code Playgroud)

}

sea*_*rth 6

我自己没有这样做过,所以我在这里有点摇摆不定......

而不是打开查找/替换:

  1. 使用 TextDocument.getText() 获取文本。
  2. 使用正则表达式来查找您的标记。
  3. 使用 TextDocument.positionAt() 获取一个位置,用于在您需要编辑的文档中构建范围。
  4. 创建一个代表您的更改的 WorkspaceEdit 对象,使用 WorkspaceEdit.replace() 指示实际编辑。
  5. 使用 Workspace.applyEdit() 应用编辑。