You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code快捷键:如何判断折叠状态以实现一键切换折叠/展开?

实现VS Code中Ctrl+M切换代码全部折叠/展开

VS Code并未提供全局的isFolded上下文变量,因此无法直接通过修改快捷键的when条件实现折叠/展开的切换。以下是两种可行的实现方案:

方案1:借助Multi-Command扩展(推荐)

这是最快捷的实现方式:

  1. 在VS Code应用内搜索并安装Multi-Command扩展
  2. 打开settings.json,添加自定义复合命令:
"multiCommand.commands": [
  {
    "command": "multiCommand.toggleFoldUnfoldAll",
    "sequence": ["editor.foldAll", "editor.unfoldAll"]
  }
]
  1. 修改keybindings.json,将Ctrl+M绑定到这个自定义命令:
{
  "key": "ctrl+m",
  "command": "multiCommand.toggleFoldUnfoldAll",
  "when": "editorTextFocus && foldingEnabled"
}

每次按下Ctrl+M,会依次触发折叠全部、展开全部的命令,从而实现切换效果。

方案2:自定义本地扩展(无依赖)

如果不想依赖第三方扩展,可以手动创建一个简单的本地扩展:

  1. 在项目的.vscode文件夹下创建toggleFoldAll.js文件,写入代码:
const vscode = require('vscode');

function activate(context) {
  let isFolded = false;
  const toggleCmd = vscode.commands.registerCommand('extension.toggleFoldAll', () => {
    const editor = vscode.window.activeTextEditor;
    if (!editor) return;

    if (isFolded) {
      vscode.commands.executeCommand('editor.unfoldAll');
    } else {
      vscode.commands.executeCommand('editor.foldAll');
    }
    isFolded = !isFolded;
  });
  context.subscriptions.push(toggleCmd);
}

exports.activate = activate;
  1. 在.vscode下创建package.json,注册扩展命令:
{
  "name": "toggle-fold-all",
  "version": "0.0.1",
  "engines": {
    "vscode": "^1.0.0"
  },
  "activationEvents": ["onCommand:extension.toggleFoldAll"],
  "main": "./toggleFoldAll.js",
  "contributes": {
    "commands": [
      {
        "command": "extension.toggleFoldAll",
        "title": "Toggle Fold/Unfold All"
      }
    ]
  }
}
  1. 最后修改keybindings.json绑定快捷键:
{
  "key": "ctrl+m",
  "command": "extension.toggleFoldAll",
  "when": "editorTextFocus && foldingEnabled"
}

重启VS Code后,这个本地扩展会生效,按下Ctrl+M即可切换折叠状态。

内容的提问来源于stack exchange,提问作者jerdub1993

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:55:24