sublime自定义snippet代码片段

相信很多人喜欢sublime编辑工具有两个原因:第一sublime很轻巧方便;第二sublime提供很多自定义拓展功能,包括很简单且和很好用的代码片段功能snippet文件。

    今天,在这里就介绍下sublime如何自定义各种代码片段,先来感受一下效果:

    

    上面看到的是我用sublime初始化一个html文件的操作gif,相信这是很多人在新项目必经的步骤。而我里面不同的时,不需要任何复制,只需几秒钟就完成整个初始化的工作,这就是sublime的魅力之一:代码片段snippet

    下面我就拿上面的动画里面用到的两个初始化:html初始化和css reset初始化来介绍,如何建立自己的代码片段。

    第一:html初始化代码片段:

    首先打开sublime,在顶部工具条,找到preferences > browser packages 浏览程序包,找到Packages\User文件夹,我们一般自定义的东西都放在user这个文件夹,方便以后直接拷贝这个文件夹,可以到新的安装环境直接使用,不需要重新配置。

    然后在这个user下面建立snippet文件,最好能够分类,建立对应的文件夹。比如html的代码片段新建一个html文件夹,css也如此类推。

    需要用到snippet语言很简单,主要有4个参数,content、tabTrigger、description、scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<snippet>
    <content><![CDATA[
     
// 缩写展开后的代码
 
]]></content>  
 
    <tabTrigger>xxxxxx</tabTrigger>  // 快捷输入的缩写
     
    <description>xxxxxxx</description>  // 片段的描述
     
    <scope>xxxxxxx</scope>  // 仅对 html 文件有效
     
</snippet>

    比如,需要新建一个html5格式的初始化html代码片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<snippet>
<content><![CDATA[
 
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>标题</title>
<meta name="keywords" content="标题" />
<meta name="description" content="标题" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
</head>
<body>
 
</body>
</html>
 
]]></content>
<tabTrigger>html5</tabTrigger>
<description>html5文件</description>  // 片段的描述
<scope>text.html</scope>
</snippet>

    content里面填你需要自动生成的代码,tabTrigger是代表这段代码并经过简化后的缩写名称,输入者个缩写,再按tab键就可以提示生成这段代码。description是紧跟在缩写名后面的提示,告诉你这段代码是代码什么,可以不要。scope是代表这个自动代码片段需要在什么文件类型下生效。细心的童鞋应该看到我上面的gif,第一步是调出控制面板,把新建文件设为html格式,否则上面的html5代码片段是无法生成的,因为它是被定义在text.html格式下生效。而css测试source.css。

    第二:css初始化代码片段

    操作流程和html是一样的,新建snippet文件,填上对应的代码就行了,然后scope要写成source.css才行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<snippet>
<content><![CDATA[
html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;}
ul,li,div,p,body{margin:0;padding:0;text-align:left;}
input{-webkit-appearance:button;}
li{list-style:none;}
a{text-decoration:none;}
img{vertical-align:top;}
i,em{font-style:normal;}
.hide{display:none;}
body, html {background:#fcf8ed;text-align: left;height: 100%;width: 100%;font-family: "Microsoft YaHei","Helvetica Neue",Arial, HelveticaNeue, "Helvetica-Neue", Helvetica, "BBAlpha Sans", sans-serif;font-size:62.5%;font-weight: normal;}
*{-webkit-tap-highlight-color:rgba(14,159,111,0.5);-webkit-touch-callout:none;}
#main{margin:0 auto;overflow:hidden;}
@media only screen and (min-width:1025px){
#main{max-width:320px}
}
]]></content>
<tabTrigger>re</tabTrigger>
<scope>source.css</scope>
</snippet>

 

    看完上面,基本都学会自己自定义代码片段了,但是可能大家还有个疑问,那个score参数又时候是test,有些又是source,我们怎么知道到底是什么。这个我们在需要自定义代码片段时,打开Packages文件,下面可以看到各种类型格式的文件:HTML/CSS/PHP....,找到你想定义的格式,在里面找找是否有snippet文件,一般都会有的,你打开snippet文件看看给出的例子就知道score参数怎么写了。

    比如php的,score是source.php。

posted @ 2014-10-02 18:44  w3cmark  阅读(1151)  评论(0编辑  收藏  举报