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