摘要
程序员总是会不断的重复写一些简单的代码片段,为了提高编码效率,我们可以把经常用到的代码保存起来再调用。
平时用sublime安装各种插件,使用Tab键快速补全,也是snippets(可译为代码片段)的一种。
Sublime编辑器还提供了自定义代码片段的功能(当然不止Sublime有此功能),其官方文档中定义如下:
Whether you are coding or writing the next vampire best-seller, you’re likely to need certain short fragments of text again and again. Use snippets to save yourself tedious typing. Snippets are smart templates that will insert text for you and adapt it to their context.
创建snippets
1.新建和保存
-
菜单栏中依次选择Tools | Developer | New Snippet...就会新建一个扩展名为.sublime-snippet
的XML语法的文档,注意后缀是识别snippets的关键。
-
代码片段可以任意存储在packages文件夹下,默认会保存在Packages\User文件夹里,为了方便管理和使用建议再新建个文件夹例如snippets,则路径为Packages\User\snippets。
-
默认结构如下:
<snippet> <content><![CDATA[ Hello, ${1:this} is a ${2:snippet}. ]]></content> <!-- Optional: Set a tabTrigger to define how to trigger the snippet --> <!-- <tabTrigger>hello</tabTrigger> --> <!-- Optional: Set a scope to limit where the snippet will trigger --> <!-- <scope>source.python</scope> --> </snippet>
2.content
3.tabTrigger
- 在
<tabTrigger></tabTrigger>
中设置让Sublime自动补全的触发词(trigger keyword)。
4.scope
5.description
6.设置光标位置Fields
<snippet> <content><![CDATA[ First Name: $1 Second Name: $2 Address: $3 ]]></content>
7.镜像域Mirrored Fields
8.占位符Placeholders
-
{数字编号}
可以得到一个Tab占位符。
-
{1:default}
可以得到一个默认值。
-
按tab键依次循环选中代码片段中的默认值。
如默认的代码片段Hello, ${1:this} is a ${2:snippet}.
会依次循环选中单词this``snippet
。
使用snippets
安装snippets