標籤:style blog http color 使用 io strong 檔案
yasnippet可以把我們常用的程式碼片段或文本儲存起來,到使用的時候只需鍵入幾個字母就會自動帶出。
比如我們在寫python代碼時,常常會在檔案的第一行寫下: #!/usr/bin/env python,經常這麼手工鍵入是不是很沒有效率,用yasnippet來幫你!
方法:
一、建立snippet
使用命令 M-x yas-new-snippet 開啟一個新buffer,或者直接建立一個檔案,輸入內容後儲存到你指定的位置即可。
用M-x yas-new-snippet 開啟的buffer內容預設如下:
# -*- mode: snippet; require-final-newline: nil -*-# name:# key:# binding: direct-keybinding# –
其實只需要以下內容就可以了:
# name: file header# key: fh# binding: direct-keybinding# --#!/usr/bin/env python# coding:utf-8# Filename:`(file-name-nondirectory buffer-file-name)`$0
解釋下
name: file header 這是片段的名稱,叫做 file header,這個 file header會顯示在emacs功能表列的yasnippet裡。
key: fh 這是快速鍵,在檔案裡輸入fh後按tab鍵就會展開這個片段。
從#-- 以下輸入程式碼片段就好了
Filename:`(file-name-nondirectory buffer-file-name)` 這個有意思了,這個是顯示當前buffer的名字的,讓emacs幫你自動寫。
$0 表示片段展開後游標所在的位置
二、儲存
snippet寫好後要儲存到哪裡呢?一般可以儲存到yasnippet的預設安裝位置(.emacs.d/elpa/yasnippet-20140729.1240/snippets),或者是自己定義的位置,比如:~/.emacs.d/custom-snippets。如果儲存到預設位置則不需特別設定即可使用;如果儲存到了自訂的位置,那麼還要在.emacs設定檔裡告訴emacs到哪裡去找這個片段:
;Yasnippet(require ‘yasnippet);設定snippet目錄(setq yas-snippet-dirs ‘("~/.emacs.d/custom-snippets" ;personal snippets"~/.emacs.d/elpa/yasnippet-20140729.1240/snippets" ;default;"~/.emacs.d/elpa/yasnippet-20140720.1534/snippets" ;default))(yas-global-mode 1)
注意yasnippet的目錄名,當你更新後這個目錄名會變的。目前還沒有辦法,只有每次更新後手工去改這個路徑。
最後注意 在自訂的 custom-snippets 目錄中要建一個python-mode目錄!把剛建立的檔案放在裡面。三、使用
建立一個python檔案,在檔案第一行鍵入 fh 然後按 tab 鍵,顯示效果如下:
--End--
附:
#!/usr/bin/env python 叫做 shebang line
http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script
In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two characters in an interpreter directive as the first line of a text file. In a Unix-like operating system, the program loader takes the presence of these two characters as an indication that the file is a script, and tries to execute that script using the interpreter specified by the rest of the first line in the file.