(Search-based Fontification): Correct a typo.
[emacs.git] / lisp / progmodes / grep.el
blobb4bcc5c88a5fa90edb99dc5fd274516759d70bfa
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>
8 ;; Maintainer: FSF
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/>.
26 ;;; Commentary:
28 ;; This package provides the grep facilities documented in the Emacs
29 ;; user's manual.
31 ;;; Code:
33 (require 'compile)
36 (defgroup grep nil
37 "Run grep as inferior of Emacs, parse error messages."
38 :group 'tools
39 :group 'processes)
42 ;;;###autoload
43 (defcustom grep-window-height nil
44 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
45 :type '(choice (const :tag "Default" nil)
46 integer)
47 :version "22.1"
48 :group 'grep)
50 (defcustom grep-highlight-matches 'auto-detect
51 "If t, use special markers to highlight grep matches.
53 Some grep programs are able to surround matches with special
54 markers in grep output. Such markers can be used to highlight
55 matches in grep mode.
57 This option sets the environment variable GREP_COLOR to specify
58 markers for highlighting and GREP_OPTIONS to add the --color
59 option in front of any explicit grep options before starting
60 the grep.
62 The default value of this variable is set up by `grep-compute-defaults';
63 call that function before using this variable in your program."
64 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
65 (const :tag "Highlight matches with grep markers" t)
66 (other :tag "Not Set" auto-detect))
67 :version "22.1"
68 :group 'grep)
70 (defcustom grep-scroll-output nil
71 "*Non-nil to scroll the *grep* buffer window as output appears.
73 Setting it causes the grep commands to put point at the end of their
74 output window so that the end of the output is always visible rather
75 than the begining."
76 :type 'boolean
77 :version "22.1"
78 :group 'grep)
80 ;;;###autoload
81 (defcustom grep-command nil
82 "The default grep command for \\[grep].
83 If the grep program used supports an option to always include file names
84 in its output (such as the `-H' option to GNU grep), it's a good idea to
85 include it when specifying `grep-command'.
87 The default value of this variable is set up by `grep-compute-defaults';
88 call that function before using this variable in your program."
89 :type '(choice string
90 (const :tag "Not Set" nil))
91 :group 'grep)
93 (defcustom grep-template nil
94 "The default command to run for \\[lgrep].
95 The default value of this variable is set up by `grep-compute-defaults';
96 call that function before using this variable in your program.
97 The following place holders should be present in the string:
98 <C> - place to put -i if case insensitive grep.
99 <F> - file names and wildcards to search.
100 <R> - the regular expression searched for.
101 <N> - place to insert null-device."
102 :type '(choice string
103 (const :tag "Not Set" nil))
104 :version "22.1"
105 :group 'grep)
107 (defcustom grep-use-null-device 'auto-detect
108 "If t, append the value of `null-device' to `grep' commands.
109 This is done to ensure that the output of grep includes the filename of
110 any match in the case where only a single file is searched, and is not
111 necessary if the grep program used supports the `-H' option.
113 The default value of this variable is set up by `grep-compute-defaults';
114 call that function before using this variable in your program."
115 :type '(choice (const :tag "Do Not Append Null Device" nil)
116 (const :tag "Append Null Device" t)
117 (other :tag "Not Set" auto-detect))
118 :group 'grep)
120 ;;;###autoload
121 (defcustom grep-find-command nil
122 "The default find command for \\[grep-find].
123 The default value of this variable is set up by `grep-compute-defaults';
124 call that function before using this variable in your program."
125 :type '(choice string
126 (const :tag "Not Set" nil))
127 :group 'grep)
129 (defcustom grep-find-template nil
130 "The default command to run for \\[rgrep].
131 The default value of this variable is set up by `grep-compute-defaults';
132 call that function before using this variable in your program.
133 The following place holders should be present in the string:
134 <D> - base directory for find
135 <X> - find options to restrict or expand the directory list
136 <F> - find options to limit the files matched
137 <C> - place to put -i if case insensitive grep
138 <R> - the regular expression searched for."
139 :type '(choice string
140 (const :tag "Not Set" nil))
141 :version "22.1"
142 :group 'grep)
144 (defcustom grep-files-aliases
145 '(("asm" . "*.[sS]")
146 ("c" . "*.c")
147 ("cc" . "*.cc *.cxx *.cpp *.C *.CC *.c++")
148 ("cchh" . "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
149 ("hh" . "*.hxx *.hpp *.[Hh] *.HH *.h++")
150 ("ch" . "*.[ch]")
151 ("el" . "*.el")
152 ("h" . "*.h")
153 ("l" . "[Cc]hange[Ll]og*")
154 ("m" . "[Mm]akefile*")
155 ("tex" . "*.tex")
156 ("texi" . "*.texi"))
157 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
158 :type 'alist
159 :group 'grep)
161 (defcustom grep-find-ignored-directories
162 vc-directory-exclusion-list
163 "*List of names of sub-directories which `rgrep' shall not recurse into."
164 :type '(repeat string)
165 :group 'grep)
167 (defcustom grep-error-screen-columns nil
168 "*If non-nil, column numbers in grep hits are screen columns.
169 See `compilation-error-screen-columns'"
170 :type '(choice (const :tag "Default" nil)
171 integer)
172 :version "22.1"
173 :group 'grep)
175 ;;;###autoload
176 (defcustom grep-setup-hook nil
177 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
178 :type 'hook
179 :group 'grep)
181 (defvar grep-mode-map
182 (let ((map (make-sparse-keymap)))
183 (set-keymap-parent map compilation-minor-mode-map)
184 (define-key map " " 'scroll-up)
185 (define-key map "\^?" 'scroll-down)
186 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
188 (define-key map "\r" 'compile-goto-error) ;; ?
189 (define-key map "n" 'next-error-no-select)
190 (define-key map "p" 'previous-error-no-select)
191 (define-key map "{" 'compilation-previous-file)
192 (define-key map "}" 'compilation-next-file)
193 (define-key map "\t" 'compilation-next-error)
194 (define-key map [backtab] 'compilation-previous-error)
196 ;; Set up the menu-bar
197 (define-key map [menu-bar grep]
198 (cons "Grep" (make-sparse-keymap "Grep")))
200 (define-key map [menu-bar grep compilation-kill-compilation]
201 '(menu-item "Kill Grep" kill-compilation
202 :help "Kill the currently running grep process"))
203 (define-key map [menu-bar grep compilation-separator2] '("----"))
204 (define-key map [menu-bar grep compilation-compile]
205 '(menu-item "Compile..." compile
206 :help "Compile the program including the current buffer. Default: run `make'"))
207 (define-key map [menu-bar grep compilation-rgrep]
208 '(menu-item "Recursive grep..." rgrep
209 :help "User-friendly recursive grep in directory tree"))
210 (define-key map [menu-bar grep compilation-lgrep]
211 '(menu-item "Local grep..." lgrep
212 :help "User-friendly grep in a directory"))
213 (define-key map [menu-bar grep compilation-grep-find]
214 '(menu-item "Grep via Find..." grep-find
215 :help "Run grep via find, with user-specified args"))
216 (define-key map [menu-bar grep compilation-grep]
217 '(menu-item "Another grep..." grep
218 :help "Run grep, with user-specified args, and collect output in a buffer."))
219 (define-key map [menu-bar grep compilation-recompile]
220 '(menu-item "Repeat grep" recompile
221 :help "Run grep again"))
222 (define-key map [menu-bar grep compilation-separator2] '("----"))
223 (define-key map [menu-bar grep compilation-first-error]
224 '(menu-item "First Match" first-error
225 :help "Restart at the first match, visit corresponding location"))
226 (define-key map [menu-bar grep compilation-previous-error]
227 '(menu-item "Previous Match" previous-error
228 :help "Visit the previous match and corresponding location"))
229 (define-key map [menu-bar grep compilation-next-error]
230 '(menu-item "Next Match" next-error
231 :help "Visit the next match and corresponding location"))
232 map)
233 "Keymap for grep buffers.
234 `compilation-minor-mode-map' is a cdr of this.")
236 (defvar grep-mode-tool-bar-map
237 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
238 ;; so don't do anything.
239 (when (keymapp (butlast tool-bar-map))
240 (let ((map (butlast (copy-keymap tool-bar-map)))
241 (help (last tool-bar-map))) ;; Keep Help last in tool bar
242 (tool-bar-local-item
243 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
244 :rtl "right-arrow"
245 :help "Goto previous match")
246 (tool-bar-local-item
247 "right-arrow" 'next-error-no-select 'next-error-no-select map
248 :rtl "left-arrow"
249 :help "Goto next match")
250 (tool-bar-local-item
251 "cancel" 'kill-compilation 'kill-compilation map
252 :enable '(let ((buffer (compilation-find-buffer)))
253 (get-buffer-process buffer))
254 :help "Stop grep")
255 (tool-bar-local-item
256 "refresh" 'recompile 'recompile map
257 :help "Restart grep")
258 (append map help))))
260 (defalias 'kill-grep 'kill-compilation)
262 ;;;; TODO --- refine this!!
264 ;; (defcustom grep-use-compilation-buffer t
265 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
266 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
267 ;; can be used to navigate between grep matches (the default).
268 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
269 ;; be used to navigate between grep matches."
270 ;; :type 'boolean
271 ;; :group 'grep)
273 ;; override compilation-last-buffer
274 (defvar grep-last-buffer nil
275 "The most recent grep buffer.
276 A grep buffer becomes most recent when you select Grep mode in it.
277 Notice that using \\[next-error] or \\[compile-goto-error] modifies
278 `complation-last-buffer' rather than `grep-last-buffer'.")
280 ;;;###autoload
281 (defvar grep-regexp-alist
282 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
283 1 3)
284 ;; Rule to match column numbers is commented out since no known grep
285 ;; produces them
286 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
287 ;; 1 3 (4 . 5))
288 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
289 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
291 ;; Calculate column positions (beg . end) of first grep match on a line
292 ((lambda ()
293 (setq compilation-error-screen-columns nil)
294 (- (match-beginning 4) (match-end 1)))
296 (lambda () (- (match-end 5) (match-end 1)
297 (- (match-end 4) (match-beginning 4)))))
298 nil 1)
299 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
300 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
302 (defvar grep-error "grep hit"
303 "Message to print when no matches are found.")
305 ;; Reverse the colors because grep hits are not errors (though we jump there
306 ;; with `next-error'), and unreadable files can't be gone to.
307 (defvar grep-hit-face compilation-info-face
308 "Face name to use for grep hits.")
310 (defvar grep-error-face 'compilation-error
311 "Face name to use for grep error messages.")
313 (defvar grep-match-face 'match
314 "Face name to use for grep matches.")
316 (defvar grep-context-face 'shadow
317 "Face name to use for grep context lines.")
319 (defvar grep-mode-font-lock-keywords
320 '(;; Command output lines.
321 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
322 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
323 1 grep-error-face)
324 ;; remove match from grep-regexp-alist before fontifying
325 ("^Grep[/a-zA-z]* started.*"
326 (0 '(face nil message nil help-echo nil mouse-face nil) t))
327 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
328 (0 '(face nil message nil help-echo nil mouse-face nil) t)
329 (1 compilation-info-face nil t)
330 (2 compilation-warning-face nil t))
331 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
332 (0 '(face nil message nil help-echo nil mouse-face nil) t)
333 (1 grep-error-face)
334 (2 grep-error-face nil t))
335 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
336 ;; Highlight grep matches and delete markers
337 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
338 ;; Refontification does not work after the markers have been
339 ;; deleted. So we use the font-lock-face property here as Font
340 ;; Lock does not clear that.
341 (2 (list 'face nil 'font-lock-face grep-match-face))
342 ((lambda (bound))
343 (progn
344 ;; Delete markers with `replace-match' because it updates
345 ;; the match-data, whereas `delete-region' would render it obsolete.
346 (replace-match "" t t nil 3)
347 (replace-match "" t t nil 1))))
348 ("\\(\033\\[[0-9;]*[mK]\\)"
349 ;; Delete all remaining escape sequences
350 ((lambda (bound))
351 (replace-match "" t t nil 1))))
352 "Additional things to highlight in grep output.
353 This gets tacked on the end of the generated expressions.")
355 ;;;###autoload
356 (defvar grep-program "grep"
357 "The default grep program for `grep-command' and `grep-find-command'.
358 This variable's value takes effect when `grep-compute-defaults' is called.")
360 ;;;###autoload
361 (defvar find-program "find"
362 "The default find program for `grep-find-command'.
363 This variable's value takes effect when `grep-compute-defaults' is called.")
365 ;;;###autoload
366 (defvar xargs-program "xargs"
367 "The default xargs program for `grep-find-command'.
368 See `grep-find-use-xargs'.
369 This variable's value takes effect when `grep-compute-defaults' is called.")
371 ;;;###autoload
372 (defvar grep-find-use-xargs nil
373 "Non-nil means that `grep-find' uses the `xargs' utility by default.
374 If `exec', use `find -exec'.
375 If `gnu', use `find -print0' and `xargs -0'.
376 Any other non-nil value means to use `find -print' and `xargs'.
378 This variable's value takes effect when `grep-compute-defaults' is called.")
380 ;; History of grep commands.
381 ;;;###autoload
382 (defvar grep-history nil)
383 ;;;###autoload
384 (defvar grep-find-history nil)
386 ;; History of lgrep and rgrep regexp and files args.
387 (defvar grep-regexp-history nil)
388 (defvar grep-files-history '("ch" "el"))
390 (defvar grep-host-defaults-alist nil
391 "Default values depending on target host.
392 `grep-compute-defaults' returns default values for every local or
393 remote host `grep' runs. These values can differ from host to
394 host. Once computed, the default values are kept here in order
395 to avoid computing them again.")
397 ;;;###autoload
398 (defun grep-process-setup ()
399 "Setup compilation variables and buffer for `grep'.
400 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
401 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
402 (grep-compute-defaults))
403 (when (eq grep-highlight-matches t)
404 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
405 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
406 (setenv "TERM" "emacs-grep")
407 ;; `--color=auto' emits escape sequences on a tty rather than on a pipe,
408 ;; thus allowing to use multiple grep filters on the command line
409 ;; and to output escape sequences only on the final grep output
410 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=auto"))
411 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
412 (setenv "GREP_COLOR" "01;31")
413 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
414 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
415 (set (make-local-variable 'compilation-exit-message-function)
416 (lambda (status code msg)
417 (if (eq status 'exit)
418 (cond ((zerop code)
419 '("finished (matches found)\n" . "matched"))
420 ((= code 1)
421 '("finished with no matches found\n" . "no match"))
423 (cons msg code)))
424 (cons msg code))))
425 (run-hooks 'grep-setup-hook))
427 (defun grep-probe (command args &optional func result)
428 (equal (condition-case nil
429 (apply (or func 'process-file) command args)
430 (error nil))
431 (or result 0)))
433 ;;;###autoload
434 (defun grep-compute-defaults ()
435 ;; Keep default values.
436 (unless grep-host-defaults-alist
437 (add-to-list
438 'grep-host-defaults-alist
439 (cons nil
440 `((grep-command ,grep-command)
441 (grep-template ,grep-template)
442 (grep-use-null-device ,grep-use-null-device)
443 (grep-find-command ,grep-find-command)
444 (grep-find-template ,grep-find-template)
445 (grep-find-use-xargs ,grep-find-use-xargs)
446 (grep-highlight-matches ,grep-highlight-matches)))))
447 (let* ((host-id
448 (intern (or (file-remote-p default-directory) "localhost")))
449 (host-defaults (assq host-id grep-host-defaults-alist))
450 (defaults (assq nil grep-host-defaults-alist)))
451 ;; There are different defaults on different hosts. They must be
452 ;; computed for every host once.
453 (setq grep-command
454 (or (cadr (assq 'grep-command host-defaults))
455 (cadr (assq 'grep-command defaults)))
457 grep-template
458 (or (cadr (assq 'grep-template host-defaults))
459 (cadr (assq 'grep-template defaults)))
461 grep-use-null-device
462 (or (cadr (assq 'grep-use-null-device host-defaults))
463 (cadr (assq 'grep-use-null-device defaults)))
465 grep-find-command
466 (or (cadr (assq 'grep-find-command host-defaults))
467 (cadr (assq 'grep-find-command defaults)))
469 grep-find-template
470 (or (cadr (assq 'grep-find-template host-defaults))
471 (cadr (assq 'grep-find-template defaults)))
473 grep-find-use-xargs
474 (or (cadr (assq 'grep-find-use-xargs host-defaults))
475 (cadr (assq 'grep-find-use-xargs defaults)))
477 grep-highlight-matches
478 (or (cadr (assq 'grep-highlight-matches host-defaults))
479 (cadr (assq 'grep-highlight-matches defaults))))
481 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
482 (setq grep-use-null-device
483 (with-temp-buffer
484 (let ((hello-file (expand-file-name "HELLO" data-directory)))
485 (not
486 (and (if grep-command
487 ;; `grep-command' is already set, so
488 ;; use that for testing.
489 (grep-probe grep-command
490 `(nil t nil "^English" ,hello-file)
491 #'call-process-shell-command)
492 ;; otherwise use `grep-program'
493 (grep-probe grep-program
494 `(nil t nil "-nH" "^English" ,hello-file)))
495 (progn
496 (goto-char (point-min))
497 (looking-at
498 (concat (regexp-quote hello-file)
499 ":[0-9]+:English")))))))))
500 (unless (and grep-command grep-find-command
501 grep-template grep-find-template)
502 (let ((grep-options
503 (concat (if grep-use-null-device "-n" "-nH")
504 (if (grep-probe grep-program
505 `(nil nil nil "-e" "foo" ,null-device)
506 nil 1)
507 " -e"))))
508 (unless grep-command
509 (setq grep-command
510 (format "%s %s " grep-program grep-options)))
511 (unless grep-template
512 (setq grep-template
513 (format "%s <C> %s <R> <F>" grep-program grep-options)))
514 (unless grep-find-use-xargs
515 (setq grep-find-use-xargs
516 (cond
517 ((and
518 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
519 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
520 'gnu)
522 'exec))))
523 (unless grep-find-command
524 (setq grep-find-command
525 (cond ((eq grep-find-use-xargs 'gnu)
526 (format "%s . -type f -print0 | %s -0 -e %s"
527 find-program xargs-program grep-command))
528 ((eq grep-find-use-xargs 'exec)
529 (let ((cmd0 (format "%s . -type f -exec %s"
530 find-program grep-command)))
531 (cons
532 (format "%s {} %s %s"
533 cmd0 null-device
534 (shell-quote-argument ";"))
535 (1+ (length cmd0)))))
537 (format "%s . -type f -print | %s %s"
538 find-program xargs-program grep-command)))))
539 (unless grep-find-template
540 (setq grep-find-template
541 (let ((gcmd (format "%s <C> %s <R>"
542 grep-program grep-options)))
543 (cond ((eq grep-find-use-xargs 'gnu)
544 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
545 find-program xargs-program gcmd))
546 ((eq grep-find-use-xargs 'exec)
547 (format "%s . <X> -type f <F> -exec %s {} %s %s"
548 find-program gcmd null-device
549 (shell-quote-argument ";")))
551 (format "%s . <X> -type f <F> -print | %s %s"
552 find-program xargs-program gcmd))))))))
553 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
554 (setq grep-highlight-matches
555 (with-temp-buffer
556 (and (grep-probe grep-program '(nil t nil "--help"))
557 (progn
558 (goto-char (point-min))
559 (search-forward "--color" nil t))
560 t))))
562 ;; Save defaults for this host.
563 (setq grep-host-defaults-alist
564 (delete (assq host-id grep-host-defaults-alist)
565 grep-host-defaults-alist))
566 (add-to-list
567 'grep-host-defaults-alist
568 (cons host-id
569 `((grep-command ,grep-command)
570 (grep-template ,grep-template)
571 (grep-use-null-device ,grep-use-null-device)
572 (grep-find-command ,grep-find-command)
573 (grep-find-template ,grep-find-template)
574 (grep-find-use-xargs ,grep-find-use-xargs)
575 (grep-highlight-matches ,grep-highlight-matches))))))
577 (defun grep-tag-default ()
578 (or (and transient-mark-mode mark-active
579 (/= (point) (mark))
580 (buffer-substring-no-properties (point) (mark)))
581 (funcall (or find-tag-default-function
582 (get major-mode 'find-tag-default-function)
583 'find-tag-default))
584 ""))
586 (defun grep-default-command ()
587 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
588 (let ((tag-default (shell-quote-argument (grep-tag-default)))
589 ;; This a regexp to match single shell arguments.
590 ;; Could someone please add comments explaining it?
591 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
592 (grep-default (or (car grep-history) grep-command)))
593 ;; In the default command, find the arg that specifies the pattern.
594 (when (or (string-match
595 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
596 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
597 grep-default)
598 ;; If the string is not yet complete.
599 (string-match "\\(\\)\\'" grep-default))
600 ;; Maybe we will replace the pattern with the default tag.
601 ;; But first, maybe replace the file name pattern.
602 (condition-case nil
603 (unless (or (not (stringp buffer-file-name))
604 (when (match-beginning 2)
605 (save-match-data
606 (string-match
607 (wildcard-to-regexp
608 (file-name-nondirectory
609 (match-string 3 grep-default)))
610 (file-name-nondirectory buffer-file-name)))))
611 (setq grep-default (concat (substring grep-default
612 0 (match-beginning 2))
613 " *."
614 (file-name-extension buffer-file-name))))
615 ;; In case wildcard-to-regexp gets an error
616 ;; from invalid data.
617 (error nil))
618 ;; Now replace the pattern with the default tag.
619 (replace-match tag-default t t grep-default 1))))
622 ;;;###autoload
623 (define-compilation-mode grep-mode "Grep"
624 "Sets `grep-last-buffer' and `compilation-window-height'."
625 (setq grep-last-buffer (current-buffer))
626 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
627 (set (make-local-variable 'compilation-error-face)
628 grep-hit-face)
629 (set (make-local-variable 'compilation-error-regexp-alist)
630 grep-regexp-alist)
631 (set (make-local-variable 'compilation-process-setup-function)
632 'grep-process-setup)
633 (set (make-local-variable 'compilation-disable-input) t))
636 ;;;###autoload
637 (defun grep (command-args)
638 "Run grep, with user-specified args, and collect output in a buffer.
639 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
640 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
641 output buffer, to go to the lines where grep
642 found matches.
644 For doing a recursive `grep', see the `rgrep' command. For running
645 `grep' in a specific directory, see `lgrep'.
647 This command uses a special history list for its COMMAND-ARGS, so you
648 can easily repeat a grep command.
650 A prefix argument says to default the argument based upon the current
651 tag the cursor is over, substituting it into the last grep command
652 in the grep command history (or into `grep-command' if that history
653 list is empty)."
654 (interactive
655 (progn
656 (grep-compute-defaults)
657 (let ((default (grep-default-command)))
658 (list (read-shell-command "Run grep (like this): "
659 (if current-prefix-arg default grep-command)
660 'grep-history
661 (if current-prefix-arg nil default))))))
663 ;; Setting process-setup-function makes exit-message-function work
664 ;; even when async processes aren't supported.
665 (compilation-start (if (and grep-use-null-device null-device)
666 (concat command-args " " null-device)
667 command-args)
668 'grep-mode))
671 ;;;###autoload
672 (defun grep-find (command-args)
673 "Run grep via find, with user-specified args COMMAND-ARGS.
674 Collect output in a buffer.
675 While find runs asynchronously, you can use the \\[next-error] command
676 to find the text that grep hits refer to.
678 This command uses a special history list for its arguments, so you can
679 easily repeat a find command."
680 (interactive
681 (progn
682 (grep-compute-defaults)
683 (if grep-find-command
684 (list (read-shell-command "Run find (like this): "
685 grep-find-command 'grep-find-history))
686 ;; No default was set
687 (read-string
688 "compile.el: No `grep-find-command' command available. Press RET.")
689 (list nil))))
690 (when command-args
691 (let ((null-device nil)) ; see grep
692 (grep command-args))))
694 ;;;###autoload
695 (defalias 'find-grep 'grep-find)
698 ;; User-friendly interactive API.
700 (defconst grep-expand-keywords
701 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
702 ("<D>" . dir)
703 ("<F>" . files)
704 ("<N>" . null-device)
705 ("<X>" . excl)
706 ("<R>" . (shell-quote-argument (or regexp ""))))
707 "List of substitutions performed by `grep-expand-template'.
708 If car of an element matches, the cdr is evalled in to get the
709 substitution string. Note dynamic scoping of variables.")
711 (defun grep-expand-template (template &optional regexp files dir excl)
712 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
713 (let ((command template)
714 (cf case-fold-search)
715 (case-fold-search nil))
716 (dolist (kw grep-expand-keywords command)
717 (if (string-match (car kw) command)
718 (setq command
719 (replace-match
720 (or (if (symbolp (cdr kw))
721 (symbol-value (cdr kw))
722 (save-match-data (eval (cdr kw))))
724 t t command))))))
726 (defun grep-read-regexp ()
727 "Read regexp arg for interactive grep."
728 (let ((default (grep-tag-default)))
729 (read-string
730 (concat "Search for"
731 (if (and default (> (length default) 0))
732 (format " (default \"%s\"): " default) ": "))
733 nil 'grep-regexp-history default)))
735 (defun grep-read-files (regexp)
736 "Read files arg for interactive grep."
737 (let* ((bn (or (buffer-file-name) (buffer-name)))
738 (fn (and bn
739 (stringp bn)
740 (file-name-nondirectory bn)))
741 (default
742 (or (and fn
743 (let ((aliases grep-files-aliases)
744 alias)
745 (while aliases
746 (setq alias (car aliases)
747 aliases (cdr aliases))
748 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
749 (setq aliases nil)
750 (setq alias nil)))
751 (cdr alias)))
752 (and fn
753 (let ((ext (file-name-extension fn)))
754 (and ext (concat "*." ext))))
755 (car grep-files-history)
756 (car (car grep-files-aliases))))
757 (files (read-string
758 (concat "Search for \"" regexp
759 "\" in files"
760 (if default (concat " (default " default ")"))
761 ": ")
762 nil 'grep-files-history default)))
763 (and files
764 (or (cdr (assoc files grep-files-aliases))
765 files))))
767 ;;;###autoload
768 (defun lgrep (regexp &optional files dir)
769 "Run grep, searching for REGEXP in FILES in directory DIR.
770 The search is limited to file names matching shell pattern FILES.
771 FILES may use abbreviations defined in `grep-files-aliases', e.g.
772 entering `ch' is equivalent to `*.[ch]'.
774 With \\[universal-argument] prefix, you can edit the constructed shell command line
775 before it is executed.
776 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
778 Collect output in a buffer. While grep runs asynchronously, you
779 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
780 in the grep output buffer,
781 to go to the lines where grep found matches.
783 This command shares argument histories with \\[rgrep] and \\[grep]."
784 (interactive
785 (progn
786 (grep-compute-defaults)
787 (cond
788 ((and grep-command (equal current-prefix-arg '(16)))
789 (list (read-from-minibuffer "Run: " grep-command
790 nil nil 'grep-history)
791 nil))
792 ((not grep-template)
793 (list nil
794 (read-string "grep.el: No `grep-template' available. Press RET.")))
795 (t (let* ((regexp (grep-read-regexp))
796 (files (grep-read-files regexp))
797 (dir (read-directory-name "In directory: "
798 nil default-directory t)))
799 (list regexp files dir))))))
800 (when (and (stringp regexp) (> (length regexp) 0))
801 (let ((command regexp))
802 (if (null files)
803 (if (string= command grep-command)
804 (setq command nil))
805 (setq dir (file-name-as-directory (expand-file-name dir)))
806 (setq command (grep-expand-template
807 grep-template
808 regexp
809 files))
810 (when command
811 (if (equal current-prefix-arg '(4))
812 (setq command
813 (read-from-minibuffer "Confirm: "
814 command nil nil 'grep-history))
815 (add-to-history 'grep-history command))))
816 (when command
817 (let ((default-directory dir))
818 ;; Setting process-setup-function makes exit-message-function work
819 ;; even when async processes aren't supported.
820 (compilation-start (if (and grep-use-null-device null-device)
821 (concat command " " null-device)
822 command)
823 'grep-mode))
824 (if (eq next-error-last-buffer (current-buffer))
825 (setq default-directory dir))))))
828 (defvar find-name-arg) ; autoloaded
830 ;;;###autoload
831 (defun rgrep (regexp &optional files dir)
832 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
833 The search is limited to file names matching shell pattern FILES.
834 FILES may use abbreviations defined in `grep-files-aliases', e.g.
835 entering `ch' is equivalent to `*.[ch]'.
837 With \\[universal-argument] prefix, you can edit the constructed shell command line
838 before it is executed.
839 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
841 Collect output in a buffer. While find runs asynchronously, you
842 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
843 in the grep output buffer,
844 to go to the lines where grep found matches.
846 This command shares argument histories with \\[lgrep] and \\[grep-find]."
847 (interactive
848 (progn
849 (grep-compute-defaults)
850 (cond
851 ((and grep-find-command (equal current-prefix-arg '(16)))
852 (list (read-from-minibuffer "Run: " grep-find-command
853 nil nil 'grep-find-history)
854 nil))
855 ((not grep-find-template)
856 (list nil nil
857 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
858 (t (let* ((regexp (grep-read-regexp))
859 (files (grep-read-files regexp))
860 (dir (read-directory-name "Base directory: "
861 nil default-directory t)))
862 (list regexp files dir))))))
863 (when (and (stringp regexp) (> (length regexp) 0))
864 (if (null files)
865 (if (not (string= regexp grep-find-command))
866 (compilation-start regexp 'grep-mode))
867 (setq dir (file-name-as-directory (expand-file-name dir)))
868 (let ((command (grep-expand-template
869 grep-find-template
870 regexp
871 (concat (shell-quote-argument "(")
872 " " find-name-arg " "
873 (mapconcat #'shell-quote-argument
874 (split-string files)
875 (concat " -o " find-name-arg " "))
877 (shell-quote-argument ")"))
879 (and grep-find-ignored-directories
880 (concat (shell-quote-argument "(")
881 ;; we should use shell-quote-argument here
882 " -path "
883 (mapconcat #'(lambda (dir)
884 (shell-quote-argument
885 (concat "*/" dir)))
886 grep-find-ignored-directories
887 " -o -path ")
889 (shell-quote-argument ")")
890 " -prune -o ")))))
891 (when command
892 (if current-prefix-arg
893 (setq command
894 (read-from-minibuffer "Confirm: "
895 command nil nil 'grep-find-history))
896 (add-to-history 'grep-find-history command))
897 (let ((default-directory dir))
898 (compilation-start command 'grep-mode))
899 ;; Set default-directory if we started rgrep in the *grep* buffer.
900 (if (eq next-error-last-buffer (current-buffer))
901 (setq default-directory dir)))))))
904 (provide 'grep)
906 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
907 ;;; grep.el ends here