代码片段

参考:Creating your own snippets


定义片段

VSCodeJSON格式进行片段的配置,片段后缀名为.code-snippets

{
    // Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
    // description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
    // is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
    // used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
    // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
    // Placeholders with the same ids are connected.
    // Example:
    // "Print to console": {
    //  "scope": "javascript,typescript",
    //  "prefix": "log",
    //  "body": [
    //      "console.log('$1');",
    //      "$2"
    //  ],
    //  "description": "Log output to console"
    // }
}

仅需几个属性,就能实现代码片段,示例如下:

{
    "c start snippet": {
        "prefix": "cstd",
        "scope": "c",
        "body": [
            "#include <stdio.h>",
            "#include <stdlib.h>",
            "",
            "int main(int argc, char **argv){",
            "   $0",
            "",
            "   return 0;",
            "}"
        ],
        "description": "c start template"
    }
}

"c start snippet"表示片段名

“prefix”表示前缀,它用于智能提示,当前前缀名是"cstd"

“scope”表示适用范围,其值参考Known language identifiers

“body”表示实际生成的代码片段,其中的$0是最终光标位置,还可以添加$1、$2,以及占位符$(1:预设值)

“description”是对该模板的描述

一个代码片段文件可以设置多个模板


设置片段

VSCode提供了两种适用范围,一是当前工作空间;二是全局设置

如果设置在当前工作空间,那么放置在.vscode文件夹内

如果设置在全局,那么放置在$HOME/.config/Code/User/snippets文件夹内

也可以通过UI进行设置

点击菜单栏File->Preferences->User Snippets,或者打开命令窗口(Ctrl+Shift+P),输入Configure User Snippets

选择New Global Snippets file...用于全局片段

选择New Snippets file for 当前空间名...用于本地设置


扩展插件

在扩展库中发现几个定义好的插件,比如C++ Quick Start Snippet for Beginners


片段实例

自己定义了几个片段snippets