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