VSCode 如何通过快捷键或鼠标点击在指定文本间切换
方案1:无需编写代码,用现有VSCode插件实现
这是最快落地的方案,只需要安装2个常用插件做简单配置即可:
- 安装依赖插件:
multi-command:用于自定义多步执行的复合命令double-click:用于给双击操作绑定自定义命令
- 配置切换逻辑:
按Ctrl+Shift+P唤起命令面板,输入Preferences: Open Settings (JSON)打开用户配置文件,添加如下配置:"multiCommand.commands": [ { "command": "multiCommand.toggleAbcMno", "sequence": [ { "command": "editor.action.replaceSelection", "args": { "text": "${selectedText == 'ABC' ? 'MNO' : (selectedText == 'MNO' ? 'ABC' : selectedText)}" } }, { "when": "editorTextFocus && !editorHasSelection", "command": "editor.action.replaceAll", "args": { "find": "(ABC|MNO)", "replace": "$1 == 'ABC' ? 'MNO' : 'ABC'", "restrictSearchToLine": true } } ] } ] - 绑定触发方式:
- 键盘快捷键:打开键盘快捷键配置文件(命令面板输入
Preferences: Open Keyboard Shortcuts (JSON)),添加如下配置,可自定义你想要的快捷键:{ "key": "ctrl+shift+q", "command": "multiCommand.toggleAbcMno", "when": "editorTextFocus" } - 双击触发:在用户配置文件中添加如下配置,实现双击选中单词自动切换:
"doubleClick.commands": [ { "when": "editorTextFocus && editorHasSelection && (selectedText == 'ABC' || selectedText == 'MNO')", "command": "multiCommand.toggleAbcMno" } ]
- 键盘快捷键:打开键盘快捷键配置文件(命令面板输入
方案2:自定义VSCode扩展实现(无第三方依赖)
如果不想安装多余插件,可以自己写极简扩展实现,核心逻辑代码不到50行:
- 初始化VSCode扩展项目后,修改
extension.ts核心代码:import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { // 注册切换命令 const toggleCommand = vscode.commands.registerTextEditorCommand('toggle-abc-mno.toggle', (editor) => { const document = editor.document; const selection = editor.selection; // 有选中文本的情况 if (!selection.isEmpty) { const selectedText = document.getText(selection); const replaceText = selectedText === 'ABC' ? 'MNO' : selectedText === 'MNO' ? 'ABC' : selectedText; editor.edit(editBuilder => editBuilder.replace(selection, replaceText)); return; } // 无选中则处理当前行 const currentLine = document.lineAt(selection.active.line); const lineText = currentLine.text; const replacedText = lineText.replace(/ABC|MNO/g, match => match === 'ABC' ? 'MNO' : 'ABC'); editor.edit(editBuilder => editBuilder.replace(currentLine.range, replacedText)); }); // 监听选中事件匹配文本自动触发 vscode.window.onDidChangeTextEditorSelection(e => { const selection = e.selections[0]; if (!selection.isEmpty) { const selectedText = e.textEditor.document.getText(selection); if (selectedText === 'ABC' || selectedText === 'MNO') { vscode.commands.executeCommand('toggle-abc-mno.toggle'); } } }); context.subscriptions.push(toggleCommand); } - 打包扩展后本地安装即可使用,也可以绑定自定义快捷键触发。
内容的提问来源于stack exchange,提问作者anwerj
相关产品推荐
相关产品推荐

