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