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