一、需求
一個代碼片段管理工具所需要的基本功能大概包括:
- 支援多語言的高亮
- 能夠儲存對代碼的說明
- 支援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)
))
三、使用