【问题标题】:emacs lisp - text search and replace list into templateemacs lisp - 文本搜索并将列表替换为模板
【发布时间】:2014-12-02 21:09:54
【问题描述】:

我对 emacs lisp 有点陌生,并试图学习做事的最佳方式。

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

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

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

这是最好的方法吗?我应该看 yasn-ps 还是宏? 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。您可以insert 多个字符串,而不是先concat

标签: emacs elisp


【解决方案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")))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2016-09-22
    相关资源
    最近更新 更多