1 ;;; grep.el --- run Grep as inferior of Emacs, parse match messages
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2011
4 ;; Free Software Foundation, Inc.
6 ;; Author: Roland McGrath <roland@gnu.org>
8 ;; Keywords: tools, processes
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides the grep facilities documented in the Emacs
36 "Run grep as inferior of Emacs, parse error messages."
40 (defvar grep-host-defaults-alist nil
41 "Default values depending on target host.
42 `grep-compute-defaults' returns default values for every local or
43 remote host `grep' runs. These values can differ from host to
44 host. Once computed, the default values are kept here in order
45 to avoid computing them again.")
47 (defun grep-apply-setting (symbol value)
48 "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
49 SYMBOL should be one of `grep-command', `grep-template',
50 `grep-use-null-device', `grep-find-command',
51 `grep-find-template', `grep-find-use-xargs', or
52 `grep-highlight-matches'."
53 (when grep-host-defaults-alist
55 (intern (or (file-remote-p default-directory) "localhost")))
56 (host-defaults (assq host-id grep-host-defaults-alist))
57 (defaults (assq nil grep-host-defaults-alist)))
58 (setcar (cdr (assq symbol host-defaults)) value)
59 (setcar (cdr (assq symbol defaults)) value)))
60 (set-default symbol value))
63 (defcustom grep-window-height nil
64 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
65 :type '(choice (const :tag "Default" nil)
70 (defcustom grep-highlight-matches 'auto-detect
71 "Use special markers to highlight grep matches.
73 Some grep programs are able to surround matches with special
74 markers in grep output. Such markers can be used to highlight
77 This option sets the environment variable GREP_COLORS to specify
78 markers for highlighting and GREP_OPTIONS to add the --color
79 option in front of any explicit grep options before starting
82 When this option is `auto', grep uses `--color=auto' to highlight
83 matches only when it outputs to a terminal (when `grep' is the last
84 command in the pipe), thus avoiding the use of any potentially-harmful
85 escape sequences when standard output goes to a file or pipe.
87 To make grep highlight matches even into a pipe, you need the option
88 `always' that forces grep to use `--color=always' to unconditionally
89 output escape sequences.
91 In interactive usage, the actual value of this variable is set up
92 by `grep-compute-defaults' when the default value is `auto-detect'.
93 To change the default value, use Customize or call the function
94 `grep-apply-setting'."
95 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
96 (const :tag "Highlight matches with grep markers" t)
97 (const :tag "Use --color=always" always)
98 (const :tag "Use --color=auto" auto)
99 (other :tag "Not Set" auto-detect))
100 :set 'grep-apply-setting
104 (defcustom grep-scroll-output nil
105 "*Non-nil to scroll the *grep* buffer window as output appears.
107 Setting it causes the grep commands to put point at the end of their
108 output window so that the end of the output is always visible rather
115 (defcustom grep-command nil
116 "The default grep command for \\[grep].
117 If the grep program used supports an option to always include file names
118 in its output (such as the `-H' option to GNU grep), it's a good idea to
119 include it when specifying `grep-command'.
121 In interactive usage, the actual value of this variable is set up
122 by `grep-compute-defaults'; to change the default value, use
123 Customize or call the function `grep-apply-setting'."
124 :type '(choice string
125 (const :tag "Not Set" nil))
126 :set 'grep-apply-setting
129 (defcustom grep-template nil
130 "The default command to run for \\[lgrep].
131 The following place holders should be present in the string:
132 <C> - place to put -i if case insensitive grep.
133 <F> - file names and wildcards to search.
134 <X> - file names and wildcards to exclude.
135 <R> - the regular expression searched for.
136 <N> - place to insert null-device.
138 In interactive usage, the actual value of this variable is set up
139 by `grep-compute-defaults'; to change the default value, use
140 Customize or call the function `grep-apply-setting'."
141 :type '(choice string
142 (const :tag "Not Set" nil))
143 :set 'grep-apply-setting
147 (defcustom grep-use-null-device 'auto-detect
148 "If t, append the value of `null-device' to `grep' commands.
149 This is done to ensure that the output of grep includes the filename of
150 any match in the case where only a single file is searched, and is not
151 necessary if the grep program used supports the `-H' option.
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 (const :tag "Do Not Append Null Device" nil)
157 (const :tag "Append Null Device" t)
158 (other :tag "Not Set" auto-detect))
159 :set 'grep-apply-setting
163 (defcustom grep-find-command nil
164 "The default find command for \\[grep-find].
165 In interactive usage, the actual value of this variable is set up
166 by `grep-compute-defaults'; to change the default value, use
167 Customize or call the function `grep-apply-setting'."
168 :type '(choice string
169 (const :tag "Not Set" nil))
170 :set 'grep-apply-setting
173 (defcustom grep-find-template nil
174 "The default command to run for \\[rgrep].
175 The following place holders should be present in the string:
176 <D> - base directory for find
177 <X> - find options to restrict or expand the directory list
178 <F> - find options to limit the files matched
179 <C> - place to put -i if case insensitive grep
180 <R> - the regular expression searched for.
181 In interactive usage, the actual value of this variable is set up
182 by `grep-compute-defaults'; to change the default value, use
183 Customize or call the function `grep-apply-setting'."
184 :type '(choice string
185 (const :tag "Not Set" nil))
186 :set 'grep-apply-setting
190 (defcustom grep-files-aliases
195 ("cc" . "*.cc *.cxx *.cpp *.C *.CC *.c++")
196 ("cchh" . "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
197 ("hh" . "*.hxx *.hpp *.[Hh] *.HH *.h++")
199 ("l" . "[Cc]hange[Ll]og*")
200 ("m" . "[Mm]akefile*")
204 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
208 (defcustom grep-find-ignored-directories
209 vc-directory-exclusion-list
210 "*List of names of sub-directories which `rgrep' shall not recurse into.
211 If an element is a cons cell, the car is called on the search directory
212 to determine whether cdr should not be recursed into."
213 :type '(choice (repeat :tag "Ignored directories" string)
214 (const :tag "No ignored directories" nil))
217 (defcustom grep-find-ignored-files
218 (cons ".#*" (delq nil (mapcar (lambda (s)
219 (unless (string-match-p "/\\'" s)
221 completion-ignored-extensions)))
222 "*List of file names which `rgrep' and `lgrep' shall exclude.
223 If an element is a cons cell, the car is called on the search directory
224 to determine whether cdr should not be excluded."
225 :type '(choice (repeat :tag "Ignored file" string)
226 (const :tag "No ignored files" nil))
229 (defcustom grep-error-screen-columns nil
230 "*If non-nil, column numbers in grep hits are screen columns.
231 See `compilation-error-screen-columns'"
232 :type '(choice (const :tag "Default" nil)
238 (defcustom grep-setup-hook nil
239 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
243 (defvar grep-mode-map
244 (let ((map (make-sparse-keymap)))
245 (set-keymap-parent map compilation-minor-mode-map)
246 (define-key map " " 'scroll-up)
247 (define-key map "\^?" 'scroll-down)
248 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
250 (define-key map "\r" 'compile-goto-error) ;; ?
251 (define-key map "n" 'next-error-no-select)
252 (define-key map "p" 'previous-error-no-select)
253 (define-key map "{" 'compilation-previous-file)
254 (define-key map "}" 'compilation-next-file)
255 (define-key map "\t" 'compilation-next-error)
256 (define-key map [backtab] 'compilation-previous-error)
258 ;; Set up the menu-bar
259 (define-key map [menu-bar grep]
260 (cons "Grep" (make-sparse-keymap "Grep")))
262 (define-key map [menu-bar grep compilation-kill-compilation]
263 '(menu-item "Kill Grep" kill-compilation
264 :help "Kill the currently running grep process"))
265 (define-key map [menu-bar grep compilation-separator2] '("----"))
266 (define-key map [menu-bar grep compilation-compile]
267 '(menu-item "Compile..." compile
268 :help "Compile the program including the current buffer. Default: run `make'"))
269 (define-key map [menu-bar grep compilation-rgrep]
270 '(menu-item "Recursive grep..." rgrep
271 :help "User-friendly recursive grep in directory tree"))
272 (define-key map [menu-bar grep compilation-lgrep]
273 '(menu-item "Local grep..." lgrep
274 :help "User-friendly grep in a directory"))
275 (define-key map [menu-bar grep compilation-grep-find]
276 '(menu-item "Grep via Find..." grep-find
277 :help "Run grep via find, with user-specified args"))
278 (define-key map [menu-bar grep compilation-grep]
279 '(menu-item "Another grep..." grep
280 :help "Run grep, with user-specified args, and collect output in a buffer."))
281 (define-key map [menu-bar grep compilation-recompile]
282 '(menu-item "Repeat grep" recompile
283 :help "Run grep again"))
284 (define-key map [menu-bar grep compilation-separator2] '("----"))
285 (define-key map [menu-bar grep compilation-first-error]
286 '(menu-item "First Match" first-error
287 :help "Restart at the first match, visit corresponding location"))
288 (define-key map [menu-bar grep compilation-previous-error]
289 '(menu-item "Previous Match" previous-error
290 :help "Visit the previous match and corresponding location"))
291 (define-key map [menu-bar grep compilation-next-error]
292 '(menu-item "Next Match" next-error
293 :help "Visit the next match and corresponding location"))
295 "Keymap for grep buffers.
296 `compilation-minor-mode-map' is a cdr of this.")
298 (defvar grep-mode-tool-bar-map
299 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
300 ;; so don't do anything.
301 (when (keymapp (butlast tool-bar-map))
302 (let ((map (butlast (copy-keymap tool-bar-map)))
303 (help (last tool-bar-map))) ;; Keep Help last in tool bar
305 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
307 :help "Goto previous match")
309 "right-arrow" 'next-error-no-select 'next-error-no-select map
311 :help "Goto next match")
313 "cancel" 'kill-compilation 'kill-compilation map
314 :enable '(let ((buffer (compilation-find-buffer)))
315 (get-buffer-process buffer))
318 "refresh" 'recompile 'recompile map
319 :help "Restart grep")
322 (defalias 'kill-grep 'kill-compilation)
324 ;;;; TODO --- refine this!!
326 ;; (defcustom grep-use-compilation-buffer t
327 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
328 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
329 ;; can be used to navigate between grep matches (the default).
330 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
331 ;; be used to navigate between grep matches."
335 ;; override compilation-last-buffer
336 (defvar grep-last-buffer nil
337 "The most recent grep buffer.
338 A grep buffer becomes most recent when you select Grep mode in it.
339 Notice that using \\[next-error] or \\[compile-goto-error] modifies
340 `complation-last-buffer' rather than `grep-last-buffer'.")
343 (defconst grep-regexp-alist
344 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
346 ;; Rule to match column numbers is commented out since no known grep
348 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
350 ;; Note that we want to use as tight a regexp as we can to try and
351 ;; handle weird file names (with colons in them) as well as possible.
352 ;; E.g. we use [1-9][0-9]* rather than [0-9]+ so as to accept ":034:" in
354 ("^\\(\\(.+?\\):\\([1-9][0-9]*\\):\\).*?\
355 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
357 ;; Calculate column positions (beg . end) of first grep match on a line
359 (setq compilation-error-screen-columns nil)
360 (- (match-beginning 4) (match-end 1)))
362 (lambda () (- (match-end 5) (match-end 1)
363 (- (match-end 4) (match-beginning 4)))))
365 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
366 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
368 (defvar grep-error "grep hit"
369 "Message to print when no matches are found.")
371 ;; Reverse the colors because grep hits are not errors (though we jump there
372 ;; with `next-error'), and unreadable files can't be gone to.
373 (defvar grep-hit-face compilation-info-face
374 "Face name to use for grep hits.")
376 (defvar grep-error-face 'compilation-error
377 "Face name to use for grep error messages.")
379 (defvar grep-match-face 'match
380 "Face name to use for grep matches.")
382 (defvar grep-context-face 'shadow
383 "Face name to use for grep context lines.")
385 (defvar grep-mode-font-lock-keywords
386 '(;; Command output lines.
387 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
388 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
390 ;; remove match from grep-regexp-alist before fontifying
391 ("^Grep[/a-zA-z]* started.*"
392 (0 '(face nil message nil help-echo nil mouse-face nil) t))
393 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
394 (0 '(face nil message nil help-echo nil mouse-face nil) t)
395 (1 compilation-info-face nil t)
396 (2 compilation-warning-face nil t))
397 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
398 (0 '(face nil message nil help-echo nil mouse-face nil) t)
400 (2 grep-error-face nil t))
401 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
402 ;; Highlight grep matches and delete markers
403 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
404 ;; Refontification does not work after the markers have been
405 ;; deleted. So we use the font-lock-face property here as Font
406 ;; Lock does not clear that.
407 (2 (list 'face nil 'font-lock-face grep-match-face))
410 ;; Delete markers with `replace-match' because it updates
411 ;; the match-data, whereas `delete-region' would render it obsolete.
412 (replace-match "" t t nil 3)
413 (replace-match "" t t nil 1))))
414 ("\\(\033\\[[0-9;]*[mK]\\)"
415 ;; Delete all remaining escape sequences
417 (replace-match "" t t nil 1))))
418 "Additional things to highlight in grep output.
419 This gets tacked on the end of the generated expressions.")
422 (defvar grep-program (purecopy "grep")
423 "The default grep program for `grep-command' and `grep-find-command'.
424 This variable's value takes effect when `grep-compute-defaults' is called.")
427 (defvar find-program (purecopy "find")
428 "The default find program for `grep-find-command'.
429 This variable's value takes effect when `grep-compute-defaults' is called.")
432 (defvar xargs-program (purecopy "xargs")
433 "The default xargs program for `grep-find-command'.
434 See `grep-find-use-xargs'.
435 This variable's value takes effect when `grep-compute-defaults' is called.")
438 (defvar grep-find-use-xargs nil
439 "Non-nil means that `grep-find' uses the `xargs' utility by default.
440 If `exec', use `find -exec'.
441 If `gnu', use `find -print0' and `xargs -0'.
442 Any other non-nil value means to use `find -print' and `xargs'.
444 This variable's value takes effect when `grep-compute-defaults' is called.")
446 ;; History of grep commands.
448 (defvar grep-history nil)
450 (defvar grep-find-history nil)
452 ;; History of lgrep and rgrep regexp and files args.
453 (defvar grep-regexp-history nil)
454 (defvar grep-files-history nil)
457 (defun grep-process-setup ()
458 "Setup compilation variables and buffer for `grep'.
459 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
460 (when (eq grep-highlight-matches 'auto-detect)
461 (grep-compute-defaults))
462 (unless (or (eq grep-highlight-matches 'auto-detect)
463 (null grep-highlight-matches))
464 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
465 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
466 (setenv "TERM" "emacs-grep")
467 (setenv "GREP_OPTIONS"
468 (concat (getenv "GREP_OPTIONS")
469 " --color=" (if (eq grep-highlight-matches 'always)
471 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
472 (setenv "GREP_COLOR" "01;31")
473 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
474 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
475 (set (make-local-variable 'compilation-exit-message-function)
476 (lambda (status code msg)
477 (if (eq status 'exit)
479 '("finished (matches found)\n" . "matched"))
481 '("finished with no matches found\n" . "no match"))
485 (run-hooks 'grep-setup-hook))
487 (defun grep-probe (command args &optional func result)
488 (let (process-file-side-effects)
489 (equal (condition-case nil
490 (apply (or func 'process-file) command args)
495 (defun grep-compute-defaults ()
496 ;; Keep default values.
497 (unless grep-host-defaults-alist
499 'grep-host-defaults-alist
501 `((grep-command ,grep-command)
502 (grep-template ,grep-template)
503 (grep-use-null-device ,grep-use-null-device)
504 (grep-find-command ,grep-find-command)
505 (grep-find-template ,grep-find-template)
506 (grep-find-use-xargs ,grep-find-use-xargs)
507 (grep-highlight-matches ,grep-highlight-matches)))))
509 (intern (or (file-remote-p default-directory) "localhost")))
510 (host-defaults (assq host-id grep-host-defaults-alist))
511 (defaults (assq nil grep-host-defaults-alist)))
512 ;; There are different defaults on different hosts. They must be
513 ;; computed for every host once.
514 (dolist (setting '(grep-command grep-template
515 grep-use-null-device grep-find-command
516 grep-find-template grep-find-use-xargs
517 grep-highlight-matches))
519 (cadr (or (assq setting host-defaults)
520 (assq setting defaults)))))
522 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
523 (setq grep-use-null-device
525 (let ((hello-file (expand-file-name "HELLO" data-directory)))
527 (and (if grep-command
528 ;; `grep-command' is already set, so
529 ;; use that for testing.
530 (grep-probe grep-command
531 `(nil t nil "^English" ,hello-file)
532 #'call-process-shell-command)
533 ;; otherwise use `grep-program'
534 (grep-probe grep-program
535 `(nil t nil "-nH" "^English" ,hello-file)))
537 (goto-char (point-min))
539 (concat (regexp-quote hello-file)
540 ":[0-9]+:English")))))))))
541 (unless (and grep-command grep-find-command
542 grep-template grep-find-template)
544 (concat (if grep-use-null-device "-n" "-nH")
545 (if (grep-probe grep-program
546 `(nil nil nil "-e" "foo" ,null-device)
551 (format "%s %s " grep-program grep-options)))
552 (unless grep-template
554 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
555 (unless grep-find-use-xargs
556 (setq grep-find-use-xargs
559 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
560 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
564 (unless grep-find-command
565 (setq grep-find-command
566 (cond ((eq grep-find-use-xargs 'gnu)
567 ;; Windows shells need the program file name
568 ;; after the pipe symbol be quoted if they use
569 ;; forward slashes as directory separators.
570 (format "%s . -type f -print0 | \"%s\" -0 -e %s"
571 find-program xargs-program grep-command))
572 ((eq grep-find-use-xargs 'exec)
573 (let ((cmd0 (format "%s . -type f -exec %s"
574 find-program grep-command)))
576 (format "%s {} %s %s"
578 (shell-quote-argument ";"))
579 (1+ (length cmd0)))))
581 (format "%s . -type f -print | \"%s\" %s"
582 find-program xargs-program grep-command)))))
583 (unless grep-find-template
584 (setq grep-find-template
585 (let ((gcmd (format "%s <C> %s <R>"
586 grep-program grep-options)))
587 (cond ((eq grep-find-use-xargs 'gnu)
588 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 -e %s"
589 find-program xargs-program gcmd))
590 ((eq grep-find-use-xargs 'exec)
591 (format "%s . <X> -type f <F> -exec %s {} %s %s"
592 find-program gcmd null-device
593 (shell-quote-argument ";")))
595 (format "%s . <X> -type f <F> -print | \"%s\" %s"
596 find-program xargs-program gcmd))))))))
597 (when (eq grep-highlight-matches 'auto-detect)
598 (setq grep-highlight-matches
600 (and (grep-probe grep-program '(nil t nil "--help"))
602 (goto-char (point-min))
603 (search-forward "--color" nil t))
604 ;; Windows and DOS pipes fail `isatty' detection in Grep.
605 (if (memq system-type '(windows-nt ms-dos))
608 ;; Save defaults for this host.
609 (setq grep-host-defaults-alist
610 (delete (assq host-id grep-host-defaults-alist)
611 grep-host-defaults-alist))
613 'grep-host-defaults-alist
615 `((grep-command ,grep-command)
616 (grep-template ,grep-template)
617 (grep-use-null-device ,grep-use-null-device)
618 (grep-find-command ,grep-find-command)
619 (grep-find-template ,grep-find-template)
620 (grep-find-use-xargs ,grep-find-use-xargs)
621 (grep-highlight-matches ,grep-highlight-matches))))))
623 (defun grep-tag-default ()
624 (or (and transient-mark-mode mark-active
626 (buffer-substring-no-properties (point) (mark)))
627 (funcall (or find-tag-default-function
628 (get major-mode 'find-tag-default-function)
632 (defun grep-default-command ()
633 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
634 (let ((tag-default (shell-quote-argument (grep-tag-default)))
635 ;; This a regexp to match single shell arguments.
636 ;; Could someone please add comments explaining it?
637 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
638 (grep-default (or (car grep-history) grep-command)))
639 ;; In the default command, find the arg that specifies the pattern.
640 (when (or (string-match
641 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
642 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
644 ;; If the string is not yet complete.
645 (string-match "\\(\\)\\'" grep-default))
646 ;; Maybe we will replace the pattern with the default tag.
647 ;; But first, maybe replace the file name pattern.
649 (unless (or (not (stringp buffer-file-name))
650 (when (match-beginning 2)
654 (file-name-nondirectory
655 (match-string 3 grep-default)))
656 (file-name-nondirectory buffer-file-name)))))
657 (setq grep-default (concat (substring grep-default
658 0 (match-beginning 2))
660 (file-name-extension buffer-file-name))))
661 ;; In case wildcard-to-regexp gets an error
662 ;; from invalid data.
664 ;; Now replace the pattern with the default tag.
665 (replace-match tag-default t t grep-default 1))))
669 (define-compilation-mode grep-mode "Grep"
670 "Sets `grep-last-buffer' and `compilation-window-height'."
671 (setq grep-last-buffer (current-buffer))
672 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
673 (set (make-local-variable 'compilation-error-face)
675 (set (make-local-variable 'compilation-error-regexp-alist)
677 (set (make-local-variable 'compilation-process-setup-function)
679 (set (make-local-variable 'compilation-disable-input) t))
683 (defun grep (command-args)
684 "Run grep, with user-specified args, and collect output in a buffer.
685 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
686 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
687 output buffer, to go to the lines where grep
690 For doing a recursive `grep', see the `rgrep' command. For running
691 `grep' in a specific directory, see `lgrep'.
693 This command uses a special history list for its COMMAND-ARGS, so you
694 can easily repeat a grep command.
696 A prefix argument says to default the argument based upon the current
697 tag the cursor is over, substituting it into the last grep command
698 in the grep command history (or into `grep-command' if that history
702 (grep-compute-defaults)
703 (let ((default (grep-default-command)))
704 (list (read-shell-command "Run grep (like this): "
705 (if current-prefix-arg default grep-command)
707 (if current-prefix-arg nil default))))))
709 ;; Setting process-setup-function makes exit-message-function work
710 ;; even when async processes aren't supported.
711 (compilation-start (if (and grep-use-null-device null-device)
712 (concat command-args " " null-device)
718 (defun grep-find (command-args)
719 "Run grep via find, with user-specified args COMMAND-ARGS.
720 Collect output in a buffer.
721 While find runs asynchronously, you can use the \\[next-error] command
722 to find the text that grep hits refer to.
724 This command uses a special history list for its arguments, so you can
725 easily repeat a find command."
728 (grep-compute-defaults)
729 (if grep-find-command
730 (list (read-shell-command "Run find (like this): "
731 grep-find-command 'grep-find-history))
732 ;; No default was set
734 "compile.el: No `grep-find-command' command available. Press RET.")
737 (let ((null-device nil)) ; see grep
738 (grep command-args))))
741 (defalias 'find-grep 'grep-find)
744 ;; User-friendly interactive API.
746 (defconst grep-expand-keywords
747 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
750 ("<N>" . null-device)
752 ("<R>" . (shell-quote-argument (or regexp ""))))
753 "List of substitutions performed by `grep-expand-template'.
754 If car of an element matches, the cdr is evalled in to get the
755 substitution string. Note dynamic scoping of variables.")
757 (defun grep-expand-template (template &optional regexp files dir excl)
758 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
759 (let ((command template)
760 (cf case-fold-search)
761 (case-fold-search nil))
762 (dolist (kw grep-expand-keywords command)
763 (if (string-match (car kw) command)
766 (or (if (symbolp (cdr kw))
767 (symbol-value (cdr kw))
768 (save-match-data (eval (cdr kw))))
772 (defun grep-read-regexp ()
773 "Read regexp arg for interactive grep."
774 (let ((default (grep-tag-default)))
777 (if (and default (> (length default) 0))
778 (format " (default \"%s\"): " default) ": "))
779 nil 'grep-regexp-history default)))
781 (defun grep-read-files (regexp)
782 "Read files arg for interactive grep."
783 (let* ((bn (or (buffer-file-name)
784 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
787 (file-name-nondirectory bn)))
790 (let ((aliases (remove (assoc "all" grep-files-aliases)
794 (setq alias (car aliases)
795 aliases (cdr aliases))
796 (if (string-match (mapconcat
798 (split-string (cdr alias) nil t)
806 (let ((ext (file-name-extension fn)))
807 (and ext (concat "*." ext)))))
811 (car grep-files-history)
812 (car (car grep-files-aliases))))
813 (files (completing-read
814 (concat "Search for \"" regexp
816 (if default (concat " (default " default ")"))
818 'read-file-name-internal
819 nil nil nil 'grep-files-history
821 (delq nil (append (list default default-alias default-extension)
822 (mapcar 'car grep-files-aliases)))))))
824 (or (cdr (assoc files grep-files-aliases))
828 (defun lgrep (regexp &optional files dir confirm)
829 "Run grep, searching for REGEXP in FILES in directory DIR.
830 The search is limited to file names matching shell pattern FILES.
831 FILES may use abbreviations defined in `grep-files-aliases', e.g.
832 entering `ch' is equivalent to `*.[ch]'.
834 With \\[universal-argument] prefix, you can edit the constructed shell command line
835 before it is executed.
836 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
838 Collect output in a buffer. While grep runs asynchronously, you
839 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
840 in the grep output buffer,
841 to go to the lines where grep found matches.
843 This command shares argument histories with \\[rgrep] and \\[grep]."
846 (grep-compute-defaults)
848 ((and grep-command (equal current-prefix-arg '(16)))
849 (list (read-from-minibuffer "Run: " grep-command
850 nil nil 'grep-history)))
852 (error "grep.el: No `grep-template' available"))
853 (t (let* ((regexp (grep-read-regexp))
854 (files (grep-read-files regexp))
855 (dir (read-directory-name "In directory: "
856 nil default-directory t))
857 (confirm (equal current-prefix-arg '(4))))
858 (list regexp files dir confirm))))))
859 (when (and (stringp regexp) (> (length regexp) 0))
860 (unless (and dir (file-directory-p dir) (file-readable-p dir))
861 (setq dir default-directory))
862 (let ((command regexp))
864 (if (string= command grep-command)
866 (setq dir (file-name-as-directory (expand-file-name dir)))
867 (setq command (grep-expand-template
872 (and grep-find-ignored-files
873 (concat " --exclude="
876 (cond ((stringp ignore)
877 (shell-quote-argument ignore))
879 (and (funcall (car ignore) dir)
880 (shell-quote-argument
882 grep-find-ignored-files
887 (read-from-minibuffer "Confirm: "
888 command nil nil 'grep-history))
889 (add-to-history 'grep-history command))))
891 (let ((default-directory dir))
892 ;; Setting process-setup-function makes exit-message-function work
893 ;; even when async processes aren't supported.
894 (compilation-start (if (and grep-use-null-device null-device)
895 (concat command " " null-device)
898 (if (eq next-error-last-buffer (current-buffer))
899 (setq default-directory dir))))))
902 (defvar find-name-arg) ; not autoloaded but defined in find-dired
905 (defun rgrep (regexp &optional files dir confirm)
906 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
907 The search is limited to file names matching shell pattern FILES.
908 FILES may use abbreviations defined in `grep-files-aliases', e.g.
909 entering `ch' is equivalent to `*.[ch]'.
911 With \\[universal-argument] prefix, you can edit the constructed shell command line
912 before it is executed.
913 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
915 Collect output in a buffer. While find runs asynchronously, you
916 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
917 in the grep output buffer,
918 to go to the lines where grep found matches.
920 This command shares argument histories with \\[lgrep] and \\[grep-find]."
923 (grep-compute-defaults)
925 ((and grep-find-command (equal current-prefix-arg '(16)))
926 (list (read-from-minibuffer "Run: " grep-find-command
927 nil nil 'grep-find-history)))
928 ((not grep-find-template)
929 (error "grep.el: No `grep-find-template' available"))
930 (t (let* ((regexp (grep-read-regexp))
931 (files (grep-read-files regexp))
932 (dir (read-directory-name "Base directory: "
933 nil default-directory t))
934 (confirm (equal current-prefix-arg '(4))))
935 (list regexp files dir confirm))))))
936 (when (and (stringp regexp) (> (length regexp) 0))
937 (unless (and dir (file-directory-p dir) (file-readable-p dir))
938 (setq dir default-directory))
940 (if (not (string= regexp grep-find-command))
941 (compilation-start regexp 'grep-mode))
942 (setq dir (file-name-as-directory (expand-file-name dir)))
943 (require 'find-dired) ; for `find-name-arg'
944 (let ((command (grep-expand-template
947 (concat (shell-quote-argument "(")
948 " " find-name-arg " "
949 (mapconcat #'shell-quote-argument
951 (concat " -o " find-name-arg " "))
953 (shell-quote-argument ")"))
956 (and grep-find-ignored-directories
957 (concat (shell-quote-argument "(")
958 ;; we should use shell-quote-argument here
962 (cond ((stringp ignore)
963 (shell-quote-argument
964 (concat "*/" ignore)))
966 (and (funcall (car ignore) dir)
967 (shell-quote-argument
970 grep-find-ignored-directories
973 (shell-quote-argument ")")
975 (and grep-find-ignored-files
976 (concat (shell-quote-argument "(")
977 ;; we should use shell-quote-argument here
981 (cond ((stringp ignore)
982 (shell-quote-argument ignore))
984 (and (funcall (car ignore) dir)
985 (shell-quote-argument
987 grep-find-ignored-files
990 (shell-quote-argument ")")
995 (read-from-minibuffer "Confirm: "
996 command nil nil 'grep-find-history))
997 (add-to-history 'grep-find-history command))
998 (let ((default-directory dir))
999 (compilation-start command 'grep-mode))
1000 ;; Set default-directory if we started rgrep in the *grep* buffer.
1001 (if (eq next-error-last-buffer (current-buffer))
1002 (setq default-directory dir)))))))
1005 (defun zrgrep (regexp &optional files dir confirm grep-find-template)
1006 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1007 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1008 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1011 ;; Compute standard default values.
1012 (grep-compute-defaults)
1013 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1014 ;; for grep program "zgrep", but not changing global values.
1015 (let ((grep-program "zgrep")
1016 ;; Don't change global values for variables computed
1017 ;; by `grep-compute-defaults'.
1018 (grep-find-template nil)
1019 (grep-find-command nil)
1020 (grep-host-defaults-alist nil)
1021 ;; Use for `grep-read-files'
1022 (grep-files-aliases '(("all" . "* .*")
1024 ;; Recompute defaults using let-bound values above.
1025 (grep-compute-defaults)
1027 ((and grep-find-command (equal current-prefix-arg '(16)))
1028 (list (read-from-minibuffer "Run: " grep-find-command
1029 nil nil 'grep-find-history)))
1030 ((not grep-find-template)
1031 (error "grep.el: No `grep-find-template' available"))
1032 (t (let* ((regexp (grep-read-regexp))
1033 (files (grep-read-files regexp))
1034 (dir (read-directory-name "Base directory: "
1035 nil default-directory t))
1036 (confirm (equal current-prefix-arg '(4))))
1037 (list regexp files dir confirm grep-find-template)))))))
1038 ;; Set `grep-highlight-matches' to `always'
1039 ;; since `zgrep' puts filters in the grep output.
1040 (let ((grep-highlight-matches 'always))
1041 ;; `rgrep' uses the dynamically bound value `grep-find-template'
1042 ;; from the argument `grep-find-template' whose value is computed
1043 ;; in the `interactive' spec.
1044 (rgrep regexp files dir confirm)))
1047 (defalias 'rzgrep 'zrgrep)
1051 ;;; grep.el ends here