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