繁体   English   中英

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

[英]How can I use M-x rgrep with the git grep command in Emacs?

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

find . -type f -exec grep -nH -e  {} +

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

(setq grep-find-command "git grep")

并使用grep-apply-setting

(grep-apply-setting 'grep-find-command "git grep")

但似乎都不起作用。 当我运行Mx rgrep它只使用与以前相同的find命令。

事实上,我敢肯定,现在rgrep甚至不使用grep-find-command的变量,但我想不通它的指令存储

Mx vc-git-grep ( Cx vf ) 呢? 这不是你需要的吗?

它会提示您:

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

对我来说很好用。

结果发现相关变量实际上是grep-find-template 这需要一个带有一些附加参数的命令:

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

默认模板如下所示:

find . <X> -type f <F> -exec grep <C> -nH -e <R> {} +

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

我对grep-find-template新值是

git --no-pager grep --no-color --line-number <C> <R>

经过一些粗略的测试,它似乎有效。

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

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

由于我不使用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)))

使用 Emacs for Windows 和 Git Bash 确保 PATH 找到git.exevc-git-grep将不起作用:

  (let ((dir "C:/Program Files/Tools/Git/bin"))
    (setenv "PATH" (concat (getenv "PATH") ";" dir))
    (setq exec-path (append exec-path '(dir))))

exec-path是不够的......这里解释了原因:Using git with emacs

由于vc-git-grep使用运行该函数的缓冲区的目录,我还发现了一个方便的包装器:

(global-set-key [(control f8)]
            (lambda() (interactive)
              (with-current-buffer ROOT (call-interactively #'vc-git-grep))))

这里 ROOT 是一个缓冲区(或评估缓冲区的函数),搜索从其目录开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM