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];
你應該使用'dolist'取代'while'。你可以「插入」多個字符串,而不是先將它們連接起來。 – npostavs 2014-12-02 21:56:00