]> code.delx.au - gnu-emacs/blob - lisp/progmodes/grep.el
Merge from origin/emacs-25
[gnu-emacs] / lisp / progmodes / grep.el
1 ;;; grep.el --- run `grep' and display the results -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2016 Free Software
4 ;; Foundation, Inc.
5
6 ;; Author: Roland McGrath <roland@gnu.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: tools, processes
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides the grep facilities documented in the Emacs
28 ;; user's manual.
29
30 ;;; Code:
31
32 (require 'compile)
33
34
35 (defgroup grep nil
36 "Run `grep' and display the results."
37 :group 'tools
38 :group 'processes)
39
40 (defvar grep-host-defaults-alist nil
41 "Default values depending on target host.
42 `grep-compute-defaults' returns default values for every local or
43 remote host `grep' runs. These values can differ from host to
44 host. Once computed, the default values are kept here in order
45 to avoid computing them again.")
46
47 (defun grep-apply-setting (symbol value)
48 "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
49 SYMBOL should be one of `grep-command', `grep-template',
50 `grep-use-null-device', `grep-find-command',
51 `grep-find-template', `grep-find-use-xargs', or
52 `grep-highlight-matches'."
53 (when grep-host-defaults-alist
54 (let* ((host-id
55 (intern (or (file-remote-p default-directory) "localhost")))
56 (host-defaults (assq host-id grep-host-defaults-alist))
57 (defaults (assq nil grep-host-defaults-alist)))
58 (setcar (cdr (assq symbol host-defaults)) value)
59 (setcar (cdr (assq symbol defaults)) value)))
60 (set-default symbol value))
61
62 ;;;###autoload
63 (defcustom grep-window-height nil
64 "Number of lines in a grep window. If nil, use `compilation-window-height'."
65 :type '(choice (const :tag "Default" nil)
66 integer)
67 :version "22.1"
68 :group 'grep)
69
70 (defcustom grep-highlight-matches 'auto-detect
71 "Use special markers to highlight grep matches.
72
73 Some grep programs are able to surround matches with special
74 markers in grep output. Such markers can be used to highlight
75 matches in grep mode. This requires `font-lock-mode' to be active
76 in grep buffers, so if you have globally disabled font-lock-mode,
77 you will not get highlighting.
78
79 This option sets the environment variable GREP_COLORS to specify
80 markers for highlighting and adds the --color option in front of
81 any explicit grep options before starting the grep.
82
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.
87
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.
91
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)
104
105 (defcustom grep-scroll-output nil
106 "Non-nil to scroll the *grep* buffer window as output appears.
107
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)
114
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'.
121
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)
129
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.
138
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)
147
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.
153
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)
162
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)
173
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)
190
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)
208
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)
217
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)
229
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)
245
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)
253
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)
259
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)
267
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)
275
276 ;; Set up the menu-bar
277 (define-key map [menu-bar grep]
278 (cons "Grep" (make-sparse-keymap "Grep")))
279
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.")
315
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))))
339
340 (defalias 'kill-grep 'kill-compilation)
341
342 ;;;; TODO --- refine this!!
343
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)
352
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'.")
359
360 ;;;###autoload
361 (defconst grep-regexp-alist
362 '(
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]*:"
367 1 2
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)))))
376 .
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'.")
387
388 (defvar grep-first-column 0 ; bug#10594
389 "Value to use for `compilation-first-column' in grep buffers.")
390
391 (defvar grep-error "grep hit"
392 "Message to print when no matches are found.")
393
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.")
398
399 (defvar grep-error-face 'compilation-error
400 "Face name to use for grep error messages.")
401
402 (defvar grep-match-face 'match
403 "Face name to use for grep matches.")
404
405 (defvar grep-context-face 'shadow
406 "Face name to use for grep context lines.")
407
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.")
428
429 ;;;###autoload
430 (defcustom 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."
433 :type 'string
434 :version "25.1"
435 :group 'grep)
436
437 ;;;###autoload
438 (defcustom grep-find-program (purecopy "find")
439 "The default find program.
440 This is used by commands like `grep-find-command', `find-dired'
441 and others."
442 :type 'string
443 :version "25.1"
444 :group 'grep)
445
446 (define-obsolete-variable-alias 'find-program 'grep-find-program "25.1")
447
448 ;;;###autoload
449 (defcustom grep-xargs-program (purecopy "xargs")
450 "The default xargs program for `grep-find-command'.
451 See `grep-find-use-xargs'.
452 This variable's value takes effect when `grep-compute-defaults' is called."
453 :type 'string
454 :version "25.1"
455 :group 'grep)
456
457 (define-obsolete-variable-alias 'xargs-program 'grep-xargs-program "25.1")
458
459 ;;;###autoload
460 (defvar grep-find-use-xargs nil
461 "How to invoke find and grep.
462 If `exec', use `find -exec {} ;'.
463 If `exec-plus' use `find -exec {} +'.
464 If `gnu', use `find -print0' and `xargs -0'.
465 Any other value means to use `find -print' and `xargs'.
466
467 This variable's value takes effect when `grep-compute-defaults' is called.")
468
469 ;; History of grep commands.
470 ;;;###autoload
471 (defvar grep-history nil "History list for grep.")
472 ;;;###autoload
473 (defvar grep-find-history nil "History list for grep-find.")
474
475 ;; History of lgrep and rgrep regexp and files args.
476 (defvar grep-regexp-history nil)
477 (defvar grep-files-history nil)
478
479 ;;;###autoload
480 (defun grep-process-setup ()
481 "Setup compilation variables and buffer for `grep'.
482 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
483 (when (eq grep-highlight-matches 'auto-detect)
484 (grep-compute-defaults))
485 (unless (or (eq grep-highlight-matches 'auto-detect)
486 (null grep-highlight-matches)
487 ;; Don't output color escapes if they can't be
488 ;; highlighted with `font-lock-face' by `grep-filter'.
489 (null font-lock-mode))
490 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
491 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
492 (setenv "TERM" "emacs-grep")
493 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
494 (setenv "GREP_COLOR" "01;31")
495 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
496 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
497 (set (make-local-variable 'compilation-exit-message-function)
498 (lambda (status code msg)
499 (if (eq status 'exit)
500 ;; This relies on the fact that `compilation-start'
501 ;; sets buffer-modified to nil before running the command,
502 ;; so the buffer is still unmodified if there is no output.
503 (cond ((and (zerop code) (buffer-modified-p))
504 '("finished (matches found)\n" . "matched"))
505 ((not (buffer-modified-p))
506 '("finished with no matches found\n" . "no match"))
507 (t
508 (cons msg code)))
509 (cons msg code))))
510 (run-hooks 'grep-setup-hook))
511
512 (defun grep-filter ()
513 "Handle match highlighting escape sequences inserted by the grep process.
514 This function is called from `compilation-filter-hook'."
515 (save-excursion
516 (forward-line 0)
517 (let ((end (point)) beg)
518 (goto-char compilation-filter-start)
519 (forward-line 0)
520 (setq beg (point))
521 ;; Only operate on whole lines so we don't get caught with part of an
522 ;; escape sequence in one chunk and the rest in another.
523 (when (< (point) end)
524 (setq end (copy-marker end))
525 ;; Highlight grep matches and delete marking sequences.
526 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
527 (replace-match (propertize (match-string 1)
528 'face nil 'font-lock-face grep-match-face)
529 t t))
530 ;; Delete all remaining escape sequences
531 (goto-char beg)
532 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
533 (replace-match "" t t))))))
534
535 (defun grep-probe (command args &optional func result)
536 (let (process-file-side-effects)
537 (equal (condition-case nil
538 (apply (or func 'process-file) command args)
539 (error nil))
540 (or result 0))))
541
542 ;;;###autoload
543 (defun grep-compute-defaults ()
544 ;; Keep default values.
545 (unless grep-host-defaults-alist
546 (add-to-list
547 'grep-host-defaults-alist
548 (cons nil
549 `((grep-command ,grep-command)
550 (grep-template ,grep-template)
551 (grep-use-null-device ,grep-use-null-device)
552 (grep-find-command ,grep-find-command)
553 (grep-find-template ,grep-find-template)
554 (grep-find-use-xargs ,grep-find-use-xargs)
555 (grep-highlight-matches ,grep-highlight-matches)))))
556 (let* ((host-id
557 (intern (or (file-remote-p default-directory) "localhost")))
558 (host-defaults (assq host-id grep-host-defaults-alist))
559 (defaults (assq nil grep-host-defaults-alist)))
560 ;; There are different defaults on different hosts. They must be
561 ;; computed for every host once.
562 (dolist (setting '(grep-command grep-template
563 grep-use-null-device grep-find-command
564 grep-find-template grep-find-use-xargs
565 grep-highlight-matches))
566 (set setting
567 (cadr (or (assq setting host-defaults)
568 (assq setting defaults)))))
569
570 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
571 (setq grep-use-null-device
572 (with-temp-buffer
573 (let ((hello-file (expand-file-name "HELLO" data-directory)))
574 (not
575 (and (if grep-command
576 ;; `grep-command' is already set, so
577 ;; use that for testing.
578 (grep-probe grep-command
579 `(nil t nil "^English" ,hello-file)
580 #'call-process-shell-command)
581 ;; otherwise use `grep-program'
582 (grep-probe grep-program
583 `(nil t nil "-nH" "^English" ,hello-file)))
584 (progn
585 (goto-char (point-min))
586 (looking-at
587 (concat (regexp-quote hello-file)
588 ":[0-9]+:English")))))))))
589
590 (when (eq grep-highlight-matches 'auto-detect)
591 (setq grep-highlight-matches
592 (with-temp-buffer
593 (and (grep-probe grep-program '(nil t nil "--help"))
594 (progn
595 (goto-char (point-min))
596 (search-forward "--color" nil t))
597 ;; Windows and DOS pipes fail `isatty' detection in Grep.
598 (if (memq system-type '(windows-nt ms-dos))
599 'always 'auto)))))
600
601 (unless (and grep-command grep-find-command
602 grep-template grep-find-template)
603 (let ((grep-options
604 (concat (if grep-use-null-device "-n" "-nH")
605 (if (grep-probe grep-program
606 `(nil nil nil "-e" "foo" ,null-device)
607 nil 1)
608 " -e"))))
609 (unless grep-command
610 (setq grep-command
611 (format "%s %s %s " grep-program
612 (or
613 (and grep-highlight-matches
614 (grep-probe grep-program
615 `(nil nil nil "--color" "x" ,null-device)
616 nil 1)
617 (if (eq grep-highlight-matches 'always)
618 "--color=always" "--color"))
619 "")
620 grep-options)))
621 (unless grep-template
622 (setq grep-template
623 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
624 (unless grep-find-use-xargs
625 (setq grep-find-use-xargs
626 (cond
627 ((grep-probe grep-find-program
628 `(nil nil nil ,null-device "-exec" "echo"
629 "{}" "+"))
630 'exec-plus)
631 ((and
632 (grep-probe grep-find-program
633 `(nil nil nil ,null-device "-print0"))
634 (grep-probe grep-xargs-program `(nil nil nil "-0" "echo")))
635 'gnu)
636 (t
637 'exec))))
638 (unless grep-find-command
639 (setq grep-find-command
640 (cond ((eq grep-find-use-xargs 'gnu)
641 ;; Windows shells need the program file name
642 ;; after the pipe symbol be quoted if they use
643 ;; forward slashes as directory separators.
644 (format "%s . -type f -print0 | \"%s\" -0 %s"
645 grep-find-program grep-xargs-program
646 grep-command))
647 ((memq grep-find-use-xargs '(exec exec-plus))
648 (let ((cmd0 (format "%s . -type f -exec %s"
649 grep-find-program grep-command))
650 (null (if grep-use-null-device
651 (format "%s " null-device)
652 "")))
653 (cons
654 (if (eq grep-find-use-xargs 'exec-plus)
655 (format "%s %s{} +" cmd0 null)
656 (format "%s {} %s%s" cmd0 null
657 (shell-quote-argument ";")))
658 (1+ (length cmd0)))))
659 (t
660 (format "%s . -type f -print | \"%s\" %s"
661 grep-find-program grep-xargs-program
662 grep-command)))))
663 (unless grep-find-template
664 (setq grep-find-template
665 (let ((gcmd (format "%s <C> %s <R>"
666 grep-program grep-options))
667 (null (if grep-use-null-device
668 (format "%s " null-device)
669 "")))
670 (cond ((eq grep-find-use-xargs 'gnu)
671 (format "%s <D> <X> -type f <F> -print0 | \"%s\" -0 %s"
672 grep-find-program grep-xargs-program gcmd))
673 ((eq grep-find-use-xargs 'exec)
674 (format "%s <D> <X> -type f <F> -exec %s {} %s%s"
675 grep-find-program gcmd null
676 (shell-quote-argument ";")))
677 ((eq grep-find-use-xargs 'exec-plus)
678 (format "%s <D> <X> -type f <F> -exec %s %s{} +"
679 grep-find-program gcmd null))
680 (t
681 (format "%s <D> <X> -type f <F> -print | \"%s\" %s"
682 grep-find-program grep-xargs-program gcmd))))))))
683
684 ;; Save defaults for this host.
685 (setq grep-host-defaults-alist
686 (delete (assq host-id grep-host-defaults-alist)
687 grep-host-defaults-alist))
688 (add-to-list
689 'grep-host-defaults-alist
690 (cons host-id
691 `((grep-command ,grep-command)
692 (grep-template ,grep-template)
693 (grep-use-null-device ,grep-use-null-device)
694 (grep-find-command ,grep-find-command)
695 (grep-find-template ,grep-find-template)
696 (grep-find-use-xargs ,grep-find-use-xargs)
697 (grep-highlight-matches ,grep-highlight-matches))))))
698
699 (defun grep-tag-default ()
700 (or (and transient-mark-mode mark-active
701 (/= (point) (mark))
702 (buffer-substring-no-properties (point) (mark)))
703 (funcall (or find-tag-default-function
704 (get major-mode 'find-tag-default-function)
705 'find-tag-default))
706 ""))
707
708 (defun grep-default-command ()
709 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
710 (let ((tag-default (shell-quote-argument (grep-tag-default)))
711 ;; This a regexp to match single shell arguments.
712 ;; Could someone please add comments explaining it?
713 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
714 (grep-default (or (car grep-history) grep-command)))
715 ;; In the default command, find the arg that specifies the pattern.
716 (when (or (string-match
717 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
718 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
719 grep-default)
720 ;; If the string is not yet complete.
721 (string-match "\\(\\)\\'" grep-default))
722 ;; Maybe we will replace the pattern with the default tag.
723 ;; But first, maybe replace the file name pattern.
724 (condition-case nil
725 (unless (or (not (stringp buffer-file-name))
726 (when (match-beginning 2)
727 (save-match-data
728 (string-match
729 (wildcard-to-regexp
730 (file-name-nondirectory
731 (match-string 3 grep-default)))
732 (file-name-nondirectory buffer-file-name)))))
733 (setq grep-default (concat (substring grep-default
734 0 (match-beginning 2))
735 " *."
736 (file-name-extension buffer-file-name))))
737 ;; In case wildcard-to-regexp gets an error
738 ;; from invalid data.
739 (error nil))
740 ;; Now replace the pattern with the default tag.
741 (replace-match tag-default t t grep-default 1))))
742
743
744 ;;;###autoload
745 (define-compilation-mode grep-mode "Grep"
746 "Sets `grep-last-buffer' and `compilation-window-height'."
747 (setq grep-last-buffer (current-buffer))
748 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
749 (set (make-local-variable 'compilation-error-face)
750 grep-hit-face)
751 (set (make-local-variable 'compilation-error-regexp-alist)
752 grep-regexp-alist)
753 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
754 ;; can never match.
755 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
756 (set (make-local-variable 'compilation-process-setup-function)
757 'grep-process-setup)
758 (set (make-local-variable 'compilation-disable-input) t)
759 (set (make-local-variable 'compilation-error-screen-columns)
760 grep-error-screen-columns)
761 (add-hook 'compilation-filter-hook 'grep-filter nil t))
762
763 (defun grep--save-buffers ()
764 (when grep-save-buffers
765 (save-some-buffers (and (not (eq grep-save-buffers 'ask))
766 (not (functionp grep-save-buffers)))
767 (and (functionp grep-save-buffers)
768 grep-save-buffers))))
769
770 ;;;###autoload
771 (defun grep (command-args)
772 "Run Grep with user-specified COMMAND-ARGS, collect output in a buffer.
773 While Grep runs asynchronously, you can use \\[next-error] (M-x next-error),
774 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
775 buffer, to go to the lines where Grep found
776 matches. To kill the Grep job before it finishes, type \\[kill-compilation].
777
778 Noninteractively, COMMAND-ARGS should specify the Grep command-line
779 arguments.
780
781 For doing a recursive `grep', see the `rgrep' command. For running
782 Grep in a specific directory, see `lgrep'.
783
784 This command uses a special history list for its COMMAND-ARGS, so you
785 can easily repeat a grep command.
786
787 A prefix argument says to default the COMMAND-ARGS based on the current
788 tag the cursor is over, substituting it into the last Grep command
789 in the Grep command history (or into `grep-command' if that history
790 list is empty)."
791 (interactive
792 (progn
793 (grep-compute-defaults)
794 (let ((default (grep-default-command)))
795 (list (read-shell-command "Run grep (like this): "
796 (if current-prefix-arg default grep-command)
797 'grep-history
798 (if current-prefix-arg nil default))))))
799
800 (grep--save-buffers)
801 ;; Setting process-setup-function makes exit-message-function work
802 ;; even when async processes aren't supported.
803 (compilation-start (if (and grep-use-null-device null-device)
804 (concat command-args " " null-device)
805 command-args)
806 'grep-mode))
807
808
809 ;;;###autoload
810 (defun grep-find (command-args)
811 "Run grep via find, with user-specified args COMMAND-ARGS.
812 Collect output in a buffer.
813 While find runs asynchronously, you can use the \\[next-error] command
814 to find the text that grep hits refer to.
815
816 This command uses a special history list for its arguments, so you can
817 easily repeat a find command."
818 (interactive
819 (progn
820 (grep-compute-defaults)
821 (if grep-find-command
822 (list (read-shell-command "Run find (like this): "
823 grep-find-command 'grep-find-history))
824 ;; No default was set
825 (read-string
826 "compile.el: No `grep-find-command' command available. Press RET.")
827 (list nil))))
828 (when command-args
829 (let ((null-device nil)) ; see grep
830 (grep command-args))))
831
832 ;;;###autoload
833 (defalias 'find-grep 'grep-find)
834
835
836 ;; User-friendly interactive API.
837
838 (defconst grep-expand-keywords
839 '(("<C>" . (mapconcat #'identity opts " "))
840 ("<D>" . (or dir "."))
841 ("<F>" . files)
842 ("<N>" . null-device)
843 ("<X>" . excl)
844 ("<R>" . (shell-quote-argument (or regexp ""))))
845 "List of substitutions performed by `grep-expand-template'.
846 If car of an element matches, the cdr is evalled in to get the
847 substitution string. Note dynamic scoping of variables.")
848
849 (defun grep-expand-template (template &optional regexp files dir excl)
850 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
851 (let* ((command template)
852 (env `((opts . ,(let (opts)
853 (when (and case-fold-search
854 (isearch-no-upper-case-p regexp t))
855 (push "-i" opts))
856 (cond
857 ((eq grep-highlight-matches 'always)
858 (push "--color=always" opts))
859 ((eq grep-highlight-matches 'auto)
860 (push "--color" opts)))
861 opts))
862 (excl . ,excl)
863 (dir . ,dir)
864 (files . ,files)
865 (regexp . ,regexp)))
866 (case-fold-search nil))
867 (dolist (kw grep-expand-keywords command)
868 (if (string-match (car kw) command)
869 (setq command
870 (replace-match
871 (or (if (symbolp (cdr kw))
872 (eval (cdr kw) env)
873 (save-match-data (eval (cdr kw) env)))
874 "")
875 t t command))))))
876
877 (defun grep-read-regexp ()
878 "Read regexp arg for interactive grep using `read-regexp'."
879 (read-regexp "Search for" 'grep-tag-default 'grep-regexp-history))
880
881 (defun grep-read-files (regexp)
882 "Read files arg for interactive grep."
883 (let* ((bn (or (buffer-file-name)
884 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
885 (fn (and bn
886 (stringp bn)
887 (file-name-nondirectory bn)))
888 (default-alias
889 (and fn
890 (let ((aliases (remove (assoc "all" grep-files-aliases)
891 grep-files-aliases))
892 alias)
893 (while aliases
894 (setq alias (car aliases)
895 aliases (cdr aliases))
896 (if (string-match (mapconcat
897 'wildcard-to-regexp
898 (split-string (cdr alias) nil t)
899 "\\|")
900 fn)
901 (setq aliases nil)
902 (setq alias nil)))
903 (cdr alias))))
904 (default-extension
905 (and fn
906 (let ((ext (file-name-extension fn)))
907 (and ext (concat "*." ext)))))
908 (default
909 (or default-alias
910 default-extension
911 (car grep-files-history)
912 (car (car grep-files-aliases))))
913 (files (completing-read
914 (concat "Search for \"" regexp
915 "\" in files"
916 (if default (concat " (default " default ")"))
917 ": ")
918 'read-file-name-internal
919 nil nil nil 'grep-files-history
920 (delete-dups
921 (delq nil (append (list default default-alias default-extension)
922 (mapcar 'car grep-files-aliases)))))))
923 (and files
924 (or (cdr (assoc files grep-files-aliases))
925 files))))
926
927 ;;;###autoload
928 (defun lgrep (regexp &optional files dir confirm)
929 "Run grep, searching for REGEXP in FILES in directory DIR.
930 The search is limited to file names matching shell pattern FILES.
931 FILES may use abbreviations defined in `grep-files-aliases', e.g.
932 entering `ch' is equivalent to `*.[ch]'.
933
934 With \\[universal-argument] prefix, you can edit the constructed shell command line
935 before it is executed.
936 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
937
938 Collect output in a buffer. While grep runs asynchronously, you
939 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
940 in the grep output buffer,
941 to go to the lines where grep found matches.
942
943 This command shares argument histories with \\[rgrep] and \\[grep]."
944 (interactive
945 (progn
946 (grep-compute-defaults)
947 (cond
948 ((and grep-command (equal current-prefix-arg '(16)))
949 (list (read-from-minibuffer "Run: " grep-command
950 nil nil 'grep-history)))
951 ((not grep-template)
952 (error "grep.el: No `grep-template' available"))
953 (t (let* ((regexp (grep-read-regexp))
954 (files (grep-read-files regexp))
955 (dir (read-directory-name "In directory: "
956 nil default-directory t))
957 (confirm (equal current-prefix-arg '(4))))
958 (list regexp files dir confirm))))))
959 (when (and (stringp regexp) (> (length regexp) 0))
960 (unless (and dir (file-accessible-directory-p dir))
961 (setq dir default-directory))
962 (let ((command regexp))
963 (if (null files)
964 (if (string= command grep-command)
965 (setq command nil))
966 (setq dir (file-name-as-directory (expand-file-name dir)))
967 (setq command (grep-expand-template
968 grep-template
969 regexp
970 files
971 nil
972 (and grep-find-ignored-files
973 (concat " --exclude="
974 (mapconcat
975 #'(lambda (ignore)
976 (cond ((stringp ignore)
977 (shell-quote-argument ignore))
978 ((consp ignore)
979 (and (funcall (car ignore) dir)
980 (shell-quote-argument
981 (cdr ignore))))))
982 grep-find-ignored-files
983 " --exclude=")))))
984 (when command
985 (if confirm
986 (setq command
987 (read-from-minibuffer "Confirm: "
988 command nil nil 'grep-history))
989 (add-to-history 'grep-history command))))
990 (when command
991 (let ((default-directory dir))
992 ;; Setting process-setup-function makes exit-message-function work
993 ;; even when async processes aren't supported.
994 (grep--save-buffers)
995 (compilation-start (if (and grep-use-null-device null-device)
996 (concat command " " null-device)
997 command)
998 'grep-mode))
999 (if (eq next-error-last-buffer (current-buffer))
1000 (setq default-directory dir))))))
1001
1002
1003 (defvar find-name-arg) ; not autoloaded but defined in find-dired
1004
1005 ;;;###autoload
1006 (defun rgrep (regexp &optional files dir confirm)
1007 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
1008 The search is limited to file names matching shell pattern FILES.
1009 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1010 entering `ch' is equivalent to `*.[ch]'.
1011
1012 With \\[universal-argument] prefix, you can edit the constructed shell command line
1013 before it is executed.
1014 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
1015
1016 Collect output in a buffer. While the recursive grep is running,
1017 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1018 in the grep output buffer,
1019 to visit the lines where matches were found. To kill the job
1020 before it finishes, type \\[kill-compilation].
1021
1022 This command shares argument histories with \\[lgrep] and \\[grep-find].
1023
1024 When called programmatically and FILES is nil, REGEXP is expected
1025 to specify a command to run."
1026 (interactive
1027 (progn
1028 (grep-compute-defaults)
1029 (cond
1030 ((and grep-find-command (equal current-prefix-arg '(16)))
1031 (list (read-from-minibuffer "Run: " grep-find-command
1032 nil nil 'grep-find-history)))
1033 ((not grep-find-template)
1034 (error "grep.el: No `grep-find-template' available"))
1035 (t (let* ((regexp (grep-read-regexp))
1036 (files (grep-read-files regexp))
1037 (dir (read-directory-name "Base directory: "
1038 nil default-directory t))
1039 (confirm (equal current-prefix-arg '(4))))
1040 (list regexp files dir confirm))))))
1041 (when (and (stringp regexp) (> (length regexp) 0))
1042 (unless (and dir (file-accessible-directory-p dir))
1043 (setq dir default-directory))
1044 (if (null files)
1045 (if (not (string= regexp (if (consp grep-find-command)
1046 (car grep-find-command)
1047 grep-find-command)))
1048 (compilation-start regexp 'grep-mode))
1049 (setq dir (file-name-as-directory (expand-file-name dir)))
1050 (let ((command (rgrep-default-command regexp files nil)))
1051 (when command
1052 (if confirm
1053 (setq command
1054 (read-from-minibuffer "Confirm: "
1055 command nil nil 'grep-find-history))
1056 (add-to-history 'grep-find-history command))
1057 (grep--save-buffers)
1058 (let ((default-directory dir))
1059 (compilation-start command 'grep-mode))
1060 ;; Set default-directory if we started rgrep in the *grep* buffer.
1061 (if (eq next-error-last-buffer (current-buffer))
1062 (setq default-directory dir)))))))
1063
1064 (defun rgrep-default-command (regexp files dir)
1065 "Compute the command for \\[rgrep] to use by default."
1066 (require 'find-dired) ; for `find-name-arg'
1067 (grep-expand-template
1068 grep-find-template
1069 regexp
1070 (concat (shell-quote-argument "(")
1071 " " find-name-arg " "
1072 (mapconcat
1073 #'shell-quote-argument
1074 (split-string files)
1075 (concat " -o " find-name-arg " "))
1076 " "
1077 (shell-quote-argument ")"))
1078 dir
1079 (concat
1080 (and grep-find-ignored-directories
1081 (concat "-type d "
1082 (shell-quote-argument "(")
1083 ;; we should use shell-quote-argument here
1084 " -path "
1085 (mapconcat
1086 'identity
1087 (delq nil (mapcar
1088 #'(lambda (ignore)
1089 (cond ((stringp ignore)
1090 (shell-quote-argument
1091 (concat "*/" ignore)))
1092 ((consp ignore)
1093 (and (funcall (car ignore) dir)
1094 (shell-quote-argument
1095 (concat "*/"
1096 (cdr ignore)))))))
1097 grep-find-ignored-directories))
1098 " -o -path ")
1099 " "
1100 (shell-quote-argument ")")
1101 " -prune -o "))
1102 (and grep-find-ignored-files
1103 (concat (shell-quote-argument "!") " -type d "
1104 (shell-quote-argument "(")
1105 ;; we should use shell-quote-argument here
1106 " -name "
1107 (mapconcat
1108 #'(lambda (ignore)
1109 (cond ((stringp ignore)
1110 (shell-quote-argument ignore))
1111 ((consp ignore)
1112 (and (funcall (car ignore) dir)
1113 (shell-quote-argument
1114 (cdr ignore))))))
1115 grep-find-ignored-files
1116 " -o -name ")
1117 " "
1118 (shell-quote-argument ")")
1119 " -prune -o ")))))
1120
1121 ;;;###autoload
1122 (defun zrgrep (regexp &optional files dir confirm template)
1123 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1124 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1125 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1126 (interactive
1127 (progn
1128 ;; Compute standard default values.
1129 (grep-compute-defaults)
1130 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1131 ;; for grep program "zgrep", but not changing global values.
1132 (let ((grep-program "zgrep")
1133 ;; Don't change global values for variables computed
1134 ;; by `grep-compute-defaults'.
1135 (grep-find-template nil)
1136 (grep-find-command nil)
1137 (grep-host-defaults-alist nil)
1138 ;; Use for `grep-read-files'
1139 (grep-files-aliases '(("all" . "* .*")
1140 ("gz" . "*.gz"))))
1141 ;; Recompute defaults using let-bound values above.
1142 (grep-compute-defaults)
1143 (cond
1144 ((and grep-find-command (equal current-prefix-arg '(16)))
1145 (list (read-from-minibuffer "Run: " grep-find-command
1146 nil nil 'grep-find-history)))
1147 ((not grep-find-template)
1148 (error "grep.el: No `grep-find-template' available"))
1149 (t (let* ((regexp (grep-read-regexp))
1150 (files (grep-read-files regexp))
1151 (dir (read-directory-name "Base directory: "
1152 nil default-directory t))
1153 (confirm (equal current-prefix-arg '(4))))
1154 (list regexp files dir confirm grep-find-template)))))))
1155 (let ((grep-find-template template)
1156 ;; Set `grep-highlight-matches' to `always'
1157 ;; since `zgrep' puts filters in the grep output.
1158 (grep-highlight-matches 'always))
1159 (rgrep regexp files dir confirm)))
1160
1161 ;;;###autoload
1162 (defalias 'rzgrep 'zrgrep)
1163
1164 (provide 'grep)
1165
1166 ;;; grep.el ends here