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