Visual studio code VS代码扩展:在工作区中查找并替换字符串

Visual studio code VS代码扩展:在工作区中查找并替换字符串,visual-studio-code,vscode-extensions,Visual Studio Code,Vscode Extensions,我在谷歌上搜索了很多次,没有找到任何有效的方法来搜索vscode.workspace中的特定文件并替换找到的术语 因此,基本上我想在vscode.workspace中搜索名为app.component.ts的文件,并检查该文件是否包含//我的标记。如果是这样,则应使用其他字符串替换此标记。 有人知道这是否可能吗?如果是,怎么做? 这是我的方法: function createAppEnvironment(name: string) { if(name != undefined) {

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

因此,基本上我想在
vscode.workspace
中搜索名为app.component.ts的文件,并检查该文件是否包含//我的标记。如果是这样,则应使用其他字符串替换此标记。

有人知道这是否可能吗?如果是,怎么做? 这是我的方法:

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.");
}

}

我自己还没有做过,所以我在这里做了一些

不打开“查找/替换”:

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

  • 嗨,谢谢你的快速回答!这听起来不错,但如何从工作区中找到正确的文档?(步骤“0”)@jlang Workspace.findFiles()应该按您现有的方式工作(尽管您可能不需要“app/”部分)。@jlang更好的解决方案是使用
    vscode.window.activeTextEditor.document
    获取当前活动的文档。