如何改进此Emacs lisp功能?

时间:2012-12-17 22:26:48

标签: emacs elisp

目的是使用git grep作为M-x grep的命令,以及随之而来的所有缓冲区优势。期望的功能:

  • 它在点读取单词/ thing作为默认值(完成,排序)
  • 如果设置了区域,它会将当前区域读取为默认参数。

以下是我到目前为止的代码:

(defun bw-read-string-at-point ()
  (interactive)
  (let ((word (word-at-point)))
    (set-text-properties 0 (length word) nil word)
    word))

(defun bw-git-grep (search-str)
  "Uses `git-grep` to find `search-str`"
  (interactive
   (list
    (read-string (format "Search for (%s): " (bw-read-string-at-point)))))
  (let ((search-str (if (= (length search-str) 0)
                        (bw-read-string-at-point) search-str)))
    (grep (concat "git --no-pager grep -i -I -nH --no-color --extended-regexp " search-str))))

我觉得interactive位非常笨拙,可以做得更好。

2 个答案:

答案 0 :(得分:4)

实际上,它看起来很不错。除非您使用default' argument of读取字符串,否则interactive中的bw-read-string-at-point不应该存在。或者更好的是,只需使用grep-tag-default即可。 这是我如何调整它:

(defun bw-git-grep (search-str)
  "Uses `git-grep` to find `search-str`"
  (interactive
   (let ((default (grep-tag-default)))
    (list
     (read-string (format "Search for (default %s): " default)
                  nil nil default))))
  (grep (concat "git --no-pager grep -i -I -nH --no-color --extended-regexp " search-str)))

答案 1 :(得分:1)

我会使用read-from-minibuffer代替read-string

(defun bw-git-grep (pattern)
  (interactive
   (list
    (read-from-minibuffer
     "Search for: "
     (if (region-active-p)
         (buffer-substring-no-properties (region-beginning) (region-end))
       (thing-at-point 'word)))))

  (let* ((grep-command "git --no-pager grep -i -I -nH --no-color --extended-regexp ")
         (command      (concat grep-command pattern))
         (grep-use-null-device nil))
    (grep command)))

此外,您可能需要确保grep-use-null-device为零以避免grep/dev/null附加到您的命令(git似乎不太喜欢)< / p>