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, 2010, 2011
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 "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_COLORS 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 When this option is `auto', grep uses `--color=auto' to highlight
84 matches only when it outputs to a terminal (when `grep' is the last
85 command in the pipe), thus avoiding the use of any potentially-harmful
86 escape sequences when standard output goes to a file or pipe.
88 To make grep highlight matches even into a pipe, you need the option
89 `always' that forces grep to use `--color=always' to unconditionally
90 output escape sequences.
92 In interactive usage, the actual value of this variable is set up
93 by `grep-compute-defaults' when the default value is `auto-detect'.
94 To change the default value, use Customize or call the function
95 `grep-apply-setting'."
96 :type
'(choice (const :tag
"Do not highlight matches with grep markers" nil
)
97 (const :tag
"Highlight matches with grep markers" t
)
98 (const :tag
"Use --color=always" always
)
99 (const :tag
"Use --color=auto" auto
)
100 (other :tag
"Not Set" auto-detect
))
101 :set
'grep-apply-setting
105 (defcustom grep-scroll-output nil
106 "*Non-nil to scroll the *grep* buffer window as output appears.
108 Setting it causes the grep commands to put point at the end of their
109 output window so that the end of the output is always visible rather
116 (defcustom grep-command nil
117 "The default grep command for \\[grep].
118 If the grep program used supports an option to always include file names
119 in its output (such as the `-H' option to GNU grep), it's a good idea to
120 include it when specifying `grep-command'.
122 In interactive usage, the actual value of this variable is set up
123 by `grep-compute-defaults'; to change the default value, use
124 Customize or call the function `grep-apply-setting'."
125 :type
'(choice string
126 (const :tag
"Not Set" nil
))
127 :set
'grep-apply-setting
130 (defcustom grep-template nil
131 "The default command to run for \\[lgrep].
132 The following place holders should be present in the string:
133 <C> - place to put -i if case insensitive grep.
134 <F> - file names and wildcards to search.
135 <X> - file names and wildcards to exclude.
136 <R> - the regular expression searched for.
137 <N> - place to insert null-device.
139 In interactive usage, the actual value of this variable is set up
140 by `grep-compute-defaults'; to change the default value, use
141 Customize or call the function `grep-apply-setting'."
142 :type
'(choice string
143 (const :tag
"Not Set" nil
))
144 :set
'grep-apply-setting
148 (defcustom grep-use-null-device
'auto-detect
149 "If t, append the value of `null-device' to `grep' commands.
150 This is done to ensure that the output of grep includes the filename of
151 any match in the case where only a single file is searched, and is not
152 necessary if the grep program used supports the `-H' option.
154 In interactive usage, the actual value of this variable is set up
155 by `grep-compute-defaults'; to change the default value, use
156 Customize or call the function `grep-apply-setting'."
157 :type
'(choice (const :tag
"Do Not Append Null Device" nil
)
158 (const :tag
"Append Null Device" t
)
159 (other :tag
"Not Set" auto-detect
))
160 :set
'grep-apply-setting
164 (defcustom grep-find-command nil
165 "The default find command for \\[grep-find].
166 In interactive usage, the actual value of this variable is set up
167 by `grep-compute-defaults'; to change the default value, use
168 Customize or call the function `grep-apply-setting'."
169 :type
'(choice string
170 (const :tag
"Not Set" nil
))
171 :set
'grep-apply-setting
174 (defcustom grep-find-template nil
175 "The default command to run for \\[rgrep].
176 The following place holders should be present in the string:
177 <D> - base directory for find
178 <X> - find options to restrict or expand the directory list
179 <F> - find options to limit the files matched
180 <C> - place to put -i if case insensitive grep
181 <R> - the regular expression searched for.
182 In interactive usage, the actual value of this variable is set up
183 by `grep-compute-defaults'; to change the default value, use
184 Customize or call the function `grep-apply-setting'."
185 :type
'(choice string
186 (const :tag
"Not Set" nil
))
187 :set
'grep-apply-setting
191 (defcustom grep-files-aliases
196 ("cc" .
"*.cc *.cxx *.cpp *.C *.CC *.c++")
197 ("cchh" .
"*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
198 ("hh" .
"*.hxx *.hpp *.[Hh] *.HH *.h++")
200 ("l" .
"[Cc]hange[Ll]og*")
201 ("m" .
"[Mm]akefile*")
205 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
209 (defcustom grep-find-ignored-directories
210 vc-directory-exclusion-list
211 "*List of names of sub-directories which `rgrep' shall not recurse into.
212 If an element is a cons cell, the car is called on the search directory
213 to determine whether cdr should not be recursed into."
214 :type
'(choice (repeat :tag
"Ignored directories" string
)
215 (const :tag
"No ignored directories" nil
))
218 (defcustom grep-find-ignored-files
219 (cons ".#*" (delq nil
(mapcar (lambda (s)
220 (unless (string-match-p "/\\'" s
)
222 completion-ignored-extensions
)))
223 "*List of file names which `rgrep' and `lgrep' shall exclude.
224 If an element is a cons cell, the car is called on the search directory
225 to determine whether cdr should not be excluded."
226 :type
'(choice (repeat :tag
"Ignored file" string
)
227 (const :tag
"No ignored files" nil
))
230 (defcustom grep-error-screen-columns nil
231 "*If non-nil, column numbers in grep hits are screen columns.
232 See `compilation-error-screen-columns'"
233 :type
'(choice (const :tag
"Default" nil
)
239 (defcustom grep-setup-hook nil
240 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
244 (defvar grep-mode-map
245 (let ((map (make-sparse-keymap)))
246 (set-keymap-parent map compilation-minor-mode-map
)
247 (define-key map
" " 'scroll-up
)
248 (define-key map
"\^?" 'scroll-down
)
249 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
251 (define-key map
"\r" 'compile-goto-error
) ;; ?
252 (define-key map
"n" 'next-error-no-select
)
253 (define-key map
"p" 'previous-error-no-select
)
254 (define-key map
"{" 'compilation-previous-file
)
255 (define-key map
"}" 'compilation-next-file
)
256 (define-key map
"\t" 'compilation-next-error
)
257 (define-key map
[backtab] 'compilation-previous-error)
259 ;; Set up the menu-bar
260 (define-key map [menu-bar grep]
261 (cons "Grep" (make-sparse-keymap "Grep")))
263 (define-key map [menu-bar grep compilation-kill-compilation]
264 '(menu-item "Kill Grep" kill-compilation
265 :help "Kill the currently running grep process"))
266 (define-key map [menu-bar grep compilation-separator2] '("----"))
267 (define-key map [menu-bar grep compilation-compile]
268 '(menu-item "Compile..." compile
269 :help "Compile the program including the current buffer. Default: run `make'"))
270 (define-key map [menu-bar grep compilation-rgrep]
271 '(menu-item "Recursive grep..." rgrep
272 :help "User-friendly recursive grep in directory tree"))
273 (define-key map [menu-bar grep compilation-lgrep]
274 '(menu-item "Local grep..." lgrep
275 :help "User-friendly grep in a directory"))
276 (define-key map [menu-bar grep compilation-grep-find]
277 '(menu-item "Grep via Find..." grep-find
278 :help "Run grep via find, with user-specified args"))
279 (define-key map [menu-bar grep compilation-grep]
280 '(menu-item "Another grep..." grep
281 :help "Run grep, with user-specified args, and collect output in a buffer."))
282 (define-key map [menu-bar grep compilation-recompile]
283 '(menu-item "Repeat grep" recompile
284 :help "Run grep again"))
285 (define-key map [menu-bar grep compilation-separator2] '("----"))
286 (define-key map [menu-bar grep compilation-first-error]
287 '(menu-item "First Match" first-error
288 :help "Restart at the first match, visit corresponding location"))
289 (define-key map [menu-bar grep compilation-previous-error]
290 '(menu-item "Previous Match" previous-error
291 :help "Visit the previous match and corresponding location"))
292 (define-key map [menu-bar grep compilation-next-error]
293 '(menu-item "Next Match" next-error
294 :help "Visit the next match and corresponding location"))
296 "Keymap for grep buffers.
297 `compilation-minor-mode-map' is a cdr of this.")
299 (defvar grep-mode-tool-bar-map
300 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
301 ;; so don't do anything.
302 (when (keymapp (butlast tool-bar-map))
303 (let ((map (butlast (copy-keymap tool-bar-map)))
304 (help (last tool-bar-map))) ;; Keep Help last in tool bar
306 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
308 :help "Goto previous match")
310 "right-arrow" 'next-error-no-select 'next-error-no-select map
312 :help "Goto next match")
314 "cancel" 'kill-compilation 'kill-compilation map
315 :enable '(let ((buffer (compilation-find-buffer)))
316 (get-buffer-process buffer))
319 "refresh" 'recompile 'recompile map
320 :help "Restart grep")
323 (defalias 'kill-grep 'kill-compilation)
325 ;;;; TODO --- refine this!!
327 ;; (defcustom grep-use-compilation-buffer t
328 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
329 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
330 ;; can be used to navigate between grep matches (the default).
331 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
332 ;; be used to navigate between grep matches."
336 ;; override compilation-last-buffer
337 (defvar grep-last-buffer nil
338 "The most recent grep buffer.
339 A grep buffer becomes most recent when you select Grep mode in it.
340 Notice that using \\[next-error] or \\[compile-goto-error] modifies
341 `complation-last-buffer' rather than `grep-last-buffer'.")
344 (defconst grep-regexp-alist
345 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
347 ;; Rule to match column numbers is commented out since no known grep
349 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
351 ;; Note that we want to use as tight a regexp as we can to try and
352 ;; handle weird file names (with colons in them) as well as possible.
353 ;; E.g. we use [1-9][0-9]* rather than [0-9]+ so as to accept ":034:" in
355 ("^\\(\\(.+?\\):\\([1-9][0-9]*\\):\\).*?\
356 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
358 ;; Calculate column positions (beg . end) of first grep match on a line
360 (setq compilation-error-screen-columns nil)
361 (- (match-beginning 4) (match-end 1)))
363 (lambda () (- (match-end 5) (match-end 1)
364 (- (match-end 4) (match-beginning 4)))))
366 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
367 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
369 (defvar grep-error "grep hit"
370 "Message to print when no matches are found.")
372 ;; Reverse the colors because grep hits are not errors (though we jump there
373 ;; with `next-error'), and unreadable files can't be gone to.
374 (defvar grep-hit-face compilation-info-face
375 "Face name to use for grep hits.")
377 (defvar grep-error-face 'compilation-error
378 "Face name to use for grep error messages.")
380 (defvar grep-match-face 'match
381 "Face name to use for grep matches.")
383 (defvar grep-context-face 'shadow
384 "Face name to use for grep context lines.")
386 (defvar grep-mode-font-lock-keywords
387 '(;; Command output lines.
388 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
389 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
391 ;; remove match from grep-regexp-alist before fontifying
392 ("^Grep[/a-zA-z]* started.*"
393 (0 '(face nil message nil help-echo nil mouse-face nil) t))
394 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
395 (0 '(face nil message nil help-echo nil mouse-face nil) t)
396 (1 compilation-info-face nil t)
397 (2 compilation-warning-face nil t))
398 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
399 (0 '(face nil message nil help-echo nil mouse-face nil) t)
401 (2 grep-error-face nil t))
402 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
403 ;; Highlight grep matches and delete markers
404 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
405 ;; Refontification does not work after the markers have been
406 ;; deleted. So we use the font-lock-face property here as Font
407 ;; Lock does not clear that.
408 (2 (list 'face nil 'font-lock-face grep-match-face))
411 ;; Delete markers with `replace-match' because it updates
412 ;; the match-data, whereas `delete-region' would render it obsolete.
413 (replace-match "" t t nil 3)
414 (replace-match "" t t nil 1))))
415 ("\\(\033\\[[0-9;]*[mK]\\)"
416 ;; Delete all remaining escape sequences
418 (replace-match "" t t nil 1))))
419 "Additional things to highlight in grep output.
420 This gets tacked on the end of the generated expressions.")
423 (defvar grep-program (purecopy "grep")
424 "The default grep program for `grep-command' and `grep-find-command'.
425 This variable's value takes effect when `grep-compute-defaults' is called.")
428 (defvar find-program (purecopy "find")
429 "The default find program for `grep-find-command'.
430 This variable's value takes effect when `grep-compute-defaults' is called.")
433 (defvar xargs-program (purecopy "xargs")
434 "The default xargs program for `grep-find-command'.
435 See `grep-find-use-xargs'.
436 This variable's value takes effect when `grep-compute-defaults' is called.")
439 (defvar grep-find-use-xargs nil
440 "Non-nil means that `grep-find' uses the `xargs' utility by default.
441 If `exec', use `find -exec'.
442 If `gnu', use `find -print0' and `xargs -0'.
443 Any other non-nil value means to use `find -print' and `xargs'.
445 This variable's value takes effect when `grep-compute-defaults' is called.")
447 ;; History of grep commands.
449 (defvar grep-history nil)
451 (defvar grep-find-history nil)
453 ;; History of lgrep and rgrep regexp and files args.
454 (defvar grep-regexp-history nil)
455 (defvar grep-files-history nil)
458 (defun grep-process-setup ()
459 "Setup compilation variables and buffer for `grep'.
460 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
461 (when (eq grep-highlight-matches 'auto-detect)
462 (grep-compute-defaults))
463 (unless (or (eq grep-highlight-matches 'auto-detect)
464 (null grep-highlight-matches))
465 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
466 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
467 (setenv "TERM" "emacs-grep")
468 (setenv "GREP_OPTIONS"
469 (concat (getenv "GREP_OPTIONS")
470 " --color=" (if (eq grep-highlight-matches 'always)
472 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
473 (setenv "GREP_COLOR" "01;31")
474 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
475 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
476 (set (make-local-variable 'compilation-exit-message-function)
477 (lambda (status code msg)
478 (if (eq status 'exit)
480 '("finished (matches found)\n" . "matched"))
482 '("finished with no matches found\n" . "no match"))
486 (run-hooks 'grep-setup-hook))
488 (defun grep-probe (command args &optional func result)
489 (let (process-file-side-effects)
490 (equal (condition-case nil
491 (apply (or func 'process-file) command args)
496 (defun grep-compute-defaults ()
497 ;; Keep default values.
498 (unless grep-host-defaults-alist
500 'grep-host-defaults-alist
502 `((grep-command ,grep-command)
503 (grep-template ,grep-template)
504 (grep-use-null-device ,grep-use-null-device)
505 (grep-find-command ,grep-find-command)
506 (grep-find-template ,grep-find-template)
507 (grep-find-use-xargs ,grep-find-use-xargs)
508 (grep-highlight-matches ,grep-highlight-matches)))))
510 (intern (or (file-remote-p default-directory) "localhost")))
511 (host-defaults (assq host-id grep-host-defaults-alist))
512 (defaults (assq nil grep-host-defaults-alist)))
513 ;; There are different defaults on different hosts. They must be
514 ;; computed for every host once.
515 (dolist (setting '(grep-command grep-template
516 grep-use-null-device grep-find-command
517 grep-find-template grep-find-use-xargs
518 grep-highlight-matches))
520 (cadr (or (assq setting host-defaults)
521 (assq setting defaults)))))
523 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
524 (setq grep-use-null-device
526 (let ((hello-file (expand-file-name "HELLO" data-directory)))
528 (and (if grep-command
529 ;; `grep-command' is already set, so
530 ;; use that for testing.
531 (grep-probe grep-command
532 `(nil t nil "^English" ,hello-file)
533 #'call-process-shell-command)
534 ;; otherwise use `grep-program'
535 (grep-probe grep-program
536 `(nil t nil "-nH" "^English" ,hello-file)))
538 (goto-char (point-min))
540 (concat (regexp-quote hello-file)
541 ":[0-9]+:English")))))))))
542 (unless (and grep-command grep-find-command
543 grep-template grep-find-template)
545 (concat (if grep-use-null-device "-n" "-nH")
546 (if (grep-probe grep-program
547 `(nil nil nil "-e" "foo" ,null-device)
552 (format "%s %s " grep-program grep-options)))
553 (unless grep-template
555 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
556 (unless grep-find-use-xargs
557 (setq grep-find-use-xargs
560 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
561 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
565 (unless grep-find-command
566 (setq grep-find-command
567 (cond ((eq grep-find-use-xargs 'gnu)
568 ;; Windows shells need the program file name
569 ;; after the pipe symbol be quoted if they use
570 ;; forward slashes as directory separators.
571 (format "%s . -type f -print0 | \"%s\" -0 -e %s"
572 find-program xargs-program grep-command))
573 ((eq grep-find-use-xargs 'exec)
574 (let ((cmd0 (format "%s . -type f -exec %s"
575 find-program grep-command)))
577 (format "%s {} %s %s"
579 (shell-quote-argument ";"))
580 (1+ (length cmd0)))))
582 (format "%s . -type f -print | \"%s\" %s"
583 find-program xargs-program grep-command)))))
584 (unless grep-find-template
585 (setq grep-find-template
586 (let ((gcmd (format "%s <C> %s <R>"
587 grep-program grep-options)))
588 (cond ((eq grep-find-use-xargs 'gnu)
589 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 -e %s"
590 find-program xargs-program gcmd))
591 ((eq grep-find-use-xargs 'exec)
592 (format "%s . <X> -type f <F> -exec %s {} %s %s"
593 find-program gcmd null-device
594 (shell-quote-argument ";")))
596 (format "%s . <X> -type f <F> -print | \"%s\" %s"
597 find-program xargs-program gcmd))))))))
598 (when (eq grep-highlight-matches 'auto-detect)
599 (setq grep-highlight-matches
601 (and (grep-probe grep-program '(nil t nil "--help"))
603 (goto-char (point-min))
604 (search-forward "--color" nil t))
605 ;; Windows and DOS pipes fail `isatty' detection in Grep.
606 (if (memq system-type '(windows-nt ms-dos))
609 ;; Save defaults for this host.
610 (setq grep-host-defaults-alist
611 (delete (assq host-id grep-host-defaults-alist)
612 grep-host-defaults-alist))
614 'grep-host-defaults-alist
616 `((grep-command ,grep-command)
617 (grep-template ,grep-template)
618 (grep-use-null-device ,grep-use-null-device)
619 (grep-find-command ,grep-find-command)
620 (grep-find-template ,grep-find-template)
621 (grep-find-use-xargs ,grep-find-use-xargs)
622 (grep-highlight-matches ,grep-highlight-matches))))))
624 (defun grep-tag-default ()
625 (or (and transient-mark-mode mark-active
627 (buffer-substring-no-properties (point) (mark)))
628 (funcall (or find-tag-default-function
629 (get major-mode 'find-tag-default-function)
633 (defun grep-default-command ()
634 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
635 (let ((tag-default (shell-quote-argument (grep-tag-default)))
636 ;; This a regexp to match single shell arguments.
637 ;; Could someone please add comments explaining it?
638 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
639 (grep-default (or (car grep-history) grep-command)))
640 ;; In the default command, find the arg that specifies the pattern.
641 (when (or (string-match
642 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
643 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
645 ;; If the string is not yet complete.
646 (string-match "\\(\\)\\'" grep-default))
647 ;; Maybe we will replace the pattern with the default tag.
648 ;; But first, maybe replace the file name pattern.
650 (unless (or (not (stringp buffer-file-name))
651 (when (match-beginning 2)
655 (file-name-nondirectory
656 (match-string 3 grep-default)))
657 (file-name-nondirectory buffer-file-name)))))
658 (setq grep-default (concat (substring grep-default
659 0 (match-beginning 2))
661 (file-name-extension buffer-file-name))))
662 ;; In case wildcard-to-regexp gets an error
663 ;; from invalid data.
665 ;; Now replace the pattern with the default tag.
666 (replace-match tag-default t t grep-default 1))))
670 (define-compilation-mode grep-mode "Grep"
671 "Sets `grep-last-buffer' and `compilation-window-height'."
672 (setq grep-last-buffer (current-buffer))
673 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
674 (set (make-local-variable 'compilation-error-face)
676 (set (make-local-variable 'compilation-error-regexp-alist)
678 (set (make-local-variable 'compilation-process-setup-function)
680 (set (make-local-variable 'compilation-disable-input) t))
684 (defun grep (command-args)
685 "Run grep, with user-specified args, and collect output in a buffer.
686 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
687 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
688 output buffer, to go to the lines where grep
691 For doing a recursive `grep', see the `rgrep' command. For running
692 `grep' in a specific directory, see `lgrep'.
694 This command uses a special history list for its COMMAND-ARGS, so you
695 can easily repeat a grep command.
697 A prefix argument says to default the argument based upon the current
698 tag the cursor is over, substituting it into the last grep command
699 in the grep command history (or into `grep-command' if that history
703 (grep-compute-defaults)
704 (let ((default (grep-default-command)))
705 (list (read-shell-command "Run grep (like this): "
706 (if current-prefix-arg default grep-command)
708 (if current-prefix-arg nil default))))))
710 ;; Setting process-setup-function makes exit-message-function work
711 ;; even when async processes aren't supported.
712 (compilation-start (if (and grep-use-null-device null-device)
713 (concat command-args " " null-device)
719 (defun grep-find (command-args)
720 "Run grep via find, with user-specified args COMMAND-ARGS.
721 Collect output in a buffer.
722 While find runs asynchronously, you can use the \\[next-error] command
723 to find the text that grep hits refer to.
725 This command uses a special history list for its arguments, so you can
726 easily repeat a find command."
729 (grep-compute-defaults)
730 (if grep-find-command
731 (list (read-shell-command "Run find (like this): "
732 grep-find-command 'grep-find-history))
733 ;; No default was set
735 "compile.el: No `grep-find-command' command available. Press RET.")
738 (let ((null-device nil)) ; see grep
739 (grep command-args))))
742 (defalias 'find-grep 'grep-find)
745 ;; User-friendly interactive API.
747 (defconst grep-expand-keywords
748 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
751 ("<N>" . null-device)
753 ("<R>" . (shell-quote-argument (or regexp ""))))
754 "List of substitutions performed by `grep-expand-template'.
755 If car of an element matches, the cdr is evalled in to get the
756 substitution string. Note dynamic scoping of variables.")
758 (defun grep-expand-template (template &optional regexp files dir excl)
759 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
760 (let ((command template)
761 (cf case-fold-search)
762 (case-fold-search nil))
763 (dolist (kw grep-expand-keywords command)
764 (if (string-match (car kw) command)
767 (or (if (symbolp (cdr kw))
768 (symbol-value (cdr kw))
769 (save-match-data (eval (cdr kw))))
773 (defun grep-read-regexp ()
774 "Read regexp arg for interactive grep."
775 (let ((default (grep-tag-default)))
778 (if (and default (> (length default) 0))
779 (format " (default \"%s\"): " default) ": "))
780 nil 'grep-regexp-history default)))
782 (defun grep-read-files (regexp)
783 "Read files arg for interactive grep."
784 (let* ((bn (or (buffer-file-name)
785 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
788 (file-name-nondirectory bn)))
791 (let ((aliases (remove (assoc "all" grep-files-aliases)
795 (setq alias (car aliases)
796 aliases (cdr aliases))
797 (if (string-match (mapconcat
799 (split-string (cdr alias) nil t)
807 (let ((ext (file-name-extension fn)))
808 (and ext (concat "*." ext)))))
812 (car grep-files-history)
813 (car (car grep-files-aliases))))
814 (files (completing-read
815 (concat "Search for \"" regexp
817 (if default (concat " (default " default ")"))
819 'read-file-name-internal
820 nil nil nil 'grep-files-history
822 (delq nil (append (list default default-alias default-extension)
823 (mapcar 'car grep-files-aliases)))))))
825 (or (cdr (assoc files grep-files-aliases))
829 (defun lgrep (regexp &optional files dir confirm)
830 "Run grep, searching for REGEXP in FILES in directory DIR.
831 The search is limited to file names matching shell pattern FILES.
832 FILES may use abbreviations defined in `grep-files-aliases', e.g.
833 entering `ch' is equivalent to `*.[ch]'.
835 With \\[universal-argument] prefix, you can edit the constructed shell command line
836 before it is executed.
837 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
839 Collect output in a buffer. While grep runs asynchronously, you
840 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
841 in the grep output buffer,
842 to go to the lines where grep found matches.
844 This command shares argument histories with \\[rgrep] and \\[grep]."
847 (grep-compute-defaults)
849 ((and grep-command (equal current-prefix-arg '(16)))
850 (list (read-from-minibuffer "Run: " grep-command
851 nil nil 'grep-history)))
853 (error "grep.el: No `grep-template' available"))
854 (t (let* ((regexp (grep-read-regexp))
855 (files (grep-read-files regexp))
856 (dir (read-directory-name "In directory: "
857 nil default-directory t))
858 (confirm (equal current-prefix-arg '(4))))
859 (list regexp files dir confirm))))))
860 (when (and (stringp regexp) (> (length regexp) 0))
861 (unless (and dir (file-directory-p dir) (file-readable-p dir))
862 (setq dir default-directory))
863 (let ((command regexp))
865 (if (string= command grep-command)
867 (setq dir (file-name-as-directory (expand-file-name dir)))
868 (setq command (grep-expand-template
873 (and grep-find-ignored-files
874 (concat " --exclude="
877 (cond ((stringp ignore)
878 (shell-quote-argument ignore))
880 (and (funcall (car ignore) dir)
881 (shell-quote-argument
883 grep-find-ignored-files
888 (read-from-minibuffer "Confirm: "
889 command nil nil 'grep-history))
890 (add-to-history 'grep-history command))))
892 (let ((default-directory dir))
893 ;; Setting process-setup-function makes exit-message-function work
894 ;; even when async processes aren't supported.
895 (compilation-start (if (and grep-use-null-device null-device)
896 (concat command " " null-device)
899 (if (eq next-error-last-buffer (current-buffer))
900 (setq default-directory dir))))))
903 (defvar find-name-arg) ; not autoloaded but defined in find-dired
906 (defun rgrep (regexp &optional files dir confirm)
907 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
908 The search is limited to file names matching shell pattern FILES.
909 FILES may use abbreviations defined in `grep-files-aliases', e.g.
910 entering `ch' is equivalent to `*.[ch]'.
912 With \\[universal-argument] prefix, you can edit the constructed shell command line
913 before it is executed.
914 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
916 Collect output in a buffer. While find runs asynchronously, you
917 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
918 in the grep output buffer,
919 to go to the lines where grep found matches.
921 This command shares argument histories with \\[lgrep] and \\[grep-find]."
924 (grep-compute-defaults)
926 ((and grep-find-command (equal current-prefix-arg '(16)))
927 (list (read-from-minibuffer "Run: " grep-find-command
928 nil nil 'grep-find-history)))
929 ((not grep-find-template)
930 (error "grep.el: No `grep-find-template' available"))
931 (t (let* ((regexp (grep-read-regexp))
932 (files (grep-read-files regexp))
933 (dir (read-directory-name "Base directory: "
934 nil default-directory t))
935 (confirm (equal current-prefix-arg '(4))))
936 (list regexp files dir confirm))))))
937 (when (and (stringp regexp) (> (length regexp) 0))
938 (unless (and dir (file-directory-p dir) (file-readable-p dir))
939 (setq dir default-directory))
941 (if (not (string= regexp grep-find-command))
942 (compilation-start regexp 'grep-mode))
943 (setq dir (file-name-as-directory (expand-file-name dir)))
944 (require 'find-dired) ; for `find-name-arg'
945 (let ((command (grep-expand-template
948 (concat (shell-quote-argument "(")
949 " " find-name-arg " "
950 (mapconcat #'shell-quote-argument
952 (concat " -o " find-name-arg " "))
954 (shell-quote-argument ")"))
957 (and grep-find-ignored-directories
958 (concat (shell-quote-argument "(")
959 ;; we should use shell-quote-argument here
963 (cond ((stringp ignore)
964 (shell-quote-argument
965 (concat "*/" ignore)))
967 (and (funcall (car ignore) dir)
968 (shell-quote-argument
971 grep-find-ignored-directories
974 (shell-quote-argument ")")
976 (and grep-find-ignored-files
977 (concat (shell-quote-argument "(")
978 ;; we should use shell-quote-argument here
982 (cond ((stringp ignore)
983 (shell-quote-argument ignore))
985 (and (funcall (car ignore) dir)
986 (shell-quote-argument
988 grep-find-ignored-files
991 (shell-quote-argument ")")
996 (read-from-minibuffer "Confirm: "
997 command nil nil 'grep-find-history))
998 (add-to-history 'grep-find-history command))
999 (let ((default-directory dir))
1000 (compilation-start command 'grep-mode))
1001 ;; Set default-directory if we started rgrep in the *grep* buffer.
1002 (if (eq next-error-last-buffer (current-buffer))
1003 (setq default-directory dir)))))))
1006 (defun zrgrep (regexp &optional files dir confirm grep-find-template)
1007 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1008 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1009 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1012 ;; Compute standard default values.
1013 (grep-compute-defaults)
1014 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1015 ;; for grep program "zgrep", but not changing global values.
1016 (let ((grep-program "zgrep")
1017 ;; Don't change global values for variables computed
1018 ;; by `grep-compute-defaults'.
1019 (grep-find-template nil)
1020 (grep-find-command nil)
1021 (grep-host-defaults-alist nil)
1022 ;; Use for `grep-read-files'
1023 (grep-files-aliases '(("all" . "* .*")
1025 ;; Recompute defaults using let-bound values above.
1026 (grep-compute-defaults)
1028 ((and grep-find-command (equal current-prefix-arg '(16)))
1029 (list (read-from-minibuffer "Run: " grep-find-command
1030 nil nil 'grep-find-history)))
1031 ((not grep-find-template)
1032 (error "grep.el: No `grep-find-template' available"))
1033 (t (let* ((regexp (grep-read-regexp))
1034 (files (grep-read-files regexp))
1035 (dir (read-directory-name "Base directory: "
1036 nil default-directory t))
1037 (confirm (equal current-prefix-arg '(4))))
1038 (list regexp files dir confirm grep-find-template)))))))
1039 ;; Set `grep-highlight-matches' to `always'
1040 ;; since `zgrep' puts filters in the grep output.
1041 (let ((grep-highlight-matches 'always))
1042 ;; `rgrep' uses the dynamically bound value `grep-find-template'
1043 ;; from the argument `grep-find-template' whose value is computed
1044 ;; in the `interactive' spec.
1045 (rgrep regexp files dir confirm)))
1048 (defalias 'rzgrep 'zrgrep)
1052 ;;; grep.el ends here