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