代码片段简介
snippet[ˈsnɪpɪt],或者说「code snippet」,也即代码片,指的是能够帮助输入重复代码模式,比如循环或条件语句,的模板。通过 snippet ,我们仅仅输入一小段字符串,就可以在代码片引擎的帮助下,生成预定义的模板代码,接着我们还可以通过在预定义的光标位置之间跳转,来快速补全模板。
当然,看图更易懂。下图将 aja 补全为 JQuery 的 ajax() 方法,并通过光标的跳转,快速补全了待填键值对:
代码片段配置流程
首先,进入代码片段设置文件有三种方法:
- 通过快捷键「Ctrl + Shift + P」打开命令窗口(All Command Window),输入「snippet」,点选「首选项:配置用户代码片片段」;
- 点击界面最左侧竖栏(也即活动栏)最下方的齿轮按钮,在弹出来的菜单中点选「用户代码片段」;
- 按下「Alt」键切换菜单栏,通过文件 > 首选项 > 用户代码片段;
接着,在设置文件里补全代码片。以 html为例,选中后你将打开一个设置文件,c.json,在文件头部你会看见一个注释,这其实是一个示例和对它的介绍。你可以试着将第 7~14 行反注释掉(选中后 Ctrl + “/”),从而尝试使用它。了解过「json」就不会对此感到奇怪。
{
// Place your WebAPP 工作区 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"
}
}
这个示例中定义了一个描述为「Print to console」的代码片,其功能为:在需要这段代码的地方或需要选中替换的代码输入 log 并选中对应代码片后,即可插入或替换 console.log(’’);。
基本语法说明
-
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 :快捷提示窗对该代码片段对描述
-
参考
https://code.visualstudio.com/docs/editor/userdefinedsnippets
https://blog.csdn.net/maokelong95/article/details/54379046