A-A+

使用emacs作为代码片段管理工具的方法

2015年12月13日 站长资讯 暂无评论

一、需求

一个代码片段管理工具所需要的基本功能大概包括:

支持多语言的高亮。

能够保存对代码的说明。

支持TAG标签。

有方便的查询功能。

而Emacs的Org-mode恰好能够完美的支持上面这些需求。

二、实现

  1. (defvar mode-file-map '((c++-mode . "cpp.org")  
  2.                         (emacs-lisp-mode . "elisp.org")  
  3.                         (python-mode . "python.org")  
  4.                         (perl-mode . "perl.org")  
  5.                         (dos-mode . "bat.org")  
  6.                         (sh-mode . "bash.org"))  
  7.   "映射major-mode与保存代码片段文件的对应关系"  
  8.   
  9.   
  10.   )  
  11.    
  12. (defvar code-library-path "d:/CodeLibrary/"  
  13.   "代码库文件存储的目录"  
  14.   )  
  15. (defun save-code-to-library()  
  16.   (interactive)  
  17.   (let (  
  18.         (code (get-region-or-thing 'defun))  
  19.         (library-file (concat code-library-path (cdr (assoc major-mode mode-file-map))))  
  20.         (head (read-string "请输入这段代码的说明"))  
  21.         (code-major-mode (replace-regexp-in-string "-mode$" "" (format "%s" major-mode))))  
  22.     (when (stringlibrary-file code-library-path)  
  23.       (setq library-file (concat code-library-path "temp.org")))  
  24.     (find-file library-file)  
  25.     (end-of-buffer)  
  26.     (newline)   
  27.     (insert (concat "* " head))  
  28.     (newline-and-indent)  
  29.     (insert (concat "#+BEGIN_SRC " code-major-mode))  
  30.     (newline-and-indent)  
  31.     (newline-and-indent)  
  32.     (insert "#+END_SRC")  
  33.     (forward-line -1)                   ;上一行  
  34.     (org-edit-src-code)  
  35.     (insert code)  
  36.     (org-edit-src-exit)  
  37.     (org-set-tags-command)              ;设置代码tags  
  38.     (save-buffer)  
  39.     ;; (kill-buffer)  
  40.   ))  

三、使用

在Emacs中看到中意的代码要保存下来,只需要选中要保存的代码,然后执行M-x save-code-to-library,Emacs会自动根据代码所处与的major-mode来挑选合适的org文件保存,并提示输入代码说明和tag。

下面是一个代码保存的截图:http://www.xiaoxiongboke.com

org-mode本身也提供了大量的搜索命令,可以通过tag或者内容作查询。

标签:

给我留言