下面由sublime教程欄目給大家介紹怎么在Sublime3中設置自己的代碼片段,希望對需要的朋友有所幫助!
在 Sublime Text 3 中設置自己的代碼片段
寫代碼的時候,經(jīng)常會在注釋里寫一下作者,創(chuàng)建時間等等,這樣子也算留下了自己的印記,今天就教大家如何構建自己的注釋代碼塊(Snippets)。
Sublime Snippets(代碼片段)
Sublime text 3 Snippets是你需要反復輸入相同片段的文本、代碼時需要的重要功能。
Snippets可以儲存在任何一個包的文件夾下,但是為了簡單,現(xiàn)在建議先保存在Packages/User目錄下
Snippets的文件格式是.sublime-snippet,通常Snippet的結構如下
<snippet> <content><![CDATA[Type your snippet here]]></content> <!-- Optional: Tab trigger to activate the snippet --> <tabTrigger>xyzzy</tabTrigger> <!-- Optional: Scope the tab trigger will be active in --> <scope>source.python</scope> <!-- Optional: Description to show in the menu --> <description>My Fancy Snippet</description> </snippet>
我們只要把CDATA中的內容替換成自己的,就可以完成一個最簡單的Snippets的編寫。
創(chuàng)建自己的Snippets
接下來我們就以自己的代碼注釋為例,寫一個Snippet。
首先,在sublime菜單欄中選擇Tools | Developer | New Snippets…,然后輸入
<snippet> <content><![CDATA[ /* * @author: ManiaU * @createTime: ${1:time} * @description: ${2:description} */ ]]></content> <!-- Optional: Set a tabTrigger to define how to trigger the snippet --> <tabTrigger>comm</tabTrigger> <!-- Optional: Set a scope to limit where the snippet will trigger --> <scope>source.js</scope> </snippet>
其中content為Snippet的內容,tabTrigger是你輸入什么內容時可以識別為Snippet,scope的表示生效的文件形式,content中 ${}為你輸入完之后,tab鍵可以選中的內容,${1:}為你輸入完之后直接選中,${2:}為按一次tab選中的內容,依此類推。
隨后保存為comment.sublime-snippet,接下來隨便在一個js文件中,輸入comm,按下tab鍵盤,你的Snippet就出現(xiàn)了。
時間輸入插件
Snippet雖然生成了,但是時間還是沒有搞定,接下來就創(chuàng)建自己的插件,在sublime菜單欄中選擇Tools | Developer | New Plugin…,輸入以下內容
import sublime, sublime_plugin from time import localtime, strftime class InsertDatetimeCommand(sublime_plugin.TextCommand): def run(self, edit): sel = self.view.sel(); for s in sel: self.view.replace(edit, s, strftime("%Y-%m-%d, %H:%M:%S GMT%z", localtime()))
保存為insert_datetime.py,然后在Preference | Key Bindings中加上
{ "keys": ["super+ctrl+t"], "command": "insert_datetime" }
這表示你按下?+Control+T,就可以插入時間了,配合上面的Snippet,插入注釋后,加上時間和描述,就可以方便地生成自己的注釋,如下
/* * @author: ManiaU * @createTime: 2017-03-14, 22:33:00 GMT+0800 * @description: This is a test! */
后記
當然,Snippets的用處不僅如此,你可以在你的環(huán)境下配置各種各樣的片段,可以大大提升的工作效率,大家一起去探索吧!