一、需求
一个代码片段管理工具所需要的基本功能大概包括:
-
支持多语言的高亮
-
能够保存对代码的说明
-
支持TAG标签
-
有方便的查询功能
而Emacs的Org-mode恰好能够完美的支持上面这些需求.
二、实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
(defvar mode-file-map '((c++-mode .
"cpp.org"
)
(emacs-lisp-mode .
"elisp.org"
)
(python-mode .
"python.org"
)
(perl-mode .
"perl.org"
)
(dos-mode .
"bat.org"
)
(sh-mode .
"bash.org"
))
"映射major-mode与保存代码片段文件的对应关系"
)
(defvar code-library-path
"d:/CodeLibrary/"
"代码库文件存储的目录"
)
(defun save-code-to-library()
(interactive)
(
let
(
(code (get-region-
or
-thing 'defun))
(library-file (concat code-library-path (cdr (assoc major-mode mode-file-map))))
(head (read-string
"请输入这段代码的说明"
))
(code-major-mode (replace-regexp-in-string
"-mode$"
""
(format
"%s"
major-mode))))
(
when
(string= library-file code-library-path)
(setq library-file (concat code-library-path
"temp.org"
)))
(find-file library-file)
(
end
-
of
-buffer)
(newline)
(insert (concat
"* "
head))
(newline-
and
-indent)
(insert (concat
"#+BEGIN_SRC "
code-major-mode))
(newline-
and
-indent)
(newline-
and
-indent)
(insert
"#+END_SRC"
)
(forward-line -1) ;上一行
(org-edit-src-code)
(insert code)
(org-edit-src-exit)
(org-set-tags-command) ;设置代码tags
(save-buffer)
;; (kill-buffer)
))
|
三、使用
在Emacs中看到中意的代码要保存下来,只需要选中要保存的代码,然后执行M-x save-code-to-library. Emacs会自动根据代码所处与的major-mode来挑选合适的org文件保存,并提示输入代码说明和tag.