1 ;;; grep.el --- run `grep' and display the results
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2013 Free Software
6 ;; Author: Roland McGrath <roland@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/>.
27 ;; This package provides the grep facilities documented in the Emacs
36 "Run `grep' and display the results."
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
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
))
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
)
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 GREP_OPTIONS to add the --color
81 option in front of any explicit grep options before starting
84 When this option is `auto', grep uses `--color=auto' to highlight
85 matches only when it outputs to a terminal (when `grep' is the last
86 command in the pipe), thus avoiding the use of any potentially-harmful
87 escape sequences when standard output goes to a file or pipe.
89 To make grep highlight matches even into a pipe, you need the option
90 `always' that forces grep to use `--color=always' to unconditionally
91 output escape sequences.
93 In interactive usage, the actual value of this variable is set up
94 by `grep-compute-defaults' when the default value is `auto-detect'.
95 To change the default value, use Customize or call the function
96 `grep-apply-setting'."
97 :type
'(choice (const :tag
"Do not highlight matches with grep markers" nil
)
98 (const :tag
"Highlight matches with grep markers" t
)
99 (const :tag
"Use --color=always" always
)
100 (const :tag
"Use --color=auto" auto
)
101 (other :tag
"Not Set" auto-detect
))
102 :set
'grep-apply-setting
106 (defcustom grep-scroll-output nil
107 "Non-nil to scroll the *grep* buffer window as output appears.
109 Setting it causes the grep commands to put point at the end of their
110 output window so that the end of the output is always visible rather
117 (defcustom grep-command nil
118 "The default grep command for \\[grep].
119 If the grep program used supports an option to always include file names
120 in its output (such as the `-H' option to GNU grep), it's a good idea to
121 include it when specifying `grep-command'.
123 In interactive usage, the actual value of this variable is set up
124 by `grep-compute-defaults'; to change the default value, use
125 Customize or call the function `grep-apply-setting'."
126 :type
'(choice string
127 (const :tag
"Not Set" nil
))
128 :set
'grep-apply-setting
131 (defcustom grep-template nil
132 "The default command to run for \\[lgrep].
133 The following place holders should be present in the string:
134 <C> - place to put -i if case insensitive grep.
135 <F> - file names and wildcards to search.
136 <X> - file names and wildcards to exclude.
137 <R> - the regular expression searched for.
138 <N> - place to insert null-device.
140 In interactive usage, the actual value of this variable is set up
141 by `grep-compute-defaults'; to change the default value, use
142 Customize or call the function `grep-apply-setting'."
143 :type
'(choice string
144 (const :tag
"Not Set" nil
))
145 :set
'grep-apply-setting
149 (defcustom grep-use-null-device
'auto-detect
150 "If t, append the value of `null-device' to `grep' commands.
151 This is done to ensure that the output of grep includes the filename of
152 any match in the case where only a single file is searched, and is not
153 necessary if the grep program used supports the `-H' option.
155 In interactive usage, the actual value of this variable is set up
156 by `grep-compute-defaults'; to change the default value, use
157 Customize or call the function `grep-apply-setting'."
158 :type
'(choice (const :tag
"Do Not Append Null Device" nil
)
159 (const :tag
"Append Null Device" t
)
160 (other :tag
"Not Set" auto-detect
))
161 :set
'grep-apply-setting
165 (defcustom grep-find-command nil
166 "The default find command for \\[grep-find].
167 In interactive usage, the actual value of this variable is set up
168 by `grep-compute-defaults'; to change the default value, use
169 Customize or call the function `grep-apply-setting'."
170 :type
'(choice string
171 (const :tag
"Not Set" nil
))
172 :set
'grep-apply-setting
175 (defcustom grep-find-template nil
176 "The default command to run for \\[rgrep].
177 The following place holders should be present in the string:
178 <D> - base directory for find
179 <X> - find options to restrict or expand the directory list
180 <F> - find options to limit the files matched
181 <C> - place to put -i if case insensitive grep
182 <R> - the regular expression searched for.
183 In interactive usage, the actual value of this variable is set up
184 by `grep-compute-defaults'; to change the default value, use
185 Customize or call the function `grep-apply-setting'."
186 :type
'(choice string
187 (const :tag
"Not Set" nil
))
188 :set
'grep-apply-setting
192 (defcustom grep-files-aliases
197 ("cc" .
"*.cc *.cxx *.cpp *.C *.CC *.c++")
198 ("cchh" .
"*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
199 ("hh" .
"*.hxx *.hpp *.[Hh] *.HH *.h++")
201 ("l" .
"[Cc]hange[Ll]og*")
202 ("m" .
"[Mm]akefile*")
206 "Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
210 (defcustom grep-find-ignored-directories
211 vc-directory-exclusion-list
212 "List of names of sub-directories which `rgrep' shall not recurse into.
213 If an element is a cons cell, the car is called on the search directory
214 to determine whether cdr should not be recursed into."
215 :type
'(choice (repeat :tag
"Ignored directories" string
)
216 (const :tag
"No ignored directories" nil
))
219 (defcustom grep-find-ignored-files
220 (cons ".#*" (delq nil
(mapcar (lambda (s)
221 (unless (string-match-p "/\\'" s
)
223 completion-ignored-extensions
)))
224 "List of file names which `rgrep' and `lgrep' shall exclude.
225 If an element is a cons cell, the car is called on the search directory
226 to determine whether cdr should not be excluded."
227 :type
'(choice (repeat :tag
"Ignored file" string
)
228 (const :tag
"No ignored files" nil
))
231 (defcustom grep-error-screen-columns nil
232 "If non-nil, column numbers in grep hits are screen columns.
233 See `compilation-error-screen-columns'"
234 :type
'(choice (const :tag
"Default" nil
)
240 (defcustom grep-setup-hook nil
241 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
245 (defvar grep-mode-map
246 (let ((map (make-sparse-keymap)))
247 (set-keymap-parent map compilation-minor-mode-map
)
248 (define-key map
" " 'scroll-up-command
)
249 (define-key map
[?\S-\
] 'scroll-down-command
)
250 (define-key map
"\^?" 'scroll-down-command
)
251 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
253 (define-key map
"\r" 'compile-goto-error
) ;; ?
254 (define-key map
"n" 'next-error-no-select
)
255 (define-key map
"p" 'previous-error-no-select
)
256 (define-key map
"{" 'compilation-previous-file
)
257 (define-key map
"}" 'compilation-next-file
)
258 (define-key map
"\t" 'compilation-next-error
)
259 (define-key map
[backtab] 'compilation-previous-error)
261 ;; Set up the menu-bar
262 (define-key map [menu-bar grep]
263 (cons "Grep" (make-sparse-keymap "Grep")))
265 (define-key map [menu-bar grep compilation-kill-compilation]
266 '(menu-item "Kill Grep" kill-compilation
267 :help "Kill the currently running grep process"))
268 (define-key map [menu-bar grep compilation-separator2] '("----"))
269 (define-key map [menu-bar grep compilation-compile]
270 '(menu-item "Compile..." compile
271 :help "Compile the program including the current buffer. Default: run `make'"))
272 (define-key map [menu-bar grep compilation-rgrep]
273 '(menu-item "Recursive grep..." rgrep
274 :help "User-friendly recursive grep in directory tree"))
275 (define-key map [menu-bar grep compilation-lgrep]
276 '(menu-item "Local grep..." lgrep
277 :help "User-friendly grep in a directory"))
278 (define-key map [menu-bar grep compilation-grep-find]
279 '(menu-item "Grep via Find..." grep-find
280 :help "Run grep via find, with user-specified args"))
281 (define-key map [menu-bar grep compilation-grep]
282 '(menu-item "Another grep..." grep
283 :help "Run grep, with user-specified args, and collect output in a buffer."))
284 (define-key map [menu-bar grep compilation-recompile]
285 '(menu-item "Repeat grep" recompile
286 :help "Run grep again"))
287 (define-key map [menu-bar grep compilation-separator2] '("----"))
288 (define-key map [menu-bar grep compilation-first-error]
289 '(menu-item "First Match" first-error
290 :help "Restart at the first match, visit corresponding location"))
291 (define-key map [menu-bar grep compilation-previous-error]
292 '(menu-item "Previous Match" previous-error
293 :help "Visit the previous match and corresponding location"))
294 (define-key map [menu-bar grep compilation-next-error]
295 '(menu-item "Next Match" next-error
296 :help "Visit the next match and corresponding location"))
298 "Keymap for grep buffers.
299 `compilation-minor-mode-map' is a cdr of this.")
301 (defvar grep-mode-tool-bar-map
302 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
303 ;; so don't do anything.
304 (when (keymapp (butlast tool-bar-map))
305 (let ((map (butlast (copy-keymap tool-bar-map)))
306 (help (last tool-bar-map))) ;; Keep Help last in tool bar
308 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
310 :help "Goto previous match")
312 "right-arrow" 'next-error-no-select 'next-error-no-select map
314 :help "Goto next match")
316 "cancel" 'kill-compilation 'kill-compilation map
317 :enable '(let ((buffer (compilation-find-buffer)))
318 (get-buffer-process buffer))
321 "refresh" 'recompile 'recompile map
322 :help "Restart grep")
325 (defalias 'kill-grep 'kill-compilation)
327 ;;;; TODO --- refine this!!
329 ;; (defcustom grep-use-compilation-buffer t
330 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
331 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
332 ;; can be used to navigate between grep matches (the default).
333 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
334 ;; be used to navigate between grep matches."
338 ;; override compilation-last-buffer
339 (defvar grep-last-buffer nil
340 "The most recent grep buffer.
341 A grep buffer becomes most recent when you select Grep mode in it.
342 Notice that using \\[next-error] or \\[compile-goto-error] modifies
343 `compilation-last-buffer' rather than `grep-last-buffer'.")
346 (defconst grep-regexp-alist
348 ;; Rule to match column numbers is commented out since no known grep
350 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([1-9][0-9]*\\)\\2\\(?:\\([1-9][0-9]*\\)\\(?:-\\([1-9][0-9]*\\)\\)?\\2\\)?"
352 ;; Note that we want to use as tight a regexp as we can to try and
353 ;; handle weird file names (with colons in them) as well as possible.
354 ;; E.g. we use [1-9][0-9]* rather than [0-9]+ so as to accept ":034:"
356 ("^\\(.+?\\)\\(:[ \t]*\\)\\([1-9][0-9]*\\)\\2"
358 ;; Calculate column positions (col . end-col) of first grep match on a line
360 (when grep-highlight-matches
361 (let* ((beg (match-end 0))
362 (end (save-excursion (goto-char beg) (line-end-position)))
363 (mbeg (text-property-any beg end 'font-lock-face grep-match-face)))
368 (when grep-highlight-matches
369 (let* ((beg (match-end 0))
370 (end (save-excursion (goto-char beg) (line-end-position)))
371 (mbeg (text-property-any beg end 'font-lock-face grep-match-face))
372 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
375 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
376 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
378 (defvar grep-first-column 0 ; bug#10594
379 "Value to use for `compilation-first-column' in grep buffers.")
381 (defvar grep-error "grep hit"
382 "Message to print when no matches are found.")
384 ;; Reverse the colors because grep hits are not errors (though we jump there
385 ;; with `next-error'), and unreadable files can't be gone to.
386 (defvar grep-hit-face compilation-info-face
387 "Face name to use for grep hits.")
389 (defvar grep-error-face 'compilation-error
390 "Face name to use for grep error messages.")
392 (defvar grep-match-face 'match
393 "Face name to use for grep matches.")
395 (defvar grep-context-face 'shadow
396 "Face name to use for grep context lines.")
398 (defvar grep-mode-font-lock-keywords
399 '(;; Command output lines.
400 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
402 ;; remove match from grep-regexp-alist before fontifying
403 ("^Grep[/a-zA-z]* started.*"
404 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
405 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
406 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
407 (1 compilation-info-face nil t)
408 (2 compilation-warning-face nil t))
409 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
410 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
412 (2 grep-error-face nil t))
413 ;; "filename-linenumber-" format is used for context lines in GNU grep,
414 ;; "filename=linenumber=" for lines with function names in "git grep -p".
415 ("^.+?[-=][0-9]+[-=].*\n" (0 grep-context-face)))
416 "Additional things to highlight in grep output.
417 This gets tacked on the end of the generated expressions.")
420 (defvar grep-program (purecopy "grep")
421 "The default grep program for `grep-command' and `grep-find-command'.
422 This variable's value takes effect when `grep-compute-defaults' is called.")
425 (defvar find-program (purecopy "find")
426 "The default find program for `grep-find-command'.
427 This variable's value takes effect when `grep-compute-defaults' is called.")
430 (defvar xargs-program (purecopy "xargs")
431 "The default xargs program for `grep-find-command'.
432 See `grep-find-use-xargs'.
433 This variable's value takes effect when `grep-compute-defaults' is called.")
436 (defvar grep-find-use-xargs nil
437 "How to invoke find and grep.
438 If `exec', use `find -exec {} ;'.
439 If `exec-plus' use `find -exec {} +'.
440 If `gnu', use `find -print0' and `xargs -0'.
441 Any other value means to use `find -print' and `xargs'.
443 This variable's value takes effect when `grep-compute-defaults' is called.")
445 ;; History of grep commands.
447 (defvar grep-history nil "History list for grep.")
449 (defvar grep-find-history nil "History list for grep-find.")
451 ;; History of lgrep and rgrep regexp and files args.
452 (defvar grep-regexp-history nil)
453 (defvar grep-files-history nil)
456 (defun grep-process-setup ()
457 "Setup compilation variables and buffer for `grep'.
458 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
459 (when (eq grep-highlight-matches 'auto-detect)
460 (grep-compute-defaults))
461 (unless (or (eq grep-highlight-matches 'auto-detect)
462 (null grep-highlight-matches)
463 ;; Don't output color escapes if they can't be
464 ;; highlighted with `font-lock-face' by `grep-filter'.
465 (null font-lock-mode))
466 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
467 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
468 (setenv "TERM" "emacs-grep")
469 (setenv "GREP_OPTIONS"
470 (concat (getenv "GREP_OPTIONS")
471 " --color=" (if (eq grep-highlight-matches 'always)
473 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
474 (setenv "GREP_COLOR" "01;31")
475 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
476 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
477 (set (make-local-variable 'compilation-exit-message-function)
478 (lambda (status code msg)
479 (if (eq status 'exit)
480 ;; This relies on the fact that `compilation-start'
481 ;; sets buffer-modified to nil before running the command,
482 ;; so the buffer is still unmodified if there is no output.
483 (cond ((and (zerop code) (buffer-modified-p))
484 '("finished (matches found)\n" . "matched"))
485 ((not (buffer-modified-p))
486 '("finished with no matches found\n" . "no match"))
490 (run-hooks 'grep-setup-hook))
492 (defun grep-filter ()
493 "Handle match highlighting escape sequences inserted by the grep process.
494 This function is called from `compilation-filter-hook'."
497 (let ((end (point)) beg)
498 (goto-char compilation-filter-start)
501 ;; Only operate on whole lines so we don't get caught with part of an
502 ;; escape sequence in one chunk and the rest in another.
503 (when (< (point) end)
504 (setq end (copy-marker end))
505 ;; Highlight grep matches and delete marking sequences.
506 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
507 (replace-match (propertize (match-string 1)
508 'face nil 'font-lock-face grep-match-face)
510 ;; Delete all remaining escape sequences
512 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
513 (replace-match "" t t))))))
515 (defun grep-probe (command args &optional func result)
516 (let (process-file-side-effects)
517 (equal (condition-case nil
518 (apply (or func 'process-file) command args)
523 (defun grep-compute-defaults ()
524 ;; Keep default values.
525 (unless grep-host-defaults-alist
527 'grep-host-defaults-alist
529 `((grep-command ,grep-command)
530 (grep-template ,grep-template)
531 (grep-use-null-device ,grep-use-null-device)
532 (grep-find-command ,grep-find-command)
533 (grep-find-template ,grep-find-template)
534 (grep-find-use-xargs ,grep-find-use-xargs)
535 (grep-highlight-matches ,grep-highlight-matches)))))
537 (intern (or (file-remote-p default-directory) "localhost")))
538 (host-defaults (assq host-id grep-host-defaults-alist))
539 (defaults (assq nil grep-host-defaults-alist)))
540 ;; There are different defaults on different hosts. They must be
541 ;; computed for every host once.
542 (dolist (setting '(grep-command grep-template
543 grep-use-null-device grep-find-command
544 grep-find-template grep-find-use-xargs
545 grep-highlight-matches))
547 (cadr (or (assq setting host-defaults)
548 (assq setting defaults)))))
550 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
551 (setq grep-use-null-device
553 (let ((hello-file (expand-file-name "HELLO" data-directory)))
555 (and (if grep-command
556 ;; `grep-command' is already set, so
557 ;; use that for testing.
558 (grep-probe grep-command
559 `(nil t nil "^English" ,hello-file)
560 #'call-process-shell-command)
561 ;; otherwise use `grep-program'
562 (grep-probe grep-program
563 `(nil t nil "-nH" "^English" ,hello-file)))
565 (goto-char (point-min))
567 (concat (regexp-quote hello-file)
568 ":[0-9]+:English")))))))))
569 (unless (and grep-command grep-find-command
570 grep-template grep-find-template)
572 (concat (if grep-use-null-device "-n" "-nH")
573 (if (grep-probe grep-program
574 `(nil nil nil "-e" "foo" ,null-device)
579 (format "%s %s " grep-program grep-options)))
580 (unless grep-template
582 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
583 (unless grep-find-use-xargs
584 (setq grep-find-use-xargs
586 ((grep-probe find-program
587 `(nil nil nil ,null-device "-exec" "echo"
591 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
592 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
596 (unless grep-find-command
597 (setq grep-find-command
598 (cond ((eq grep-find-use-xargs 'gnu)
599 ;; Windows shells need the program file name
600 ;; after the pipe symbol be quoted if they use
601 ;; forward slashes as directory separators.
602 (format "%s . -type f -print0 | \"%s\" -0 %s"
603 find-program xargs-program grep-command))
604 ((memq grep-find-use-xargs '(exec exec-plus))
605 (let ((cmd0 (format "%s . -type f -exec %s"
606 find-program grep-command))
607 (null (if grep-use-null-device
608 (format "%s " null-device)
611 (if (eq grep-find-use-xargs 'exec-plus)
612 (format "%s %s{} +" cmd0 null)
613 (format "%s {} %s%s" cmd0 null
614 (shell-quote-argument ";")))
615 (1+ (length cmd0)))))
617 (format "%s . -type f -print | \"%s\" %s"
618 find-program xargs-program grep-command)))))
619 (unless grep-find-template
620 (setq grep-find-template
621 (let ((gcmd (format "%s <C> %s <R>"
622 grep-program grep-options))
623 (null (if grep-use-null-device
624 (format "%s " null-device)
626 (cond ((eq grep-find-use-xargs 'gnu)
627 (format "%s . <X> -type f <F> -print0 | \"%s\" -0 %s"
628 find-program xargs-program gcmd))
629 ((eq grep-find-use-xargs 'exec)
630 (format "%s . <X> -type f <F> -exec %s {} %s%s"
631 find-program gcmd null
632 (shell-quote-argument ";")))
633 ((eq grep-find-use-xargs 'exec-plus)
634 (format "%s . <X> -type f <F> -exec %s %s{} +"
635 find-program gcmd null))
637 (format "%s . <X> -type f <F> -print | \"%s\" %s"
638 find-program xargs-program gcmd))))))))
639 (when (eq grep-highlight-matches 'auto-detect)
640 (setq grep-highlight-matches
642 (and (grep-probe grep-program '(nil t nil "--help"))
644 (goto-char (point-min))
645 (search-forward "--color" nil t))
646 ;; Windows and DOS pipes fail `isatty' detection in Grep.
647 (if (memq system-type '(windows-nt ms-dos))
650 ;; Save defaults for this host.
651 (setq grep-host-defaults-alist
652 (delete (assq host-id grep-host-defaults-alist)
653 grep-host-defaults-alist))
655 'grep-host-defaults-alist
657 `((grep-command ,grep-command)
658 (grep-template ,grep-template)
659 (grep-use-null-device ,grep-use-null-device)
660 (grep-find-command ,grep-find-command)
661 (grep-find-template ,grep-find-template)
662 (grep-find-use-xargs ,grep-find-use-xargs)
663 (grep-highlight-matches ,grep-highlight-matches))))))
665 (defun grep-tag-default ()
666 (or (and transient-mark-mode mark-active
668 (buffer-substring-no-properties (point) (mark)))
669 (funcall (or find-tag-default-function
670 (get major-mode 'find-tag-default-function)
674 (defun grep-default-command ()
675 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
676 (let ((tag-default (shell-quote-argument (grep-tag-default)))
677 ;; This a regexp to match single shell arguments.
678 ;; Could someone please add comments explaining it?
679 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
680 (grep-default (or (car grep-history) grep-command)))
681 ;; In the default command, find the arg that specifies the pattern.
682 (when (or (string-match
683 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
684 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
686 ;; If the string is not yet complete.
687 (string-match "\\(\\)\\'" grep-default))
688 ;; Maybe we will replace the pattern with the default tag.
689 ;; But first, maybe replace the file name pattern.
691 (unless (or (not (stringp buffer-file-name))
692 (when (match-beginning 2)
696 (file-name-nondirectory
697 (match-string 3 grep-default)))
698 (file-name-nondirectory buffer-file-name)))))
699 (setq grep-default (concat (substring grep-default
700 0 (match-beginning 2))
702 (file-name-extension buffer-file-name))))
703 ;; In case wildcard-to-regexp gets an error
704 ;; from invalid data.
706 ;; Now replace the pattern with the default tag.
707 (replace-match tag-default t t grep-default 1))))
711 (define-compilation-mode grep-mode "Grep"
712 "Sets `grep-last-buffer' and `compilation-window-height'."
713 (setq grep-last-buffer (current-buffer))
714 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
715 (set (make-local-variable 'compilation-error-face)
717 (set (make-local-variable 'compilation-error-regexp-alist)
719 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
721 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
722 (set (make-local-variable 'compilation-process-setup-function)
724 (set (make-local-variable 'compilation-disable-input) t)
725 (set (make-local-variable 'compilation-error-screen-columns)
726 grep-error-screen-columns)
727 (add-hook 'compilation-filter-hook 'grep-filter nil t))
731 (defun grep (command-args)
732 "Run grep, with user-specified args, and collect output in a buffer.
733 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
734 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
735 buffer, to go to the lines where grep found
736 matches. To kill the grep job before it finishes, type \\[kill-compilation].
738 For doing a recursive `grep', see the `rgrep' command. For running
739 `grep' in a specific directory, see `lgrep'.
741 This command uses a special history list for its COMMAND-ARGS, so you
742 can easily repeat a grep command.
744 A prefix argument says to default the argument based upon the current
745 tag the cursor is over, substituting it into the last grep command
746 in the grep command history (or into `grep-command' if that history
750 (grep-compute-defaults)
751 (let ((default (grep-default-command)))
752 (list (read-shell-command "Run grep (like this): "
753 (if current-prefix-arg default grep-command)
755 (if current-prefix-arg nil default))))))
757 ;; Setting process-setup-function makes exit-message-function work
758 ;; even when async processes aren't supported.
759 (compilation-start (if (and grep-use-null-device null-device)
760 (concat command-args " " null-device)
766 (defun grep-find (command-args)
767 "Run grep via find, with user-specified args COMMAND-ARGS.
768 Collect output in a buffer.
769 While find runs asynchronously, you can use the \\[next-error] command
770 to find the text that grep hits refer to.
772 This command uses a special history list for its arguments, so you can
773 easily repeat a find command."
776 (grep-compute-defaults)
777 (if grep-find-command
778 (list (read-shell-command "Run find (like this): "
779 grep-find-command 'grep-find-history))
780 ;; No default was set
782 "compile.el: No `grep-find-command' command available. Press RET.")
785 (let ((null-device nil)) ; see grep
786 (grep command-args))))
789 (defalias 'find-grep 'grep-find)
792 ;; User-friendly interactive API.
794 (defconst grep-expand-keywords
795 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
798 ("<N>" . null-device)
800 ("<R>" . (shell-quote-argument (or regexp ""))))
801 "List of substitutions performed by `grep-expand-template'.
802 If car of an element matches, the cdr is evalled in to get the
803 substitution string. Note dynamic scoping of variables.")
805 (defun grep-expand-template (template &optional regexp files dir excl)
806 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
807 (let ((command template)
808 (cf case-fold-search)
809 (case-fold-search nil))
810 (dolist (kw grep-expand-keywords command)
811 (if (string-match (car kw) command)
814 (or (if (symbolp (cdr kw))
815 (symbol-value (cdr kw))
816 (save-match-data (eval (cdr kw))))
820 (defun grep-read-regexp ()
821 "Read regexp arg for interactive grep."
822 (let ((default (grep-tag-default)))
825 (if (and default (> (length default) 0))
826 (format " (default \"%s\"): " default) ": "))
827 default 'grep-regexp-history)))
829 (defun grep-read-files (regexp)
830 "Read files arg for interactive grep."
831 (let* ((bn (or (buffer-file-name)
832 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
835 (file-name-nondirectory bn)))
838 (let ((aliases (remove (assoc "all" grep-files-aliases)
842 (setq alias (car aliases)
843 aliases (cdr aliases))
844 (if (string-match (mapconcat
846 (split-string (cdr alias) nil t)
854 (let ((ext (file-name-extension fn)))
855 (and ext (concat "*." ext)))))
859 (car grep-files-history)
860 (car (car grep-files-aliases))))
861 (files (completing-read
862 (concat "Search for \"" regexp
864 (if default (concat " (default " default ")"))
866 'read-file-name-internal
867 nil nil nil 'grep-files-history
869 (delq nil (append (list default default-alias default-extension)
870 (mapcar 'car grep-files-aliases)))))))
872 (or (cdr (assoc files grep-files-aliases))
876 (defun lgrep (regexp &optional files dir confirm)
877 "Run grep, searching for REGEXP in FILES in directory DIR.
878 The search is limited to file names matching shell pattern FILES.
879 FILES may use abbreviations defined in `grep-files-aliases', e.g.
880 entering `ch' is equivalent to `*.[ch]'.
882 With \\[universal-argument] prefix, you can edit the constructed shell command line
883 before it is executed.
884 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
886 Collect output in a buffer. While grep runs asynchronously, you
887 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
888 in the grep output buffer,
889 to go to the lines where grep found matches.
891 This command shares argument histories with \\[rgrep] and \\[grep]."
894 (grep-compute-defaults)
896 ((and grep-command (equal current-prefix-arg '(16)))
897 (list (read-from-minibuffer "Run: " grep-command
898 nil nil 'grep-history)))
900 (error "grep.el: No `grep-template' available"))
901 (t (let* ((regexp (grep-read-regexp))
902 (files (grep-read-files regexp))
903 (dir (read-directory-name "In directory: "
904 nil default-directory t))
905 (confirm (equal current-prefix-arg '(4))))
906 (list regexp files dir confirm))))))
907 (when (and (stringp regexp) (> (length regexp) 0))
908 (unless (and dir (file-directory-p dir) (file-readable-p dir))
909 (setq dir default-directory))
910 (let ((command regexp))
912 (if (string= command grep-command)
914 (setq dir (file-name-as-directory (expand-file-name dir)))
915 (setq command (grep-expand-template
920 (and grep-find-ignored-files
921 (concat " --exclude="
924 (cond ((stringp ignore)
925 (shell-quote-argument ignore))
927 (and (funcall (car ignore) dir)
928 (shell-quote-argument
930 grep-find-ignored-files
935 (read-from-minibuffer "Confirm: "
936 command nil nil 'grep-history))
937 (add-to-history 'grep-history command))))
939 (let ((default-directory dir))
940 ;; Setting process-setup-function makes exit-message-function work
941 ;; even when async processes aren't supported.
942 (compilation-start (if (and grep-use-null-device null-device)
943 (concat command " " null-device)
946 (if (eq next-error-last-buffer (current-buffer))
947 (setq default-directory dir))))))
950 (defvar find-name-arg) ; not autoloaded but defined in find-dired
953 (defun rgrep (regexp &optional files dir confirm)
954 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
955 The search is limited to file names matching shell pattern FILES.
956 FILES may use abbreviations defined in `grep-files-aliases', e.g.
957 entering `ch' is equivalent to `*.[ch]'.
959 With \\[universal-argument] prefix, you can edit the constructed shell command line
960 before it is executed.
961 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
963 Collect output in a buffer. While the recursive grep is running,
964 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
965 in the grep output buffer,
966 to visit the lines where matches were found. To kill the job
967 before it finishes, type \\[kill-compilation].
969 This command shares argument histories with \\[lgrep] and \\[grep-find].
971 When called programmatically and FILES is nil, REGEXP is expected
972 to specify a command to run."
975 (grep-compute-defaults)
977 ((and grep-find-command (equal current-prefix-arg '(16)))
978 (list (read-from-minibuffer "Run: " grep-find-command
979 nil nil 'grep-find-history)))
980 ((not grep-find-template)
981 (error "grep.el: No `grep-find-template' available"))
982 (t (let* ((regexp (grep-read-regexp))
983 (files (grep-read-files regexp))
984 (dir (read-directory-name "Base directory: "
985 nil default-directory t))
986 (confirm (equal current-prefix-arg '(4))))
987 (list regexp files dir confirm))))))
988 (when (and (stringp regexp) (> (length regexp) 0))
989 (unless (and dir (file-directory-p dir) (file-readable-p dir))
990 (setq dir default-directory))
992 (if (not (string= regexp (if (consp grep-find-command)
993 (car grep-find-command)
995 (compilation-start regexp 'grep-mode))
996 (setq dir (file-name-as-directory (expand-file-name dir)))
997 (require 'find-dired) ; for `find-name-arg'
998 ;; In Tramp, there could be problems if the command line is too
999 ;; long. We escape it, therefore.
1000 (let ((command (grep-expand-template
1003 (concat (shell-quote-argument "(")
1004 " " find-name-arg " "
1006 #'shell-quote-argument
1007 (split-string files)
1008 (concat "\\\n" " -o " find-name-arg " "))
1010 (shell-quote-argument ")"))
1013 (and grep-find-ignored-directories
1015 (shell-quote-argument "(")
1016 ;; we should use shell-quote-argument here
1020 (cond ((stringp ignore)
1021 (shell-quote-argument
1022 (concat "*/" ignore)))
1024 (and (funcall (car ignore) dir)
1025 (shell-quote-argument
1028 grep-find-ignored-directories
1031 (shell-quote-argument ")")
1033 (and grep-find-ignored-files
1034 (concat (shell-quote-argument "!") " -type d "
1035 (shell-quote-argument "(")
1036 ;; we should use shell-quote-argument here
1040 (cond ((stringp ignore)
1041 (shell-quote-argument ignore))
1043 (and (funcall (car ignore) dir)
1044 (shell-quote-argument
1046 grep-find-ignored-files
1049 (shell-quote-argument ")")
1054 (read-from-minibuffer "Confirm: "
1055 command nil nil 'grep-find-history))
1056 (add-to-history 'grep-find-history command))
1057 (let ((default-directory dir))
1058 (compilation-start command 'grep-mode))
1059 ;; Set default-directory if we started rgrep in the *grep* buffer.
1060 (if (eq next-error-last-buffer (current-buffer))
1061 (setq default-directory dir)))))))
1064 (defun zrgrep (regexp &optional files dir confirm grep-find-template)
1065 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1066 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1067 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1070 ;; Compute standard default values.
1071 (grep-compute-defaults)
1072 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1073 ;; for grep program "zgrep", but not changing global values.
1074 (let ((grep-program "zgrep")
1075 ;; Don't change global values for variables computed
1076 ;; by `grep-compute-defaults'.
1077 (grep-find-template nil)
1078 (grep-find-command nil)
1079 (grep-host-defaults-alist nil)
1080 ;; Use for `grep-read-files'
1081 (grep-files-aliases '(("all" . "* .*")
1083 ;; Recompute defaults using let-bound values above.
1084 (grep-compute-defaults)
1086 ((and grep-find-command (equal current-prefix-arg '(16)))
1087 (list (read-from-minibuffer "Run: " grep-find-command
1088 nil nil 'grep-find-history)))
1089 ((not grep-find-template)
1090 (error "grep.el: No `grep-find-template' available"))
1091 (t (let* ((regexp (grep-read-regexp))
1092 (files (grep-read-files regexp))
1093 (dir (read-directory-name "Base directory: "
1094 nil default-directory t))
1095 (confirm (equal current-prefix-arg '(4))))
1096 (list regexp files dir confirm grep-find-template)))))))
1097 ;; Set `grep-highlight-matches' to `always'
1098 ;; since `zgrep' puts filters in the grep output.
1099 (let ((grep-highlight-matches 'always))
1100 ;; `rgrep' uses the dynamically bound value `grep-find-template'
1101 ;; from the argument `grep-find-template' whose value is computed
1102 ;; in the `interactive' spec.
1103 (rgrep regexp files dir confirm)))
1106 (defalias 'rzgrep 'zrgrep)
1110 ;;; grep.el ends here