1 ;;; grep.el --- run `grep' and display the results -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2017 Free Software
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 <https://www.gnu.org/licenses/>.
27 ;; This package provides the grep facilities documented in the Emacs
35 "Run `grep' and display the results."
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.")
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' `grep-find-template',
50 `grep-find-use-xargs', `grep-use-null-filename-separator', or
51 `grep-highlight-matches'."
52 (when grep-host-defaults-alist
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
))
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
)
69 (defcustom grep-highlight-matches
'auto-detect
70 "Use special markers to highlight grep matches.
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.
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.
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.
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.
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
104 (defcustom grep-scroll-output nil
105 "Non-nil to scroll the *grep* buffer window as output appears.
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
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'.
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
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 the options like -i and --color.
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.
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
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.
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
162 (defcustom grep-use-null-filename-separator
'auto-detect
163 "If non-nil, use `grep's `--null' option.
164 This is done to disambiguate file names in `grep's output."
165 :type
'(choice (const :tag
"Do Not Use `--null'" nil
)
166 (const :tag
"Use `--null'" t
)
167 (other :tag
"Not Set" auto-detect
))
168 :set
'grep-apply-setting
172 (defcustom grep-find-command nil
173 "The default find command for \\[grep-find].
174 In interactive usage, the actual value of this variable is set up
175 by `grep-compute-defaults'; to change the default value, use
176 Customize or call the function `grep-apply-setting'."
177 :type
'(choice string
178 (const :tag
"Not Set" nil
))
179 :set
'grep-apply-setting
182 (defcustom grep-find-template nil
183 "The default command to run for \\[rgrep].
184 The following place holders should be present in the string:
185 <D> - base directory for find
186 <X> - find options to restrict or expand the directory list
187 <F> - find options to limit the files matched
188 <C> - place to put the grep options like -i and --color
189 <R> - the regular expression searched for.
190 In interactive usage, the actual value of this variable is set up
191 by `grep-compute-defaults'; to change the default value, use
192 Customize or call the function `grep-apply-setting'."
193 :type
'(choice string
194 (const :tag
"Not Set" nil
))
195 :set
'grep-apply-setting
199 (defcustom grep-files-aliases
200 '(("all" .
"* .[!.]* ..?*") ;; Don't match `..'. See bug#22577
204 ("cc" .
"*.cc *.cxx *.cpp *.C *.CC *.c++")
205 ("cchh" .
"*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
206 ("hh" .
"*.hxx *.hpp *.[Hh] *.HH *.h++")
208 ("l" .
"[Cc]hange[Ll]og*")
209 ("m" .
"[Mm]akefile*")
213 "Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
217 (defcustom grep-find-ignored-directories
218 vc-directory-exclusion-list
219 "List of names of sub-directories which `rgrep' shall not recurse into.
220 If an element is a cons cell, the car is called on the search directory
221 to determine whether cdr should not be recursed into."
222 :type
'(choice (repeat :tag
"Ignored directories" string
)
223 (const :tag
"No ignored directories" nil
))
226 (defcustom grep-find-ignored-files
227 (cons ".#*" (delq nil
(mapcar (lambda (s)
228 (unless (string-match-p "/\\'" s
)
230 completion-ignored-extensions
)))
231 "List of file names which `rgrep' and `lgrep' shall exclude.
232 If an element is a cons cell, the car is called on the search directory
233 to determine whether cdr should not be excluded."
234 :type
'(choice (repeat :tag
"Ignored file" string
)
235 (const :tag
"No ignored files" nil
))
238 (defcustom grep-save-buffers
'ask
239 "If non-nil, save buffers before running the grep commands.
240 If `ask', ask before saving. If a function, call it with no arguments
241 with each buffer current, as a predicate to determine whether that
242 buffer should be saved or not. E.g., one can set this to
244 (string-prefix-p my-grep-root (file-truename (buffer-file-name))))
245 to limit saving to files located under `my-grep-root'."
248 (const :tag
"Ask before saving" ask
)
249 (const :tag
"Don't save buffers" nil
)
251 (other :tag
"Save all buffers" t
))
254 (defcustom grep-error-screen-columns nil
255 "If non-nil, column numbers in grep hits are screen columns.
256 See `compilation-error-screen-columns'"
257 :type
'(choice (const :tag
"Default" nil
)
263 (defcustom grep-setup-hook nil
264 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
268 (defvar grep-mode-map
269 (let ((map (make-sparse-keymap)))
270 (set-keymap-parent map compilation-minor-mode-map
)
271 (define-key map
" " 'scroll-up-command
)
272 (define-key map
[?\S-\
] 'scroll-down-command
)
273 (define-key map
"\^?" 'scroll-down-command
)
274 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
276 (define-key map
"\r" 'compile-goto-error
) ;; ?
277 (define-key map
"n" 'next-error-no-select
)
278 (define-key map
"p" 'previous-error-no-select
)
279 (define-key map
"{" 'compilation-previous-file
)
280 (define-key map
"}" 'compilation-next-file
)
281 (define-key map
"\t" 'compilation-next-error
)
282 (define-key map
[backtab] 'compilation-previous-error)
284 ;; Set up the menu-bar
285 (define-key map [menu-bar grep]
286 (cons "Grep" (make-sparse-keymap "Grep")))
288 (define-key map [menu-bar grep compilation-kill-compilation]
289 '(menu-item "Kill Grep" kill-compilation
290 :help "Kill the currently running grep process"))
291 (define-key map [menu-bar grep compilation-separator2] '("----"))
292 (define-key map [menu-bar grep compilation-compile]
293 '(menu-item "Compile..." compile
294 :help "Compile the program including the current buffer. Default: run `make'"))
295 (define-key map [menu-bar grep compilation-rgrep]
296 '(menu-item "Recursive grep..." rgrep
297 :help "User-friendly recursive grep in directory tree"))
298 (define-key map [menu-bar grep compilation-lgrep]
299 '(menu-item "Local grep..." lgrep
300 :help "User-friendly grep in a directory"))
301 (define-key map [menu-bar grep compilation-grep-find]
302 '(menu-item "Grep via Find..." grep-find
303 :help "Run grep via find, with user-specified args"))
304 (define-key map [menu-bar grep compilation-grep]
305 '(menu-item "Another grep..." grep
306 :help "Run grep, with user-specified args, and collect output in a buffer."))
307 (define-key map [menu-bar grep compilation-recompile]
308 '(menu-item "Repeat grep" recompile
309 :help "Run grep again"))
310 (define-key map [menu-bar grep compilation-separator2] '("----"))
311 (define-key map [menu-bar grep compilation-first-error]
312 '(menu-item "First Match" first-error
313 :help "Restart at the first match, visit corresponding location"))
314 (define-key map [menu-bar grep compilation-previous-error]
315 '(menu-item "Previous Match" previous-error
316 :help "Visit the previous match and corresponding location"))
317 (define-key map [menu-bar grep compilation-next-error]
318 '(menu-item "Next Match" next-error
319 :help "Visit the next match and corresponding location"))
321 "Keymap for grep buffers.
322 `compilation-minor-mode-map' is a cdr of this.")
324 (defvar grep-mode-tool-bar-map
325 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
326 ;; so don't do anything.
327 (when (keymapp (butlast tool-bar-map))
328 (let ((map (butlast (copy-keymap tool-bar-map)))
329 (help (last tool-bar-map))) ;; Keep Help last in tool bar
331 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
333 :help "Goto previous match")
335 "right-arrow" 'next-error-no-select 'next-error-no-select map
337 :help "Goto next match")
339 "cancel" 'kill-compilation 'kill-compilation map
340 :enable '(let ((buffer (compilation-find-buffer)))
341 (get-buffer-process buffer))
344 "refresh" 'recompile 'recompile map
345 :help "Restart grep")
348 (defalias 'kill-grep 'kill-compilation)
350 ;;;; TODO --- refine this!!
352 ;; (defcustom grep-use-compilation-buffer t
353 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
354 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
355 ;; can be used to navigate between grep matches (the default).
356 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
357 ;; be used to navigate between grep matches."
361 ;; override compilation-last-buffer
362 (defvar grep-last-buffer nil
363 "The most recent grep buffer.
364 A grep buffer becomes most recent when you select Grep mode in it.
365 Notice that using \\[next-error] or \\[compile-goto-error] modifies
366 `compilation-last-buffer' rather than `grep-last-buffer'.")
369 (defconst grep-regexp-alist
371 ;; Parse using NUL characters when `--null' is used.
372 ;; Note that we must still assume no newlines in
373 ;; filenames due to "foo: Is a directory." type
375 "\\(?1:[^\0\n]+\\)\\(?3:\0\\)\\(?2:[0-9]+\\):"
377 ;; Fallback if `--null' is not used, use a tight regexp
378 ;; to handle weird file names (with colons in them) as
379 ;; well as possible. E.g., use [1-9][0-9]* rather than
380 ;; [0-9]+ so as to accept ":034:" in file names.
381 "\\(?1:[^\n:]+?[^\n/:]\\):[\t ]*\\(?2:[1-9][0-9]*\\)[\t ]*:"
384 ;; Calculate column positions (col . end-col) of first grep match on a line
386 (when grep-highlight-matches
387 (let* ((beg (match-end 0))
388 (end (save-excursion (goto-char beg) (line-end-position)))
389 (mbeg (text-property-any beg end 'font-lock-face 'grep-match-face)))
394 (when grep-highlight-matches
395 (let* ((beg (match-end 0))
396 (end (save-excursion (goto-char beg) (line-end-position)))
397 (mbeg (text-property-any beg end 'font-lock-face 'grep-match-face))
398 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
402 (3 '(face nil display ":")))
403 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
404 "Regexp used to match grep hits.
405 See `compilation-error-regexp-alist' for format details.")
407 (defvar grep-first-column 0 ; bug#10594
408 "Value to use for `compilation-first-column' in grep buffers.")
410 (defvar grep-error "grep hit"
411 "Message to print when no matches are found.")
413 ;; Reverse the colors because grep hits are not errors (though we jump there
414 ;; with `next-error'), and unreadable files can't be gone to.
415 (defvar grep-hit-face compilation-info-face
416 "Face name to use for grep hits.")
418 (defvar grep-error-face 'compilation-error
419 "Face name to use for grep error messages.")
421 (defvar grep-match-face 'match
422 "Face name to use for grep matches.")
424 (defvar grep-context-face 'shadow
425 "Face name to use for grep context lines.")
427 (defvar grep-mode-font-lock-keywords
428 '(;; Command output lines.
429 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
431 ;; remove match from grep-regexp-alist before fontifying
432 ("^Grep[/a-zA-z]* started.*"
433 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
434 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
435 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
436 (1 compilation-info-face nil t)
437 (2 compilation-warning-face nil t))
438 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
439 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
441 (2 grep-error-face nil t))
442 ;; "filename-linenumber-" format is used for context lines in GNU grep,
443 ;; "filename=linenumber=" for lines with function names in "git grep -p".
444 ("^.+?\\([-=\0]\\)[0-9]+\\([-=]\\).*\n" (0 grep-context-face)
445 (1 (if (eq (char-after (match-beginning 1)) ?\0)
446 `(face nil display ,(match-string 2))))))
447 "Additional things to highlight in grep output.
448 This gets tacked on the end of the generated expressions.")
451 (defvar grep-program (purecopy "grep")
452 "The default grep program for `grep-command' and `grep-find-command'.
453 This variable's value takes effect when `grep-compute-defaults' is called.")
456 (defvar find-program (purecopy "find")
457 "The default find program.
458 This is used by commands like `grep-find-command', `find-dired'
462 (defvar xargs-program (purecopy "xargs")
463 "The default xargs program for `grep-find-command'.
464 See `grep-find-use-xargs'.
465 This variable's value takes effect when `grep-compute-defaults' is called.")
468 (defvar grep-find-use-xargs nil
469 "How to invoke find and grep.
470 If `exec', use `find -exec {} ;'.
471 If `exec-plus' use `find -exec {} +'.
472 If `gnu', use `find -print0' and `xargs -0'.
473 Any other value means to use `find -print' and `xargs'.
475 This variable's value takes effect when `grep-compute-defaults' is called.")
477 ;; History of grep commands.
479 (defvar grep-history nil "History list for grep.")
481 (defvar grep-find-history nil "History list for grep-find.")
483 ;; History of lgrep and rgrep regexp and files args.
484 (defvar grep-regexp-history nil)
485 (defvar grep-files-history nil)
488 (defun grep-process-setup ()
489 "Setup compilation variables and buffer for `grep'.
490 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
491 (when (eq grep-highlight-matches 'auto-detect)
492 (grep-compute-defaults))
493 (unless (or (eq grep-highlight-matches 'auto-detect)
494 (null grep-highlight-matches)
495 ;; Don't output color escapes if they can't be
496 ;; highlighted with `font-lock-face' by `grep-filter'.
497 (null font-lock-mode))
498 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
499 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
500 (setenv "TERM" "emacs-grep")
501 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
502 (setenv "GREP_COLOR" "01;31")
503 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
504 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
505 (set (make-local-variable 'compilation-exit-message-function)
506 (lambda (status code msg)
507 (if (eq status 'exit)
508 ;; This relies on the fact that `compilation-start'
509 ;; sets buffer-modified to nil before running the command,
510 ;; so the buffer is still unmodified if there is no output.
511 (cond ((and (zerop code) (buffer-modified-p))
512 '("finished (matches found)\n" . "matched"))
513 ((not (buffer-modified-p))
514 '("finished with no matches found\n" . "no match"))
518 (run-hooks 'grep-setup-hook))
520 (defun grep-filter ()
521 "Handle match highlighting escape sequences inserted by the grep process.
522 This function is called from `compilation-filter-hook'."
525 (let ((end (point)) beg)
526 (goto-char compilation-filter-start)
529 ;; Only operate on whole lines so we don't get caught with part of an
530 ;; escape sequence in one chunk and the rest in another.
531 (when (< (point) end)
532 (setq end (copy-marker end))
533 ;; Highlight grep matches and delete marking sequences.
534 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
535 (replace-match (propertize (match-string 1)
536 'face nil 'font-lock-face grep-match-face)
538 ;; Delete all remaining escape sequences
540 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
541 (replace-match "" t t))))))
543 (defun grep-probe (command args &optional func result)
544 (let (process-file-side-effects)
545 (equal (condition-case nil
546 (apply (or func 'process-file) command args)
551 (defun grep-compute-defaults ()
552 ;; Keep default values.
553 (unless grep-host-defaults-alist
555 'grep-host-defaults-alist
557 `((grep-command ,grep-command)
558 (grep-template ,grep-template)
559 (grep-use-null-device ,grep-use-null-device)
560 (grep-find-command ,grep-find-command)
561 (grep-find-template ,grep-find-template)
562 (grep-use-null-filename-separator
563 ,grep-use-null-filename-separator)
564 (grep-find-use-xargs ,grep-find-use-xargs)
565 (grep-highlight-matches ,grep-highlight-matches)))))
567 (intern (or (file-remote-p default-directory) "localhost")))
568 (host-defaults (assq host-id grep-host-defaults-alist))
569 (defaults (assq nil grep-host-defaults-alist))
570 (quot-braces (shell-quote-argument "{}"))
571 (quot-scolon (shell-quote-argument ";")))
572 ;; There are different defaults on different hosts. They must be
573 ;; computed for every host once.
574 (dolist (setting '(grep-command grep-template
575 grep-use-null-device grep-find-command
576 grep-use-null-filename-separator
577 grep-find-template grep-find-use-xargs
578 grep-highlight-matches))
580 (cadr (or (assq setting host-defaults)
581 (assq setting defaults)))))
583 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
584 (setq grep-use-null-device
586 (let ((hello-file (expand-file-name "HELLO" data-directory)))
588 (and (if grep-command
589 ;; `grep-command' is already set, so
590 ;; use that for testing.
591 (grep-probe grep-command
592 `(nil t nil "^English" ,hello-file)
593 #'call-process-shell-command)
594 ;; otherwise use `grep-program'
595 (grep-probe grep-program
596 `(nil t nil "-nH" "^English" ,hello-file)))
598 (goto-char (point-min))
600 (concat (regexp-quote hello-file)
601 ":[0-9]+:English")))))))))
603 (when (eq grep-use-null-filename-separator 'auto-detect)
604 (setq grep-use-null-filename-separator
606 (let* ((hello-file (expand-file-name "HELLO" data-directory))
607 (args `("--null" "-ne" "^English" ,hello-file)))
608 (if grep-use-null-device
609 (setq args (append args (list null-device)))
611 (and (grep-probe grep-program `(nil t nil ,@args))
613 (goto-char (point-min))
615 (concat (regexp-quote hello-file)
616 "\0[0-9]+:English"))))))))
618 (when (eq grep-highlight-matches 'auto-detect)
619 (setq grep-highlight-matches
621 (and (grep-probe grep-program '(nil t nil "--help"))
623 (goto-char (point-min))
624 (search-forward "--color" nil t))
625 ;; Windows and DOS pipes fail `isatty' detection in Grep.
626 (if (memq system-type '(windows-nt ms-dos))
629 (unless (and grep-command grep-find-command
630 grep-template grep-find-template)
632 (concat (if grep-use-null-device "-n" "-nH")
633 (if grep-use-null-filename-separator " --null")
634 (if (grep-probe grep-program
635 `(nil nil nil "-e" "foo" ,null-device)
640 (format "%s %s %s " grep-program
642 (and grep-highlight-matches
643 (grep-probe grep-program
644 `(nil nil nil "--color" "x" ,null-device)
646 (if (eq grep-highlight-matches 'always)
647 "--color=always" "--color"))
650 (unless grep-template
652 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
653 (unless grep-find-use-xargs
654 (setq grep-find-use-xargs
656 ((grep-probe find-program
657 `(nil nil nil ,null-device "-exec" "echo"
661 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
662 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
666 (unless grep-find-command
667 (setq grep-find-command
668 (cond ((eq grep-find-use-xargs 'gnu)
669 ;; Windows shells need the program file name
670 ;; after the pipe symbol be quoted if they use
671 ;; forward slashes as directory separators.
672 (format "%s . -type f -print0 | \"%s\" -0 %s"
673 find-program xargs-program grep-command))
674 ((memq grep-find-use-xargs '(exec exec-plus))
675 (let ((cmd0 (format "%s . -type f -exec %s"
676 find-program grep-command))
677 (null (if grep-use-null-device
678 (format "%s " null-device)
681 (if (eq grep-find-use-xargs 'exec-plus)
682 (format "%s %s%s +" cmd0 null quot-braces)
683 (format "%s %s %s%s" cmd0 quot-braces null quot-scolon))
684 (1+ (length cmd0)))))
686 (format "%s . -type f -print | \"%s\" %s"
687 find-program xargs-program grep-command)))))
688 (unless grep-find-template
689 (setq grep-find-template
690 (let ((gcmd (format "%s <C> %s <R>"
691 grep-program grep-options))
692 (null (if grep-use-null-device
693 (format "%s " null-device)
695 (cond ((eq grep-find-use-xargs 'gnu)
696 (format "%s <D> <X> -type f <F> -print0 | \"%s\" -0 %s"
697 find-program xargs-program gcmd))
698 ((eq grep-find-use-xargs 'exec)
699 (format "%s <D> <X> -type f <F> -exec %s %s %s%s"
700 find-program gcmd quot-braces null quot-scolon))
701 ((eq grep-find-use-xargs 'exec-plus)
702 (format "%s <D> <X> -type f <F> -exec %s %s%s +"
703 find-program gcmd null quot-braces))
705 (format "%s <D> <X> -type f <F> -print | \"%s\" %s"
706 find-program xargs-program gcmd))))))))
708 ;; Save defaults for this host.
709 (setq grep-host-defaults-alist
710 (delete (assq host-id grep-host-defaults-alist)
711 grep-host-defaults-alist))
713 'grep-host-defaults-alist
715 `((grep-command ,grep-command)
716 (grep-template ,grep-template)
717 (grep-use-null-device ,grep-use-null-device)
718 (grep-find-command ,grep-find-command)
719 (grep-find-template ,grep-find-template)
720 (grep-find-use-xargs ,grep-find-use-xargs)
721 (grep-highlight-matches ,grep-highlight-matches))))))
723 (defun grep-tag-default ()
724 (or (and transient-mark-mode mark-active
726 (buffer-substring-no-properties (point) (mark)))
727 (funcall (or find-tag-default-function
728 (get major-mode 'find-tag-default-function)
732 (defun grep-default-command ()
733 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
734 (let ((tag-default (shell-quote-argument (grep-tag-default)))
735 ;; This a regexp to match single shell arguments.
736 ;; Could someone please add comments explaining it?
737 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
738 (grep-default (or (car grep-history) grep-command)))
739 ;; In the default command, find the arg that specifies the pattern.
740 (when (or (string-match
741 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
742 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
744 ;; If the string is not yet complete.
745 (string-match "\\(\\)\\'" grep-default))
746 ;; Maybe we will replace the pattern with the default tag.
747 ;; But first, maybe replace the file name pattern.
749 (unless (or (not (stringp buffer-file-name))
750 (when (match-beginning 2)
754 (file-name-nondirectory
755 (match-string 3 grep-default)))
756 (file-name-nondirectory buffer-file-name)))))
757 (setq grep-default (concat (substring grep-default
758 0 (match-beginning 2))
760 (file-name-extension buffer-file-name))))
761 ;; In case wildcard-to-regexp gets an error
762 ;; from invalid data.
764 ;; Now replace the pattern with the default tag.
765 (replace-match tag-default t t grep-default 1))))
769 (define-compilation-mode grep-mode "Grep"
770 "Sets `grep-last-buffer' and `compilation-window-height'."
771 (setq grep-last-buffer (current-buffer))
772 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
773 (set (make-local-variable 'compilation-error-face)
775 (set (make-local-variable 'compilation-error-regexp-alist)
777 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
779 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
780 (set (make-local-variable 'compilation-process-setup-function)
782 (set (make-local-variable 'compilation-disable-input) t)
783 (set (make-local-variable 'compilation-error-screen-columns)
784 grep-error-screen-columns)
785 (add-hook 'compilation-filter-hook 'grep-filter nil t))
787 (defun grep--save-buffers ()
788 (when grep-save-buffers
789 (save-some-buffers (and (not (eq grep-save-buffers 'ask))
790 (not (functionp grep-save-buffers)))
791 (and (functionp grep-save-buffers)
792 grep-save-buffers))))
795 (defun grep (command-args)
796 "Run Grep with user-specified COMMAND-ARGS, collect output in a buffer.
797 While Grep runs asynchronously, you can use \\[next-error] (M-x next-error),
798 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
799 buffer, to go to the lines where Grep found
800 matches. To kill the Grep job before it finishes, type \\[kill-compilation].
802 Noninteractively, COMMAND-ARGS should specify the Grep command-line
805 For doing a recursive `grep', see the `rgrep' command. For running
806 Grep in a specific directory, see `lgrep'.
808 This command uses a special history list for its COMMAND-ARGS, so you
809 can easily repeat a grep command.
811 A prefix argument says to default the COMMAND-ARGS based on the current
812 tag the cursor is over, substituting it into the last Grep command
813 in the Grep command history (or into `grep-command' if that history
817 (grep-compute-defaults)
818 (let ((default (grep-default-command)))
819 (list (read-shell-command "Run grep (like this): "
820 (if current-prefix-arg default grep-command)
822 (if current-prefix-arg nil default))))))
825 ;; Setting process-setup-function makes exit-message-function work
826 ;; even when async processes aren't supported.
827 (compilation-start (if (and grep-use-null-device null-device)
828 (concat command-args " " null-device)
834 (defun grep-find (command-args)
835 "Run grep via find, with user-specified args COMMAND-ARGS.
836 Collect output in a buffer.
837 While find runs asynchronously, you can use the \\[next-error] command
838 to find the text that grep hits refer to.
840 This command uses a special history list for its arguments, so you can
841 easily repeat a find command."
844 (grep-compute-defaults)
845 (if grep-find-command
846 (list (read-shell-command "Run find (like this): "
847 grep-find-command 'grep-find-history))
848 ;; No default was set
850 "compile.el: No `grep-find-command' command available. Press RET.")
853 (let ((null-device nil)) ; see grep
854 (grep command-args))))
857 (defalias 'find-grep 'grep-find)
860 ;; User-friendly interactive API.
862 (defconst grep-expand-keywords
863 '(("<C>" . (mapconcat #'identity opts " "))
864 ("<D>" . (or dir "."))
866 ("<N>" . null-device)
868 ("<R>" . (shell-quote-argument (or regexp ""))))
869 "List of substitutions performed by `grep-expand-template'.
870 If car of an element matches, the cdr is evalled in to get the
871 substitution string. Note dynamic scoping of variables.")
873 (defun grep-expand-template (template &optional regexp files dir excl)
874 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
875 (let* ((command template)
876 (env `((opts . ,(let (opts)
877 (when (and case-fold-search
878 (isearch-no-upper-case-p regexp t))
881 ((eq grep-highlight-matches 'always)
882 (push "--color=always" opts))
883 ((eq grep-highlight-matches 'auto)
884 (push "--color" opts)))
890 (case-fold-search nil))
891 (dolist (kw grep-expand-keywords command)
892 (if (string-match (car kw) command)
895 (or (if (symbolp (cdr kw))
897 (save-match-data (eval (cdr kw) env)))
901 (defun grep-read-regexp ()
902 "Read regexp arg for interactive grep using `read-regexp'."
903 (read-regexp "Search for" 'grep-tag-default 'grep-regexp-history))
905 (defun grep-read-files (regexp)
906 "Read a file-name pattern arg for interactive grep.
907 The pattern can include shell wildcards."
908 (let* ((bn (or (buffer-file-name)
909 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
912 (file-name-nondirectory bn)))
915 (let ((aliases (remove (assoc "all" grep-files-aliases)
919 (setq alias (car aliases)
920 aliases (cdr aliases))
921 (if (string-match (mapconcat
923 (split-string (cdr alias) nil t)
931 (let ((ext (file-name-extension fn)))
932 (and ext (concat "*." ext)))))
936 (car grep-files-history)
937 (car (car grep-files-aliases))))
938 (files (completing-read
939 (concat "Search for \"" regexp
940 "\" in files matching wildcard"
941 (if default (concat " (default " default ")"))
943 'read-file-name-internal
944 nil nil nil 'grep-files-history
946 (delq nil (append (list default default-alias default-extension)
947 (mapcar 'car grep-files-aliases)))))))
949 (or (cdr (assoc files grep-files-aliases))
953 (defun lgrep (regexp &optional files dir confirm)
954 "Run grep, searching for REGEXP in FILES in directory DIR.
955 The search is limited to file names matching shell pattern FILES.
956 FILES may use abbreviations defined in `grep-files-aliases', e.g.
957 entering `ch' is equivalent to `*.[ch]'.
959 With \\[universal-argument] prefix, you can edit the constructed shell command line
960 before it is executed.
961 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
963 Collect output in a buffer. While grep runs asynchronously, you
964 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
965 in the grep output buffer,
966 to go to the lines where grep found matches.
968 This command shares argument histories with \\[rgrep] and \\[grep]."
971 (grep-compute-defaults)
973 ((and grep-command (equal current-prefix-arg '(16)))
974 (list (read-from-minibuffer "Run: " grep-command
975 nil nil 'grep-history)))
977 (error "grep.el: No `grep-template' available"))
978 (t (let* ((regexp (grep-read-regexp))
979 (files (grep-read-files regexp))
980 (dir (read-directory-name "In directory: "
981 nil default-directory t))
982 (confirm (equal current-prefix-arg '(4))))
983 (list regexp files dir confirm))))))
984 (when (and (stringp regexp) (> (length regexp) 0))
985 (unless (and dir (file-accessible-directory-p dir))
986 (setq dir default-directory))
987 (let ((command regexp))
989 (if (string= command grep-command)
991 (setq dir (file-name-as-directory (expand-file-name dir)))
992 (setq command (grep-expand-template
997 (and grep-find-ignored-files
998 (concat " --exclude="
1001 (cond ((stringp ignore)
1002 (shell-quote-argument ignore))
1004 (and (funcall (car ignore) dir)
1005 (shell-quote-argument
1007 grep-find-ignored-files
1012 (read-from-minibuffer "Confirm: "
1013 command nil nil 'grep-history))
1014 (add-to-history 'grep-history command))))
1016 (let ((default-directory dir))
1017 ;; Setting process-setup-function makes exit-message-function work
1018 ;; even when async processes aren't supported.
1019 (grep--save-buffers)
1020 (compilation-start (if (and grep-use-null-device null-device)
1021 (concat command " " null-device)
1024 (if (eq next-error-last-buffer (current-buffer))
1025 (setq default-directory dir))))))
1028 (defvar find-name-arg) ; not autoloaded but defined in find-dired
1031 (defun rgrep (regexp &optional files dir confirm)
1032 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
1033 The search is limited to file names matching shell pattern FILES.
1034 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1035 entering `ch' is equivalent to `*.[ch]'.
1037 With \\[universal-argument] prefix, you can edit the constructed shell command line
1038 before it is executed.
1039 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
1041 Collect output in a buffer. While the recursive grep is running,
1042 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1043 in the grep output buffer,
1044 to visit the lines where matches were found. To kill the job
1045 before it finishes, type \\[kill-compilation].
1047 This command shares argument histories with \\[lgrep] and \\[grep-find].
1049 When called programmatically and FILES is nil, REGEXP is expected
1050 to specify a command to run."
1053 (grep-compute-defaults)
1055 ((and grep-find-command (equal current-prefix-arg '(16)))
1056 (list (read-from-minibuffer "Run: " grep-find-command
1057 nil nil 'grep-find-history)))
1058 ((not grep-find-template)
1059 (error "grep.el: No `grep-find-template' available"))
1060 (t (let* ((regexp (grep-read-regexp))
1061 (files (grep-read-files regexp))
1062 (dir (read-directory-name "Base directory: "
1063 nil default-directory t))
1064 (confirm (equal current-prefix-arg '(4))))
1065 (list regexp files dir confirm))))))
1066 (when (and (stringp regexp) (> (length regexp) 0))
1067 (unless (and dir (file-accessible-directory-p dir))
1068 (setq dir default-directory))
1070 (if (not (string= regexp (if (consp grep-find-command)
1071 (car grep-find-command)
1072 grep-find-command)))
1073 (compilation-start regexp 'grep-mode))
1074 (setq dir (file-name-as-directory (expand-file-name dir)))
1075 (let ((command (rgrep-default-command regexp files nil)))
1079 (read-from-minibuffer "Confirm: "
1080 command nil nil 'grep-find-history))
1081 (add-to-history 'grep-find-history command))
1082 (grep--save-buffers)
1083 (let ((default-directory dir))
1084 (compilation-start command 'grep-mode))
1085 ;; Set default-directory if we started rgrep in the *grep* buffer.
1086 (if (eq next-error-last-buffer (current-buffer))
1087 (setq default-directory dir)))))))
1089 (defun rgrep-find-ignored-directories (dir)
1090 "Return the list of ignored directories applicable to `dir'."
1093 (cond ((stringp ignore) ignore)
1095 (and (funcall (car ignore) dir) (cdr ignore)))))
1096 grep-find-ignored-directories)))
1098 (defun rgrep-default-command (regexp files dir)
1099 "Compute the command for \\[rgrep] to use by default."
1100 (require 'find-dired) ; for `find-name-arg'
1101 (grep-expand-template
1104 (concat (shell-quote-argument "(")
1105 " " find-name-arg " "
1107 #'shell-quote-argument
1108 (split-string files)
1109 (concat " -o " find-name-arg " "))
1111 (shell-quote-argument ")"))
1114 (and grep-find-ignored-directories
1116 (shell-quote-argument "(")
1117 ;; we should use shell-quote-argument here
1119 (mapconcat (lambda (d) (shell-quote-argument (concat "*/" d)))
1120 (rgrep-find-ignored-directories dir)
1123 (shell-quote-argument ")")
1125 (and grep-find-ignored-files
1126 (concat (shell-quote-argument "!") " -type d "
1127 (shell-quote-argument "(")
1128 ;; we should use shell-quote-argument here
1132 (cond ((stringp ignore)
1133 (shell-quote-argument ignore))
1135 (and (funcall (car ignore) dir)
1136 (shell-quote-argument
1138 grep-find-ignored-files
1141 (shell-quote-argument ")")
1145 (defun zrgrep (regexp &optional files dir confirm template)
1146 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1147 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1148 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1151 ;; Compute standard default values.
1152 (grep-compute-defaults)
1153 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1154 ;; for grep program "zgrep", but not changing global values.
1155 (let ((grep-program "zgrep")
1156 ;; Don't change global values for variables computed
1157 ;; by `grep-compute-defaults'.
1158 (grep-find-template nil)
1159 (grep-find-command nil)
1160 (grep-host-defaults-alist nil)
1161 ;; Use for `grep-read-files'
1162 (grep-files-aliases '(("all" . "* .*")
1164 ;; Recompute defaults using let-bound values above.
1165 (grep-compute-defaults)
1167 ((and grep-find-command (equal current-prefix-arg '(16)))
1168 (list (read-from-minibuffer "Run: " grep-find-command
1169 nil nil 'grep-find-history)))
1170 ((not grep-find-template)
1171 (error "grep.el: No `grep-find-template' available"))
1172 (t (let* ((regexp (grep-read-regexp))
1173 (files (grep-read-files regexp))
1174 (dir (read-directory-name "Base directory: "
1175 nil default-directory t))
1176 (confirm (equal current-prefix-arg '(4))))
1177 (list regexp files dir confirm grep-find-template)))))))
1178 (let ((grep-find-template template)
1179 ;; Set `grep-highlight-matches' to `always'
1180 ;; since `zgrep' puts filters in the grep output.
1181 (grep-highlight-matches 'always))
1182 (rgrep regexp files dir confirm)))
1185 (defalias 'rzgrep 'zrgrep)
1189 ;;; grep.el ends here