Skip to content

Instantly share code, notes, and snippets.

@jglick
Created July 24, 2012 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jglick/3172561 to your computer and use it in GitHub Desktop.
Save jglick/3172561 to your computer and use it in GitHub Desktop.
M-x git-grep-dired: Emacs command to search for text patterns in a Git repo à la find-grep-dired
(defun git-grep-dired (repo wildcards regexp)
"Find Git-controlled files in DIR with a name like WILDCARDS containing a regexp REGEXP and start Dired on output."
(interactive "DGit-grep (directory): \nsGit-grep (filename wildcard(s), e.g. *.xml): \nsGit-grep (grep regexp): ")
(setq repo (file-name-as-directory (expand-file-name repo)))
(switch-to-buffer (concat "*Git Grep " repo "*"))
(fundamental-mode)
(setq buffer-read-only nil)
(erase-buffer)
(setq default-directory repo)
(let ((cmd (format "git --git-dir %s/.git ls-files -z%s | xargs -0 grep -lZ -- %s | xargs -0 ls -l"
repo
(apply 'concat (mapcar (lambda (s) (concat " " (shell-quote-argument s))) (split-string wildcards)))
(shell-quote-argument regexp))))
(insert " " cmd "\n " repo ":\n")
(call-process-shell-command (concat cmd " | sed -e 's/^/ /g'") nil t))
(dired-mode)
(dired-build-subdir-alist)
(goto-line 2))
@surajacharya
Copy link

I had to make the following change before the dired buffer worked correctly.

  • ;; (dired-build-subdir-alist)
  • ;; From find-dired:
  • ;; Set subdir-alist so that Tree Dired will work:
  • (if (fboundp 'dired-simple-subdir-alist)
  •  ;; will work even with nested dired format (dired-nstd.el,v 1.15
    
  •  ;; and later)
    
  •  (dired-simple-subdir-alist)
    
  • ;; else we have an ancient tree dired (or classic dired, where
  • ;; this does no harm)
  • (set (make-local-variable 'dired-subdir-alist)
  •     (list (cons default-directory (point-min-marker)))))
    

@surajacharya
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment