]> code.delx.au - gnu-emacs/blob - lisp/progmodes/grep.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / 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]*\\)\\([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 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
388 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
389 1 grep-error-face)
390 ;; remove match from grep-regexp-alist before fontifying
391 ("^Grep[/a-zA-z]* started.*"
392 (0 '(face nil message nil help-echo nil mouse-face nil) t))
393 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
394 (0 '(face nil message nil help-echo nil mouse-face nil) t)
395 (1 compilation-info-face nil t)
396 (2 compilation-warning-face nil t))
397 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
398 (0 '(face nil message nil help-echo nil mouse-face nil) t)
399 (1 grep-error-face)
400 (2 grep-error-face nil t))
401 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
402 ;; Highlight grep matches and delete markers
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 (replace-match "" t t nil 3)
413 (replace-match "" t t nil 1))))
414 ("\\(\033\\[[0-9;]*[mK]\\)"
415 ;; Delete all remaining escape sequences
416 ((lambda (bound))
417 (replace-match "" t t nil 1))))
418 "Additional things to highlight in grep output.
419 This gets tacked on the end of the generated expressions.")
420
421 ;;;###autoload
422 (defvar grep-program (purecopy "grep")
423 "The default grep program for `grep-command' and `grep-find-command'.
424 This variable's value takes effect when `grep-compute-defaults' is called.")
425
426 ;;;###autoload
427 (defvar find-program (purecopy "find")
428 "The default find program for `grep-find-command'.
429 This variable's value takes effect when `grep-compute-defaults' is called.")
430
431 ;;;###autoload
432 (defvar xargs-program (purecopy "xargs")
433 "The default xargs program for `grep-find-command'.
434 See `grep-find-use-xargs'.
435 This variable's value takes effect when `grep-compute-defaults' is called.")
436
437 ;;;###autoload
438 (defvar grep-find-use-xargs nil
439 "Non-nil means that `grep-find' uses the `xargs' utility by default.
440 If `exec', use `find -exec'.
441 If `gnu', use `find -print0' and `xargs -0'.
442 Any other non-nil value means to use `find -print' and `xargs'.
443
444 This variable's value takes effect when `grep-compute-defaults' is called.")
445
446 ;; History of grep commands.
447 ;;;###autoload
448 (defvar grep-history nil)
449 ;;;###autoload
450 (defvar grep-find-history nil)
451
452 ;; History of lgrep and rgrep regexp and files args.
453 (defvar grep-regexp-history nil)
454 (defvar grep-files-history nil)
455
456 ;;;###autoload
457 (defun grep-process-setup ()
458 "Setup compilation variables and buffer for `grep'.
459 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
460 (when (eq grep-highlight-matches 'auto-detect)
461 (grep-compute-defaults))
462 (unless (or (eq grep-highlight-matches 'auto-detect)
463 (null grep-highlight-matches))
464 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
465 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
466 (setenv "TERM" "emacs-grep")
467 (setenv "GREP_OPTIONS"
468 (concat (getenv "GREP_OPTIONS")
469 " --color=" (if (eq grep-highlight-matches 'always)
470 "always" "auto")))
471 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
472 (setenv "GREP_COLOR" "01;31")
473 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
474 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
475 (set (make-local-variable 'compilation-exit-message-function)
476 (lambda (status code msg)
477 (if (eq status 'exit)
478 (cond ((zerop code)
479 '("finished (matches found)\n" . "matched"))
480 ((= code 1)
481 '("finished with no matches found\n" . "no match"))
482 (t
483 (cons msg code)))
484 (cons msg code))))
485 (run-hooks 'grep-setup-hook))
486
487 (defun grep-probe (command args &optional func result)
488 (let (process-file-side-effects)
489 (equal (condition-case nil
490 (apply (or func 'process-file) command args)
491 (error nil))
492 (or result 0))))
493
494 ;;;###autoload
495 (defun grep-compute-defaults ()
496 ;; Keep default values.
497 (unless grep-host-defaults-alist
498 (add-to-list
499 'grep-host-defaults-alist
500 (cons nil
501 `((grep-command ,grep-command)
502 (grep-template ,grep-template)
503 (grep-use-null-device ,grep-use-null-device)
504 (grep-find-command ,grep-find-command)
505 (grep-find-template ,grep-find-template)
506 (grep-find-use-xargs ,grep-find-use-xargs)
507 (grep-highlight-matches ,grep-highlight-matches)))))
508 (let* ((host-id
509 (intern (or (file-remote-p default-directory) "localhost")))
510 (host-defaults (assq host-id grep-host-defaults-alist))
511 (defaults (assq nil grep-host-defaults-alist)))
512 ;; There are different defaults on different hosts. They must be
513 ;; computed for every host once.
514 (dolist (setting '(grep-command grep-template
515 grep-use-null-device grep-find-command
516 grep-find-template grep-find-use-xargs
517 grep-highlight-matches))
518 (set setting
519 (cadr (or (assq setting host-defaults)
520 (assq setting defaults)))))
521
522 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
523 (setq grep-use-null-device
524 (with-temp-buffer
525 (let ((hello-file (expand-file-name "HELLO" data-directory)))
526 (not
527 (and (if grep-command
528 ;; `grep-command' is already set, so
529 ;; use that for testing.
530 (grep-probe grep-command
531 `(nil t nil "^English" ,hello-file)
532 #'call-process-shell-command)
533 ;; otherwise use `grep-program'
534 (grep-probe grep-program
535 `(nil t nil "-nH" "^English" ,hello-file)))
536 (progn
537 (goto-char (point-min))
538 (looking-at
539 (concat (regexp-quote hello-file)
540 ":[0-9]+:English")))))))))
541 (unless (and grep-command grep-find-command
542 grep-template grep-find-template)
543 (let ((grep-options
544 (concat (if grep-use-null-device "-n" "-nH")
545 (if (grep-probe grep-program
546 `(nil nil nil "-e" "foo" ,null-device)
547 nil 1)
548 " -e"))))
549 (unless grep-command
550 (setq grep-command
551 (format "%s %s " grep-program grep-options)))
552 (unless grep-template
553 (setq grep-template
554 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
555 (unless grep-find-use-xargs
556 (setq grep-find-use-xargs
557 (cond
558 ((and
559 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
560 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
561 'gnu)
562 (t
563 'exec))))
564 (unless grep-find-command
565 (setq grep-find-command
566 (cond ((eq grep-find-use-xargs 'gnu)
567 ;; Windows shells need the program file name
568 ;; after the pipe symbol be quoted if they use
569 ;; forward slashes as directory separators.
570 (format "%s . -type f -print0 | \"%s\" -0 -e %s"
571 find-program xargs-program grep-command))
572 ((eq grep-find-use-xargs 'exec)
573 (let ((cmd0 (format "%s . -type f -exec %s"
574 find-program grep-command)))
575 (cons
576 (format "%s {} %s %s"
577 cmd0 null-device
578 (shell-quote-argument ";"))
579 (1+ (length cmd0)))))
580 (t
581 (format "%s . -type f -print | \"%s\" %s"
582 find-program xargs-program grep-command)))))
583 (unless grep-find-template
584 (setq grep-find-template
585 (let ((gcmd (format "%s <C> %s <R>"
586 grep-program grep-options)))
587 (cond ((eq grep-find-use-xargs 'gnu)
588 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 -e %s"
589 find-program xargs-program gcmd))
590 ((eq grep-find-use-xargs 'exec)
591 (format "%s . <X> -type f <F> -exec %s {} %s %s"
592 find-program gcmd null-device
593 (shell-quote-argument ";")))
594 (t
595 (format "%s . <X> -type f <F> -print | \"%s\" %s"
596 find-program xargs-program gcmd))))))))
597 (when (eq grep-highlight-matches 'auto-detect)
598 (setq grep-highlight-matches
599 (with-temp-buffer
600 (and (grep-probe grep-program '(nil t nil "--help"))
601 (progn
602 (goto-char (point-min))
603 (search-forward "--color" nil t))
604 ;; Windows and DOS pipes fail `isatty' detection in Grep.
605 (if (memq system-type '(windows-nt ms-dos))
606 'always 'auto)))))
607
608 ;; Save defaults for this host.
609 (setq grep-host-defaults-alist
610 (delete (assq host-id grep-host-defaults-alist)
611 grep-host-defaults-alist))
612 (add-to-list
613 'grep-host-defaults-alist
614 (cons host-id
615 `((grep-command ,grep-command)
616 (grep-template ,grep-template)
617 (grep-use-null-device ,grep-use-null-device)
618 (grep-find-command ,grep-find-command)
619 (grep-find-template ,grep-find-template)
620 (grep-find-use-xargs ,grep-find-use-xargs)
621 (grep-highlight-matches ,grep-highlight-matches))))))
622
623 (defun grep-tag-default ()
624 (or (and transient-mark-mode mark-active
625 (/= (point) (mark))
626 (buffer-substring-no-properties (point) (mark)))
627 (funcall (or find-tag-default-function
628 (get major-mode 'find-tag-default-function)
629 'find-tag-default))
630 ""))
631
632 (defun grep-default-command ()
633 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
634 (let ((tag-default (shell-quote-argument (grep-tag-default)))
635 ;; This a regexp to match single shell arguments.
636 ;; Could someone please add comments explaining it?
637 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
638 (grep-default (or (car grep-history) grep-command)))
639 ;; In the default command, find the arg that specifies the pattern.
640 (when (or (string-match
641 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
642 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
643 grep-default)
644 ;; If the string is not yet complete.
645 (string-match "\\(\\)\\'" grep-default))
646 ;; Maybe we will replace the pattern with the default tag.
647 ;; But first, maybe replace the file name pattern.
648 (condition-case nil
649 (unless (or (not (stringp buffer-file-name))
650 (when (match-beginning 2)
651 (save-match-data
652 (string-match
653 (wildcard-to-regexp
654 (file-name-nondirectory
655 (match-string 3 grep-default)))
656 (file-name-nondirectory buffer-file-name)))))
657 (setq grep-default (concat (substring grep-default
658 0 (match-beginning 2))
659 " *."
660 (file-name-extension buffer-file-name))))
661 ;; In case wildcard-to-regexp gets an error
662 ;; from invalid data.
663 (error nil))
664 ;; Now replace the pattern with the default tag.
665 (replace-match tag-default t t grep-default 1))))
666
667
668 ;;;###autoload
669 (define-compilation-mode grep-mode "Grep"
670 "Sets `grep-last-buffer' and `compilation-window-height'."
671 (setq grep-last-buffer (current-buffer))
672 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
673 (set (make-local-variable 'compilation-error-face)
674 grep-hit-face)
675 (set (make-local-variable 'compilation-error-regexp-alist)
676 grep-regexp-alist)
677 (set (make-local-variable 'compilation-process-setup-function)
678 'grep-process-setup)
679 (set (make-local-variable 'compilation-disable-input) t))
680
681
682 ;;;###autoload
683 (defun grep (command-args)
684 "Run grep, with user-specified args, and collect output in a buffer.
685 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
686 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
687 output buffer, to go to the lines where grep
688 found matches.
689
690 For doing a recursive `grep', see the `rgrep' command. For running
691 `grep' in a specific directory, see `lgrep'.
692
693 This command uses a special history list for its COMMAND-ARGS, so you
694 can easily repeat a grep command.
695
696 A prefix argument says to default the argument based upon the current
697 tag the cursor is over, substituting it into the last grep command
698 in the grep command history (or into `grep-command' if that history
699 list is empty)."
700 (interactive
701 (progn
702 (grep-compute-defaults)
703 (let ((default (grep-default-command)))
704 (list (read-shell-command "Run grep (like this): "
705 (if current-prefix-arg default grep-command)
706 'grep-history
707 (if current-prefix-arg nil default))))))
708
709 ;; Setting process-setup-function makes exit-message-function work
710 ;; even when async processes aren't supported.
711 (compilation-start (if (and grep-use-null-device null-device)
712 (concat command-args " " null-device)
713 command-args)
714 'grep-mode))
715
716
717 ;;;###autoload
718 (defun grep-find (command-args)
719 "Run grep via find, with user-specified args COMMAND-ARGS.
720 Collect output in a buffer.
721 While find runs asynchronously, you can use the \\[next-error] command
722 to find the text that grep hits refer to.
723
724 This command uses a special history list for its arguments, so you can
725 easily repeat a find command."
726 (interactive
727 (progn
728 (grep-compute-defaults)
729 (if grep-find-command
730 (list (read-shell-command "Run find (like this): "
731 grep-find-command 'grep-find-history))
732 ;; No default was set
733 (read-string
734 "compile.el: No `grep-find-command' command available. Press RET.")
735 (list nil))))
736 (when command-args
737 (let ((null-device nil)) ; see grep
738 (grep command-args))))
739
740 ;;;###autoload
741 (defalias 'find-grep 'grep-find)
742
743
744 ;; User-friendly interactive API.
745
746 (defconst grep-expand-keywords
747 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
748 ("<D>" . dir)
749 ("<F>" . files)
750 ("<N>" . null-device)
751 ("<X>" . excl)
752 ("<R>" . (shell-quote-argument (or regexp ""))))
753 "List of substitutions performed by `grep-expand-template'.
754 If car of an element matches, the cdr is evalled in to get the
755 substitution string. Note dynamic scoping of variables.")
756
757 (defun grep-expand-template (template &optional regexp files dir excl)
758 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
759 (let ((command template)
760 (cf case-fold-search)
761 (case-fold-search nil))
762 (dolist (kw grep-expand-keywords command)
763 (if (string-match (car kw) command)
764 (setq command
765 (replace-match
766 (or (if (symbolp (cdr kw))
767 (symbol-value (cdr kw))
768 (save-match-data (eval (cdr kw))))
769 "")
770 t t command))))))
771
772 (defun grep-read-regexp ()
773 "Read regexp arg for interactive grep."
774 (let ((default (grep-tag-default)))
775 (read-string
776 (concat "Search for"
777 (if (and default (> (length default) 0))
778 (format " (default \"%s\"): " default) ": "))
779 nil 'grep-regexp-history default)))
780
781 (defun grep-read-files (regexp)
782 "Read files arg for interactive grep."
783 (let* ((bn (or (buffer-file-name)
784 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
785 (fn (and bn
786 (stringp bn)
787 (file-name-nondirectory bn)))
788 (default-alias
789 (and fn
790 (let ((aliases (remove (assoc "all" grep-files-aliases)
791 grep-files-aliases))
792 alias)
793 (while aliases
794 (setq alias (car aliases)
795 aliases (cdr aliases))
796 (if (string-match (mapconcat
797 'wildcard-to-regexp
798 (split-string (cdr alias) nil t)
799 "\\|")
800 fn)
801 (setq aliases nil)
802 (setq alias nil)))
803 (cdr alias))))
804 (default-extension
805 (and fn
806 (let ((ext (file-name-extension fn)))
807 (and ext (concat "*." ext)))))
808 (default
809 (or default-alias
810 default-extension
811 (car grep-files-history)
812 (car (car grep-files-aliases))))
813 (files (completing-read
814 (concat "Search for \"" regexp
815 "\" in files"
816 (if default (concat " (default " default ")"))
817 ": ")
818 'read-file-name-internal
819 nil nil nil 'grep-files-history
820 (delete-dups
821 (delq nil (append (list default default-alias default-extension)
822 (mapcar 'car grep-files-aliases)))))))
823 (and files
824 (or (cdr (assoc files grep-files-aliases))
825 files))))
826
827 ;;;###autoload
828 (defun lgrep (regexp &optional files dir confirm)
829 "Run grep, searching for REGEXP in FILES in directory DIR.
830 The search is limited to file names matching shell pattern FILES.
831 FILES may use abbreviations defined in `grep-files-aliases', e.g.
832 entering `ch' is equivalent to `*.[ch]'.
833
834 With \\[universal-argument] prefix, you can edit the constructed shell command line
835 before it is executed.
836 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
837
838 Collect output in a buffer. While grep runs asynchronously, you
839 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
840 in the grep output buffer,
841 to go to the lines where grep found matches.
842
843 This command shares argument histories with \\[rgrep] and \\[grep]."
844 (interactive
845 (progn
846 (grep-compute-defaults)
847 (cond
848 ((and grep-command (equal current-prefix-arg '(16)))
849 (list (read-from-minibuffer "Run: " grep-command
850 nil nil 'grep-history)))
851 ((not grep-template)
852 (error "grep.el: No `grep-template' available"))
853 (t (let* ((regexp (grep-read-regexp))
854 (files (grep-read-files regexp))
855 (dir (read-directory-name "In directory: "
856 nil default-directory t))
857 (confirm (equal current-prefix-arg '(4))))
858 (list regexp files dir confirm))))))
859 (when (and (stringp regexp) (> (length regexp) 0))
860 (unless (and dir (file-directory-p dir) (file-readable-p dir))
861 (setq dir default-directory))
862 (let ((command regexp))
863 (if (null files)
864 (if (string= command grep-command)
865 (setq command nil))
866 (setq dir (file-name-as-directory (expand-file-name dir)))
867 (setq command (grep-expand-template
868 grep-template
869 regexp
870 files
871 nil
872 (and grep-find-ignored-files
873 (concat " --exclude="
874 (mapconcat
875 #'(lambda (ignore)
876 (cond ((stringp ignore)
877 (shell-quote-argument ignore))
878 ((consp ignore)
879 (and (funcall (car ignore) dir)
880 (shell-quote-argument
881 (cdr ignore))))))
882 grep-find-ignored-files
883 " --exclude=")))))
884 (when command
885 (if confirm
886 (setq command
887 (read-from-minibuffer "Confirm: "
888 command nil nil 'grep-history))
889 (add-to-history 'grep-history command))))
890 (when command
891 (let ((default-directory dir))
892 ;; Setting process-setup-function makes exit-message-function work
893 ;; even when async processes aren't supported.
894 (compilation-start (if (and grep-use-null-device null-device)
895 (concat command " " null-device)
896 command)
897 'grep-mode))
898 (if (eq next-error-last-buffer (current-buffer))
899 (setq default-directory dir))))))
900
901
902 (defvar find-name-arg) ; not autoloaded but defined in find-dired
903
904 ;;;###autoload
905 (defun rgrep (regexp &optional files dir confirm)
906 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
907 The search is limited to file names matching shell pattern FILES.
908 FILES may use abbreviations defined in `grep-files-aliases', e.g.
909 entering `ch' is equivalent to `*.[ch]'.
910
911 With \\[universal-argument] prefix, you can edit the constructed shell command line
912 before it is executed.
913 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
914
915 Collect output in a buffer. While find runs asynchronously, you
916 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
917 in the grep output buffer,
918 to go to the lines where grep found matches.
919
920 This command shares argument histories with \\[lgrep] and \\[grep-find]."
921 (interactive
922 (progn
923 (grep-compute-defaults)
924 (cond
925 ((and grep-find-command (equal current-prefix-arg '(16)))
926 (list (read-from-minibuffer "Run: " grep-find-command
927 nil nil 'grep-find-history)))
928 ((not grep-find-template)
929 (error "grep.el: No `grep-find-template' available"))
930 (t (let* ((regexp (grep-read-regexp))
931 (files (grep-read-files regexp))
932 (dir (read-directory-name "Base directory: "
933 nil default-directory t))
934 (confirm (equal current-prefix-arg '(4))))
935 (list regexp files dir confirm))))))
936 (when (and (stringp regexp) (> (length regexp) 0))
937 (unless (and dir (file-directory-p dir) (file-readable-p dir))
938 (setq dir default-directory))
939 (if (null files)
940 (if (not (string= regexp grep-find-command))
941 (compilation-start regexp 'grep-mode))
942 (setq dir (file-name-as-directory (expand-file-name dir)))
943 (require 'find-dired) ; for `find-name-arg'
944 (let ((command (grep-expand-template
945 grep-find-template
946 regexp
947 (concat (shell-quote-argument "(")
948 " " find-name-arg " "
949 (mapconcat #'shell-quote-argument
950 (split-string files)
951 (concat " -o " find-name-arg " "))
952 " "
953 (shell-quote-argument ")"))
954 dir
955 (concat
956 (and grep-find-ignored-directories
957 (concat (shell-quote-argument "(")
958 ;; we should use shell-quote-argument here
959 " -path "
960 (mapconcat
961 #'(lambda (ignore)
962 (cond ((stringp ignore)
963 (shell-quote-argument
964 (concat "*/" ignore)))
965 ((consp ignore)
966 (and (funcall (car ignore) dir)
967 (shell-quote-argument
968 (concat "*/"
969 (cdr ignore)))))))
970 grep-find-ignored-directories
971 " -o -path ")
972 " "
973 (shell-quote-argument ")")
974 " -prune -o "))
975 (and grep-find-ignored-files
976 (concat (shell-quote-argument "(")
977 ;; we should use shell-quote-argument here
978 " -name "
979 (mapconcat
980 #'(lambda (ignore)
981 (cond ((stringp ignore)
982 (shell-quote-argument ignore))
983 ((consp ignore)
984 (and (funcall (car ignore) dir)
985 (shell-quote-argument
986 (cdr ignore))))))
987 grep-find-ignored-files
988 " -o -name ")
989 " "
990 (shell-quote-argument ")")
991 " -prune -o "))))))
992 (when command
993 (if confirm
994 (setq command
995 (read-from-minibuffer "Confirm: "
996 command nil nil 'grep-find-history))
997 (add-to-history 'grep-find-history command))
998 (let ((default-directory dir))
999 (compilation-start command 'grep-mode))
1000 ;; Set default-directory if we started rgrep in the *grep* buffer.
1001 (if (eq next-error-last-buffer (current-buffer))
1002 (setq default-directory dir)))))))
1003
1004 ;;;###autoload
1005 (defun zrgrep (regexp &optional files dir confirm grep-find-template)
1006 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1007 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1008 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1009 (interactive
1010 (progn
1011 ;; Compute standard default values.
1012 (grep-compute-defaults)
1013 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1014 ;; for grep program "zgrep", but not changing global values.
1015 (let ((grep-program "zgrep")
1016 ;; Don't change global values for variables computed
1017 ;; by `grep-compute-defaults'.
1018 (grep-find-template nil)
1019 (grep-find-command nil)
1020 (grep-host-defaults-alist nil)
1021 ;; Use for `grep-read-files'
1022 (grep-files-aliases '(("all" . "* .*")
1023 ("gz" . "*.gz"))))
1024 ;; Recompute defaults using let-bound values above.
1025 (grep-compute-defaults)
1026 (cond
1027 ((and grep-find-command (equal current-prefix-arg '(16)))
1028 (list (read-from-minibuffer "Run: " grep-find-command
1029 nil nil 'grep-find-history)))
1030 ((not grep-find-template)
1031 (error "grep.el: No `grep-find-template' available"))
1032 (t (let* ((regexp (grep-read-regexp))
1033 (files (grep-read-files regexp))
1034 (dir (read-directory-name "Base directory: "
1035 nil default-directory t))
1036 (confirm (equal current-prefix-arg '(4))))
1037 (list regexp files dir confirm grep-find-template)))))))
1038 ;; Set `grep-highlight-matches' to `always'
1039 ;; since `zgrep' puts filters in the grep output.
1040 (let ((grep-highlight-matches 'always))
1041 ;; `rgrep' uses the dynamically bound value `grep-find-template'
1042 ;; from the argument `grep-find-template' whose value is computed
1043 ;; in the `interactive' spec.
1044 (rgrep regexp files dir confirm)))
1045
1046 ;;;###autoload
1047 (defalias 'rzgrep 'zrgrep)
1048
1049 (provide 'grep)
1050
1051 ;;; grep.el ends here