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