【问题标题】:VSCode programatically search and replace in an extensionVSCode 以编程方式在扩展中搜索和替换
【发布时间】:2020-08-20 13:55:20
【问题描述】:

我想在我的扩展程序中执行一个命令,在工作区的所有文件中搜索某个词(工作区包含超过 15k 个文件),然后用其他词替换该词,但我没有找到任何 VSCode API那种东西。

你们可能知道是否有一些命令吗?

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:

    您可以使用宏来做到这一点。您可以编写代码依次打开每个文件,搜索 + 替换文本,然后保存文件。

    类似 VSCode 宏的东西:

    https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros

    【讨论】:

      【解决方案2】:

      我扩展了我编写的扩展程序,它使用用户定义的搜索和替换命令来满足您的需求。见Find and Transform。它基本上为workbench.action.findInFiles 命令构建参数,如下所示。此处显示的代码太多,但请查看repository,尤其是search.js


      在扩展中,您可以这样做:

      vscode.commands.executeCommand('workbench.action.findInFiles',
        {
          query: "customCommentHowdy",   // arguments to the findInFiles command
          replace: "that's so swell",
          triggerSearch: true,
          preserveCase: true,
          useExcludeSettingsAndIgnoreFiles: true,
          isRegex: false,
          isCaseSensitive: true,
          matchWholeWord: true,
          filesToInclude: "",
          filesToExclude: "./*.css"
        }).then(() => {                      // this command just returns 'undefined'
          setTimeout(() => {
            vscode.commands.executeCommand('search.action.replaceAll');
          }, 1000);
      });
      

      我无法在没有延迟的情况下触发replaceAll - 对于 15k 个文件,您可能需要增加一点。 Async/await 似乎也没有帮助。

      您仍然会收到有关实际执行replace 的确认框,我认为这是无法避免的。

      如果您没有将search.action.replaceAll 命令放在那里,那么用户将不得不自己点击replaceAll 按钮(然后验证是否确实要进行替换)。

      执行此操作时,搜索面板将出现并获得焦点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-19
        • 2014-10-24
        • 2016-08-24
        • 1970-01-01
        • 1970-01-01
        • 2019-11-03
        相关资源
        最近更新 更多