前言
代码片段,指的是能够帮助输入重复代码模式,比如初始页面的模板。通过 snippet ,我们仅仅输入一小段字符串,就可以在代码片引擎的帮助下,生成预定义的模板代码,接着我们还可以通过在预定义的光标位置之间跳转,来快速补全模板。
流程
首先,进入代码片段设置文件
有三种方法:
-
通过快捷键「Ctrl + Shift + P」打开命令窗口(All Command Window),输入「snippet」,点选「首选项:配置用户代码片片段」
-
点击界面最左侧竖栏(也即活动栏)最下方的齿轮按钮,在弹出来的菜单中点选「用户代码片段」
-
通过文件 > 首选项 > 用户代码片段
配置json文件
{
// Place your 全局 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"
// }
}
基本语法说明
- scope:域。代码片适用的「语言」(可选),
为空意为适用所有语言
- prefix :触发快捷提示的字符串前缀
- body :代码片段主体
\$num
是每次按 tab 键光标移动对位置,\$0
表示光标最后停留位置,不设置 $0,这光标最终位置在文件末尾;\${2:默认文本}
跳转到指定位置到同时选中默认文本,方便修改;- $CURRENT_YEAR是引用的 snippets 内置变量,其它还有:
- TM_FILENAME 当前文件名
- TM_FILENAME_BASE 当前文件名,不带扩展名
- TM_DIRECTORY 当前文件所属目录的绝对路径
- TM_FILEPATH 当前文件的绝对路径
- CURRENT_YEAR 当前年份
- CURRENT_YEAR_SHORT 当前年份,最后两位数字
- CURRENT_MONTH 当前月份数字形式,两位表示
- CURRENT_MONTH_NAME 当前月份英文形式,如 July
- CURRENT_MONTH_NAME_SHORT 当前月份英文缩写形式,如 Jul
- CURRENT_DATE 当前日
- CURRENT_DAY_NAME 当前星期,如 Monday
- CURRENT_DAY_NAME_SHORT 当前星期缩写形式,如 Mon
- CURRENT_HOUR 当前小时,24小时格式,两位表示
- CURRENT_MINUTE 当前分钟,两位表示
- CURRENT_SECOND 当前秒,两位表示
\n
换行\t
制表符
- description :快捷提示窗对该代码片段对描述
举例
这里以前言中的 “qbr” 举例
{
// Place your 全局 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:
"create react component": {
// "scope": "javascript,typescript",
"prefix": "qbr",
"body": [
"import { useState } from \"react\"",
"",
"const ${1:Demo} = () => {",
"\treturn <div>$2</div>",
"}",
"export default ${1:Demo}"
],
"description": "Log output to console"
}
}
效果
输入快捷键qbr,回车后生成代码片段如下
由于${1:Demo}
包裹了两处,默认会同时选中,便于修改
修改完毕后按下Tab键,由于$2
,光标移入到第4行的div标签中