Emacs org-mode 预设模板与使用

时间:2022-05-24 00:50:05

1 整合到org-structure-template-alist

Org mode定义了一种键盘快捷模式,通过输入“<字母”然后按TAB键补全,可以得到预定义的代码块模板。它的定义是在org.el中设置的:

(defcustom org-structure-template-alist
'(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
"<literal style=\"latex\">\n?\n</literal>")
("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
("h" "#+BEGIN_HTML\n?\n#+END_HTML"
"<literal style=\"html\">\n?\n</literal>")
("H" "#+HTML: " "<literal style=\"html\">?</literal>")
("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
("A" "#+ASCII: " "")
("i" "#+INDEX: ?" "#+INDEX: ?")
("I" "#+INCLUDE: %file ?"
"<include file=%file markup=\"?\">"))
"Structure completion elements.
This is a list of abbreviation keys and values. The value gets inserted
if you type `<' followed by the key and then press the completion key,
usually `M-TAB'. %file will be replaced by a file name after prompting
for the file using completion. The cursor will be placed at the position
of the `?` in the template.
There are two templates for each key, the first uses the original Org syntax,
the second uses Emacs Muse-like syntax tags. These Muse-like tags become
the default when the /org-mtags.el/ module has been loaded. See also the
variable `org-mtags-prefer-muse-templates'."
:group 'org-completion
:type '(repeat
(list
(string :tag "Key")
(string :tag "Template")
(string :tag "Muse Template"))))


我们可以利用 org-structure-template-alist 列表定义一些常用的快捷键。比如,要插入可执行R语言代码块可以这样:

(add-to-list 'org-structure-template-alist
'("srx" "#+BEGIN_SRC R :eval no-export :ravel\n?\n#+END_SRC" "<src lang=\"R\">\n?\n</src>"))


而插入不可执行的代码块也类似:

(add-to-list 'org-structure-template-alist
'("sre" "#+BEGIN_SRC R :eval never :ravel eval=FALSE\n?\n#+END_SRC" "<src lang=\"R\">\n?\n</src>"))


把代码加入到emacs配置文件中,放到org-mode加载代码后面。在org-moe模式下输入“<srx”补全后可获得可执行R语言代码块插入模板。


2 使用 org-mode-abbrev-table

这种方法是输入缩写代码后按空格键即补全可获得模板。定义方法如下:

(define-skeleton ibrx
"R语言代码块:可导出,可提取,导出时不执行"
""
"#+BEGIN_SRC R :exports code :tangle yes :eval no-export :ravel \n"
_ "\n"
"#+END_SRC")
(define-abbrev org-mode-abbrev-table "ibrx" "" 'ibrx)


同样是把代码加入到emacs配置文件中,放到org-mode加载代码后面。输入ibrx(前面不能有其他非空白字符)和空格键即可。

用这种方法的缺点是要特别小心避免常用英文单词,自己定义的代码还要牢记,避免重复。



作者: ZGUANG@LZU

Created: 2016-04-09 六 09:03

Emacs 24.4.1 (Org mode 8.2.10)