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