自定义 Yasnippet 模板

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的目录名,当你更新后这个目录名会变的。目前还没有办法,只有每次更新后手工去改这个路径。

2014.09.04更新:

新版的yasnippet已经有了改进,

yas-snippet-dirs 的默认值现在是这样:
("~/.emacs.d/snippets" yas-installed-snippets-dir)

yas-installed-snippets-dir 会自动找到下载的新版本号,比如:/.emacs.d/elpa/yasnippet-20140821.38/snippets,以后不必操心版本号了。

所以现在.emacs文件里就很简单了:

;;yasnippet
(require 'yasnippet)
(yas-global-mode 1)

是的,这样就可以了,记得把自定义的snippet文件夹custom-snippets改成snippets,这样在配置文件里也不用特别说明了,因为默认的路径里已经预设了这个。

 

最后注意 在自定义的 custom-snippets 目录中要建一个python-mode目录!把刚创建的文件放在里面。

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.

posted @ 2014-08-08 23:25  ibg  阅读(2149)  评论(0编辑  收藏  举报