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