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