如何在Emacs中使用Mx rgrep和git grep命令?

Tik*_*vis 9 emacs grep elisp

我希望能够使用正常的M-x rgrep工作流程(输入路径,模式并在*grep*缓冲区中显示链接的结果),但使用git grep而不是使用正常的find命令:

find . -type f -exec grep -nH -e  {} +
Run Code Online (Sandbox Code Playgroud)

我试着直接设置grep-find-command变量:

(setq grep-find-command "git grep")
Run Code Online (Sandbox Code Playgroud)

和使用 grep-apply-setting

(grep-apply-setting 'grep-find-command "git grep")
Run Code Online (Sandbox Code Playgroud)

但似乎都不起作用.当我运行M-x rgrep它时,只需使用与find以前相同的命令.

事实上,我敢肯定,现在rgrep甚至没有用到的grep-find-command变量,但我想不出它的命令存储.

Jam*_*son 13

怎么样M-x vc-git-grep(C-x v f).这不是你需要的吗?

它会提示您:

  • 搜索模式(默认:点或区域的标记)
  • 文件名模式(默认:当前文件后缀)
  • 基本搜索目录(默认,当前目录)

适合我.


Tik*_*vis 12

事实证明相关变量grep-find-template.这需要一个带有一些附加参数的命令:

  • <D> 对于基目录
  • <X> 用于查找限制目录列表的选项
  • <F> 用于限制匹配文件的查找选项
  • <C>-i如果搜索不区分大小写,则放置该位置
  • <R> 用于搜索正则表达式

默认模板如下所示:

find . <X> -type f <F> -exec grep <C> -nH -e <R> {} +
Run Code Online (Sandbox Code Playgroud)

为了使命令有效git grep,我必须传递一些选项以确保git不使用寻呼机并以正确的格式输出内容.我也忽略了一些模板选项,因为git grep已经以自然的方式限制了搜索的文件.但是,以某种方式添加它们可能是有意义的.

我的新价值grep-find-template

git --no-pager grep --no-color --line-number <C> <R>
Run Code Online (Sandbox Code Playgroud)

经过一些粗略的测试,它似乎工作.

请注意,您应该使用此变量grep-apply-setting而不是直接修改它:

(grep-apply-setting 'grep-find-template "git --no-pager grep --no-color --line-number <C> <R>")
Run Code Online (Sandbox Code Playgroud)

由于我没有使用其中的两个输入rgrep,我编写了自己的git-grep命令,暂时隐藏旧命令并将其grep-find-template替换为我的命令.这感觉有点hacky,但似乎也有效.

(defcustom git-grep-command "git --no-pager grep --no-color --line-number <C> <R>"
  "The command to run with M-x git-grep.")
(defun git-grep (regexp)
  "Search for the given regexp using `git grep' in the current directory."
  (interactive "sRegexp: ")
  (unless (boundp 'grep-find-template) (grep-compute-defaults))
  (let ((old-command grep-find-template))
    (grep-apply-setting 'grep-find-template git-grep-command)
    (rgrep regexp "*" "")
    (grep-apply-setting 'grep-find-template old-command)))
Run Code Online (Sandbox Code Playgroud)