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