; * etc/NEWS: Fix last change.
[emacs.git] / lisp / progmodes / grep.el
blobdac3726bb140d7cc9c91be4dc8a15877b13e651e
1 ;;; grep.el --- run `grep' and display the results -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2017 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 <https://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)
34 (defgroup grep nil
35 "Run `grep' and display the results."
36 :group 'tools
37 :group 'processes)
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
53 (let* ((host-id
54 (intern (or (file-remote-p default-directory) "localhost")))
55 (host-defaults (assq host-id grep-host-defaults-alist))
56 (defaults (assq nil grep-host-defaults-alist)))
57 (setcar (cdr (assq symbol host-defaults)) value)
58 (setcar (cdr (assq symbol defaults)) value)))
59 (set-default symbol value))
61 ;;;###autoload
62 (defcustom grep-window-height nil
63 "Number of lines in a grep window. If nil, use `compilation-window-height'."
64 :type '(choice (const :tag "Default" nil)
65 integer)
66 :version "22.1"
67 :group 'grep)
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
101 :version "22.1"
102 :group 'grep)
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
109 than the beginning."
110 :type 'boolean
111 :version "22.1"
112 :group 'grep)
114 ;;;###autoload
115 (defcustom grep-command nil
116 "The default grep command for \\[grep].
117 If the grep program used supports an option to always include file names
118 in its output (such as the `-H' option to GNU grep), it's a good idea to
119 include it when specifying `grep-command'.
121 In interactive usage, the actual value of this variable is set up
122 by `grep-compute-defaults'; to change the default value, use
123 Customize or call the function `grep-apply-setting'."
124 :type '(choice string
125 (const :tag "Not Set" nil))
126 :set 'grep-apply-setting
127 :group 'grep)
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
144 :version "22.1"
145 :group 'grep)
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
160 :group 'grep)
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 :version "26.1"
166 :type '(choice (const :tag "Do Not Use `--null'" nil)
167 (const :tag "Use `--null'" t)
168 (other :tag "Not Set" auto-detect))
169 :set 'grep-apply-setting
170 :group 'grep)
172 ;;;###autoload
173 (defcustom grep-find-command nil
174 "The default find command for \\[grep-find].
175 In interactive usage, the actual value of this variable is set up
176 by `grep-compute-defaults'; to change the default value, use
177 Customize or call the function `grep-apply-setting'."
178 :type '(choice string
179 (const :tag "Not Set" nil))
180 :set 'grep-apply-setting
181 :group 'grep)
183 (defcustom grep-find-template nil
184 "The default command to run for \\[rgrep].
185 The following place holders should be present in the string:
186 <D> - base directory for find
187 <X> - find options to restrict or expand the directory list
188 <F> - find options to limit the files matched
189 <C> - place to put the grep options like -i and --color
190 <R> - the regular expression searched for.
191 In interactive usage, the actual value of this variable is set up
192 by `grep-compute-defaults'; to change the default value, use
193 Customize or call the function `grep-apply-setting'."
194 :type '(choice string
195 (const :tag "Not Set" nil))
196 :set 'grep-apply-setting
197 :version "22.1"
198 :group 'grep)
200 (defcustom grep-files-aliases
201 '(("all" . "* .[!.]* ..?*") ;; Don't match `..'. See bug#22577
202 ("el" . "*.el")
203 ("ch" . "*.[ch]")
204 ("c" . "*.c")
205 ("cc" . "*.cc *.cxx *.cpp *.C *.CC *.c++")
206 ("cchh" . "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
207 ("hh" . "*.hxx *.hpp *.[Hh] *.HH *.h++")
208 ("h" . "*.h")
209 ("l" . "[Cc]hange[Ll]og*")
210 ("m" . "[Mm]akefile*")
211 ("tex" . "*.tex")
212 ("texi" . "*.texi")
213 ("asm" . "*.[sS]"))
214 "Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
215 :type 'alist
216 :group 'grep)
218 (defcustom grep-find-ignored-directories
219 vc-directory-exclusion-list
220 "List of names of sub-directories which `rgrep' shall not recurse into.
221 If an element is a cons cell, the car is called on the search directory
222 to determine whether cdr should not be recursed into."
223 :type '(choice (repeat :tag "Ignored directories" string)
224 (const :tag "No ignored directories" nil))
225 :group 'grep)
227 (defcustom grep-find-ignored-files
228 (cons ".#*" (delq nil (mapcar (lambda (s)
229 (unless (string-match-p "/\\'" s)
230 (concat "*" s)))
231 completion-ignored-extensions)))
232 "List of file names which `rgrep' and `lgrep' shall exclude.
233 If an element is a cons cell, the car is called on the search directory
234 to determine whether cdr should not be excluded."
235 :type '(choice (repeat :tag "Ignored file" string)
236 (const :tag "No ignored files" nil))
237 :group 'grep)
239 (defcustom grep-save-buffers 'ask
240 "If non-nil, save buffers before running the grep commands.
241 If `ask', ask before saving. If a function, call it with no arguments
242 with each buffer current, as a predicate to determine whether that
243 buffer should be saved or not. E.g., one can set this to
244 (lambda ()
245 (string-prefix-p my-grep-root (file-truename (buffer-file-name))))
246 to limit saving to files located under `my-grep-root'."
247 :version "26.1"
248 :type '(choice
249 (const :tag "Ask before saving" ask)
250 (const :tag "Don't save buffers" nil)
251 function
252 (other :tag "Save all buffers" t))
253 :group 'grep)
255 (defcustom grep-error-screen-columns nil
256 "If non-nil, column numbers in grep hits are screen columns.
257 See `compilation-error-screen-columns'"
258 :type '(choice (const :tag "Default" nil)
259 integer)
260 :version "22.1"
261 :group 'grep)
263 ;;;###autoload
264 (defcustom grep-setup-hook nil
265 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
266 :type 'hook
267 :group 'grep)
269 (defvar grep-mode-map
270 (let ((map (make-sparse-keymap)))
271 (set-keymap-parent map compilation-minor-mode-map)
272 (define-key map " " 'scroll-up-command)
273 (define-key map [?\S-\ ] 'scroll-down-command)
274 (define-key map "\^?" 'scroll-down-command)
275 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
277 (define-key map "\r" 'compile-goto-error) ;; ?
278 (define-key map "n" 'next-error-no-select)
279 (define-key map "p" 'previous-error-no-select)
280 (define-key map "{" 'compilation-previous-file)
281 (define-key map "}" 'compilation-next-file)
282 (define-key map "\t" 'compilation-next-error)
283 (define-key map [backtab] 'compilation-previous-error)
285 ;; Set up the menu-bar
286 (define-key map [menu-bar grep]
287 (cons "Grep" (make-sparse-keymap "Grep")))
289 (define-key map [menu-bar grep compilation-kill-compilation]
290 '(menu-item "Kill Grep" kill-compilation
291 :help "Kill the currently running grep process"))
292 (define-key map [menu-bar grep compilation-separator2] '("----"))
293 (define-key map [menu-bar grep compilation-compile]
294 '(menu-item "Compile..." compile
295 :help "Compile the program including the current buffer. Default: run `make'"))
296 (define-key map [menu-bar grep compilation-rgrep]
297 '(menu-item "Recursive grep..." rgrep
298 :help "User-friendly recursive grep in directory tree"))
299 (define-key map [menu-bar grep compilation-lgrep]
300 '(menu-item "Local grep..." lgrep
301 :help "User-friendly grep in a directory"))
302 (define-key map [menu-bar grep compilation-grep-find]
303 '(menu-item "Grep via Find..." grep-find
304 :help "Run grep via find, with user-specified args"))
305 (define-key map [menu-bar grep compilation-grep]
306 '(menu-item "Another grep..." grep
307 :help "Run grep, with user-specified args, and collect output in a buffer."))
308 (define-key map [menu-bar grep compilation-recompile]
309 '(menu-item "Repeat grep" recompile
310 :help "Run grep again"))
311 (define-key map [menu-bar grep compilation-separator2] '("----"))
312 (define-key map [menu-bar grep compilation-first-error]
313 '(menu-item "First Match" first-error
314 :help "Restart at the first match, visit corresponding location"))
315 (define-key map [menu-bar grep compilation-previous-error]
316 '(menu-item "Previous Match" previous-error
317 :help "Visit the previous match and corresponding location"))
318 (define-key map [menu-bar grep compilation-next-error]
319 '(menu-item "Next Match" next-error
320 :help "Visit the next match and corresponding location"))
321 map)
322 "Keymap for grep buffers.
323 `compilation-minor-mode-map' is a cdr of this.")
325 (defvar grep-mode-tool-bar-map
326 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
327 ;; so don't do anything.
328 (when (keymapp (butlast tool-bar-map))
329 (let ((map (butlast (copy-keymap tool-bar-map)))
330 (help (last tool-bar-map))) ;; Keep Help last in tool bar
331 (tool-bar-local-item
332 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
333 :rtl "right-arrow"
334 :help "Goto previous match")
335 (tool-bar-local-item
336 "right-arrow" 'next-error-no-select 'next-error-no-select map
337 :rtl "left-arrow"
338 :help "Goto next match")
339 (tool-bar-local-item
340 "cancel" 'kill-compilation 'kill-compilation map
341 :enable '(let ((buffer (compilation-find-buffer)))
342 (get-buffer-process buffer))
343 :help "Stop grep")
344 (tool-bar-local-item
345 "refresh" 'recompile 'recompile map
346 :help "Restart grep")
347 (append map help))))
349 (defalias 'kill-grep 'kill-compilation)
351 ;;;; TODO --- refine this!!
353 ;; (defcustom grep-use-compilation-buffer t
354 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
355 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
356 ;; can be used to navigate between grep matches (the default).
357 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
358 ;; be used to navigate between grep matches."
359 ;; :type 'boolean
360 ;; :group 'grep)
362 ;; override compilation-last-buffer
363 (defvar grep-last-buffer nil
364 "The most recent grep buffer.
365 A grep buffer becomes most recent when you select Grep mode in it.
366 Notice that using \\[next-error] or \\[compile-goto-error] modifies
367 `compilation-last-buffer' rather than `grep-last-buffer'.")
369 ;;;###autoload
370 (defconst grep-regexp-alist
371 `((,(concat "^\\(?:"
372 ;; Parse using NUL characters when `--null' is used.
373 ;; Note that we must still assume no newlines in
374 ;; filenames due to "foo: Is a directory." type
375 ;; messages.
376 "\\(?1:[^\0\n]+\\)\\(?3:\0\\)\\(?2:[0-9]+\\):"
377 "\\|"
378 ;; Fallback if `--null' is not used, use a tight regexp
379 ;; to handle weird file names (with colons in them) as
380 ;; well as possible. E.g., use [1-9][0-9]* rather than
381 ;; [0-9]+ so as to accept ":034:" in file names.
382 "\\(?1:[^\n:]+?[^\n/:]\\):[\t ]*\\(?2:[1-9][0-9]*\\)[\t ]*:"
383 "\\)")
385 ;; Calculate column positions (col . end-col) of first grep match on a line
386 (,(lambda ()
387 (when grep-highlight-matches
388 (let* ((beg (match-end 0))
389 (end (save-excursion (goto-char beg) (line-end-position)))
390 (mbeg (text-property-any beg end 'font-lock-face 'grep-match-face)))
391 (when mbeg
392 (- mbeg beg)))))
394 ,(lambda ()
395 (when grep-highlight-matches
396 (let* ((beg (match-end 0))
397 (end (save-excursion (goto-char beg) (line-end-position)))
398 (mbeg (text-property-any beg end 'font-lock-face 'grep-match-face))
399 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
400 (when mend
401 (- mend beg))))))
402 nil nil
403 (3 '(face nil display ":")))
404 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
405 "Regexp used to match grep hits.
406 See `compilation-error-regexp-alist' for format details.")
408 (defvar grep-first-column 0 ; bug#10594
409 "Value to use for `compilation-first-column' in grep buffers.")
411 (defvar grep-error "grep hit"
412 "Message to print when no matches are found.")
414 ;; Reverse the colors because grep hits are not errors (though we jump there
415 ;; with `next-error'), and unreadable files can't be gone to.
416 (defvar grep-hit-face compilation-info-face
417 "Face name to use for grep hits.")
419 (defvar grep-error-face 'compilation-error
420 "Face name to use for grep error messages.")
422 (defvar grep-match-face 'match
423 "Face name to use for grep matches.")
425 (defvar grep-context-face 'shadow
426 "Face name to use for grep context lines.")
428 (defvar grep-mode-font-lock-keywords
429 '(;; Command output lines.
430 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
431 1 grep-error-face)
432 ;; remove match from grep-regexp-alist before fontifying
433 ("^Grep[/a-zA-z]* started.*"
434 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
435 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
436 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
437 (1 compilation-info-face nil t)
438 (2 compilation-warning-face nil t))
439 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
440 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
441 (1 grep-error-face)
442 (2 grep-error-face nil t))
443 ;; "filename-linenumber-" format is used for context lines in GNU grep,
444 ;; "filename=linenumber=" for lines with function names in "git grep -p".
445 ("^.+?\\([-=\0]\\)[0-9]+\\([-=]\\).*\n" (0 grep-context-face)
446 (1 (if (eq (char-after (match-beginning 1)) ?\0)
447 `(face nil display ,(match-string 2))))))
448 "Additional things to highlight in grep output.
449 This gets tacked on the end of the generated expressions.")
451 ;;;###autoload
452 (defvar grep-program (purecopy "grep")
453 "The default grep program for `grep-command' and `grep-find-command'.
454 This variable's value takes effect when `grep-compute-defaults' is called.")
456 ;;;###autoload
457 (defvar find-program (purecopy "find")
458 "The default find program.
459 This is used by commands like `grep-find-command', `find-dired'
460 and others.")
462 ;;;###autoload
463 (defvar xargs-program (purecopy "xargs")
464 "The default xargs program for `grep-find-command'.
465 See `grep-find-use-xargs'.
466 This variable's value takes effect when `grep-compute-defaults' is called.")
468 ;;;###autoload
469 (defvar grep-find-use-xargs nil
470 "How to invoke find and grep.
471 If `exec', use `find -exec {} ;'.
472 If `exec-plus' use `find -exec {} +'.
473 If `gnu', use `find -print0' and `xargs -0'.
474 Any other value means to use `find -print' and `xargs'.
476 This variable's value takes effect when `grep-compute-defaults' is called.")
478 ;; History of grep commands.
479 ;;;###autoload
480 (defvar grep-history nil "History list for grep.")
481 ;;;###autoload
482 (defvar grep-find-history nil "History list for grep-find.")
484 ;; History of lgrep and rgrep regexp and files args.
485 (defvar grep-regexp-history nil)
486 (defvar grep-files-history nil)
488 ;;;###autoload
489 (defun grep-process-setup ()
490 "Setup compilation variables and buffer for `grep'.
491 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
492 (when (eq grep-highlight-matches 'auto-detect)
493 (grep-compute-defaults))
494 (unless (or (eq grep-highlight-matches 'auto-detect)
495 (null grep-highlight-matches)
496 ;; Don't output color escapes if they can't be
497 ;; highlighted with `font-lock-face' by `grep-filter'.
498 (null font-lock-mode))
499 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
500 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
501 (setenv "TERM" "emacs-grep")
502 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
503 (setenv "GREP_COLOR" "01;31")
504 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
505 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
506 (set (make-local-variable 'compilation-exit-message-function)
507 (lambda (status code msg)
508 (if (eq status 'exit)
509 ;; This relies on the fact that `compilation-start'
510 ;; sets buffer-modified to nil before running the command,
511 ;; so the buffer is still unmodified if there is no output.
512 (cond ((and (zerop code) (buffer-modified-p))
513 '("finished (matches found)\n" . "matched"))
514 ((not (buffer-modified-p))
515 '("finished with no matches found\n" . "no match"))
517 (cons msg code)))
518 (cons msg code))))
519 (run-hooks 'grep-setup-hook))
521 (defun grep-filter ()
522 "Handle match highlighting escape sequences inserted by the grep process.
523 This function is called from `compilation-filter-hook'."
524 (save-excursion
525 (forward-line 0)
526 (let ((end (point)) beg)
527 (goto-char compilation-filter-start)
528 (forward-line 0)
529 (setq beg (point))
530 ;; Only operate on whole lines so we don't get caught with part of an
531 ;; escape sequence in one chunk and the rest in another.
532 (when (< (point) end)
533 (setq end (copy-marker end))
534 ;; Highlight grep matches and delete marking sequences.
535 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
536 (replace-match (propertize (match-string 1)
537 'face nil 'font-lock-face grep-match-face)
538 t t))
539 ;; Delete all remaining escape sequences
540 (goto-char beg)
541 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
542 (replace-match "" t t))))))
544 (defun grep-probe (command args &optional func result)
545 (let (process-file-side-effects)
546 (equal (condition-case nil
547 (apply (or func 'process-file) command args)
548 (error nil))
549 (or result 0))))
551 ;;;###autoload
552 (defun grep-compute-defaults ()
553 ;; Keep default values.
554 (unless grep-host-defaults-alist
555 (add-to-list
556 'grep-host-defaults-alist
557 (cons nil
558 `((grep-command ,grep-command)
559 (grep-template ,grep-template)
560 (grep-use-null-device ,grep-use-null-device)
561 (grep-find-command ,grep-find-command)
562 (grep-find-template ,grep-find-template)
563 (grep-use-null-filename-separator
564 ,grep-use-null-filename-separator)
565 (grep-find-use-xargs ,grep-find-use-xargs)
566 (grep-highlight-matches ,grep-highlight-matches)))))
567 (let* ((host-id
568 (intern (or (file-remote-p default-directory) "localhost")))
569 (host-defaults (assq host-id grep-host-defaults-alist))
570 (defaults (assq nil grep-host-defaults-alist))
571 (quot-braces (shell-quote-argument "{}"))
572 (quot-scolon (shell-quote-argument ";")))
573 ;; There are different defaults on different hosts. They must be
574 ;; computed for every host once.
575 (dolist (setting '(grep-command grep-template
576 grep-use-null-device grep-find-command
577 grep-use-null-filename-separator
578 grep-find-template grep-find-use-xargs
579 grep-highlight-matches))
580 (set setting
581 (cadr (or (assq setting host-defaults)
582 (assq setting defaults)))))
584 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
585 (setq grep-use-null-device
586 (with-temp-buffer
587 (let ((hello-file (expand-file-name "HELLO" data-directory)))
588 (not
589 (and (if grep-command
590 ;; `grep-command' is already set, so
591 ;; use that for testing.
592 (grep-probe grep-command
593 `(nil t nil "^English" ,hello-file)
594 #'call-process-shell-command)
595 ;; otherwise use `grep-program'
596 (grep-probe grep-program
597 `(nil t nil "-nH" "^English" ,hello-file)))
598 (progn
599 (goto-char (point-min))
600 (looking-at
601 (concat (regexp-quote hello-file)
602 ":[0-9]+:English")))))))))
604 (when (eq grep-use-null-filename-separator 'auto-detect)
605 (setq grep-use-null-filename-separator
606 (with-temp-buffer
607 (let* ((hello-file (expand-file-name "HELLO" data-directory))
608 (args `("--null" "-ne" "^English" ,hello-file)))
609 (if grep-use-null-device
610 (setq args (append args (list null-device)))
611 (push "-H" args))
612 (and (grep-probe grep-program `(nil t nil ,@args))
613 (progn
614 (goto-char (point-min))
615 (looking-at
616 (concat (regexp-quote hello-file)
617 "\0[0-9]+:English"))))))))
619 (when (eq grep-highlight-matches 'auto-detect)
620 (setq grep-highlight-matches
621 (with-temp-buffer
622 (and (grep-probe grep-program '(nil t nil "--help"))
623 (progn
624 (goto-char (point-min))
625 (search-forward "--color" nil t))
626 ;; Windows and DOS pipes fail `isatty' detection in Grep.
627 (if (memq system-type '(windows-nt ms-dos))
628 'always 'auto)))))
630 (unless (and grep-command grep-find-command
631 grep-template grep-find-template)
632 (let ((grep-options
633 (concat (if grep-use-null-device "-n" "-nH")
634 (if grep-use-null-filename-separator " --null")
635 (if (grep-probe grep-program
636 `(nil nil nil "-e" "foo" ,null-device)
637 nil 1)
638 " -e"))))
639 (unless grep-command
640 (setq grep-command
641 (format "%s %s %s " grep-program
643 (and grep-highlight-matches
644 (grep-probe grep-program
645 `(nil nil nil "--color" "x" ,null-device)
646 nil 1)
647 (if (eq grep-highlight-matches 'always)
648 "--color=always" "--color"))
650 grep-options)))
651 (unless grep-template
652 (setq grep-template
653 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
654 (unless grep-find-use-xargs
655 (setq grep-find-use-xargs
656 (cond
657 ((grep-probe find-program
658 `(nil nil nil ,null-device "-exec" "echo"
659 "{}" "+"))
660 'exec-plus)
661 ((and
662 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
663 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
664 'gnu)
666 'exec))))
667 (unless grep-find-command
668 (setq grep-find-command
669 (cond ((eq grep-find-use-xargs 'gnu)
670 ;; Windows shells need the program file name
671 ;; after the pipe symbol be quoted if they use
672 ;; forward slashes as directory separators.
673 (format "%s . -type f -print0 | \"%s\" -0 %s"
674 find-program xargs-program grep-command))
675 ((memq grep-find-use-xargs '(exec exec-plus))
676 (let ((cmd0 (format "%s . -type f -exec %s"
677 find-program grep-command))
678 (null (if grep-use-null-device
679 (format "%s " null-device)
680 "")))
681 (cons
682 (if (eq grep-find-use-xargs 'exec-plus)
683 (format "%s %s%s +" cmd0 null quot-braces)
684 (format "%s %s %s%s" cmd0 quot-braces null quot-scolon))
685 (1+ (length cmd0)))))
687 (format "%s . -type f -print | \"%s\" %s"
688 find-program xargs-program grep-command)))))
689 (unless grep-find-template
690 (setq grep-find-template
691 (let ((gcmd (format "%s <C> %s <R>"
692 grep-program grep-options))
693 (null (if grep-use-null-device
694 (format "%s " null-device)
695 "")))
696 (cond ((eq grep-find-use-xargs 'gnu)
697 (format "%s <D> <X> -type f <F> -print0 | \"%s\" -0 %s"
698 find-program xargs-program gcmd))
699 ((eq grep-find-use-xargs 'exec)
700 (format "%s <D> <X> -type f <F> -exec %s %s %s%s"
701 find-program gcmd quot-braces null quot-scolon))
702 ((eq grep-find-use-xargs 'exec-plus)
703 (format "%s <D> <X> -type f <F> -exec %s %s%s +"
704 find-program gcmd null quot-braces))
706 (format "%s <D> <X> -type f <F> -print | \"%s\" %s"
707 find-program xargs-program gcmd))))))))
709 ;; Save defaults for this host.
710 (setq grep-host-defaults-alist
711 (delete (assq host-id grep-host-defaults-alist)
712 grep-host-defaults-alist))
713 (add-to-list
714 'grep-host-defaults-alist
715 (cons host-id
716 `((grep-command ,grep-command)
717 (grep-template ,grep-template)
718 (grep-use-null-device ,grep-use-null-device)
719 (grep-find-command ,grep-find-command)
720 (grep-find-template ,grep-find-template)
721 (grep-find-use-xargs ,grep-find-use-xargs)
722 (grep-highlight-matches ,grep-highlight-matches))))))
724 (defun grep-tag-default ()
725 (or (and transient-mark-mode mark-active
726 (/= (point) (mark))
727 (buffer-substring-no-properties (point) (mark)))
728 (funcall (or find-tag-default-function
729 (get major-mode 'find-tag-default-function)
730 'find-tag-default))
731 ""))
733 (defun grep-default-command ()
734 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
735 (let ((tag-default (shell-quote-argument (grep-tag-default)))
736 ;; This a regexp to match single shell arguments.
737 ;; Could someone please add comments explaining it?
738 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
739 (grep-default (or (car grep-history) grep-command)))
740 ;; In the default command, find the arg that specifies the pattern.
741 (when (or (string-match
742 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
743 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
744 grep-default)
745 ;; If the string is not yet complete.
746 (string-match "\\(\\)\\'" grep-default))
747 ;; Maybe we will replace the pattern with the default tag.
748 ;; But first, maybe replace the file name pattern.
749 (condition-case nil
750 (unless (or (not (stringp buffer-file-name))
751 (when (match-beginning 2)
752 (save-match-data
753 (string-match
754 (wildcard-to-regexp
755 (file-name-nondirectory
756 (match-string 3 grep-default)))
757 (file-name-nondirectory buffer-file-name)))))
758 (setq grep-default (concat (substring grep-default
759 0 (match-beginning 2))
760 " *."
761 (file-name-extension buffer-file-name))))
762 ;; In case wildcard-to-regexp gets an error
763 ;; from invalid data.
764 (error nil))
765 ;; Now replace the pattern with the default tag.
766 (replace-match tag-default t t grep-default 1))))
769 ;;;###autoload
770 (define-compilation-mode grep-mode "Grep"
771 "Sets `grep-last-buffer' and `compilation-window-height'."
772 (setq grep-last-buffer (current-buffer))
773 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
774 (set (make-local-variable 'compilation-error-face)
775 grep-hit-face)
776 (set (make-local-variable 'compilation-error-regexp-alist)
777 grep-regexp-alist)
778 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
779 ;; can never match.
780 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
781 (set (make-local-variable 'compilation-process-setup-function)
782 'grep-process-setup)
783 (set (make-local-variable 'compilation-disable-input) t)
784 (set (make-local-variable 'compilation-error-screen-columns)
785 grep-error-screen-columns)
786 (add-hook 'compilation-filter-hook 'grep-filter nil t))
788 (defun grep--save-buffers ()
789 (when grep-save-buffers
790 (save-some-buffers (and (not (eq grep-save-buffers 'ask))
791 (not (functionp grep-save-buffers)))
792 (and (functionp grep-save-buffers)
793 grep-save-buffers))))
795 ;;;###autoload
796 (defun grep (command-args)
797 "Run Grep with user-specified COMMAND-ARGS, collect output in a buffer.
798 While Grep runs asynchronously, you can use \\[next-error] (M-x next-error),
799 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
800 buffer, to go to the lines where Grep found
801 matches. To kill the Grep job before it finishes, type \\[kill-compilation].
803 Noninteractively, COMMAND-ARGS should specify the Grep command-line
804 arguments.
806 For doing a recursive `grep', see the `rgrep' command. For running
807 Grep in a specific directory, see `lgrep'.
809 This command uses a special history list for its COMMAND-ARGS, so you
810 can easily repeat a grep command.
812 A prefix argument says to default the COMMAND-ARGS based on the current
813 tag the cursor is over, substituting it into the last Grep command
814 in the Grep command history (or into `grep-command' if that history
815 list is empty)."
816 (interactive
817 (progn
818 (grep-compute-defaults)
819 (let ((default (grep-default-command)))
820 (list (read-shell-command "Run grep (like this): "
821 (if current-prefix-arg default grep-command)
822 'grep-history
823 (if current-prefix-arg nil default))))))
825 (grep--save-buffers)
826 ;; Setting process-setup-function makes exit-message-function work
827 ;; even when async processes aren't supported.
828 (compilation-start (if (and grep-use-null-device null-device)
829 (concat command-args " " null-device)
830 command-args)
831 'grep-mode))
834 ;;;###autoload
835 (defun grep-find (command-args)
836 "Run grep via find, with user-specified args COMMAND-ARGS.
837 Collect output in a buffer.
838 While find runs asynchronously, you can use the \\[next-error] command
839 to find the text that grep hits refer to.
841 This command uses a special history list for its arguments, so you can
842 easily repeat a find command."
843 (interactive
844 (progn
845 (grep-compute-defaults)
846 (if grep-find-command
847 (list (read-shell-command "Run find (like this): "
848 grep-find-command 'grep-find-history))
849 ;; No default was set
850 (read-string
851 "compile.el: No `grep-find-command' command available. Press RET.")
852 (list nil))))
853 (when command-args
854 (let ((null-device nil)) ; see grep
855 (grep command-args))))
857 ;;;###autoload
858 (defalias 'find-grep 'grep-find)
861 ;; User-friendly interactive API.
863 (defconst grep-expand-keywords
864 '(("<C>" . (mapconcat #'identity opts " "))
865 ("<D>" . (or dir "."))
866 ("<F>" . files)
867 ("<N>" . null-device)
868 ("<X>" . excl)
869 ("<R>" . (shell-quote-argument (or regexp ""))))
870 "List of substitutions performed by `grep-expand-template'.
871 If car of an element matches, the cdr is evalled in to get the
872 substitution string. Note dynamic scoping of variables.")
874 (defun grep-expand-template (template &optional regexp files dir excl)
875 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
876 (let* ((command template)
877 (env `((opts . ,(let (opts)
878 (when (and case-fold-search
879 (isearch-no-upper-case-p regexp t))
880 (push "-i" opts))
881 (cond
882 ((eq grep-highlight-matches 'always)
883 (push "--color=always" opts))
884 ((eq grep-highlight-matches 'auto)
885 (push "--color" opts)))
886 opts))
887 (excl . ,excl)
888 (dir . ,dir)
889 (files . ,files)
890 (regexp . ,regexp)))
891 (case-fold-search nil))
892 (dolist (kw grep-expand-keywords command)
893 (if (string-match (car kw) command)
894 (setq command
895 (replace-match
896 (or (if (symbolp (cdr kw))
897 (eval (cdr kw) env)
898 (save-match-data (eval (cdr kw) env)))
900 t t command))))))
902 (defun grep-read-regexp ()
903 "Read regexp arg for interactive grep using `read-regexp'."
904 (read-regexp "Search for" 'grep-tag-default 'grep-regexp-history))
906 (defun grep-read-files (regexp)
907 "Read a file-name pattern arg for interactive grep.
908 The pattern can include shell wildcards. As whitespace triggers
909 completion when entering a pattern, including it requires
910 quoting, e.g. `\\[quoted-insert]<space>'."
911 (let* ((bn (or (buffer-file-name)
912 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
913 (fn (and bn
914 (stringp bn)
915 (file-name-nondirectory bn)))
916 (default-alias
917 (and fn
918 (let ((aliases (remove (assoc "all" grep-files-aliases)
919 grep-files-aliases))
920 alias)
921 (while aliases
922 (setq alias (car aliases)
923 aliases (cdr aliases))
924 (if (string-match (mapconcat
925 'wildcard-to-regexp
926 (split-string (cdr alias) nil t)
927 "\\|")
929 (setq aliases nil)
930 (setq alias nil)))
931 (cdr alias))))
932 (default-extension
933 (and fn
934 (let ((ext (file-name-extension fn)))
935 (and ext (concat "*." ext)))))
936 (default
937 (or default-alias
938 default-extension
939 (car grep-files-history)
940 (car (car grep-files-aliases))))
941 (files (completing-read
942 (concat "Search for \"" regexp
943 "\" in files matching wildcard"
944 (if default (concat " (default " default ")"))
945 ": ")
946 'read-file-name-internal
947 nil nil nil 'grep-files-history
948 (delete-dups
949 (delq nil (append (list default default-alias default-extension)
950 (mapcar 'car grep-files-aliases)))))))
951 (and files
952 (or (cdr (assoc files grep-files-aliases))
953 files))))
955 ;;;###autoload
956 (defun lgrep (regexp &optional files dir confirm)
957 "Run grep, searching for REGEXP in FILES in directory DIR.
958 The search is limited to file names matching shell pattern FILES.
959 FILES may use abbreviations defined in `grep-files-aliases', e.g.
960 entering `ch' is equivalent to `*.[ch]'. As whitespace triggers
961 completion when entering a pattern, including it requires
962 quoting, e.g. `\\[quoted-insert]<space>'.
964 With \\[universal-argument] prefix, you can edit the constructed shell command line
965 before it is executed.
966 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
968 Collect output in a buffer. While grep runs asynchronously, you
969 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
970 in the grep output buffer,
971 to go to the lines where grep found matches.
973 This command shares argument histories with \\[rgrep] and \\[grep]."
974 (interactive
975 (progn
976 (grep-compute-defaults)
977 (cond
978 ((and grep-command (equal current-prefix-arg '(16)))
979 (list (read-from-minibuffer "Run: " grep-command
980 nil nil 'grep-history)))
981 ((not grep-template)
982 (error "grep.el: No `grep-template' available"))
983 (t (let* ((regexp (grep-read-regexp))
984 (files (grep-read-files regexp))
985 (dir (read-directory-name "In directory: "
986 nil default-directory t))
987 (confirm (equal current-prefix-arg '(4))))
988 (list regexp files dir confirm))))))
989 (when (and (stringp regexp) (> (length regexp) 0))
990 (unless (and dir (file-accessible-directory-p dir))
991 (setq dir default-directory))
992 (let ((command regexp))
993 (if (null files)
994 (if (string= command grep-command)
995 (setq command nil))
996 (setq dir (file-name-as-directory (expand-file-name dir)))
997 (setq command (grep-expand-template
998 grep-template
999 regexp
1000 files
1002 (and grep-find-ignored-files
1003 (concat " --exclude="
1004 (mapconcat
1005 #'(lambda (ignore)
1006 (cond ((stringp ignore)
1007 (shell-quote-argument ignore))
1008 ((consp ignore)
1009 (and (funcall (car ignore) dir)
1010 (shell-quote-argument
1011 (cdr ignore))))))
1012 grep-find-ignored-files
1013 " --exclude=")))))
1014 (when command
1015 (if confirm
1016 (setq command
1017 (read-from-minibuffer "Confirm: "
1018 command nil nil 'grep-history))
1019 (add-to-history 'grep-history command))))
1020 (when command
1021 (let ((default-directory dir))
1022 ;; Setting process-setup-function makes exit-message-function work
1023 ;; even when async processes aren't supported.
1024 (grep--save-buffers)
1025 (compilation-start (if (and grep-use-null-device null-device)
1026 (concat command " " null-device)
1027 command)
1028 'grep-mode))
1029 (if (eq next-error-last-buffer (current-buffer))
1030 (setq default-directory dir))))))
1033 (defvar find-name-arg) ; not autoloaded but defined in find-dired
1035 ;;;###autoload
1036 (defun rgrep (regexp &optional files dir confirm)
1037 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
1038 The search is limited to file names matching shell pattern FILES.
1039 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1040 entering `ch' is equivalent to `*.[ch]'. As whitespace triggers
1041 completion when entering a pattern, including it requires
1042 quoting, e.g. `\\[quoted-insert]<space>'.
1044 With \\[universal-argument] prefix, you can edit the constructed shell command line
1045 before it is executed.
1046 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
1048 Collect output in a buffer. While the recursive grep is running,
1049 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1050 in the grep output buffer,
1051 to visit the lines where matches were found. To kill the job
1052 before it finishes, type \\[kill-compilation].
1054 This command shares argument histories with \\[lgrep] and \\[grep-find].
1056 When called programmatically and FILES is nil, REGEXP is expected
1057 to specify a command to run."
1058 (interactive
1059 (progn
1060 (grep-compute-defaults)
1061 (cond
1062 ((and grep-find-command (equal current-prefix-arg '(16)))
1063 (list (read-from-minibuffer "Run: " grep-find-command
1064 nil nil 'grep-find-history)))
1065 ((not grep-find-template)
1066 (error "grep.el: No `grep-find-template' available"))
1067 (t (let* ((regexp (grep-read-regexp))
1068 (files (grep-read-files regexp))
1069 (dir (read-directory-name "Base directory: "
1070 nil default-directory t))
1071 (confirm (equal current-prefix-arg '(4))))
1072 (list regexp files dir confirm))))))
1073 (when (and (stringp regexp) (> (length regexp) 0))
1074 (unless (and dir (file-accessible-directory-p dir))
1075 (setq dir default-directory))
1076 (if (null files)
1077 (if (not (string= regexp (if (consp grep-find-command)
1078 (car grep-find-command)
1079 grep-find-command)))
1080 (compilation-start regexp 'grep-mode))
1081 (setq dir (file-name-as-directory (expand-file-name dir)))
1082 (let ((command (rgrep-default-command regexp files nil)))
1083 (when command
1084 (if confirm
1085 (setq command
1086 (read-from-minibuffer "Confirm: "
1087 command nil nil 'grep-find-history))
1088 (add-to-history 'grep-find-history command))
1089 (grep--save-buffers)
1090 (let ((default-directory dir))
1091 (compilation-start command 'grep-mode))
1092 ;; Set default-directory if we started rgrep in the *grep* buffer.
1093 (if (eq next-error-last-buffer (current-buffer))
1094 (setq default-directory dir)))))))
1096 (defun rgrep-find-ignored-directories (dir)
1097 "Return the list of ignored directories applicable to `dir'."
1098 (delq nil (mapcar
1099 (lambda (ignore)
1100 (cond ((stringp ignore) ignore)
1101 ((consp ignore)
1102 (and (funcall (car ignore) dir) (cdr ignore)))))
1103 grep-find-ignored-directories)))
1105 (defun rgrep-default-command (regexp files dir)
1106 "Compute the command for \\[rgrep] to use by default."
1107 (require 'find-dired) ; for `find-name-arg'
1108 (grep-expand-template
1109 grep-find-template
1110 regexp
1111 (concat (shell-quote-argument "(")
1112 " " find-name-arg " "
1113 (mapconcat
1114 #'shell-quote-argument
1115 (split-string files)
1116 (concat " -o " find-name-arg " "))
1118 (shell-quote-argument ")"))
1120 (concat
1121 (and grep-find-ignored-directories
1122 (concat "-type d "
1123 (shell-quote-argument "(")
1124 ;; we should use shell-quote-argument here
1125 " -path "
1126 (mapconcat (lambda (d) (shell-quote-argument (concat "*/" d)))
1127 (rgrep-find-ignored-directories dir)
1128 " -o -path ")
1130 (shell-quote-argument ")")
1131 " -prune -o "))
1132 (and grep-find-ignored-files
1133 (concat (shell-quote-argument "!") " -type d "
1134 (shell-quote-argument "(")
1135 ;; we should use shell-quote-argument here
1136 " -name "
1137 (mapconcat
1138 #'(lambda (ignore)
1139 (cond ((stringp ignore)
1140 (shell-quote-argument ignore))
1141 ((consp ignore)
1142 (and (funcall (car ignore) dir)
1143 (shell-quote-argument
1144 (cdr ignore))))))
1145 grep-find-ignored-files
1146 " -o -name ")
1148 (shell-quote-argument ")")
1149 " -prune -o ")))))
1151 ;;;###autoload
1152 (defun zrgrep (regexp &optional files dir confirm template)
1153 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1154 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1155 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1156 (interactive
1157 (progn
1158 ;; Compute standard default values.
1159 (grep-compute-defaults)
1160 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1161 ;; for grep program "zgrep", but not changing global values.
1162 (let ((grep-program "zgrep")
1163 ;; Don't change global values for variables computed
1164 ;; by `grep-compute-defaults'.
1165 (grep-find-template nil)
1166 (grep-find-command nil)
1167 (grep-host-defaults-alist nil)
1168 ;; Use for `grep-read-files'
1169 (grep-files-aliases '(("all" . "* .*")
1170 ("gz" . "*.gz"))))
1171 ;; Recompute defaults using let-bound values above.
1172 (grep-compute-defaults)
1173 (cond
1174 ((and grep-find-command (equal current-prefix-arg '(16)))
1175 (list (read-from-minibuffer "Run: " grep-find-command
1176 nil nil 'grep-find-history)))
1177 ((not grep-find-template)
1178 (error "grep.el: No `grep-find-template' available"))
1179 (t (let* ((regexp (grep-read-regexp))
1180 (files (grep-read-files regexp))
1181 (dir (read-directory-name "Base directory: "
1182 nil default-directory t))
1183 (confirm (equal current-prefix-arg '(4))))
1184 (list regexp files dir confirm grep-find-template)))))))
1185 (let ((grep-find-template template)
1186 ;; Set `grep-highlight-matches' to `always'
1187 ;; since `zgrep' puts filters in the grep output.
1188 (grep-highlight-matches 'always))
1189 (rgrep regexp files dir confirm)))
1191 ;;;###autoload
1192 (defalias 'rzgrep 'zrgrep)
1194 (provide 'grep)
1196 ;;; grep.el ends here