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