首页 > 解决方案 > 如何使用脚本折叠 Visual Studio 代码中所有打开的编辑器

问题描述

我希望能够创建/编写一个命令来折叠 Visual Studio 代码中所有打开的编辑器中的所有代码。

我相信我非常接近。

我正在使用Marcel J. Kloubert编写的“脚本命令”扩展

当我在一个组中使用以下脚本和 7 个左右的打开编辑器时。我实现了以下目标:

  1. 打开的编辑器(在执行时)将其代码折叠起来
  2. VSC 将遍历打开的编辑器
  3. 没有其他编辑器的代码被折叠

我正在使用的脚本:

// Fold all code in all open editors.
function execute(args) {

    // Obtain access to vscode
    var vscode = args.require('vscode');

    // Set number of open editors... (future: query vscode for number of open editors)
    var numOpenEditor = 20;


    // Loop for numOpenEditor times
    for (var i = 0; i <= numOpenEditor; i++){

        // Fold the current open editor
        vscode.commands.executeCommand('editor.foldAll');

        // Move to the next editor to the right
        vscode.commands.executeCommand('workbench.action.nextEditor');

        // Loop message
        var statusString = 'Loop ->' + i

        // print message
        vscode.window.showErrorMessage(statusString);
    }

}

// Script Commands must have a public execute() function to work.
exports.execute = execute;

我做了一个有趣的观察,当我使用上面的脚本和 7 个左右的开放编辑器和两个或更多组时。关于切换到新组的某些内容将允许该命令editor.foldAll起作用。请注意,如果一个组有多个编辑器,则折叠其代码的唯一编辑器是该组中打开的编辑器。因此,所有其他编辑器都不会折叠。

我还想也许……脚本需要放慢速度,所以我添加了一个函数来暂停每次迭代。结果也没有用。

任何帮助都会很棒!

标签: visual-studio-code

解决方案


您只需将此函数设为异步并等待 executeCommand 调用完成,然后再继续:

// Fold all code in all open editors.
async function execute(args) {

    // Obtain access to vscode
    var vscode = args.require('vscode');

    // Set number of open editors... (future: query vscode for number of open editors)
    var numOpenEditor = 5;


    // Loop for numOpenEditor times
    for (var i = 0; i <= numOpenEditor; i++) {

        // Fold the current open editor
        await vscode.commands.executeCommand('editor.foldAll');

        // Move to the next editor to the right
        await vscode.commands.executeCommand('workbench.action.nextEditor');

        // Loop message
        var statusString = 'Loop ->' + i

        // print message
        vscode.window.showErrorMessage(statusString);
    }

}

// Script Commands must have a public execute() function to work.
exports.execute = execute;

推荐阅读