2014-12-02 57 views
1

我对emacs lisp有点新,并试图学习最好的方式来做事情。emacs lisp - 文本搜索和替换列表到模板

我手头的示例任务是生成“授予数据库权限”语句的集合(这可能是我经常做的事情)。

为了最有效地做到这一点,我想我需要两个列表,一个数据库和一个应用权限。

我写了一个通用函数来搜索和替换,另一个函数调用该函数并将所需的文本插入到我的缓冲区中。

这是最好的方法吗?我应该看看yasnippets,还是宏? while循环是这个的首选选项吗?我只是想指出正确的方向来做这种工作的emacs方式......在我的vim日子里,我可能会在python或bash中做这样的事情。

(工作,尽管不是最佳实践?)代码如下。
(附加信息是在cygwin的emacs 24.4,通过spacemacs邪恶。)

(setq database-list 
     (list 
     "[database_1]" 
     "[database_2]" 
     "[database_3]")) 

(setq perm-list 
     (list "EXECUTE" 
      "SELECT" 
      "SHOWPLAN")) 

(defun generic-string-replace-list (template search in-list) 
    "takes a string template in, a search token, and a list. Iterates 
through the search list generating an output string with the 
searh/replace of each list item." 
    (setq out "") 
    (while in-list 
    (setq out (concat 
        out 
        (replace-regexp-in-string search (car in-list) template) 
        "\n")) 
    (setq in-list (cdr in-list))) 
    out) 


(defun generate-perm-list-for-db-list (perm-list database-list) 
    (forward-line) 
    (while database-list 
    (insert (concat "\nuse " (car database-list) ";\n")) 
    (setq template (concat 
         "grant \$perm to " 
         (car database-list) 
         " to [Public];")) 
    (insert (generic-string-replace-list 
          template 
          "\$perm" 
          perm-list)) 
    (setq database-list (cdr database-list)))) 

;; Call things above with this: 
(generate-perm-list-for-db-list perm-list database-list) 

;; sample output from the functions: 

use [database_1]; 
grant EXECUTE to [database_1] to [Public]; 
grant SELECT to [database_1] to [Public]; 
grant SHOWPLAN to [database_1] to [Public]; 

use [database_2]; 
grant EXECUTE to [database_2] to [Public]; 
grant SELECT to [database_2] to [Public]; 
grant SHOWPLAN to [database_2] to [Public]; 

use [database_3]; 
grant EXECUTE to [database_3] to [Public]; 
grant SELECT to [database_3] to [Public]; 
grant SHOWPLAN to [database_3] to [Public]; 
+0

你应该使用'dolist'取代'while'。你可以“插入”多个字符串,而不是先将它们连接起来。 – npostavs 2014-12-02 21:56:00

回答

1

这里是你的代码,简化:

(setq database-list '("[database_1]" "[database_2]" "[database_3]")) 

(setq perm-list '("EXECUTE" "SELECT" "SHOWPLAN")) 

(defun generate-perm-list-for-db-list (perm-list database-list) 
    (forward-line) 
    (dolist (db database-list) 
    (insert 
    "\nuse " db ";\n" 
    (mapconcat 
     (lambda (x) 
     (format "grant %s to %s to [Public];" x db)) 
     perm-list 
     "\n") 
    "\n")))