我对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 :(得分: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")))