(defgroup reftex): Update home page url-link.
[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 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 2, 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 )
154 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
155 :type 'alist
156 :group 'grep)
157
158 (defcustom grep-find-ignored-directories '("CVS" ".svn" "{arch}" ".hg" "_darcs")
159 "*List of names of sub-directories which `rgrep' shall not recurse into."
160 :type '(repeat string)
161 :group 'grep)
162
163 (defcustom grep-error-screen-columns nil
164 "*If non-nil, column numbers in grep hits are screen columns.
165 See `compilation-error-screen-columns'"
166 :type '(choice (const :tag "Default" nil)
167 integer)
168 :version "22.1"
169 :group 'grep)
170
171 ;;;###autoload
172 (defcustom grep-setup-hook nil
173 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
174 :type 'hook
175 :group 'grep)
176
177 (defvar grep-mode-map
178 (let ((map (cons 'keymap compilation-minor-mode-map)))
179 (define-key map " " 'scroll-up)
180 (define-key map "\^?" 'scroll-down)
181 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
182
183 (define-key map "\r" 'compile-goto-error) ;; ?
184 (define-key map "n" 'next-error-no-select)
185 (define-key map "p" 'previous-error-no-select)
186 (define-key map "{" 'compilation-previous-file)
187 (define-key map "}" 'compilation-next-file)
188 (define-key map "\t" 'compilation-next-error)
189 (define-key map [backtab] 'compilation-previous-error)
190
191 ;; Set up the menu-bar
192 (define-key map [menu-bar grep]
193 (cons "Grep" (make-sparse-keymap "Grep")))
194
195 (define-key map [menu-bar grep compilation-kill-compilation]
196 '("Kill Grep" . kill-compilation))
197 (define-key map [menu-bar grep compilation-separator2]
198 '("----" . nil))
199 (define-key map [menu-bar grep compilation-compile]
200 '("Compile..." . compile))
201 (define-key map [menu-bar grep compilation-grep]
202 '("Another grep..." . grep))
203 (define-key map [menu-bar grep compilation-grep-find]
204 '("Recursive grep..." . grep-find))
205 (define-key map [menu-bar grep compilation-recompile]
206 '("Repeat grep" . recompile))
207 (define-key map [menu-bar grep compilation-separator2]
208 '("----" . nil))
209 (define-key map [menu-bar grep compilation-first-error]
210 '("First Match" . first-error))
211 (define-key map [menu-bar grep compilation-previous-error]
212 '("Previous Match" . previous-error))
213 (define-key map [menu-bar grep compilation-next-error]
214 '("Next Match" . next-error))
215 map)
216 "Keymap for grep buffers.
217 `compilation-minor-mode-map' is a cdr of this.")
218
219 (defalias 'kill-grep 'kill-compilation)
220
221 ;;;; TODO --- refine this!!
222
223 ;;; (defcustom grep-use-compilation-buffer t
224 ;;; "When non-nil, grep specific commands update `compilation-last-buffer'.
225 ;;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
226 ;;; can be used to navigate between grep matches (the default).
227 ;;; Otherwise, the grep specific commands like \\[grep-next-match] must
228 ;;; be used to navigate between grep matches."
229 ;;; :type 'boolean
230 ;;; :group 'grep)
231
232 ;; override compilation-last-buffer
233 (defvar grep-last-buffer nil
234 "The most recent grep buffer.
235 A grep buffer becomes most recent when you select Grep mode in it.
236 Notice that using \\[next-error] or \\[compile-goto-error] modifies
237 `complation-last-buffer' rather than `grep-last-buffer'.")
238
239 ;;;###autoload
240 (defvar grep-regexp-alist
241 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
242 1 3)
243 ;; Rule to match column numbers is commented out since no known grep
244 ;; produces them
245 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
246 ;; 1 3 (4 . 5))
247 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
248 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
249 2 3
250 ;; Calculate column positions (beg . end) of first grep match on a line
251 ((lambda ()
252 (setq compilation-error-screen-columns nil)
253 (- (match-beginning 4) (match-end 1)))
254 .
255 (lambda () (- (match-end 5) (match-end 1)
256 (- (match-end 4) (match-beginning 4)))))
257 nil 1)
258 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
259 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
260
261 (defvar grep-error "grep hit"
262 "Message to print when no matches are found.")
263
264 ;; Reverse the colors because grep hits are not errors (though we jump there
265 ;; with `next-error'), and unreadable files can't be gone to.
266 (defvar grep-hit-face compilation-info-face
267 "Face name to use for grep hits.")
268
269 (defvar grep-error-face 'compilation-error
270 "Face name to use for grep error messages.")
271
272 (defvar grep-match-face 'match
273 "Face name to use for grep matches.")
274
275 (defvar grep-context-face 'shadow
276 "Face name to use for grep context lines.")
277
278 (defvar grep-mode-font-lock-keywords
279 '(;; Command output lines.
280 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
281 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
282 1 grep-error-face)
283 ;; remove match from grep-regexp-alist before fontifying
284 ("^Grep[/a-zA-z]* started.*"
285 (0 '(face nil message nil help-echo nil mouse-face nil) t))
286 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
287 (0 '(face nil message nil help-echo nil mouse-face nil) t)
288 (1 compilation-info-face nil t)
289 (2 compilation-warning-face nil t))
290 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
291 (0 '(face nil message nil help-echo nil mouse-face nil) t)
292 (1 grep-error-face)
293 (2 grep-error-face nil t))
294 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
295 ;; Highlight grep matches and delete markers
296 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
297 ;; Refontification does not work after the markers have been
298 ;; deleted. So we use the font-lock-face property here as Font
299 ;; Lock does not clear that.
300 (2 (list 'face nil 'font-lock-face grep-match-face))
301 ((lambda (bound))
302 (progn
303 ;; Delete markers with `replace-match' because it updates
304 ;; the match-data, whereas `delete-region' would render it obsolete.
305 (replace-match "" t t nil 3)
306 (replace-match "" t t nil 1))))
307 ("\\(\033\\[[0-9;]*[mK]\\)"
308 ;; Delete all remaining escape sequences
309 ((lambda (bound))
310 (replace-match "" t t nil 1))))
311 "Additional things to highlight in grep output.
312 This gets tacked on the end of the generated expressions.")
313
314 ;;;###autoload
315 (defvar grep-program
316 ;; Currently zgrep has trouble. It runs egrep instead of grep,
317 ;; and it doesn't pass along long options right.
318 "grep"
319 ;; (if (equal (condition-case nil ; in case "zgrep" isn't in exec-path
320 ;; (call-process "zgrep" nil nil nil
321 ;; "foo" null-device)
322 ;; (error nil))
323 ;; 1)
324 ;; "zgrep"
325 ;; "grep")
326 "The default grep program for `grep-command' and `grep-find-command'.
327 This variable's value takes effect when `grep-compute-defaults' is called.")
328
329 ;;;###autoload
330 (defvar find-program "find"
331 "The default find program for `grep-find-command'.
332 This variable's value takes effect when `grep-compute-defaults' is called.")
333
334 ;;;###autoload
335 (defvar grep-find-use-xargs nil
336 "Whether \\[grep-find] uses the `xargs' utility by default.
337
338 If `exec', it uses `find -exec'; if `gnu', it uses `find -print0' and `xargs -0';
339 if not nil and not `gnu', it uses `find -print' and `xargs'.
340
341 This variable's value takes effect when `grep-compute-defaults' is called.")
342
343 ;; History of grep commands.
344 ;;;###autoload
345 (defvar grep-history nil)
346 ;;;###autoload
347 (defvar grep-find-history nil)
348
349 ;; History of lgrep and rgrep regexp and files args.
350 (defvar grep-regexp-history nil)
351 (defvar grep-files-history '("ch" "el"))
352
353
354 ;;;###autoload
355 (defun grep-process-setup ()
356 "Setup compilation variables and buffer for `grep'.
357 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
358 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
359 (grep-compute-defaults))
360 (when (eq grep-highlight-matches t)
361 ;; Modify `process-environment' locally bound in `compilation-start'
362 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=always"))
363 ;; for GNU grep 2.5.1
364 (setenv "GREP_COLOR" "01;31")
365 ;; for GNU grep 2.5.1-cvs
366 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
367 (set (make-local-variable 'compilation-exit-message-function)
368 (lambda (status code msg)
369 (if (eq status 'exit)
370 (cond ((zerop code)
371 '("finished (matches found)\n" . "matched"))
372 ((= code 1)
373 '("finished with no matches found\n" . "no match"))
374 (t
375 (cons msg code)))
376 (cons msg code))))
377 (run-hooks 'grep-setup-hook))
378
379 (defun grep-probe (command args &optional func result)
380 (equal (condition-case nil
381 (apply (or func 'call-process) command args)
382 (error nil))
383 (or result 0)))
384
385 ;;;###autoload
386 (defun grep-compute-defaults ()
387 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
388 (setq grep-use-null-device
389 (with-temp-buffer
390 (let ((hello-file (expand-file-name "HELLO" data-directory)))
391 (not
392 (and (if grep-command
393 ;; `grep-command' is already set, so
394 ;; use that for testing.
395 (grep-probe grep-command
396 `(nil t nil "^English" ,hello-file)
397 #'call-process-shell-command)
398 ;; otherwise use `grep-program'
399 (grep-probe grep-program
400 `(nil t nil "-nH" "^English" ,hello-file)))
401 (progn
402 (goto-char (point-min))
403 (looking-at
404 (concat (regexp-quote hello-file)
405 ":[0-9]+:English")))))))))
406 (unless (and grep-command grep-find-command
407 grep-template grep-find-template)
408 (let ((grep-options
409 (concat (if grep-use-null-device "-n" "-nH")
410 (if (grep-probe grep-program
411 `(nil nil nil "-e" "foo" ,null-device)
412 nil 1)
413 " -e"))))
414 (unless grep-command
415 (setq grep-command
416 (format "%s %s " grep-program grep-options)))
417 (unless grep-template
418 (setq grep-template
419 (format "%s <C> %s <R> <F>" grep-program grep-options)))
420 (unless grep-find-use-xargs
421 (setq grep-find-use-xargs
422 (cond
423 ((and
424 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
425 (grep-probe "xargs" `(nil nil nil "-0" "-e" "echo")))
426 'gnu)
427 (t
428 'exec))))
429 (unless grep-find-command
430 (setq grep-find-command
431 (cond ((eq grep-find-use-xargs 'gnu)
432 (format "%s . -type f -print0 | xargs -0 -e %s"
433 find-program grep-command))
434 ((eq grep-find-use-xargs 'exec)
435 (let ((cmd0 (format "%s . -type f -exec %s"
436 find-program grep-command)))
437 (cons
438 (format "%s {} %s %s"
439 cmd0 null-device
440 (shell-quote-argument ";"))
441 (1+ (length cmd0)))))
442 (t
443 (format "%s . -type f -print | xargs %s"
444 find-program grep-command)))))
445 (unless grep-find-template
446 (setq grep-find-template
447 (let ((gcmd (format "%s <C> %s <R>"
448 grep-program grep-options)))
449 (cond ((eq grep-find-use-xargs 'gnu)
450 (format "%s . <X> -type f <F> -print0 | xargs -0 -e %s"
451 find-program gcmd))
452 ((eq grep-find-use-xargs 'exec)
453 (format "%s . <X> -type f <F> -exec %s {} %s %s"
454 find-program gcmd null-device
455 (shell-quote-argument ";")))
456 (t
457 (format "%s . <X> -type f <F> -print | xargs %s"
458 find-program gcmd))))))))
459 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
460 (setq grep-highlight-matches
461 (with-temp-buffer
462 (and (grep-probe grep-program '(nil t nil "--help"))
463 (progn
464 (goto-char (point-min))
465 (search-forward "--color" nil t))
466 t)))))
467
468 (defun grep-tag-default ()
469 (or (and transient-mark-mode mark-active
470 (/= (point) (mark))
471 (buffer-substring-no-properties (point) (mark)))
472 (funcall (or find-tag-default-function
473 (get major-mode 'find-tag-default-function)
474 'find-tag-default))
475 ""))
476
477 (defun grep-default-command ()
478 "Compute the default grep command for C-u M-x grep to offer."
479 (let ((tag-default (shell-quote-argument (grep-tag-default)))
480 ;; This a regexp to match single shell arguments.
481 ;; Could someone please add comments explaining it?
482 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
483 (grep-default (or (car grep-history) grep-command)))
484 ;; In the default command, find the arg that specifies the pattern.
485 (when (or (string-match
486 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
487 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
488 grep-default)
489 ;; If the string is not yet complete.
490 (string-match "\\(\\)\\'" grep-default))
491 ;; Maybe we will replace the pattern with the default tag.
492 ;; But first, maybe replace the file name pattern.
493 (condition-case nil
494 (unless (or (not (stringp buffer-file-name))
495 (when (match-beginning 2)
496 (save-match-data
497 (string-match
498 (wildcard-to-regexp
499 (file-name-nondirectory
500 (match-string 3 grep-default)))
501 (file-name-nondirectory buffer-file-name)))))
502 (setq grep-default (concat (substring grep-default
503 0 (match-beginning 2))
504 " *."
505 (file-name-extension buffer-file-name))))
506 ;; In case wildcard-to-regexp gets an error
507 ;; from invalid data.
508 (error nil))
509 ;; Now replace the pattern with the default tag.
510 (replace-match tag-default t t grep-default 1))))
511
512
513 ;;;###autoload
514 (define-compilation-mode grep-mode "Grep"
515 "Sets `grep-last-buffer' and `compilation-window-height'."
516 (setq grep-last-buffer (current-buffer))
517 (set (make-local-variable 'compilation-error-face)
518 grep-hit-face)
519 (set (make-local-variable 'compilation-error-regexp-alist)
520 grep-regexp-alist)
521 (set (make-local-variable 'compilation-process-setup-function)
522 'grep-process-setup)
523 (set (make-local-variable 'compilation-disable-input) t))
524
525
526 ;;;###autoload
527 (defun grep (command-args)
528 "Run grep, with user-specified args, and collect output in a buffer.
529 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
530 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
531 output buffer, to go to the lines
532 where grep found matches.
533
534 This command uses a special history list for its COMMAND-ARGS, so you can
535 easily repeat a grep command.
536
537 A prefix argument says to default the argument based upon the current
538 tag the cursor is over, substituting it into the last grep command
539 in the grep command history (or into `grep-command'
540 if that history list is empty)."
541 (interactive
542 (progn
543 (grep-compute-defaults)
544 (let ((default (grep-default-command)))
545 (list (read-from-minibuffer "Run grep (like this): "
546 (if current-prefix-arg
547 default grep-command)
548 nil nil 'grep-history
549 (if current-prefix-arg nil default))))))
550
551 ;; Setting process-setup-function makes exit-message-function work
552 ;; even when async processes aren't supported.
553 (compilation-start (if (and grep-use-null-device null-device)
554 (concat command-args " " null-device)
555 command-args)
556 'grep-mode))
557
558
559 ;;;###autoload
560 (defun grep-find (command-args)
561 "Run grep via find, with user-specified args COMMAND-ARGS.
562 Collect output in a buffer.
563 While find runs asynchronously, you can use the \\[next-error] command
564 to find the text that grep hits refer to.
565
566 This command uses a special history list for its arguments, so you can
567 easily repeat a find command."
568 (interactive
569 (progn
570 (grep-compute-defaults)
571 (if grep-find-command
572 (list (read-from-minibuffer "Run find (like this): "
573 grep-find-command nil nil
574 'grep-find-history))
575 ;; No default was set
576 (read-string
577 "compile.el: No `grep-find-command' command available. Press RET.")
578 (list nil))))
579 (when command-args
580 (let ((null-device nil)) ; see grep
581 (grep command-args))))
582
583 ;;;###autoload
584 (defalias 'find-grep 'grep-find)
585
586
587 ;; User-friendly interactive API.
588
589 (defconst grep-expand-keywords
590 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
591 ("<D>" . dir)
592 ("<F>" . files)
593 ("<N>" . null-device)
594 ("<X>" . excl)
595 ("<R>" . (shell-quote-argument (or regexp ""))))
596 "List of substitutions performed by `grep-expand-template'.
597 If car of an element matches, the cdr is evalled in to get the
598 substitution string. Note dynamic scoping of variables.")
599
600 (defun grep-expand-template (template &optional regexp files dir excl)
601 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
602 (let ((command template)
603 (cf case-fold-search)
604 (case-fold-search nil))
605 (dolist (kw grep-expand-keywords command)
606 (if (string-match (car kw) command)
607 (setq command
608 (replace-match
609 (or (if (symbolp (cdr kw))
610 (symbol-value (cdr kw))
611 (save-match-data (eval (cdr kw))))
612 "")
613 t t command))))))
614
615 (defun grep-read-regexp ()
616 "Read regexp arg for interactive grep."
617 (let ((default (grep-tag-default)))
618 (read-string
619 (concat "Search for"
620 (if (and default (> (length default) 0))
621 (format " (default \"%s\"): " default) ": "))
622 nil 'grep-regexp-history default)))
623
624 (defun grep-read-files (regexp)
625 "Read files arg for interactive grep."
626 (let* ((bn (or (buffer-file-name) (buffer-name)))
627 (fn (and bn
628 (stringp bn)
629 (file-name-nondirectory bn)))
630 (default
631 (or (and fn
632 (let ((aliases grep-files-aliases)
633 alias)
634 (while aliases
635 (setq alias (car aliases)
636 aliases (cdr aliases))
637 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
638 (setq aliases nil)
639 (setq alias nil)))
640 (cdr alias)))
641 (and fn
642 (let ((ext (file-name-extension fn)))
643 (and ext (concat "*." ext))))
644 (car grep-files-history)
645 (car (car grep-files-aliases))))
646 (files (read-string
647 (concat "Search for \"" regexp
648 "\" in files"
649 (if default (concat " (default " default ")"))
650 ": ")
651 nil 'grep-files-history default)))
652 (and files
653 (or (cdr (assoc files grep-files-aliases))
654 files))))
655
656 ;;;###autoload
657 (defun lgrep (regexp &optional files)
658 "Run grep, searching for REGEXP in FILES in current directory.
659 The search is limited to file names matching shell pattern FILES.
660 FILES may use abbreviations defined in `grep-files-aliases', e.g.
661 entering `ch' is equivalent to `*.[ch]'.
662
663 With \\[universal-argument] prefix, you can edit the constructed shell command line
664 before it is executed.
665 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
666
667 Collect output in a buffer. While grep runs asynchronously, you
668 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error]
669 in the grep output buffer, to go to the lines where grep found matches.
670
671 This command shares argument histories with \\[rgrep] and \\[grep]."
672 (interactive
673 (progn
674 (grep-compute-defaults)
675 (cond
676 ((and grep-command (equal current-prefix-arg '(16)))
677 (list (read-from-minibuffer "Run: " grep-command
678 nil nil 'grep-history)
679 nil))
680 ((not grep-template)
681 (list nil
682 (read-string "grep.el: No `grep-template' available. Press RET.")))
683 (t (let* ((regexp (grep-read-regexp))
684 (files (grep-read-files regexp)))
685 (list regexp files))))))
686 (when (and (stringp regexp) (> (length regexp) 0))
687 (let ((command regexp))
688 (if (null files)
689 (if (string= command grep-command)
690 (setq command nil))
691 (setq command (grep-expand-template
692 grep-template
693 regexp
694 files))
695 (when command
696 (if (equal current-prefix-arg '(4))
697 (setq command
698 (read-from-minibuffer "Confirm: "
699 command nil nil 'grep-history))
700 (add-to-history 'grep-history command))))
701 (when command
702 ;; Setting process-setup-function makes exit-message-function work
703 ;; even when async processes aren't supported.
704 (compilation-start (if (and grep-use-null-device null-device)
705 (concat command " " null-device)
706 command) 'grep-mode)))))
707
708
709 ;;;###autoload
710 (defun rgrep (regexp &optional files dir)
711 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
712 The search is limited to file names matching shell pattern FILES.
713 FILES may use abbreviations defined in `grep-files-aliases', e.g.
714 entering `ch' is equivalent to `*.[ch]'.
715
716 With \\[universal-argument] prefix, you can edit the constructed shell command line
717 before it is executed.
718 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
719
720 Collect output in a buffer. While find runs asynchronously, you
721 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error]
722 in the grep output buffer, to go to the lines where grep found matches.
723
724 This command shares argument histories with \\[lgrep] and \\[grep-find]."
725 (interactive
726 (progn
727 (grep-compute-defaults)
728 (cond
729 ((and grep-find-command (equal current-prefix-arg '(16)))
730 (list (read-from-minibuffer "Run: " grep-find-command
731 nil nil 'grep-find-history)
732 nil))
733 ((not grep-find-template)
734 (list nil nil
735 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
736 (t (let* ((regexp (grep-read-regexp))
737 (files (grep-read-files regexp))
738 (dir (read-directory-name "Base directory: "
739 nil default-directory t)))
740 (list regexp files dir))))))
741 (when (and (stringp regexp) (> (length regexp) 0))
742 (if (null files)
743 (if (not (string= regexp grep-find-command))
744 (compilation-start regexp 'grep-mode))
745 (setq dir (file-name-as-directory (expand-file-name dir)))
746 (let ((command (grep-expand-template
747 grep-find-template
748 regexp
749 (concat (shell-quote-argument "(")
750 " -name "
751 (mapconcat #'shell-quote-argument
752 (split-string files)
753 " -o -name ")
754 " "
755 (shell-quote-argument ")"))
756 dir
757 (and grep-find-ignored-directories
758 (concat (shell-quote-argument "(")
759 ;; we should use shell-quote-argument here
760 " -path "
761 (mapconcat #'(lambda (dir)
762 (shell-quote-argument
763 (concat "*/" dir)))
764 grep-find-ignored-directories
765 " -o -path ")
766 " "
767 (shell-quote-argument ")")
768 " -prune -o ")))))
769 (when command
770 (if current-prefix-arg
771 (setq command
772 (read-from-minibuffer "Confirm: "
773 command nil nil 'grep-find-history))
774 (add-to-history 'grep-find-history command))
775 (let ((default-directory dir))
776 (compilation-start command 'grep-mode))
777 ;; Set default-directory if we started rgrep in the *grep* buffer.
778 (if (eq next-error-last-buffer (current-buffer))
779 (setq default-directory dir)))))))
780
781
782 (provide 'grep)
783
784 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
785 ;;; grep.el ends here