]> code.delx.au - gnu-emacs/blob - lisp/progmodes/grep.el
Merge from emacs-24; up to 2012-12-17T11:17:34Z!rgm@gnu.org
[gnu-emacs] / lisp / progmodes / grep.el
1 ;;; grep.el --- run `grep' and display the results
2
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2013 Free Software
4 ;; 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' and display the results."
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 beginning."
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-command)
249 (define-key map [?\S-\ ] 'scroll-down-command)
250 (define-key map "\^?" 'scroll-down-command)
251 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
252
253 (define-key map "\r" 'compile-goto-error) ;; ?
254 (define-key map "n" 'next-error-no-select)
255 (define-key map "p" 'previous-error-no-select)
256 (define-key map "{" 'compilation-previous-file)
257 (define-key map "}" 'compilation-next-file)
258 (define-key map "\t" 'compilation-next-error)
259 (define-key map [backtab] 'compilation-previous-error)
260
261 ;; Set up the menu-bar
262 (define-key map [menu-bar grep]
263 (cons "Grep" (make-sparse-keymap "Grep")))
264
265 (define-key map [menu-bar grep compilation-kill-compilation]
266 '(menu-item "Kill Grep" kill-compilation
267 :help "Kill the currently running grep process"))
268 (define-key map [menu-bar grep compilation-separator2] '("----"))
269 (define-key map [menu-bar grep compilation-compile]
270 '(menu-item "Compile..." compile
271 :help "Compile the program including the current buffer. Default: run `make'"))
272 (define-key map [menu-bar grep compilation-rgrep]
273 '(menu-item "Recursive grep..." rgrep
274 :help "User-friendly recursive grep in directory tree"))
275 (define-key map [menu-bar grep compilation-lgrep]
276 '(menu-item "Local grep..." lgrep
277 :help "User-friendly grep in a directory"))
278 (define-key map [menu-bar grep compilation-grep-find]
279 '(menu-item "Grep via Find..." grep-find
280 :help "Run grep via find, with user-specified args"))
281 (define-key map [menu-bar grep compilation-grep]
282 '(menu-item "Another grep..." grep
283 :help "Run grep, with user-specified args, and collect output in a buffer."))
284 (define-key map [menu-bar grep compilation-recompile]
285 '(menu-item "Repeat grep" recompile
286 :help "Run grep again"))
287 (define-key map [menu-bar grep compilation-separator2] '("----"))
288 (define-key map [menu-bar grep compilation-first-error]
289 '(menu-item "First Match" first-error
290 :help "Restart at the first match, visit corresponding location"))
291 (define-key map [menu-bar grep compilation-previous-error]
292 '(menu-item "Previous Match" previous-error
293 :help "Visit the previous match and corresponding location"))
294 (define-key map [menu-bar grep compilation-next-error]
295 '(menu-item "Next Match" next-error
296 :help "Visit the next match and corresponding location"))
297 map)
298 "Keymap for grep buffers.
299 `compilation-minor-mode-map' is a cdr of this.")
300
301 (defvar grep-mode-tool-bar-map
302 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
303 ;; so don't do anything.
304 (when (keymapp (butlast tool-bar-map))
305 (let ((map (butlast (copy-keymap tool-bar-map)))
306 (help (last tool-bar-map))) ;; Keep Help last in tool bar
307 (tool-bar-local-item
308 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
309 :rtl "right-arrow"
310 :help "Goto previous match")
311 (tool-bar-local-item
312 "right-arrow" 'next-error-no-select 'next-error-no-select map
313 :rtl "left-arrow"
314 :help "Goto next match")
315 (tool-bar-local-item
316 "cancel" 'kill-compilation 'kill-compilation map
317 :enable '(let ((buffer (compilation-find-buffer)))
318 (get-buffer-process buffer))
319 :help "Stop grep")
320 (tool-bar-local-item
321 "refresh" 'recompile 'recompile map
322 :help "Restart grep")
323 (append map help))))
324
325 (defalias 'kill-grep 'kill-compilation)
326
327 ;;;; TODO --- refine this!!
328
329 ;; (defcustom grep-use-compilation-buffer t
330 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
331 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
332 ;; can be used to navigate between grep matches (the default).
333 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
334 ;; be used to navigate between grep matches."
335 ;; :type 'boolean
336 ;; :group 'grep)
337
338 ;; override compilation-last-buffer
339 (defvar grep-last-buffer nil
340 "The most recent grep buffer.
341 A grep buffer becomes most recent when you select Grep mode in it.
342 Notice that using \\[next-error] or \\[compile-goto-error] modifies
343 `compilation-last-buffer' rather than `grep-last-buffer'.")
344
345 ;;;###autoload
346 (defconst grep-regexp-alist
347 '(
348 ;; Rule to match column numbers is commented out since no known grep
349 ;; produces them
350 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([1-9][0-9]*\\)\\2\\(?:\\([1-9][0-9]*\\)\\(?:-\\([1-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:"
355 ;; in file names.
356 ("^\\(.+?\\)\\(:[ \t]*\\)\\([1-9][0-9]*\\)\\2"
357 1 3
358 ;; Calculate column positions (col . end-col) of first grep match on a line
359 ((lambda ()
360 (when grep-highlight-matches
361 (let* ((beg (match-end 0))
362 (end (save-excursion (goto-char beg) (line-end-position)))
363 (mbeg (text-property-any beg end 'font-lock-face grep-match-face)))
364 (when mbeg
365 (- mbeg beg)))))
366 .
367 (lambda ()
368 (when grep-highlight-matches
369 (let* ((beg (match-end 0))
370 (end (save-excursion (goto-char beg) (line-end-position)))
371 (mbeg (text-property-any beg end 'font-lock-face grep-match-face))
372 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
373 (when mend
374 (- mend beg)))))))
375 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
376 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
377
378 (defvar grep-first-column 0 ; bug#10594
379 "Value to use for `compilation-first-column' in grep buffers.")
380
381 (defvar grep-error "grep hit"
382 "Message to print when no matches are found.")
383
384 ;; Reverse the colors because grep hits are not errors (though we jump there
385 ;; with `next-error'), and unreadable files can't be gone to.
386 (defvar grep-hit-face compilation-info-face
387 "Face name to use for grep hits.")
388
389 (defvar grep-error-face 'compilation-error
390 "Face name to use for grep error messages.")
391
392 (defvar grep-match-face 'match
393 "Face name to use for grep matches.")
394
395 (defvar grep-context-face 'shadow
396 "Face name to use for grep context lines.")
397
398 (defvar grep-mode-font-lock-keywords
399 '(;; Command output lines.
400 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
401 1 grep-error-face)
402 ;; remove match from grep-regexp-alist before fontifying
403 ("^Grep[/a-zA-z]* started.*"
404 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
405 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
406 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
407 (1 compilation-info-face nil t)
408 (2 compilation-warning-face nil t))
409 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
410 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
411 (1 grep-error-face)
412 (2 grep-error-face nil t))
413 ("^.+?-[0-9]+-.*\n" (0 grep-context-face)))
414 "Additional things to highlight in grep output.
415 This gets tacked on the end of the generated expressions.")
416
417 ;;;###autoload
418 (defvar grep-program (purecopy "grep")
419 "The default grep program for `grep-command' and `grep-find-command'.
420 This variable's value takes effect when `grep-compute-defaults' is called.")
421
422 ;;;###autoload
423 (defvar find-program (purecopy "find")
424 "The default find program for `grep-find-command'.
425 This variable's value takes effect when `grep-compute-defaults' is called.")
426
427 ;;;###autoload
428 (defvar xargs-program (purecopy "xargs")
429 "The default xargs program for `grep-find-command'.
430 See `grep-find-use-xargs'.
431 This variable's value takes effect when `grep-compute-defaults' is called.")
432
433 ;;;###autoload
434 (defvar grep-find-use-xargs nil
435 "How to invoke find and grep.
436 If `exec', use `find -exec {} ;'.
437 If `exec-plus' use `find -exec {} +'.
438 If `gnu', use `find -print0' and `xargs -0'.
439 Any other 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 "History list for grep.")
446 ;;;###autoload
447 (defvar grep-find-history nil "History list for grep-find.")
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 ;; Don't output color escapes if they can't be
462 ;; highlighted with `font-lock-face' by `grep-filter'.
463 (null font-lock-mode))
464 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
465 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
466 (setenv "TERM" "emacs-grep")
467 (setenv "GREP_OPTIONS"
468 (concat (getenv "GREP_OPTIONS")
469 " --color=" (if (eq grep-highlight-matches 'always)
470 "always" "auto")))
471 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
472 (setenv "GREP_COLOR" "01;31")
473 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
474 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
475 (set (make-local-variable 'compilation-exit-message-function)
476 (lambda (status code msg)
477 (if (eq status 'exit)
478 ;; This relies on the fact that `compilation-start'
479 ;; sets buffer-modified to nil before running the command,
480 ;; so the buffer is still unmodified if there is no output.
481 (cond ((and (zerop code) (buffer-modified-p))
482 '("finished (matches found)\n" . "matched"))
483 ((not (buffer-modified-p))
484 '("finished with no matches found\n" . "no match"))
485 (t
486 (cons msg code)))
487 (cons msg code))))
488 (run-hooks 'grep-setup-hook))
489
490 (defun grep-filter ()
491 "Handle match highlighting escape sequences inserted by the grep process.
492 This function is called from `compilation-filter-hook'."
493 (save-excursion
494 (forward-line 0)
495 (let ((end (point)) beg)
496 (goto-char compilation-filter-start)
497 (forward-line 0)
498 (setq beg (point))
499 ;; Only operate on whole lines so we don't get caught with part of an
500 ;; escape sequence in one chunk and the rest in another.
501 (when (< (point) end)
502 (setq end (copy-marker end))
503 ;; Highlight grep matches and delete marking sequences.
504 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
505 (replace-match (propertize (match-string 1)
506 'face nil 'font-lock-face grep-match-face)
507 t t))
508 ;; Delete all remaining escape sequences
509 (goto-char beg)
510 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
511 (replace-match "" t t))))))
512
513 (defun grep-probe (command args &optional func result)
514 (let (process-file-side-effects)
515 (equal (condition-case nil
516 (apply (or func 'process-file) command args)
517 (error nil))
518 (or result 0))))
519
520 ;;;###autoload
521 (defun grep-compute-defaults ()
522 ;; Keep default values.
523 (unless grep-host-defaults-alist
524 (add-to-list
525 'grep-host-defaults-alist
526 (cons nil
527 `((grep-command ,grep-command)
528 (grep-template ,grep-template)
529 (grep-use-null-device ,grep-use-null-device)
530 (grep-find-command ,grep-find-command)
531 (grep-find-template ,grep-find-template)
532 (grep-find-use-xargs ,grep-find-use-xargs)
533 (grep-highlight-matches ,grep-highlight-matches)))))
534 (let* ((host-id
535 (intern (or (file-remote-p default-directory) "localhost")))
536 (host-defaults (assq host-id grep-host-defaults-alist))
537 (defaults (assq nil grep-host-defaults-alist)))
538 ;; There are different defaults on different hosts. They must be
539 ;; computed for every host once.
540 (dolist (setting '(grep-command grep-template
541 grep-use-null-device grep-find-command
542 grep-find-template grep-find-use-xargs
543 grep-highlight-matches))
544 (set setting
545 (cadr (or (assq setting host-defaults)
546 (assq setting defaults)))))
547
548 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
549 (setq grep-use-null-device
550 (with-temp-buffer
551 (let ((hello-file (expand-file-name "HELLO" data-directory)))
552 (not
553 (and (if grep-command
554 ;; `grep-command' is already set, so
555 ;; use that for testing.
556 (grep-probe grep-command
557 `(nil t nil "^English" ,hello-file)
558 #'call-process-shell-command)
559 ;; otherwise use `grep-program'
560 (grep-probe grep-program
561 `(nil t nil "-nH" "^English" ,hello-file)))
562 (progn
563 (goto-char (point-min))
564 (looking-at
565 (concat (regexp-quote hello-file)
566 ":[0-9]+:English")))))))))
567 (unless (and grep-command grep-find-command
568 grep-template grep-find-template)
569 (let ((grep-options
570 (concat (if grep-use-null-device "-n" "-nH")
571 (if (grep-probe grep-program
572 `(nil nil nil "-e" "foo" ,null-device)
573 nil 1)
574 " -e"))))
575 (unless grep-command
576 (setq grep-command
577 (format "%s %s " grep-program grep-options)))
578 (unless grep-template
579 (setq grep-template
580 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
581 (unless grep-find-use-xargs
582 (setq grep-find-use-xargs
583 (cond
584 ((grep-probe find-program
585 `(nil nil nil ,null-device "-exec" "echo"
586 "{}" "+"))
587 'exec-plus)
588 ((and
589 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
590 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
591 'gnu)
592 (t
593 'exec))))
594 (unless grep-find-command
595 (setq grep-find-command
596 (cond ((eq grep-find-use-xargs 'gnu)
597 ;; Windows shells need the program file name
598 ;; after the pipe symbol be quoted if they use
599 ;; forward slashes as directory separators.
600 (format "%s . -type f -print0 | \"%s\" -0 %s"
601 find-program xargs-program grep-command))
602 ((memq grep-find-use-xargs '(exec exec-plus))
603 (let ((cmd0 (format "%s . -type f -exec %s"
604 find-program grep-command))
605 (null (if grep-use-null-device
606 (format "%s " null-device)
607 "")))
608 (cons
609 (if (eq grep-find-use-xargs 'exec-plus)
610 (format "%s %s{} +" cmd0 null)
611 (format "%s {} %s%s" cmd0 null
612 (shell-quote-argument ";")))
613 (1+ (length cmd0)))))
614 (t
615 (format "%s . -type f -print | \"%s\" %s"
616 find-program xargs-program grep-command)))))
617 (unless grep-find-template
618 (setq grep-find-template
619 (let ((gcmd (format "%s <C> %s <R>"
620 grep-program grep-options))
621 (null (if grep-use-null-device
622 (format "%s " null-device)
623 "")))
624 (cond ((eq grep-find-use-xargs 'gnu)
625 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 %s"
626 find-program xargs-program gcmd))
627 ((eq grep-find-use-xargs 'exec)
628 (format "%s . <X> -type f <F> -exec %s {} %s%s"
629 find-program gcmd null
630 (shell-quote-argument ";")))
631 ((eq grep-find-use-xargs 'exec-plus)
632 (format "%s . <X> -type f <F> -exec %s %s{} +"
633 find-program gcmd null))
634 (t
635 (format "%s . <X> -type f <F> -print | \"%s\" %s"
636 find-program xargs-program gcmd))))))))
637 (when (eq grep-highlight-matches 'auto-detect)
638 (setq grep-highlight-matches
639 (with-temp-buffer
640 (and (grep-probe grep-program '(nil t nil "--help"))
641 (progn
642 (goto-char (point-min))
643 (search-forward "--color" nil t))
644 ;; Windows and DOS pipes fail `isatty' detection in Grep.
645 (if (memq system-type '(windows-nt ms-dos))
646 'always 'auto)))))
647
648 ;; Save defaults for this host.
649 (setq grep-host-defaults-alist
650 (delete (assq host-id grep-host-defaults-alist)
651 grep-host-defaults-alist))
652 (add-to-list
653 'grep-host-defaults-alist
654 (cons host-id
655 `((grep-command ,grep-command)
656 (grep-template ,grep-template)
657 (grep-use-null-device ,grep-use-null-device)
658 (grep-find-command ,grep-find-command)
659 (grep-find-template ,grep-find-template)
660 (grep-find-use-xargs ,grep-find-use-xargs)
661 (grep-highlight-matches ,grep-highlight-matches))))))
662
663 (defun grep-tag-default ()
664 (or (and transient-mark-mode mark-active
665 (/= (point) (mark))
666 (buffer-substring-no-properties (point) (mark)))
667 (funcall (or find-tag-default-function
668 (get major-mode 'find-tag-default-function)
669 'find-tag-default))
670 ""))
671
672 (defun grep-default-command ()
673 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
674 (let ((tag-default (shell-quote-argument (grep-tag-default)))
675 ;; This a regexp to match single shell arguments.
676 ;; Could someone please add comments explaining it?
677 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
678 (grep-default (or (car grep-history) grep-command)))
679 ;; In the default command, find the arg that specifies the pattern.
680 (when (or (string-match
681 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
682 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
683 grep-default)
684 ;; If the string is not yet complete.
685 (string-match "\\(\\)\\'" grep-default))
686 ;; Maybe we will replace the pattern with the default tag.
687 ;; But first, maybe replace the file name pattern.
688 (condition-case nil
689 (unless (or (not (stringp buffer-file-name))
690 (when (match-beginning 2)
691 (save-match-data
692 (string-match
693 (wildcard-to-regexp
694 (file-name-nondirectory
695 (match-string 3 grep-default)))
696 (file-name-nondirectory buffer-file-name)))))
697 (setq grep-default (concat (substring grep-default
698 0 (match-beginning 2))
699 " *."
700 (file-name-extension buffer-file-name))))
701 ;; In case wildcard-to-regexp gets an error
702 ;; from invalid data.
703 (error nil))
704 ;; Now replace the pattern with the default tag.
705 (replace-match tag-default t t grep-default 1))))
706
707
708 ;;;###autoload
709 (define-compilation-mode grep-mode "Grep"
710 "Sets `grep-last-buffer' and `compilation-window-height'."
711 (setq grep-last-buffer (current-buffer))
712 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
713 (set (make-local-variable 'compilation-error-face)
714 grep-hit-face)
715 (set (make-local-variable 'compilation-error-regexp-alist)
716 grep-regexp-alist)
717 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
718 ;; can never match.
719 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
720 (set (make-local-variable 'compilation-process-setup-function)
721 'grep-process-setup)
722 (set (make-local-variable 'compilation-disable-input) t)
723 (set (make-local-variable 'compilation-error-screen-columns)
724 grep-error-screen-columns)
725 (add-hook 'compilation-filter-hook 'grep-filter nil t))
726
727
728 ;;;###autoload
729 (defun grep (command-args)
730 "Run grep, with user-specified args, and collect output in a buffer.
731 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
732 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
733 buffer, to go to the lines where grep found
734 matches. To kill the grep job before it finishes, type \\[kill-compilation].
735
736 For doing a recursive `grep', see the `rgrep' command. For running
737 `grep' in a specific directory, see `lgrep'.
738
739 This command uses a special history list for its COMMAND-ARGS, so you
740 can easily repeat a grep command.
741
742 A prefix argument says to default the argument based upon the current
743 tag the cursor is over, substituting it into the last grep command
744 in the grep command history (or into `grep-command' if that history
745 list is empty)."
746 (interactive
747 (progn
748 (grep-compute-defaults)
749 (let ((default (grep-default-command)))
750 (list (read-shell-command "Run grep (like this): "
751 (if current-prefix-arg default grep-command)
752 'grep-history
753 (if current-prefix-arg nil default))))))
754
755 ;; Setting process-setup-function makes exit-message-function work
756 ;; even when async processes aren't supported.
757 (compilation-start (if (and grep-use-null-device null-device)
758 (concat command-args " " null-device)
759 command-args)
760 'grep-mode))
761
762
763 ;;;###autoload
764 (defun grep-find (command-args)
765 "Run grep via find, with user-specified args COMMAND-ARGS.
766 Collect output in a buffer.
767 While find runs asynchronously, you can use the \\[next-error] command
768 to find the text that grep hits refer to.
769
770 This command uses a special history list for its arguments, so you can
771 easily repeat a find command."
772 (interactive
773 (progn
774 (grep-compute-defaults)
775 (if grep-find-command
776 (list (read-shell-command "Run find (like this): "
777 grep-find-command 'grep-find-history))
778 ;; No default was set
779 (read-string
780 "compile.el: No `grep-find-command' command available. Press RET.")
781 (list nil))))
782 (when command-args
783 (let ((null-device nil)) ; see grep
784 (grep command-args))))
785
786 ;;;###autoload
787 (defalias 'find-grep 'grep-find)
788
789
790 ;; User-friendly interactive API.
791
792 (defconst grep-expand-keywords
793 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
794 ("<D>" . dir)
795 ("<F>" . files)
796 ("<N>" . null-device)
797 ("<X>" . excl)
798 ("<R>" . (shell-quote-argument (or regexp ""))))
799 "List of substitutions performed by `grep-expand-template'.
800 If car of an element matches, the cdr is evalled in to get the
801 substitution string. Note dynamic scoping of variables.")
802
803 (defun grep-expand-template (template &optional regexp files dir excl)
804 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
805 (let ((command template)
806 (cf case-fold-search)
807 (case-fold-search nil))
808 (dolist (kw grep-expand-keywords command)
809 (if (string-match (car kw) command)
810 (setq command
811 (replace-match
812 (or (if (symbolp (cdr kw))
813 (symbol-value (cdr kw))
814 (save-match-data (eval (cdr kw))))
815 "")
816 t t command))))))
817
818 (defun grep-read-regexp ()
819 "Read regexp arg for interactive grep."
820 (let ((default (grep-tag-default)))
821 (read-regexp
822 (concat "Search for"
823 (if (and default (> (length default) 0))
824 (format " (default \"%s\"): " default) ": "))
825 default 'grep-regexp-history)))
826
827 (defun grep-read-files (regexp)
828 "Read files arg for interactive grep."
829 (let* ((bn (or (buffer-file-name)
830 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
831 (fn (and bn
832 (stringp bn)
833 (file-name-nondirectory bn)))
834 (default-alias
835 (and fn
836 (let ((aliases (remove (assoc "all" grep-files-aliases)
837 grep-files-aliases))
838 alias)
839 (while aliases
840 (setq alias (car aliases)
841 aliases (cdr aliases))
842 (if (string-match (mapconcat
843 'wildcard-to-regexp
844 (split-string (cdr alias) nil t)
845 "\\|")
846 fn)
847 (setq aliases nil)
848 (setq alias nil)))
849 (cdr alias))))
850 (default-extension
851 (and fn
852 (let ((ext (file-name-extension fn)))
853 (and ext (concat "*." ext)))))
854 (default
855 (or default-alias
856 default-extension
857 (car grep-files-history)
858 (car (car grep-files-aliases))))
859 (files (completing-read
860 (concat "Search for \"" regexp
861 "\" in files"
862 (if default (concat " (default " default ")"))
863 ": ")
864 'read-file-name-internal
865 nil nil nil 'grep-files-history
866 (delete-dups
867 (delq nil (append (list default default-alias default-extension)
868 (mapcar 'car grep-files-aliases)))))))
869 (and files
870 (or (cdr (assoc files grep-files-aliases))
871 files))))
872
873 ;;;###autoload
874 (defun lgrep (regexp &optional files dir confirm)
875 "Run grep, searching for REGEXP in FILES in directory DIR.
876 The search is limited to file names matching shell pattern FILES.
877 FILES may use abbreviations defined in `grep-files-aliases', e.g.
878 entering `ch' is equivalent to `*.[ch]'.
879
880 With \\[universal-argument] prefix, you can edit the constructed shell command line
881 before it is executed.
882 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
883
884 Collect output in a buffer. While grep runs asynchronously, you
885 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
886 in the grep output buffer,
887 to go to the lines where grep found matches.
888
889 This command shares argument histories with \\[rgrep] and \\[grep]."
890 (interactive
891 (progn
892 (grep-compute-defaults)
893 (cond
894 ((and grep-command (equal current-prefix-arg '(16)))
895 (list (read-from-minibuffer "Run: " grep-command
896 nil nil 'grep-history)))
897 ((not grep-template)
898 (error "grep.el: No `grep-template' available"))
899 (t (let* ((regexp (grep-read-regexp))
900 (files (grep-read-files regexp))
901 (dir (read-directory-name "In directory: "
902 nil default-directory t))
903 (confirm (equal current-prefix-arg '(4))))
904 (list regexp files dir confirm))))))
905 (when (and (stringp regexp) (> (length regexp) 0))
906 (unless (and dir (file-directory-p dir) (file-readable-p dir))
907 (setq dir default-directory))
908 (let ((command regexp))
909 (if (null files)
910 (if (string= command grep-command)
911 (setq command nil))
912 (setq dir (file-name-as-directory (expand-file-name dir)))
913 (setq command (grep-expand-template
914 grep-template
915 regexp
916 files
917 nil
918 (and grep-find-ignored-files
919 (concat " --exclude="
920 (mapconcat
921 #'(lambda (ignore)
922 (cond ((stringp ignore)
923 (shell-quote-argument ignore))
924 ((consp ignore)
925 (and (funcall (car ignore) dir)
926 (shell-quote-argument
927 (cdr ignore))))))
928 grep-find-ignored-files
929 " --exclude=")))))
930 (when command
931 (if confirm
932 (setq command
933 (read-from-minibuffer "Confirm: "
934 command nil nil 'grep-history))
935 (add-to-history 'grep-history command))))
936 (when command
937 (let ((default-directory dir))
938 ;; Setting process-setup-function makes exit-message-function work
939 ;; even when async processes aren't supported.
940 (compilation-start (if (and grep-use-null-device null-device)
941 (concat command " " null-device)
942 command)
943 'grep-mode))
944 (if (eq next-error-last-buffer (current-buffer))
945 (setq default-directory dir))))))
946
947
948 (defvar find-name-arg) ; not autoloaded but defined in find-dired
949
950 ;;;###autoload
951 (defun rgrep (regexp &optional files dir confirm)
952 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
953 The search is limited to file names matching shell pattern FILES.
954 FILES may use abbreviations defined in `grep-files-aliases', e.g.
955 entering `ch' is equivalent to `*.[ch]'.
956
957 With \\[universal-argument] prefix, you can edit the constructed shell command line
958 before it is executed.
959 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
960
961 Collect output in a buffer. While the recursive grep is running,
962 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
963 in the grep output buffer,
964 to visit the lines where matches were found. To kill the job
965 before it finishes, type \\[kill-compilation].
966
967 This command shares argument histories with \\[lgrep] and \\[grep-find].
968
969 When called programmatically and FILES is nil, REGEXP is expected
970 to specify a command to run."
971 (interactive
972 (progn
973 (grep-compute-defaults)
974 (cond
975 ((and grep-find-command (equal current-prefix-arg '(16)))
976 (list (read-from-minibuffer "Run: " grep-find-command
977 nil nil 'grep-find-history)))
978 ((not grep-find-template)
979 (error "grep.el: No `grep-find-template' available"))
980 (t (let* ((regexp (grep-read-regexp))
981 (files (grep-read-files regexp))
982 (dir (read-directory-name "Base directory: "
983 nil default-directory t))
984 (confirm (equal current-prefix-arg '(4))))
985 (list regexp files dir confirm))))))
986 (when (and (stringp regexp) (> (length regexp) 0))
987 (unless (and dir (file-directory-p dir) (file-readable-p dir))
988 (setq dir default-directory))
989 (if (null files)
990 (if (not (string= regexp (if (consp grep-find-command)
991 (car grep-find-command)
992 grep-find-command)))
993 (compilation-start regexp 'grep-mode))
994 (setq dir (file-name-as-directory (expand-file-name dir)))
995 (require 'find-dired) ; for `find-name-arg'
996 ;; In Tramp, there could be problems if the command line is too
997 ;; long. We escape it, therefore.
998 (let ((command (grep-expand-template
999 grep-find-template
1000 regexp
1001 (concat (shell-quote-argument "(")
1002 " " find-name-arg " "
1003 (mapconcat
1004 #'shell-quote-argument
1005 (split-string files)
1006 (concat "\\\n" " -o " find-name-arg " "))
1007 " "
1008 (shell-quote-argument ")"))
1009 dir
1010 (concat
1011 (and grep-find-ignored-directories
1012 (concat "-type d "
1013 (shell-quote-argument "(")
1014 ;; we should use shell-quote-argument here
1015 " -path "
1016 (mapconcat
1017 #'(lambda (ignore)
1018 (cond ((stringp ignore)
1019 (shell-quote-argument
1020 (concat "*/" ignore)))
1021 ((consp ignore)
1022 (and (funcall (car ignore) dir)
1023 (shell-quote-argument
1024 (concat "*/"
1025 (cdr ignore)))))))
1026 grep-find-ignored-directories
1027 "\\\n -o -path ")
1028 " "
1029 (shell-quote-argument ")")
1030 " -prune -o "))
1031 (and grep-find-ignored-files
1032 (concat (shell-quote-argument "!") " -type d "
1033 (shell-quote-argument "(")
1034 ;; we should use shell-quote-argument here
1035 " -name "
1036 (mapconcat
1037 #'(lambda (ignore)
1038 (cond ((stringp ignore)
1039 (shell-quote-argument ignore))
1040 ((consp ignore)
1041 (and (funcall (car ignore) dir)
1042 (shell-quote-argument
1043 (cdr ignore))))))
1044 grep-find-ignored-files
1045 "\\\n -o -name ")
1046 " "
1047 (shell-quote-argument ")")
1048 " -prune -o "))))))
1049 (when command
1050 (if confirm
1051 (setq command
1052 (read-from-minibuffer "Confirm: "
1053 command nil nil 'grep-find-history))
1054 (add-to-history 'grep-find-history command))
1055 (let ((default-directory dir))
1056 (compilation-start command 'grep-mode))
1057 ;; Set default-directory if we started rgrep in the *grep* buffer.
1058 (if (eq next-error-last-buffer (current-buffer))
1059 (setq default-directory dir)))))))
1060
1061 ;;;###autoload
1062 (defun zrgrep (regexp &optional files dir confirm grep-find-template)
1063 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1064 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1065 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1066 (interactive
1067 (progn
1068 ;; Compute standard default values.
1069 (grep-compute-defaults)
1070 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1071 ;; for grep program "zgrep", but not changing global values.
1072 (let ((grep-program "zgrep")
1073 ;; Don't change global values for variables computed
1074 ;; by `grep-compute-defaults'.
1075 (grep-find-template nil)
1076 (grep-find-command nil)
1077 (grep-host-defaults-alist nil)
1078 ;; Use for `grep-read-files'
1079 (grep-files-aliases '(("all" . "* .*")
1080 ("gz" . "*.gz"))))
1081 ;; Recompute defaults using let-bound values above.
1082 (grep-compute-defaults)
1083 (cond
1084 ((and grep-find-command (equal current-prefix-arg '(16)))
1085 (list (read-from-minibuffer "Run: " grep-find-command
1086 nil nil 'grep-find-history)))
1087 ((not grep-find-template)
1088 (error "grep.el: No `grep-find-template' available"))
1089 (t (let* ((regexp (grep-read-regexp))
1090 (files (grep-read-files regexp))
1091 (dir (read-directory-name "Base directory: "
1092 nil default-directory t))
1093 (confirm (equal current-prefix-arg '(4))))
1094 (list regexp files dir confirm grep-find-template)))))))
1095 ;; Set `grep-highlight-matches' to `always'
1096 ;; since `zgrep' puts filters in the grep output.
1097 (let ((grep-highlight-matches 'always))
1098 ;; `rgrep' uses the dynamically bound value `grep-find-template'
1099 ;; from the argument `grep-find-template' whose value is computed
1100 ;; in the `interactive' spec.
1101 (rgrep regexp files dir confirm)))
1102
1103 ;;;###autoload
1104 (defalias 'rzgrep 'zrgrep)
1105
1106 (provide 'grep)
1107
1108 ;;; grep.el ends here