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