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