本章总览
src/keybindings/ 是 Claude Code 的「可配置键盘绑定引擎」:15 文件、约 3191 行,负责默认 chord 表、用户 keybindings.json 热加载、Ink 事件解析、context 优先级与 useKeybinding Hook。与 hooks/useGlobalKeybindings、hooks/useCommandKeybindings 配合:前者注册 app:* / transcript:* 动作,后者扫描 command:* 动态映射斜杠命令。Vim 编辑语义留在 hooks/useVimInput + vim/,故意不全部迁入 keybindings。
学完本章你应该能
- 理解 KeybindingProvider + ChordInterceptor 架构
- 知道 DEFAULT_BINDINGS 按 context 分块
- 理解 command:* 与 slash 命令的桥接
- 区分声明式 useKeybinding 与 vim 内联 handleVimInput
- 能找到 ~/.claude/keybindings.json 加载与校验路径
- 理解 Windows VT 模式对 shift+tab 的影响
建议学习步骤
- 浏览子章节导航表
- 点击 SourceTree module=keybindings
- 建议顺序:keybinding-registry → default-bindings → command-bindings → vim-bindings
模块在架构中的位置
keybindings 是 src/ 下的一级目录,共 15 个文件、3,191 行。建议结合「系统架构」章节理解它与其他层的调用关系。
概览
| 指标 | 数值 |
|---|---|
| 行数 | 3,191 |
| 文件 | 15 |
子章节导航
| 子章节 | 主题 | 核心路径 |
|---|---|---|
| keybinding-registry | 注册、useKeybinding | KeybindingContext.tsx, useKeybinding.ts, resolver.ts |
| default-bindings | 默认键位表 | defaultBindings.ts, reservedShortcuts.ts |
| command-bindings | command:* 动态绑定 | hooks/useCommandKeybindings.tsx |
| vim-bindings | Vim 与 keybindings 边界 | hooks/useVimInput.ts, types/textInputTypes.ts |
数据流概览
defaultBindings + user keybindings.json
→ parseBindings → ParsedBinding[]
→ KeybindingProvider(bindings)
→ useKeybinding(action, handler) 注册 handler
→ Ink useInput → resolveKeyWithChordState
→ match | chord_started | unbound | none
→ stopImmediatePropagation 吞事件
KeybindingSetup(KeybindingProviderSetup.tsx)在 REPL 根包裹,内含 ChordInterceptor 与热加载 watcher。
Context 优先级
KeybindingContextName 是 string,常用值:Global、Chat、Autocomplete、Settings、Confirmation、Transcript 等。
useKeybinding 检查顺序:activeContexts(组件 registerActiveContext)→ 声明 context → Global。同一 keystroke 多 binding 时 后者覆盖前者(用户 JSON 在默认表之后 parse)。
Modal overlay 或 local JSX 命令激活时,Global/Command handlers 的 isActive 为 false。
15 文件涵盖 parser、match、validate、schema、template、shortcutFormat、useShortcutDisplay 等。子章节按主题聚合,完整树见 SourceTree。
与 hooks/ 的分工
| 层 | 位置 | 职责 |
|---|---|---|
| 引擎 | keybindings/ | 解析、chord、配置、display text |
| 注册 | hooks/useGlobalKeybindings | app:toggleTodos 等 |
| 命令 | hooks/useCommandKeybindings | command:commit → /commit |
| 搜索 | hooks/useSearchInput | transcript / 搜索,内联键位 |
| Vim | hooks/useVimInput | NORMAL/INSERT,不配置 Esc |
改默认快捷键编辑 defaultBindings.ts;改用户可配项编辑 schema + validate + loadUserBindings。
本章小结与延伸
keybindings = keystroke → action 解析层。先读 registry(Provider、resolver、useKeybinding),再读默认表与 command:*,最后读 vim 边界。 继续学习: