Use quit-window to hide buffers temporarily displayed by xref
[emacs.git] / lisp / progmodes / grep.el
blob048fa1180a95a46c3b3df3836b77e7f82a9a93ce
1 ;;; grep.el --- run `grep' and display the results -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2015 Free Software
4 ;; Foundation, Inc.
6 ;; Author: Roland McGrath <roland@gnu.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: tools, processes
10 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;;; Commentary:
27 ;; This package provides the grep facilities documented in the Emacs
28 ;; user's manual.
30 ;;; Code:
32 (require 'compile)
35 (defgroup grep nil
36 "Run `grep' and display the results."
37 :group 'tools
38 :group 'processes)
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.")
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))
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)
70 (defcustom grep-highlight-matches 'auto-detect
71 "Use special markers to highlight grep matches.
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.
79 This option sets the environment variable GREP_COLORS to specify
80 markers for highlighting and adds the --color option in front of
81 any explicit grep options before starting the grep.
83 When this option is `auto', grep uses `--color' to highlight
84 matches only when it outputs to a terminal (when `grep' is the last
85 command in the pipe), thus avoiding the use of any potentially-harmful
86 escape sequences when standard output goes to a file or pipe.
88 To make grep highlight matches even into a pipe, you need the option
89 `always' that forces grep to use `--color=always' to unconditionally
90 output escape sequences.
92 In interactive usage, the actual value of this variable is set up
93 by `grep-compute-defaults' when the default value is `auto-detect'.
94 To change the default value, use Customize or call the function
95 `grep-apply-setting'."
96 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
97 (const :tag "Highlight matches with grep markers" t)
98 (const :tag "Use --color=always" always)
99 (const :tag "Use --color" auto)
100 (other :tag "Not Set" auto-detect))
101 :set 'grep-apply-setting
102 :version "22.1"
103 :group 'grep)
105 (defcustom grep-scroll-output nil
106 "Non-nil to scroll the *grep* buffer window as output appears.
108 Setting it causes the grep commands to put point at the end of their
109 output window so that the end of the output is always visible rather
110 than the beginning."
111 :type 'boolean
112 :version "22.1"
113 :group 'grep)
115 ;;;###autoload
116 (defcustom grep-command nil
117 "The default grep command for \\[grep].
118 If the grep program used supports an option to always include file names
119 in its output (such as the `-H' option to GNU grep), it's a good idea to
120 include it when specifying `grep-command'.
122 In interactive usage, the actual value of this variable is set up
123 by `grep-compute-defaults'; to change the default value, use
124 Customize or call the function `grep-apply-setting'."
125 :type '(choice string
126 (const :tag "Not Set" nil))
127 :set 'grep-apply-setting
128 :group 'grep)
130 (defcustom grep-template nil
131 "The default command to run for \\[lgrep].
132 The following place holders should be present in the string:
133 <C> - place to put -i if case insensitive grep.
134 <F> - file names and wildcards to search.
135 <X> - file names and wildcards to exclude.
136 <R> - the regular expression searched for.
137 <N> - place to insert null-device.
139 In interactive usage, the actual value of this variable is set up
140 by `grep-compute-defaults'; to change the default value, use
141 Customize or call the function `grep-apply-setting'."
142 :type '(choice string
143 (const :tag "Not Set" nil))
144 :set 'grep-apply-setting
145 :version "22.1"
146 :group 'grep)
148 (defcustom grep-use-null-device 'auto-detect
149 "If t, append the value of `null-device' to `grep' commands.
150 This is done to ensure that the output of grep includes the filename of
151 any match in the case where only a single file is searched, and is not
152 necessary if the grep program used supports the `-H' option.
154 In interactive usage, the actual value of this variable is set up
155 by `grep-compute-defaults'; to change the default value, use
156 Customize or call the function `grep-apply-setting'."
157 :type '(choice (const :tag "Do Not Append Null Device" nil)
158 (const :tag "Append Null Device" t)
159 (other :tag "Not Set" auto-detect))
160 :set 'grep-apply-setting
161 :group 'grep)
163 ;;;###autoload
164 (defcustom grep-find-command nil
165 "The default find command for \\[grep-find].
166 In interactive usage, the actual value of this variable is set up
167 by `grep-compute-defaults'; to change the default value, use
168 Customize or call the function `grep-apply-setting'."
169 :type '(choice string
170 (const :tag "Not Set" nil))
171 :set 'grep-apply-setting
172 :group 'grep)
174 (defcustom grep-find-template nil
175 "The default command to run for \\[rgrep].
176 The following place holders should be present in the string:
177 <D> - base directory for find
178 <X> - find options to restrict or expand the directory list
179 <F> - find options to limit the files matched
180 <C> - place to put -i if case insensitive grep
181 <R> - the regular expression searched for.
182 In interactive usage, the actual value of this variable is set up
183 by `grep-compute-defaults'; to change the default value, use
184 Customize or call the function `grep-apply-setting'."
185 :type '(choice string
186 (const :tag "Not Set" nil))
187 :set 'grep-apply-setting
188 :version "22.1"
189 :group 'grep)
191 (defcustom grep-files-aliases
192 '(("all" . "* .*")
193 ("el" . "*.el")
194 ("ch" . "*.[ch]")
195 ("c" . "*.c")
196 ("cc" . "*.cc *.cxx *.cpp *.C *.CC *.c++")
197 ("cchh" . "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
198 ("hh" . "*.hxx *.hpp *.[Hh] *.HH *.h++")
199 ("h" . "*.h")
200 ("l" . "[Cc]hange[Ll]og*")
201 ("m" . "[Mm]akefile*")
202 ("tex" . "*.tex")
203 ("texi" . "*.texi")
204 ("asm" . "*.[sS]"))
205 "Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
206 :type 'alist
207 :group 'grep)
209 (defcustom grep-find-ignored-directories
210 vc-directory-exclusion-list
211 "List of names of sub-directories which `rgrep' shall not recurse into.
212 If an element is a cons cell, the car is called on the search directory
213 to determine whether cdr should not be recursed into."
214 :type '(choice (repeat :tag "Ignored directories" string)
215 (const :tag "No ignored directories" nil))
216 :group 'grep)
218 (defcustom grep-find-ignored-files
219 (cons ".#*" (delq nil (mapcar (lambda (s)
220 (unless (string-match-p "/\\'" s)
221 (concat "*" s)))
222 completion-ignored-extensions)))
223 "List of file names which `rgrep' and `lgrep' shall exclude.
224 If an element is a cons cell, the car is called on the search directory
225 to determine whether cdr should not be excluded."
226 :type '(choice (repeat :tag "Ignored file" string)
227 (const :tag "No ignored files" nil))
228 :group 'grep)
230 (defcustom grep-error-screen-columns nil
231 "If non-nil, column numbers in grep hits are screen columns.
232 See `compilation-error-screen-columns'"
233 :type '(choice (const :tag "Default" nil)
234 integer)
235 :version "22.1"
236 :group 'grep)
238 ;;;###autoload
239 (defcustom grep-setup-hook nil
240 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
241 :type 'hook
242 :group 'grep)
244 (defvar grep-mode-map
245 (let ((map (make-sparse-keymap)))
246 (set-keymap-parent map compilation-minor-mode-map)
247 (define-key map " " 'scroll-up-command)
248 (define-key map [?\S-\ ] 'scroll-down-command)
249 (define-key map "\^?" 'scroll-down-command)
250 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
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)
260 ;; Set up the menu-bar
261 (define-key map [menu-bar grep]
262 (cons "Grep" (make-sparse-keymap "Grep")))
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.")
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))))
324 (defalias 'kill-grep 'kill-compilation)
326 ;;;; TODO --- refine this!!
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)
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'.")
344 ;;;###autoload
345 (defconst grep-regexp-alist
347 ;; Use a tight regexp to handle weird file names (with colons
348 ;; in them) as well as possible. E.g., use [1-9][0-9]* rather
349 ;; than [0-9]+ so as to accept ":034:" in file names.
350 ("^\\(.*?[^/\n]\\):[ \t]*\\([1-9][0-9]*\\)[ \t]*:"
352 ;; Calculate column positions (col . end-col) of first grep match on a line
353 ((lambda ()
354 (when grep-highlight-matches
355 (let* ((beg (match-end 0))
356 (end (save-excursion (goto-char beg) (line-end-position)))
357 (mbeg (text-property-any beg end 'font-lock-face grep-match-face)))
358 (when mbeg
359 (- mbeg beg)))))
361 (lambda ()
362 (when grep-highlight-matches
363 (let* ((beg (match-end 0))
364 (end (save-excursion (goto-char beg) (line-end-position)))
365 (mbeg (text-property-any beg end 'font-lock-face grep-match-face))
366 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
367 (when mend
368 (- mend beg)))))))
369 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
370 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
372 (defvar grep-first-column 0 ; bug#10594
373 "Value to use for `compilation-first-column' in grep buffers.")
375 (defvar grep-error "grep hit"
376 "Message to print when no matches are found.")
378 ;; Reverse the colors because grep hits are not errors (though we jump there
379 ;; with `next-error'), and unreadable files can't be gone to.
380 (defvar grep-hit-face compilation-info-face
381 "Face name to use for grep hits.")
383 (defvar grep-error-face 'compilation-error
384 "Face name to use for grep error messages.")
386 (defvar grep-match-face 'match
387 "Face name to use for grep matches.")
389 (defvar grep-context-face 'shadow
390 "Face name to use for grep context lines.")
392 (defvar grep-mode-font-lock-keywords
393 '(;; Command output lines.
394 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
395 1 grep-error-face)
396 ;; remove match from grep-regexp-alist before fontifying
397 ("^Grep[/a-zA-z]* started.*"
398 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
399 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
400 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
401 (1 compilation-info-face nil t)
402 (2 compilation-warning-face nil t))
403 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
404 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
405 (1 grep-error-face)
406 (2 grep-error-face nil t))
407 ;; "filename-linenumber-" format is used for context lines in GNU grep,
408 ;; "filename=linenumber=" for lines with function names in "git grep -p".
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.")
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.")
418 ;;;###autoload
419 (defvar find-program (purecopy "find")
420 "The default find program.
421 This is used by commands like `grep-find-command', `find-dired'
422 and others.")
424 ;;;###autoload
425 (defvar xargs-program (purecopy "xargs")
426 "The default xargs program for `grep-find-command'.
427 See `grep-find-use-xargs'.
428 This variable's value takes effect when `grep-compute-defaults' is called.")
430 ;;;###autoload
431 (defvar grep-find-use-xargs nil
432 "How to invoke find and grep.
433 If `exec', use `find -exec {} ;'.
434 If `exec-plus' use `find -exec {} +'.
435 If `gnu', use `find -print0' and `xargs -0'.
436 Any other value means to use `find -print' and `xargs'.
438 This variable's value takes effect when `grep-compute-defaults' is called.")
440 ;; History of grep commands.
441 ;;;###autoload
442 (defvar grep-history nil "History list for grep.")
443 ;;;###autoload
444 (defvar grep-find-history nil "History list for grep-find.")
446 ;; History of lgrep and rgrep regexp and files args.
447 (defvar grep-regexp-history nil)
448 (defvar grep-files-history nil)
450 ;;;###autoload
451 (defun grep-process-setup ()
452 "Setup compilation variables and buffer for `grep'.
453 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
454 (when (eq grep-highlight-matches 'auto-detect)
455 (grep-compute-defaults))
456 (unless (or (eq grep-highlight-matches 'auto-detect)
457 (null grep-highlight-matches)
458 ;; Don't output color escapes if they can't be
459 ;; highlighted with `font-lock-face' by `grep-filter'.
460 (null font-lock-mode))
461 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
462 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
463 (setenv "TERM" "emacs-grep")
464 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
465 (setenv "GREP_COLOR" "01;31")
466 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
467 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
468 (set (make-local-variable 'compilation-exit-message-function)
469 (lambda (status code msg)
470 (if (eq status 'exit)
471 ;; This relies on the fact that `compilation-start'
472 ;; sets buffer-modified to nil before running the command,
473 ;; so the buffer is still unmodified if there is no output.
474 (cond ((and (zerop code) (buffer-modified-p))
475 '("finished (matches found)\n" . "matched"))
476 ((not (buffer-modified-p))
477 '("finished with no matches found\n" . "no match"))
479 (cons msg code)))
480 (cons msg code))))
481 (run-hooks 'grep-setup-hook))
483 (defun grep-filter ()
484 "Handle match highlighting escape sequences inserted by the grep process.
485 This function is called from `compilation-filter-hook'."
486 (save-excursion
487 (forward-line 0)
488 (let ((end (point)) beg)
489 (goto-char compilation-filter-start)
490 (forward-line 0)
491 (setq beg (point))
492 ;; Only operate on whole lines so we don't get caught with part of an
493 ;; escape sequence in one chunk and the rest in another.
494 (when (< (point) end)
495 (setq end (copy-marker end))
496 ;; Highlight grep matches and delete marking sequences.
497 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
498 (replace-match (propertize (match-string 1)
499 'face nil 'font-lock-face grep-match-face)
500 t t))
501 ;; Delete all remaining escape sequences
502 (goto-char beg)
503 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
504 (replace-match "" t t))))))
506 (defun grep-probe (command args &optional func result)
507 (let (process-file-side-effects)
508 (equal (condition-case nil
509 (apply (or func 'process-file) command args)
510 (error nil))
511 (or result 0))))
513 ;;;###autoload
514 (defun grep-compute-defaults ()
515 ;; Keep default values.
516 (unless grep-host-defaults-alist
517 (add-to-list
518 'grep-host-defaults-alist
519 (cons nil
520 `((grep-command ,grep-command)
521 (grep-template ,grep-template)
522 (grep-use-null-device ,grep-use-null-device)
523 (grep-find-command ,grep-find-command)
524 (grep-find-template ,grep-find-template)
525 (grep-find-use-xargs ,grep-find-use-xargs)
526 (grep-highlight-matches ,grep-highlight-matches)))))
527 (let* ((host-id
528 (intern (or (file-remote-p default-directory) "localhost")))
529 (host-defaults (assq host-id grep-host-defaults-alist))
530 (defaults (assq nil grep-host-defaults-alist)))
531 ;; There are different defaults on different hosts. They must be
532 ;; computed for every host once.
533 (dolist (setting '(grep-command grep-template
534 grep-use-null-device grep-find-command
535 grep-find-template grep-find-use-xargs
536 grep-highlight-matches))
537 (set setting
538 (cadr (or (assq setting host-defaults)
539 (assq setting defaults)))))
541 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
542 (setq grep-use-null-device
543 (with-temp-buffer
544 (let ((hello-file (expand-file-name "HELLO" data-directory)))
545 (not
546 (and (if grep-command
547 ;; `grep-command' is already set, so
548 ;; use that for testing.
549 (grep-probe grep-command
550 `(nil t nil "^English" ,hello-file)
551 #'call-process-shell-command)
552 ;; otherwise use `grep-program'
553 (grep-probe grep-program
554 `(nil t nil "-nH" "^English" ,hello-file)))
555 (progn
556 (goto-char (point-min))
557 (looking-at
558 (concat (regexp-quote hello-file)
559 ":[0-9]+:English")))))))))
561 (when (eq grep-highlight-matches 'auto-detect)
562 (setq grep-highlight-matches
563 (with-temp-buffer
564 (and (grep-probe grep-program '(nil t nil "--help"))
565 (progn
566 (goto-char (point-min))
567 (search-forward "--color" nil t))
568 ;; Windows and DOS pipes fail `isatty' detection in Grep.
569 (if (memq system-type '(windows-nt ms-dos))
570 'always 'auto)))))
572 (unless (and grep-command grep-find-command
573 grep-template grep-find-template)
574 (let ((grep-options
575 (concat (and grep-highlight-matches
576 (grep-probe grep-program
577 `(nil nil nil "--color" "x" ,null-device)
578 nil 1)
579 (if (eq grep-highlight-matches 'always)
580 "--color=always " "--color "))
581 (if grep-use-null-device "-n" "-nH")
582 (if (grep-probe grep-program
583 `(nil nil nil "-e" "foo" ,null-device)
584 nil 1)
585 " -e"))))
586 (unless grep-command
587 (setq grep-command
588 (format "%s %s " grep-program grep-options)))
589 (unless grep-template
590 (setq grep-template
591 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
592 (unless grep-find-use-xargs
593 (setq grep-find-use-xargs
594 (cond
595 ((grep-probe find-program
596 `(nil nil nil ,null-device "-exec" "echo"
597 "{}" "+"))
598 'exec-plus)
599 ((and
600 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
601 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
602 'gnu)
604 'exec))))
605 (unless grep-find-command
606 (setq grep-find-command
607 (cond ((eq grep-find-use-xargs 'gnu)
608 ;; Windows shells need the program file name
609 ;; after the pipe symbol be quoted if they use
610 ;; forward slashes as directory separators.
611 (format "%s . -type f -print0 | \"%s\" -0 %s"
612 find-program xargs-program grep-command))
613 ((memq grep-find-use-xargs '(exec exec-plus))
614 (let ((cmd0 (format "%s . -type f -exec %s"
615 find-program grep-command))
616 (null (if grep-use-null-device
617 (format "%s " null-device)
618 "")))
619 (cons
620 (if (eq grep-find-use-xargs 'exec-plus)
621 (format "%s %s{} +" cmd0 null)
622 (format "%s {} %s%s" cmd0 null
623 (shell-quote-argument ";")))
624 (1+ (length cmd0)))))
626 (format "%s . -type f -print | \"%s\" %s"
627 find-program xargs-program grep-command)))))
628 (unless grep-find-template
629 (setq grep-find-template
630 (let ((gcmd (format "%s <C> %s <R>"
631 grep-program grep-options))
632 (null (if grep-use-null-device
633 (format "%s " null-device)
634 "")))
635 (cond ((eq grep-find-use-xargs 'gnu)
636 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 %s"
637 find-program xargs-program gcmd))
638 ((eq grep-find-use-xargs 'exec)
639 (format "%s . <X> -type f <F> -exec %s {} %s%s"
640 find-program gcmd null
641 (shell-quote-argument ";")))
642 ((eq grep-find-use-xargs 'exec-plus)
643 (format "%s . <X> -type f <F> -exec %s %s{} +"
644 find-program gcmd null))
646 (format "%s . <X> -type f <F> -print | \"%s\" %s"
647 find-program xargs-program gcmd))))))))
649 ;; Save defaults for this host.
650 (setq grep-host-defaults-alist
651 (delete (assq host-id grep-host-defaults-alist)
652 grep-host-defaults-alist))
653 (add-to-list
654 'grep-host-defaults-alist
655 (cons host-id
656 `((grep-command ,grep-command)
657 (grep-template ,grep-template)
658 (grep-use-null-device ,grep-use-null-device)
659 (grep-find-command ,grep-find-command)
660 (grep-find-template ,grep-find-template)
661 (grep-find-use-xargs ,grep-find-use-xargs)
662 (grep-highlight-matches ,grep-highlight-matches))))))
664 (defun grep-tag-default ()
665 (or (and transient-mark-mode mark-active
666 (/= (point) (mark))
667 (buffer-substring-no-properties (point) (mark)))
668 (funcall (or find-tag-default-function
669 (get major-mode 'find-tag-default-function)
670 'find-tag-default))
671 ""))
673 (defun grep-default-command ()
674 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
675 (let ((tag-default (shell-quote-argument (grep-tag-default)))
676 ;; This a regexp to match single shell arguments.
677 ;; Could someone please add comments explaining it?
678 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
679 (grep-default (or (car grep-history) grep-command)))
680 ;; In the default command, find the arg that specifies the pattern.
681 (when (or (string-match
682 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
683 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
684 grep-default)
685 ;; If the string is not yet complete.
686 (string-match "\\(\\)\\'" grep-default))
687 ;; Maybe we will replace the pattern with the default tag.
688 ;; But first, maybe replace the file name pattern.
689 (condition-case nil
690 (unless (or (not (stringp buffer-file-name))
691 (when (match-beginning 2)
692 (save-match-data
693 (string-match
694 (wildcard-to-regexp
695 (file-name-nondirectory
696 (match-string 3 grep-default)))
697 (file-name-nondirectory buffer-file-name)))))
698 (setq grep-default (concat (substring grep-default
699 0 (match-beginning 2))
700 " *."
701 (file-name-extension buffer-file-name))))
702 ;; In case wildcard-to-regexp gets an error
703 ;; from invalid data.
704 (error nil))
705 ;; Now replace the pattern with the default tag.
706 (replace-match tag-default t t grep-default 1))))
709 ;;;###autoload
710 (define-compilation-mode grep-mode "Grep"
711 "Sets `grep-last-buffer' and `compilation-window-height'."
712 (setq grep-last-buffer (current-buffer))
713 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
714 (set (make-local-variable 'compilation-error-face)
715 grep-hit-face)
716 (set (make-local-variable 'compilation-error-regexp-alist)
717 grep-regexp-alist)
718 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
719 ;; can never match.
720 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
721 (set (make-local-variable 'compilation-process-setup-function)
722 'grep-process-setup)
723 (set (make-local-variable 'compilation-disable-input) t)
724 (set (make-local-variable 'compilation-error-screen-columns)
725 grep-error-screen-columns)
726 (add-hook 'compilation-filter-hook 'grep-filter nil t))
729 ;;;###autoload
730 (defun grep (command-args)
731 "Run grep, with user-specified args, and collect output in a buffer.
732 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
733 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
734 buffer, to go to the lines where grep found
735 matches. To kill the grep job before it finishes, type \\[kill-compilation].
737 For doing a recursive `grep', see the `rgrep' command. For running
738 `grep' in a specific directory, see `lgrep'.
740 This command uses a special history list for its COMMAND-ARGS, so you
741 can easily repeat a grep command.
743 A prefix argument says to default the argument based upon the current
744 tag the cursor is over, substituting it into the last grep command
745 in the grep command history (or into `grep-command' if that history
746 list is empty)."
747 (interactive
748 (progn
749 (grep-compute-defaults)
750 (let ((default (grep-default-command)))
751 (list (read-shell-command "Run grep (like this): "
752 (if current-prefix-arg default grep-command)
753 'grep-history
754 (if current-prefix-arg nil default))))))
756 ;; Setting process-setup-function makes exit-message-function work
757 ;; even when async processes aren't supported.
758 (compilation-start (if (and grep-use-null-device null-device)
759 (concat command-args " " null-device)
760 command-args)
761 'grep-mode))
764 ;;;###autoload
765 (defun grep-find (command-args)
766 "Run grep via find, with user-specified args COMMAND-ARGS.
767 Collect output in a buffer.
768 While find runs asynchronously, you can use the \\[next-error] command
769 to find the text that grep hits refer to.
771 This command uses a special history list for its arguments, so you can
772 easily repeat a find command."
773 (interactive
774 (progn
775 (grep-compute-defaults)
776 (if grep-find-command
777 (list (read-shell-command "Run find (like this): "
778 grep-find-command 'grep-find-history))
779 ;; No default was set
780 (read-string
781 "compile.el: No `grep-find-command' command available. Press RET.")
782 (list nil))))
783 (when command-args
784 (let ((null-device nil)) ; see grep
785 (grep command-args))))
787 ;;;###autoload
788 (defalias 'find-grep 'grep-find)
791 ;; User-friendly interactive API.
793 (defconst grep-expand-keywords
794 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
795 ("<D>" . dir)
796 ("<F>" . files)
797 ("<N>" . null-device)
798 ("<X>" . excl)
799 ("<R>" . (shell-quote-argument (or regexp ""))))
800 "List of substitutions performed by `grep-expand-template'.
801 If car of an element matches, the cdr is evalled in to get the
802 substitution string. Note dynamic scoping of variables.")
804 (defun grep-expand-template (template &optional regexp files dir excl)
805 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
806 (let* ((command template)
807 (env `((cf . ,case-fold-search)
808 (excl . ,excl)
809 (dir . ,dir)
810 (files . ,files)
811 (regexp . ,regexp)))
812 (case-fold-search nil))
813 (dolist (kw grep-expand-keywords command)
814 (if (string-match (car kw) command)
815 (setq command
816 (replace-match
817 (or (if (symbolp (cdr kw))
818 (eval (cdr kw) env)
819 (save-match-data (eval (cdr kw) env)))
821 t t command))))))
823 (defun grep-read-regexp ()
824 "Read regexp arg for interactive grep using `read-regexp'."
825 (read-regexp "Search for" 'grep-tag-default 'grep-regexp-history))
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 "\\|")
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))))
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]'.
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'.
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.
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-accessible-directory-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
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))))))
948 (defvar find-name-arg) ; not autoloaded but defined in find-dired
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]'.
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'.
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].
967 This command shares argument histories with \\[lgrep] and \\[grep-find].
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-accessible-directory-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 (let ((command (grep-expand-template
997 grep-find-template
998 regexp
999 (concat (shell-quote-argument "(")
1000 " " find-name-arg " "
1001 (mapconcat
1002 #'shell-quote-argument
1003 (split-string files)
1004 (concat " -o " find-name-arg " "))
1006 (shell-quote-argument ")"))
1008 (concat
1009 (and grep-find-ignored-directories
1010 (concat "-type d "
1011 (shell-quote-argument "(")
1012 ;; we should use shell-quote-argument here
1013 " -path "
1014 (mapconcat
1015 #'(lambda (ignore)
1016 (cond ((stringp ignore)
1017 (shell-quote-argument
1018 (concat "*/" ignore)))
1019 ((consp ignore)
1020 (and (funcall (car ignore) dir)
1021 (shell-quote-argument
1022 (concat "*/"
1023 (cdr ignore)))))))
1024 grep-find-ignored-directories
1025 " -o -path ")
1027 (shell-quote-argument ")")
1028 " -prune -o "))
1029 (and grep-find-ignored-files
1030 (concat (shell-quote-argument "!") " -type d "
1031 (shell-quote-argument "(")
1032 ;; we should use shell-quote-argument here
1033 " -name "
1034 (mapconcat
1035 #'(lambda (ignore)
1036 (cond ((stringp ignore)
1037 (shell-quote-argument ignore))
1038 ((consp ignore)
1039 (and (funcall (car ignore) dir)
1040 (shell-quote-argument
1041 (cdr ignore))))))
1042 grep-find-ignored-files
1043 " -o -name ")
1045 (shell-quote-argument ")")
1046 " -prune -o "))))))
1047 (when command
1048 (if confirm
1049 (setq command
1050 (read-from-minibuffer "Confirm: "
1051 command nil nil 'grep-find-history))
1052 (add-to-history 'grep-find-history command))
1053 (let ((default-directory dir))
1054 (compilation-start command 'grep-mode))
1055 ;; Set default-directory if we started rgrep in the *grep* buffer.
1056 (if (eq next-error-last-buffer (current-buffer))
1057 (setq default-directory dir)))))))
1059 ;;;###autoload
1060 (defun zrgrep (regexp &optional files dir confirm template)
1061 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1062 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1063 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1064 (interactive
1065 (progn
1066 ;; Compute standard default values.
1067 (grep-compute-defaults)
1068 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1069 ;; for grep program "zgrep", but not changing global values.
1070 (let ((grep-program "zgrep")
1071 ;; Don't change global values for variables computed
1072 ;; by `grep-compute-defaults'.
1073 (grep-find-template nil)
1074 (grep-find-command nil)
1075 (grep-host-defaults-alist nil)
1076 ;; Use for `grep-read-files'
1077 (grep-files-aliases '(("all" . "* .*")
1078 ("gz" . "*.gz"))))
1079 ;; Recompute defaults using let-bound values above.
1080 (grep-compute-defaults)
1081 (cond
1082 ((and grep-find-command (equal current-prefix-arg '(16)))
1083 (list (read-from-minibuffer "Run: " grep-find-command
1084 nil nil 'grep-find-history)))
1085 ((not grep-find-template)
1086 (error "grep.el: No `grep-find-template' available"))
1087 (t (let* ((regexp (grep-read-regexp))
1088 (files (grep-read-files regexp))
1089 (dir (read-directory-name "Base directory: "
1090 nil default-directory t))
1091 (confirm (equal current-prefix-arg '(4))))
1092 (list regexp files dir confirm grep-find-template)))))))
1093 ;; Set `grep-highlight-matches' to `always'
1094 ;; since `zgrep' puts filters in the grep output.
1095 (let ((grep-find-template template)
1096 (grep-highlight-matches 'always))
1097 (rgrep regexp files dir confirm)))
1099 ;;;###autoload
1100 (defalias 'rzgrep 'zrgrep)
1102 (provide 'grep)
1104 ;;; grep.el ends here