Visual Studio Code片段作为键盘快捷键

yod*_*alr 14 visual-studio-code

我知道如何修改和创建代码片段,我知道如何修改快捷键,但是如何将这两者组合在一起呢?

Ste*_*bos 19

请注意,下面的行将打开为您当前使用的语言定义的代码段列表

"args": { "snippet": "'$TM_SELECTED_TEXT'" }
Run Code Online (Sandbox Code Playgroud)

然而,使用下面的行,作为参数给出的片段将立即执行

"args": { "name": "your_snippets_name" }
Run Code Online (Sandbox Code Playgroud)

以下是我为HTML定义一个代码段的方法,我想要选择一个文本,并在按下CTRL-B文本时将其包含在<strong></strong>标记中:

"make_strong": {
    "prefix": "strong",
    "body": [
        "<strong>$TM_SELECTED_TEXT${1:}</strong>"
    ],
    "description": "Encloses selected text in <strong></strong> tags"
}
Run Code Online (Sandbox Code Playgroud)

注意${1:}上面 - 它的作用是将光标放在那里.这使您可以按CTRL-B光标,然后将光标放在<strong></strong>标签内.选择字符串并按下时CTRL-B,字符串将放在<strong>选项卡之间,光标将放在结束<strong>标记之前.按TAB此时,将光标放在结束<strong>标记之后.

并在我keybindings.json的以下内容中添加:

{
    "key": "ctrl+b",
    "command": "editor.action.insertSnippet",
    "args": { "name": "make_strong" }
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 10

从版本1.9开始,Visual Studio Code似乎可以满足您的需求,无需其他扩展.

来自https://code.visualstudio.com/updates/v1_9#_insert-snippets

"现在,您可以将自己喜欢的代码段绑定到键绑定.用单引号括起选区的示例如下所示:"

添加下面的代码段keybindings.json(打开键盘快捷键编辑器,然后单击For advanced customizations open and edit keybindings.json链接)

{
    "key": "cmd+k",
    "command": "editor.action.insertSnippet",
    "args": { "snippet": "'$TM_SELECTED_TEXT'" }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

以下是创建代码片段和快捷方式的 3 个步骤。

\n
\n

1 . 代码->首选项->键盘快捷键

\n
\n

在此输入图像描述

\n
\n

2 . 单击keybindings.json文件的图标

\n
\n

在此输入图像描述

\n
\n

3 . 为代码片段/快捷方式添加 JavaScript 对象

\n
\n

在此输入图像描述

\n

例如,我创建了用于记录目的的片段,因为我主要使用 JavaScript 框架。

\n

1.console.log(\'\')使用快捷键Control(或 Ctrl)\xe2\x8c\x83 + l

\n

2.console.warn(\'\')使用 Control(或 Ctrl)\xe2\x8c\x83 + w

\n

3.console.error(\'\')使用Control(或 Ctrl)\xe2\x8c\x83 + e

\n

代码:

\n
{\n    "key": "ctrl+l",\n    "command": "editor.action.insertSnippet",\n    "when": "editorTextFocus",\n    "args": {\n        "snippet": "console.log(\'${TM_SELECTED_TEXT}$1\')$2"\n    }\n},\n{\n    "key": "ctrl+w",\n    "command": "editor.action.insertSnippet",\n    "when": "editorTextFocus",\n    "args": {\n        "snippet": "console.warn(\'${TM_SELECTED_TEXT}$1\')$2"\n    }\n},\n{\n    "key": "ctrl+e",\n    "command": "editor.action.insertSnippet",\n    "when": "editorTextFocus",\n    "args": {\n        "snippet": "console.error(\'${TM_SELECTED_TEXT}$1\')$2"\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n