1 ;;; grep.el --- run Grep as inferior of Emacs, parse match messages
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
5 ;; Free Software Foundation, Inc.
7 ;; Author: Roland McGrath <roland@gnu.org>
9 ;; Keywords: tools, processes
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This package provides the grep facilities documented in the Emacs
37 "Run grep as inferior of Emacs, parse error messages."
41 (defvar grep-host-defaults-alist nil
42 "Default values depending on target host.
43 `grep-compute-defaults' returns default values for every local or
44 remote host `grep' runs. These values can differ from host to
45 host. Once computed, the default values are kept here in order
46 to avoid computing them again.")
48 (defun grep-apply-setting (symbol value
)
49 "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
50 SYMBOL should be one of `grep-command', `grep-template',
51 `grep-use-null-device', `grep-find-command',
52 `grep-find-template', `grep-find-use-xargs', or
53 `grep-highlight-matches'."
54 (when grep-host-defaults-alist
56 (intern (or (file-remote-p default-directory
) "localhost")))
57 (host-defaults (assq host-id grep-host-defaults-alist
))
58 (defaults (assq nil grep-host-defaults-alist
)))
59 (setcar (cdr (assq symbol host-defaults
)) value
)
60 (setcar (cdr (assq symbol defaults
)) value
)))
61 (set-default symbol value
))
64 (defcustom grep-window-height nil
65 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
66 :type
'(choice (const :tag
"Default" nil
)
71 (defcustom grep-highlight-matches
'auto-detect
72 "If t, use special markers to highlight grep matches.
74 Some grep programs are able to surround matches with special
75 markers in grep output. Such markers can be used to highlight
78 This option sets the environment variable GREP_COLOR to specify
79 markers for highlighting and GREP_OPTIONS to add the --color
80 option in front of any explicit grep options before starting
83 In interactive usage, the actual value of this variable is set up
84 by `grep-compute-defaults'; to change the default value, use
85 Customize or call the function `grep-apply-setting'."
86 :type
'(choice (const :tag
"Do not highlight matches with grep markers" nil
)
87 (const :tag
"Highlight matches with grep markers" t
)
88 (other :tag
"Not Set" auto-detect
))
89 :set
'grep-apply-setting
93 (defcustom grep-scroll-output nil
94 "*Non-nil to scroll the *grep* buffer window as output appears.
96 Setting it causes the grep commands to put point at the end of their
97 output window so that the end of the output is always visible rather
104 (defcustom grep-command nil
105 "The default grep command for \\[grep].
106 If the grep program used supports an option to always include file names
107 in its output (such as the `-H' option to GNU grep), it's a good idea to
108 include it when specifying `grep-command'.
110 In interactive usage, the actual value of this variable is set up
111 by `grep-compute-defaults'; to change the default value, use
112 Customize or call the function `grep-apply-setting'."
113 :type
'(choice string
114 (const :tag
"Not Set" nil
))
115 :set
'grep-apply-setting
118 (defcustom grep-template nil
119 "The default command to run for \\[lgrep].
120 The following place holders should be present in the string:
121 <C> - place to put -i if case insensitive grep.
122 <F> - file names and wildcards to search.
123 <R> - the regular expression searched for.
124 <N> - place to insert null-device.
126 In interactive usage, the actual value of this variable is set up
127 by `grep-compute-defaults'; to change the default value, use
128 Customize or call the function `grep-apply-setting'."
129 :type
'(choice string
130 (const :tag
"Not Set" nil
))
131 :set
'grep-apply-setting
135 (defcustom grep-use-null-device
'auto-detect
136 "If t, append the value of `null-device' to `grep' commands.
137 This is done to ensure that the output of grep includes the filename of
138 any match in the case where only a single file is searched, and is not
139 necessary if the grep program used supports the `-H' option.
141 In interactive usage, the actual value of this variable is set up
142 by `grep-compute-defaults'; to change the default value, use
143 Customize or call the function `grep-apply-setting'."
144 :type
'(choice (const :tag
"Do Not Append Null Device" nil
)
145 (const :tag
"Append Null Device" t
)
146 (other :tag
"Not Set" auto-detect
))
147 :set
'grep-apply-setting
151 (defcustom grep-find-command nil
152 "The default find command for \\[grep-find].
153 In interactive usage, the actual value of this variable is set up
154 by `grep-compute-defaults'; to change the default value, use
155 Customize or call the function `grep-apply-setting'."
156 :type
'(choice string
157 (const :tag
"Not Set" nil
))
158 :set
'grep-apply-setting
161 (defcustom grep-find-template nil
162 "The default command to run for \\[rgrep].
163 The following place holders should be present in the string:
164 <D> - base directory for find
165 <X> - find options to restrict or expand the directory list
166 <F> - find options to limit the files matched
167 <C> - place to put -i if case insensitive grep
168 <R> - the regular expression searched for.
169 In interactive usage, the actual value of this variable is set up
170 by `grep-compute-defaults'; to change the default value, use
171 Customize or call the function `grep-apply-setting'."
172 :type
'(choice string
173 (const :tag
"Not Set" nil
))
174 :set
'grep-apply-setting
178 (defcustom grep-files-aliases
181 ("cc" .
"*.cc *.cxx *.cpp *.C *.CC *.c++")
182 ("cchh" .
"*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
183 ("hh" .
"*.hxx *.hpp *.[Hh] *.HH *.h++")
187 ("l" .
"[Cc]hange[Ll]og*")
188 ("m" .
"[Mm]akefile*")
191 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
195 (defcustom grep-find-ignored-directories
196 vc-directory-exclusion-list
197 "*List of names of sub-directories which `rgrep' shall not recurse into.
198 If an element is a cons cell, the car is called on the search directory
199 to determine whether cdr should not be recursed into."
200 :type
'(repeat string
)
203 (defcustom grep-error-screen-columns nil
204 "*If non-nil, column numbers in grep hits are screen columns.
205 See `compilation-error-screen-columns'"
206 :type
'(choice (const :tag
"Default" nil
)
212 (defcustom grep-setup-hook nil
213 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
217 (defvar grep-mode-map
218 (let ((map (make-sparse-keymap)))
219 (set-keymap-parent map compilation-minor-mode-map
)
220 (define-key map
" " 'scroll-up
)
221 (define-key map
"\^?" 'scroll-down
)
222 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
224 (define-key map
"\r" 'compile-goto-error
) ;; ?
225 (define-key map
"n" 'next-error-no-select
)
226 (define-key map
"p" 'previous-error-no-select
)
227 (define-key map
"{" 'compilation-previous-file
)
228 (define-key map
"}" 'compilation-next-file
)
229 (define-key map
"\t" 'compilation-next-error
)
230 (define-key map
[backtab] 'compilation-previous-error)
232 ;; Set up the menu-bar
233 (define-key map [menu-bar grep]
234 (cons "Grep" (make-sparse-keymap "Grep")))
236 (define-key map [menu-bar grep compilation-kill-compilation]
237 '(menu-item "Kill Grep" kill-compilation
238 :help "Kill the currently running grep process"))
239 (define-key map [menu-bar grep compilation-separator2] '("----"))
240 (define-key map [menu-bar grep compilation-compile]
241 '(menu-item "Compile..." compile
242 :help "Compile the program including the current buffer. Default: run `make'"))
243 (define-key map [menu-bar grep compilation-rgrep]
244 '(menu-item "Recursive grep..." rgrep
245 :help "User-friendly recursive grep in directory tree"))
246 (define-key map [menu-bar grep compilation-lgrep]
247 '(menu-item "Local grep..." lgrep
248 :help "User-friendly grep in a directory"))
249 (define-key map [menu-bar grep compilation-grep-find]
250 '(menu-item "Grep via Find..." grep-find
251 :help "Run grep via find, with user-specified args"))
252 (define-key map [menu-bar grep compilation-grep]
253 '(menu-item "Another grep..." grep
254 :help "Run grep, with user-specified args, and collect output in a buffer."))
255 (define-key map [menu-bar grep compilation-recompile]
256 '(menu-item "Repeat grep" recompile
257 :help "Run grep again"))
258 (define-key map [menu-bar grep compilation-separator2] '("----"))
259 (define-key map [menu-bar grep compilation-first-error]
260 '(menu-item "First Match" first-error
261 :help "Restart at the first match, visit corresponding location"))
262 (define-key map [menu-bar grep compilation-previous-error]
263 '(menu-item "Previous Match" previous-error
264 :help "Visit the previous match and corresponding location"))
265 (define-key map [menu-bar grep compilation-next-error]
266 '(menu-item "Next Match" next-error
267 :help "Visit the next match and corresponding location"))
269 "Keymap for grep buffers.
270 `compilation-minor-mode-map' is a cdr of this.")
272 (defvar grep-mode-tool-bar-map
273 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
274 ;; so don't do anything.
275 (when (keymapp (butlast tool-bar-map))
276 (let ((map (butlast (copy-keymap tool-bar-map)))
277 (help (last tool-bar-map))) ;; Keep Help last in tool bar
279 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
281 :help "Goto previous match")
283 "right-arrow" 'next-error-no-select 'next-error-no-select map
285 :help "Goto next match")
287 "cancel" 'kill-compilation 'kill-compilation map
288 :enable '(let ((buffer (compilation-find-buffer)))
289 (get-buffer-process buffer))
292 "refresh" 'recompile 'recompile map
293 :help "Restart grep")
296 (defalias 'kill-grep 'kill-compilation)
298 ;;;; TODO --- refine this!!
300 ;; (defcustom grep-use-compilation-buffer t
301 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
302 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
303 ;; can be used to navigate between grep matches (the default).
304 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
305 ;; be used to navigate between grep matches."
309 ;; override compilation-last-buffer
310 (defvar grep-last-buffer nil
311 "The most recent grep buffer.
312 A grep buffer becomes most recent when you select Grep mode in it.
313 Notice that using \\[next-error] or \\[compile-goto-error] modifies
314 `complation-last-buffer' rather than `grep-last-buffer'.")
317 (defvar grep-regexp-alist
318 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
320 ;; Rule to match column numbers is commented out since no known grep
322 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
324 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
325 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
327 ;; Calculate column positions (beg . end) of first grep match on a line
329 (setq compilation-error-screen-columns nil)
330 (- (match-beginning 4) (match-end 1)))
332 (lambda () (- (match-end 5) (match-end 1)
333 (- (match-end 4) (match-beginning 4)))))
335 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
336 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
338 (defvar grep-error "grep hit"
339 "Message to print when no matches are found.")
341 ;; Reverse the colors because grep hits are not errors (though we jump there
342 ;; with `next-error'), and unreadable files can't be gone to.
343 (defvar grep-hit-face compilation-info-face
344 "Face name to use for grep hits.")
346 (defvar grep-error-face 'compilation-error
347 "Face name to use for grep error messages.")
349 (defvar grep-match-face 'match
350 "Face name to use for grep matches.")
352 (defvar grep-context-face 'shadow
353 "Face name to use for grep context lines.")
355 (defvar grep-mode-font-lock-keywords
356 '(;; Command output lines.
357 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
358 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
360 ;; remove match from grep-regexp-alist before fontifying
361 ("^Grep[/a-zA-z]* started.*"
362 (0 '(face nil message nil help-echo nil mouse-face nil) t))
363 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
364 (0 '(face nil message nil help-echo nil mouse-face nil) t)
365 (1 compilation-info-face nil t)
366 (2 compilation-warning-face nil t))
367 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
368 (0 '(face nil message nil help-echo nil mouse-face nil) t)
370 (2 grep-error-face nil t))
371 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
372 ;; Highlight grep matches and delete markers
373 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
374 ;; Refontification does not work after the markers have been
375 ;; deleted. So we use the font-lock-face property here as Font
376 ;; Lock does not clear that.
377 (2 (list 'face nil 'font-lock-face grep-match-face))
380 ;; Delete markers with `replace-match' because it updates
381 ;; the match-data, whereas `delete-region' would render it obsolete.
382 (replace-match "" t t nil 3)
383 (replace-match "" t t nil 1))))
384 ("\\(\033\\[[0-9;]*[mK]\\)"
385 ;; Delete all remaining escape sequences
387 (replace-match "" t t nil 1))))
388 "Additional things to highlight in grep output.
389 This gets tacked on the end of the generated expressions.")
392 (defvar grep-program "grep"
393 "The default grep program for `grep-command' and `grep-find-command'.
394 This variable's value takes effect when `grep-compute-defaults' is called.")
397 (defvar find-program "find"
398 "The default find program for `grep-find-command'.
399 This variable's value takes effect when `grep-compute-defaults' is called.")
402 (defvar xargs-program "xargs"
403 "The default xargs program for `grep-find-command'.
404 See `grep-find-use-xargs'.
405 This variable's value takes effect when `grep-compute-defaults' is called.")
408 (defvar grep-find-use-xargs nil
409 "Non-nil means that `grep-find' uses the `xargs' utility by default.
410 If `exec', use `find -exec'.
411 If `gnu', use `find -print0' and `xargs -0'.
412 Any other non-nil value means to use `find -print' and `xargs'.
414 This variable's value takes effect when `grep-compute-defaults' is called.")
416 ;; History of grep commands.
418 (defvar grep-history nil)
420 (defvar grep-find-history nil)
422 ;; History of lgrep and rgrep regexp and files args.
423 (defvar grep-regexp-history nil)
424 (defvar grep-files-history '("ch" "el"))
427 (defun grep-process-setup ()
428 "Setup compilation variables and buffer for `grep'.
429 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
430 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
431 (grep-compute-defaults))
432 (when (eq grep-highlight-matches t)
433 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
434 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
435 (setenv "TERM" "emacs-grep")
436 ;; `--color=auto' emits escape sequences on a tty rather than on a pipe,
437 ;; thus allowing to use multiple grep filters on the command line
438 ;; and to output escape sequences only on the final grep output
439 (setenv "GREP_OPTIONS"
440 (concat (getenv "GREP_OPTIONS")
441 ;; Windows and DOS pipes fail `isatty' detection in Grep.
442 " --color=" (if (memq system-type '(windows-nt ms-dos))
444 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
445 (setenv "GREP_COLOR" "01;31")
446 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
447 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
448 (set (make-local-variable 'compilation-exit-message-function)
449 (lambda (status code msg)
450 (if (eq status 'exit)
452 '("finished (matches found)\n" . "matched"))
454 '("finished with no matches found\n" . "no match"))
458 (run-hooks 'grep-setup-hook))
460 (defun grep-probe (command args &optional func result)
461 (equal (condition-case nil
462 (apply (or func 'process-file) command args)
467 (defun grep-compute-defaults ()
468 ;; Keep default values.
469 (unless grep-host-defaults-alist
471 'grep-host-defaults-alist
473 `((grep-command ,grep-command)
474 (grep-template ,grep-template)
475 (grep-use-null-device ,grep-use-null-device)
476 (grep-find-command ,grep-find-command)
477 (grep-find-template ,grep-find-template)
478 (grep-find-use-xargs ,grep-find-use-xargs)
479 (grep-highlight-matches ,grep-highlight-matches)))))
481 (intern (or (file-remote-p default-directory) "localhost")))
482 (host-defaults (assq host-id grep-host-defaults-alist))
483 (defaults (assq nil grep-host-defaults-alist)))
484 ;; There are different defaults on different hosts. They must be
485 ;; computed for every host once.
486 (dolist (setting '(grep-command grep-template
487 grep-use-null-device grep-find-command
488 grep-find-template grep-find-use-xargs
489 grep-highlight-matches))
491 (or (cadr (assq setting host-defaults))
492 (cadr (assq setting defaults)))))
494 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
495 (setq grep-use-null-device
497 (let ((hello-file (expand-file-name "HELLO" data-directory)))
499 (and (if grep-command
500 ;; `grep-command' is already set, so
501 ;; use that for testing.
502 (grep-probe grep-command
503 `(nil t nil "^English" ,hello-file)
504 #'call-process-shell-command)
505 ;; otherwise use `grep-program'
506 (grep-probe grep-program
507 `(nil t nil "-nH" "^English" ,hello-file)))
509 (goto-char (point-min))
511 (concat (regexp-quote hello-file)
512 ":[0-9]+:English")))))))))
513 (unless (and grep-command grep-find-command
514 grep-template grep-find-template)
516 (concat (if grep-use-null-device "-n" "-nH")
517 (if (grep-probe grep-program
518 `(nil nil nil "-e" "foo" ,null-device)
523 (format "%s %s " grep-program grep-options)))
524 (unless grep-template
526 (format "%s <C> %s <R> <F>" grep-program grep-options)))
527 (unless grep-find-use-xargs
528 (setq grep-find-use-xargs
531 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
532 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
536 (unless grep-find-command
537 (setq grep-find-command
538 (cond ((eq grep-find-use-xargs 'gnu)
539 (format "%s . -type f -print0 | %s -0 -e %s"
540 find-program xargs-program grep-command))
541 ((eq grep-find-use-xargs 'exec)
542 (let ((cmd0 (format "%s . -type f -exec %s"
543 find-program grep-command)))
545 (format "%s {} %s %s"
547 (shell-quote-argument ";"))
548 (1+ (length cmd0)))))
550 (format "%s . -type f -print | %s %s"
551 find-program xargs-program grep-command)))))
552 (unless grep-find-template
553 (setq grep-find-template
554 (let ((gcmd (format "%s <C> %s <R>"
555 grep-program grep-options)))
556 (cond ((eq grep-find-use-xargs 'gnu)
557 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
558 find-program xargs-program gcmd))
559 ((eq grep-find-use-xargs 'exec)
560 (format "%s . <X> -type f <F> -exec %s {} %s %s"
561 find-program gcmd null-device
562 (shell-quote-argument ";")))
564 (format "%s . <X> -type f <F> -print | %s %s"
565 find-program xargs-program gcmd))))))))
566 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
567 (setq grep-highlight-matches
569 (and (grep-probe grep-program '(nil t nil "--help"))
571 (goto-char (point-min))
572 (search-forward "--color" nil t))
575 ;; Save defaults for this host.
576 (setq grep-host-defaults-alist
577 (delete (assq host-id grep-host-defaults-alist)
578 grep-host-defaults-alist))
580 'grep-host-defaults-alist
582 `((grep-command ,grep-command)
583 (grep-template ,grep-template)
584 (grep-use-null-device ,grep-use-null-device)
585 (grep-find-command ,grep-find-command)
586 (grep-find-template ,grep-find-template)
587 (grep-find-use-xargs ,grep-find-use-xargs)
588 (grep-highlight-matches ,grep-highlight-matches))))))
590 (defun grep-tag-default ()
591 (or (and transient-mark-mode mark-active
593 (buffer-substring-no-properties (point) (mark)))
594 (funcall (or find-tag-default-function
595 (get major-mode 'find-tag-default-function)
599 (defun grep-default-command ()
600 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
601 (let ((tag-default (shell-quote-argument (grep-tag-default)))
602 ;; This a regexp to match single shell arguments.
603 ;; Could someone please add comments explaining it?
604 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
605 (grep-default (or (car grep-history) grep-command)))
606 ;; In the default command, find the arg that specifies the pattern.
607 (when (or (string-match
608 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
609 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
611 ;; If the string is not yet complete.
612 (string-match "\\(\\)\\'" grep-default))
613 ;; Maybe we will replace the pattern with the default tag.
614 ;; But first, maybe replace the file name pattern.
616 (unless (or (not (stringp buffer-file-name))
617 (when (match-beginning 2)
621 (file-name-nondirectory
622 (match-string 3 grep-default)))
623 (file-name-nondirectory buffer-file-name)))))
624 (setq grep-default (concat (substring grep-default
625 0 (match-beginning 2))
627 (file-name-extension buffer-file-name))))
628 ;; In case wildcard-to-regexp gets an error
629 ;; from invalid data.
631 ;; Now replace the pattern with the default tag.
632 (replace-match tag-default t t grep-default 1))))
636 (define-compilation-mode grep-mode "Grep"
637 "Sets `grep-last-buffer' and `compilation-window-height'."
638 (setq grep-last-buffer (current-buffer))
639 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
640 (set (make-local-variable 'compilation-error-face)
642 (set (make-local-variable 'compilation-error-regexp-alist)
644 (set (make-local-variable 'compilation-process-setup-function)
646 (set (make-local-variable 'compilation-disable-input) t))
650 (defun grep (command-args)
651 "Run grep, with user-specified args, and collect output in a buffer.
652 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
653 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
654 output buffer, to go to the lines where grep
657 For doing a recursive `grep', see the `rgrep' command. For running
658 `grep' in a specific directory, see `lgrep'.
660 This command uses a special history list for its COMMAND-ARGS, so you
661 can easily repeat a grep command.
663 A prefix argument says to default the argument based upon the current
664 tag the cursor is over, substituting it into the last grep command
665 in the grep command history (or into `grep-command' if that history
669 (grep-compute-defaults)
670 (let ((default (grep-default-command)))
671 (list (read-shell-command "Run grep (like this): "
672 (if current-prefix-arg default grep-command)
674 (if current-prefix-arg nil default))))))
676 ;; Setting process-setup-function makes exit-message-function work
677 ;; even when async processes aren't supported.
678 (compilation-start (if (and grep-use-null-device null-device)
679 (concat command-args " " null-device)
685 (defun grep-find (command-args)
686 "Run grep via find, with user-specified args COMMAND-ARGS.
687 Collect output in a buffer.
688 While find runs asynchronously, you can use the \\[next-error] command
689 to find the text that grep hits refer to.
691 This command uses a special history list for its arguments, so you can
692 easily repeat a find command."
695 (grep-compute-defaults)
696 (if grep-find-command
697 (list (read-shell-command "Run find (like this): "
698 grep-find-command 'grep-find-history))
699 ;; No default was set
701 "compile.el: No `grep-find-command' command available. Press RET.")
704 (let ((null-device nil)) ; see grep
705 (grep command-args))))
708 (defalias 'find-grep 'grep-find)
711 ;; User-friendly interactive API.
713 (defconst grep-expand-keywords
714 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
717 ("<N>" . null-device)
719 ("<R>" . (shell-quote-argument (or regexp ""))))
720 "List of substitutions performed by `grep-expand-template'.
721 If car of an element matches, the cdr is evalled in to get the
722 substitution string. Note dynamic scoping of variables.")
724 (defun grep-expand-template (template &optional regexp files dir excl)
725 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
726 (let ((command template)
727 (cf case-fold-search)
728 (case-fold-search nil))
729 (dolist (kw grep-expand-keywords command)
730 (if (string-match (car kw) command)
733 (or (if (symbolp (cdr kw))
734 (symbol-value (cdr kw))
735 (save-match-data (eval (cdr kw))))
739 (defun grep-read-regexp ()
740 "Read regexp arg for interactive grep."
741 (let ((default (grep-tag-default)))
744 (if (and default (> (length default) 0))
745 (format " (default \"%s\"): " default) ": "))
746 nil 'grep-regexp-history default)))
748 (defun grep-read-files (regexp)
749 "Read files arg for interactive grep."
750 (let* ((bn (or (buffer-file-name) (buffer-name)))
753 (file-name-nondirectory bn)))
756 (let ((aliases grep-files-aliases)
759 (setq alias (car aliases)
760 aliases (cdr aliases))
761 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
766 (let ((ext (file-name-extension fn)))
767 (and ext (concat "*." ext))))
768 (car grep-files-history)
769 (car (car grep-files-aliases))))
771 (concat "Search for \"" regexp
773 (if default (concat " (default " default ")"))
775 nil 'grep-files-history default)))
777 (or (cdr (assoc files grep-files-aliases))
781 (defun lgrep (regexp &optional files dir)
782 "Run grep, searching for REGEXP in FILES in directory DIR.
783 The search is limited to file names matching shell pattern FILES.
784 FILES may use abbreviations defined in `grep-files-aliases', e.g.
785 entering `ch' is equivalent to `*.[ch]'.
787 With \\[universal-argument] prefix, you can edit the constructed shell command line
788 before it is executed.
789 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
791 Collect output in a buffer. While grep runs asynchronously, you
792 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
793 in the grep output buffer,
794 to go to the lines where grep found matches.
796 This command shares argument histories with \\[rgrep] and \\[grep]."
799 (grep-compute-defaults)
801 ((and grep-command (equal current-prefix-arg '(16)))
802 (list (read-from-minibuffer "Run: " grep-command
803 nil nil 'grep-history)
807 (read-string "grep.el: No `grep-template' available. Press RET.")))
808 (t (let* ((regexp (grep-read-regexp))
809 (files (grep-read-files regexp))
810 (dir (read-directory-name "In directory: "
811 nil default-directory t)))
812 (list regexp files dir))))))
813 (when (and (stringp regexp) (> (length regexp) 0))
814 (let ((command regexp))
816 (if (string= command grep-command)
818 (setq dir (file-name-as-directory (expand-file-name dir)))
819 (setq command (grep-expand-template
824 (if (equal current-prefix-arg '(4))
826 (read-from-minibuffer "Confirm: "
827 command nil nil 'grep-history))
828 (add-to-history 'grep-history command))))
830 (let ((default-directory (or dir default-directory)))
831 ;; Setting process-setup-function makes exit-message-function work
832 ;; even when async processes aren't supported.
833 (compilation-start (if (and grep-use-null-device null-device)
834 (concat command " " null-device)
837 (if (eq next-error-last-buffer (current-buffer))
838 (setq default-directory dir))))))
841 (defvar find-name-arg) ; autoloaded
844 (defun rgrep (regexp &optional files dir)
845 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
846 The search is limited to file names matching shell pattern FILES.
847 FILES may use abbreviations defined in `grep-files-aliases', e.g.
848 entering `ch' is equivalent to `*.[ch]'.
850 With \\[universal-argument] prefix, you can edit the constructed shell command line
851 before it is executed.
852 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
854 Collect output in a buffer. While find runs asynchronously, you
855 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
856 in the grep output buffer,
857 to go to the lines where grep found matches.
859 This command shares argument histories with \\[lgrep] and \\[grep-find]."
862 (grep-compute-defaults)
864 ((and grep-find-command (equal current-prefix-arg '(16)))
865 (list (read-from-minibuffer "Run: " grep-find-command
866 nil nil 'grep-find-history)
868 ((not grep-find-template)
870 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
871 (t (let* ((regexp (grep-read-regexp))
872 (files (grep-read-files regexp))
873 (dir (read-directory-name "Base directory: "
874 nil default-directory t)))
875 (list regexp files dir))))))
876 (when (and (stringp regexp) (> (length regexp) 0))
878 (if (not (string= regexp grep-find-command))
879 (compilation-start regexp 'grep-mode))
880 (setq dir (file-name-as-directory (expand-file-name dir)))
881 (let ((command (grep-expand-template
884 (concat (shell-quote-argument "(")
885 " " find-name-arg " "
886 (mapconcat #'shell-quote-argument
888 (concat " -o " find-name-arg " "))
890 (shell-quote-argument ")"))
892 (and grep-find-ignored-directories
893 (concat (shell-quote-argument "(")
894 ;; we should use shell-quote-argument here
898 (cond ((stringp ignore)
899 (shell-quote-argument
900 (concat "*/" ignore)))
902 (and (funcall (car ignore) dir)
903 (shell-quote-argument
906 grep-find-ignored-directories
909 (shell-quote-argument ")")
912 (if current-prefix-arg
914 (read-from-minibuffer "Confirm: "
915 command nil nil 'grep-find-history))
916 (add-to-history 'grep-find-history command))
917 (let ((default-directory dir))
918 (compilation-start command 'grep-mode))
919 ;; Set default-directory if we started rgrep in the *grep* buffer.
920 (if (eq next-error-last-buffer (current-buffer))
921 (setq default-directory dir)))))))
926 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
927 ;;; grep.el ends here