一、需求
一个代码片段管理工具所需要的基本功能大概包括:
- 支持多语言的高亮
- 能够保存对代码的说明
- 支持TAG标签
- 有方便的查询功能
而Emacs的Org-mode恰好能够完美的支持上面这些需求.
二、实现
(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)
))
三、使用