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