]> code.delx.au - gnu-emacs/blob - lisp/progmodes/grep.el
Merge from emacs--devo--0
[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 "grep"
319 "The default grep program for `grep-command' and `grep-find-command'.
320 This variable's value takes effect when `grep-compute-defaults' is called.")
321
322 ;;;###autoload
323 (defvar find-program "find"
324 "The default find program for `grep-find-command'.
325 This variable's value takes effect when `grep-compute-defaults' is called.")
326
327 ;;;###autoload
328 (defvar grep-find-use-xargs nil
329 "Non-nil means that `grep-find' uses the `xargs' utility by default.
330 If `exec', use `find -exec'.
331 If `gnu', use `find -print0' and `xargs -0'.
332 Any other non-nil value means to use `find -print' and `xargs'.
333
334 This variable's value takes effect when `grep-compute-defaults' is called.")
335
336 ;; History of grep commands.
337 ;;;###autoload
338 (defvar grep-history nil)
339 ;;;###autoload
340 (defvar grep-find-history nil)
341
342 ;; History of lgrep and rgrep regexp and files args.
343 (defvar grep-regexp-history nil)
344 (defvar grep-files-history '("ch" "el"))
345
346
347 ;;;###autoload
348 (defun grep-process-setup ()
349 "Setup compilation variables and buffer for `grep'.
350 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
351 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
352 (grep-compute-defaults))
353 (when (eq grep-highlight-matches t)
354 ;; Modify `process-environment' locally bound in `compilation-start'
355 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=always"))
356 ;; for GNU grep 2.5.1
357 (setenv "GREP_COLOR" "01;31")
358 ;; for GNU grep 2.5.1-cvs
359 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
360 (set (make-local-variable 'compilation-exit-message-function)
361 (lambda (status code msg)
362 (if (eq status 'exit)
363 (cond ((zerop code)
364 '("finished (matches found)\n" . "matched"))
365 ((= code 1)
366 '("finished with no matches found\n" . "no match"))
367 (t
368 (cons msg code)))
369 (cons msg code))))
370 (run-hooks 'grep-setup-hook))
371
372 (defun grep-probe (command args &optional func result)
373 (equal (condition-case nil
374 (apply (or func 'process-file) command args)
375 (error nil))
376 (or result 0)))
377
378 ;;;###autoload
379 (defun grep-compute-defaults ()
380 (let ((host-id
381 (intern (or (file-remote-p default-directory 'host) "localhost"))))
382 ;; There are different defaults on different hosts. They must be
383 ;; computed for every host once, then they are kept in the
384 ;; variables' property host-id for reuse.
385 (setq grep-command
386 (or (get 'grep-command host-id)
387 (eval (car (get 'grep-command 'standard-value))))
388
389 grep-template
390 (or (get 'grep-template host-id)
391 (eval (car (get 'grep-template 'standard-value))))
392
393 grep-use-null-device
394 (or (get 'grep-use-null-device host-id)
395 (eval (car (get 'grep-use-null-device 'standard-value))))
396
397 grep-find-command
398 (or (get 'grep-find-command host-id)
399 (eval (car (get 'grep-find-command 'standard-value))))
400
401 grep-find-template
402 (or (get 'grep-find-template host-id)
403 (eval (car (get 'grep-find-template 'standard-value))))
404
405 grep-find-use-xargs
406 (or (get 'grep-find-use-xargs host-id)
407 (eval (car (get 'grep-find-use-xargs 'standard-value))))
408
409 grep-highlight-matches
410 (or (get 'grep-highlight-matches host-id)
411 (eval (car (get 'grep-highlight-matches 'standard-value)))))
412
413 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
414 (setq grep-use-null-device
415 (with-temp-buffer
416 (let ((hello-file (expand-file-name "HELLO" data-directory)))
417 (not
418 (and (if grep-command
419 ;; `grep-command' is already set, so
420 ;; use that for testing.
421 (grep-probe grep-command
422 `(nil t nil "^English" ,hello-file)
423 #'call-process-shell-command)
424 ;; otherwise use `grep-program'
425 (grep-probe grep-program
426 `(nil t nil "-nH" "^English" ,hello-file)))
427 (progn
428 (goto-char (point-min))
429 (looking-at
430 (concat (regexp-quote hello-file)
431 ":[0-9]+:English")))))))))
432 (unless (and grep-command grep-find-command
433 grep-template grep-find-template)
434 (let ((grep-options
435 (concat (if grep-use-null-device "-n" "-nH")
436 (if (grep-probe grep-program
437 `(nil nil nil "-e" "foo" ,null-device)
438 nil 1)
439 " -e"))))
440 (unless grep-command
441 (setq grep-command
442 (format "%s %s " grep-program grep-options)))
443 (unless grep-template
444 (setq grep-template
445 (format "%s <C> %s <R> <F>" grep-program grep-options)))
446 (unless grep-find-use-xargs
447 (setq grep-find-use-xargs
448 (cond
449 ((and
450 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
451 (grep-probe "xargs" `(nil nil nil "-0" "-e" "echo")))
452 'gnu)
453 (t
454 'exec))))
455 (unless grep-find-command
456 (setq grep-find-command
457 (cond ((eq grep-find-use-xargs 'gnu)
458 (format "%s . -type f -print0 | xargs -0 -e %s"
459 find-program grep-command))
460 ((eq grep-find-use-xargs 'exec)
461 (let ((cmd0 (format "%s . -type f -exec %s"
462 find-program grep-command)))
463 (cons
464 (format "%s {} %s %s"
465 cmd0 null-device
466 (shell-quote-argument ";"))
467 (1+ (length cmd0)))))
468 (t
469 (format "%s . -type f -print | xargs %s"
470 find-program grep-command)))))
471 (unless grep-find-template
472 (setq grep-find-template
473 (let ((gcmd (format "%s <C> %s <R>"
474 grep-program grep-options)))
475 (cond ((eq grep-find-use-xargs 'gnu)
476 (format "%s . <X> -type f <F> -print0 | xargs -0 -e %s"
477 find-program gcmd))
478 ((eq grep-find-use-xargs 'exec)
479 (format "%s . <X> -type f <F> -exec %s {} %s %s"
480 find-program gcmd null-device
481 (shell-quote-argument ";")))
482 (t
483 (format "%s . <X> -type f <F> -print | xargs %s"
484 find-program gcmd))))))))
485 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
486 (setq grep-highlight-matches
487 (with-temp-buffer
488 (and (grep-probe grep-program '(nil t nil "--help"))
489 (progn
490 (goto-char (point-min))
491 (search-forward "--color" nil t))
492 t))))
493
494 ;; Save defaults for this host.
495 (put 'grep-command host-id grep-command)
496 (put 'grep-template host-id grep-template)
497 (put 'grep-use-null-device host-id grep-use-null-device)
498 (put 'grep-find-command host-id grep-find-command)
499 (put 'grep-find-template host-id grep-find-template)
500 (put 'grep-find-use-xargs host-id grep-find-use-xargs)
501 (put 'grep-highlight-matches host-id grep-highlight-matches)))
502
503 (defun grep-tag-default ()
504 (or (and transient-mark-mode mark-active
505 (/= (point) (mark))
506 (buffer-substring-no-properties (point) (mark)))
507 (funcall (or find-tag-default-function
508 (get major-mode 'find-tag-default-function)
509 'find-tag-default))
510 ""))
511
512 (defun grep-default-command ()
513 "Compute the default grep command for C-u M-x grep to offer."
514 (let ((tag-default (shell-quote-argument (grep-tag-default)))
515 ;; This a regexp to match single shell arguments.
516 ;; Could someone please add comments explaining it?
517 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
518 (grep-default (or (car grep-history) grep-command)))
519 ;; In the default command, find the arg that specifies the pattern.
520 (when (or (string-match
521 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
522 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
523 grep-default)
524 ;; If the string is not yet complete.
525 (string-match "\\(\\)\\'" grep-default))
526 ;; Maybe we will replace the pattern with the default tag.
527 ;; But first, maybe replace the file name pattern.
528 (condition-case nil
529 (unless (or (not (stringp buffer-file-name))
530 (when (match-beginning 2)
531 (save-match-data
532 (string-match
533 (wildcard-to-regexp
534 (file-name-nondirectory
535 (match-string 3 grep-default)))
536 (file-name-nondirectory buffer-file-name)))))
537 (setq grep-default (concat (substring grep-default
538 0 (match-beginning 2))
539 " *."
540 (file-name-extension buffer-file-name))))
541 ;; In case wildcard-to-regexp gets an error
542 ;; from invalid data.
543 (error nil))
544 ;; Now replace the pattern with the default tag.
545 (replace-match tag-default t t grep-default 1))))
546
547
548 ;;;###autoload
549 (define-compilation-mode grep-mode "Grep"
550 "Sets `grep-last-buffer' and `compilation-window-height'."
551 (setq grep-last-buffer (current-buffer))
552 (set (make-local-variable 'compilation-error-face)
553 grep-hit-face)
554 (set (make-local-variable 'compilation-error-regexp-alist)
555 grep-regexp-alist)
556 (set (make-local-variable 'compilation-process-setup-function)
557 'grep-process-setup)
558 (set (make-local-variable 'compilation-disable-input) t))
559
560
561 ;;;###autoload
562 (defun grep (command-args)
563 "Run grep, with user-specified args, and collect output in a buffer.
564 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
565 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
566 output buffer, to go to the lines
567 where grep found matches.
568
569 For doing a recursive `grep', see the `rgrep' command. For running
570 `grep' in a specific directory, see `lgrep'.
571
572 This command uses a special history list for its COMMAND-ARGS, so you can
573 easily repeat a grep command.
574
575 A prefix argument says to default the argument based upon the current
576 tag the cursor is over, substituting it into the last grep command
577 in the grep command history (or into `grep-command'
578 if that history list is empty)."
579 (interactive
580 (progn
581 (grep-compute-defaults)
582 (let ((default (grep-default-command)))
583 (list (read-from-minibuffer "Run grep (like this): "
584 (if current-prefix-arg
585 default grep-command)
586 nil nil 'grep-history
587 (if current-prefix-arg nil default))))))
588
589 ;; Setting process-setup-function makes exit-message-function work
590 ;; even when async processes aren't supported.
591 (compilation-start (if (and grep-use-null-device null-device)
592 (concat command-args " " null-device)
593 command-args)
594 'grep-mode))
595
596
597 ;;;###autoload
598 (defun grep-find (command-args)
599 "Run grep via find, with user-specified args COMMAND-ARGS.
600 Collect output in a buffer.
601 While find runs asynchronously, you can use the \\[next-error] command
602 to find the text that grep hits refer to.
603
604 This command uses a special history list for its arguments, so you can
605 easily repeat a find command."
606 (interactive
607 (progn
608 (grep-compute-defaults)
609 (if grep-find-command
610 (list (read-from-minibuffer "Run find (like this): "
611 grep-find-command nil nil
612 'grep-find-history))
613 ;; No default was set
614 (read-string
615 "compile.el: No `grep-find-command' command available. Press RET.")
616 (list nil))))
617 (when command-args
618 (let ((null-device nil)) ; see grep
619 (grep command-args))))
620
621 ;;;###autoload
622 (defalias 'find-grep 'grep-find)
623
624
625 ;; User-friendly interactive API.
626
627 (defconst grep-expand-keywords
628 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
629 ("<D>" . dir)
630 ("<F>" . files)
631 ("<N>" . null-device)
632 ("<X>" . excl)
633 ("<R>" . (shell-quote-argument (or regexp ""))))
634 "List of substitutions performed by `grep-expand-template'.
635 If car of an element matches, the cdr is evalled in to get the
636 substitution string. Note dynamic scoping of variables.")
637
638 (defun grep-expand-template (template &optional regexp files dir excl)
639 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
640 (let ((command template)
641 (cf case-fold-search)
642 (case-fold-search nil))
643 (dolist (kw grep-expand-keywords command)
644 (if (string-match (car kw) command)
645 (setq command
646 (replace-match
647 (or (if (symbolp (cdr kw))
648 (symbol-value (cdr kw))
649 (save-match-data (eval (cdr kw))))
650 "")
651 t t command))))))
652
653 (defun grep-read-regexp ()
654 "Read regexp arg for interactive grep."
655 (let ((default (grep-tag-default)))
656 (read-string
657 (concat "Search for"
658 (if (and default (> (length default) 0))
659 (format " (default \"%s\"): " default) ": "))
660 nil 'grep-regexp-history default)))
661
662 (defun grep-read-files (regexp)
663 "Read files arg for interactive grep."
664 (let* ((bn (or (buffer-file-name) (buffer-name)))
665 (fn (and bn
666 (stringp bn)
667 (file-name-nondirectory bn)))
668 (default
669 (or (and fn
670 (let ((aliases grep-files-aliases)
671 alias)
672 (while aliases
673 (setq alias (car aliases)
674 aliases (cdr aliases))
675 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
676 (setq aliases nil)
677 (setq alias nil)))
678 (cdr alias)))
679 (and fn
680 (let ((ext (file-name-extension fn)))
681 (and ext (concat "*." ext))))
682 (car grep-files-history)
683 (car (car grep-files-aliases))))
684 (files (read-string
685 (concat "Search for \"" regexp
686 "\" in files"
687 (if default (concat " (default " default ")"))
688 ": ")
689 nil 'grep-files-history default)))
690 (and files
691 (or (cdr (assoc files grep-files-aliases))
692 files))))
693
694 ;;;###autoload
695 (defun lgrep (regexp &optional files dir)
696 "Run grep, searching for REGEXP in FILES in directory DIR.
697 The search is limited to file names matching shell pattern FILES.
698 FILES may use abbreviations defined in `grep-files-aliases', e.g.
699 entering `ch' is equivalent to `*.[ch]'.
700
701 With \\[universal-argument] prefix, you can edit the constructed shell command line
702 before it is executed.
703 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
704
705 Collect output in a buffer. While grep runs asynchronously, you
706 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error]
707 in the grep output buffer, to go to the lines where grep found matches.
708
709 This command shares argument histories with \\[rgrep] and \\[grep]."
710 (interactive
711 (progn
712 (grep-compute-defaults)
713 (cond
714 ((and grep-command (equal current-prefix-arg '(16)))
715 (list (read-from-minibuffer "Run: " grep-command
716 nil nil 'grep-history)
717 nil))
718 ((not grep-template)
719 (list nil
720 (read-string "grep.el: No `grep-template' available. Press RET.")))
721 (t (let* ((regexp (grep-read-regexp))
722 (files (grep-read-files regexp))
723 (dir (read-directory-name "In directory: "
724 nil default-directory t)))
725 (list regexp files dir))))))
726 (when (and (stringp regexp) (> (length regexp) 0))
727 (let ((command regexp))
728 (if (null files)
729 (if (string= command grep-command)
730 (setq command nil))
731 (setq dir (file-name-as-directory (expand-file-name dir)))
732 (setq command (grep-expand-template
733 grep-template
734 regexp
735 files))
736 (when command
737 (if (equal current-prefix-arg '(4))
738 (setq command
739 (read-from-minibuffer "Confirm: "
740 command nil nil 'grep-history))
741 (add-to-history 'grep-history command))))
742 (when command
743 (let ((default-directory dir))
744 ;; Setting process-setup-function makes exit-message-function work
745 ;; even when async processes aren't supported.
746 (compilation-start (if (and grep-use-null-device null-device)
747 (concat command " " null-device)
748 command) 'grep-mode))
749 (if (eq next-error-last-buffer (current-buffer))
750 (setq default-directory dir))))))
751
752
753
754 ;;;###autoload
755 (defun rgrep (regexp &optional files dir)
756 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
757 The search is limited to file names matching shell pattern FILES.
758 FILES may use abbreviations defined in `grep-files-aliases', e.g.
759 entering `ch' is equivalent to `*.[ch]'.
760
761 With \\[universal-argument] prefix, you can edit the constructed shell command line
762 before it is executed.
763 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
764
765 Collect output in a buffer. While find runs asynchronously, you
766 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error]
767 in the grep output buffer, to go to the lines where grep found matches.
768
769 This command shares argument histories with \\[lgrep] and \\[grep-find]."
770 (interactive
771 (progn
772 (grep-compute-defaults)
773 (cond
774 ((and grep-find-command (equal current-prefix-arg '(16)))
775 (list (read-from-minibuffer "Run: " grep-find-command
776 nil nil 'grep-find-history)
777 nil))
778 ((not grep-find-template)
779 (list nil nil
780 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
781 (t (let* ((regexp (grep-read-regexp))
782 (files (grep-read-files regexp))
783 (dir (read-directory-name "Base directory: "
784 nil default-directory t)))
785 (list regexp files dir))))))
786 (when (and (stringp regexp) (> (length regexp) 0))
787 (if (null files)
788 (if (not (string= regexp grep-find-command))
789 (compilation-start regexp 'grep-mode))
790 (setq dir (file-name-as-directory (expand-file-name dir)))
791 (let ((command (grep-expand-template
792 grep-find-template
793 regexp
794 (concat (shell-quote-argument "(")
795 " -name "
796 (mapconcat #'shell-quote-argument
797 (split-string files)
798 " -o -name ")
799 " "
800 (shell-quote-argument ")"))
801 dir
802 (and grep-find-ignored-directories
803 (concat (shell-quote-argument "(")
804 ;; we should use shell-quote-argument here
805 " -path "
806 (mapconcat #'(lambda (dir)
807 (shell-quote-argument
808 (concat "*/" dir)))
809 grep-find-ignored-directories
810 " -o -path ")
811 " "
812 (shell-quote-argument ")")
813 " -prune -o ")))))
814 (when command
815 (if current-prefix-arg
816 (setq command
817 (read-from-minibuffer "Confirm: "
818 command nil nil 'grep-find-history))
819 (add-to-history 'grep-find-history command))
820 (let ((default-directory dir))
821 (compilation-start command 'grep-mode))
822 ;; Set default-directory if we started rgrep in the *grep* buffer.
823 (if (eq next-error-last-buffer (current-buffer))
824 (setq default-directory dir)))))))
825
826
827 (provide 'grep)
828
829 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
830 ;;; grep.el ends here