1 ;;; grep.el --- run Grep as inferior of Emacs, parse match messages
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
5 ;; Free Software Foundation, Inc.
7 ;; Author: Roland McGrath <roland@gnu.org>
9 ;; Keywords: tools, processes
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This package provides the grep facilities documented in the Emacs
37 "Run grep as inferior of Emacs, parse error messages."
43 (defcustom grep-window-height nil
44 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
45 :type
'(choice (const :tag
"Default" nil
)
50 (defcustom grep-highlight-matches
'auto-detect
51 "If t, use special markers to highlight grep matches.
53 Some grep programs are able to surround matches with special
54 markers in grep output. Such markers can be used to highlight
57 This option sets the environment variable GREP_COLOR to specify
58 markers for highlighting and GREP_OPTIONS to add the --color
59 option in front of any explicit grep options before starting
62 The default value of this variable is set up by `grep-compute-defaults';
63 call that function before using this variable in your program."
64 :type
'(choice (const :tag
"Do not highlight matches with grep markers" nil
)
65 (const :tag
"Highlight matches with grep markers" t
)
66 (other :tag
"Not Set" auto-detect
))
70 (defcustom grep-scroll-output nil
71 "*Non-nil to scroll the *grep* buffer window as output appears.
73 Setting it causes the grep commands to put point at the end of their
74 output window so that the end of the output is always visible rather
81 (defcustom grep-command nil
82 "The default grep command for \\[grep].
83 If the grep program used supports an option to always include file names
84 in its output (such as the `-H' option to GNU grep), it's a good idea to
85 include it when specifying `grep-command'.
87 The default value of this variable is set up by `grep-compute-defaults';
88 call that function before using this variable in your program."
90 (const :tag
"Not Set" nil
))
93 (defcustom grep-template nil
94 "The default command to run for \\[lgrep].
95 The default value of this variable is set up by `grep-compute-defaults';
96 call that function before using this variable in your program.
97 The following place holders should be present in the string:
98 <C> - place to put -i if case insensitive grep.
99 <F> - file names and wildcards to search.
100 <R> - the regular expression searched for.
101 <N> - place to insert null-device."
102 :type
'(choice string
103 (const :tag
"Not Set" nil
))
107 (defcustom grep-use-null-device
'auto-detect
108 "If t, append the value of `null-device' to `grep' commands.
109 This is done to ensure that the output of grep includes the filename of
110 any match in the case where only a single file is searched, and is not
111 necessary if the grep program used supports the `-H' option.
113 The default value of this variable is set up by `grep-compute-defaults';
114 call that function before using this variable in your program."
115 :type
'(choice (const :tag
"Do Not Append Null Device" nil
)
116 (const :tag
"Append Null Device" t
)
117 (other :tag
"Not Set" auto-detect
))
121 (defcustom grep-find-command nil
122 "The default find command for \\[grep-find].
123 The default value of this variable is set up by `grep-compute-defaults';
124 call that function before using this variable in your program."
125 :type
'(choice string
126 (const :tag
"Not Set" nil
))
129 (defcustom grep-find-template nil
130 "The default command to run for \\[rgrep].
131 The default value of this variable is set up by `grep-compute-defaults';
132 call that function before using this variable in your program.
133 The following place holders should be present in the string:
134 <D> - base directory for find
135 <X> - find options to restrict or expand the directory list
136 <F> - find options to limit the files matched
137 <C> - place to put -i if case insensitive grep
138 <R> - the regular expression searched for."
139 :type
'(choice string
140 (const :tag
"Not Set" nil
))
144 (defcustom grep-files-aliases
147 ("cc" .
"*.cc *.cxx *.cpp *.C *.CC *.c++")
148 ("cchh" .
"*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
149 ("hh" .
"*.hxx *.hpp *.[Hh] *.HH *.h++")
153 ("l" .
"[Cc]hange[Ll]og*")
154 ("m" .
"[Mm]akefile*")
157 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
161 (defcustom grep-find-ignored-directories
162 vc-directory-exclusion-list
163 "*List of names of sub-directories which `rgrep' shall not recurse into."
164 :type
'(repeat string
)
167 (defcustom grep-error-screen-columns nil
168 "*If non-nil, column numbers in grep hits are screen columns.
169 See `compilation-error-screen-columns'"
170 :type
'(choice (const :tag
"Default" nil
)
176 (defcustom grep-setup-hook nil
177 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
181 (defvar grep-mode-map
182 (let ((map (make-sparse-keymap)))
183 (set-keymap-parent map compilation-minor-mode-map
)
184 (define-key map
" " 'scroll-up
)
185 (define-key map
"\^?" 'scroll-down
)
186 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
188 (define-key map
"\r" 'compile-goto-error
) ;; ?
189 (define-key map
"n" 'next-error-no-select
)
190 (define-key map
"p" 'previous-error-no-select
)
191 (define-key map
"{" 'compilation-previous-file
)
192 (define-key map
"}" 'compilation-next-file
)
193 (define-key map
"\t" 'compilation-next-error
)
194 (define-key map
[backtab] 'compilation-previous-error)
196 ;; Set up the menu-bar
197 (define-key map [menu-bar grep]
198 (cons "Grep" (make-sparse-keymap "Grep")))
200 (define-key map [menu-bar grep compilation-kill-compilation]
201 '(menu-item "Kill Grep" kill-compilation
202 :help "Kill the currently running grep process"))
203 (define-key map [menu-bar grep compilation-separator2] '("----"))
204 (define-key map [menu-bar grep compilation-compile]
205 '(menu-item "Compile..." compile
206 :help "Compile the program including the current buffer. Default: run `make'"))
207 (define-key map [menu-bar grep compilation-grep]
208 '(menu-item "Another grep..." grep
209 :help "Run grep, with user-specified args, and collect output in a buffer."))
210 (define-key map [menu-bar grep compilation-grep-find]
211 '(menu-item "Recursive grep..." grep-find
212 :help "Run grep via find, with user-specified args"))
213 (define-key map [menu-bar grep compilation-recompile]
214 '(menu-item "Repeat grep" recompile
215 :help "Run grep again"))
216 (define-key map [menu-bar grep compilation-separator2] '("----"))
217 (define-key map [menu-bar grep compilation-first-error]
218 '(menu-item "First Match" first-error
219 :help "Restart at the first match, visit corresponding location"))
220 (define-key map [menu-bar grep compilation-previous-error]
221 '(menu-item "Previous Match" previous-error
222 :help "Visit the previous match and corresponding location"))
223 (define-key map [menu-bar grep compilation-next-error]
224 '(menu-item "Next Match" next-error
225 :help "Visit the next match and corresponding location"))
227 "Keymap for grep buffers.
228 `compilation-minor-mode-map' is a cdr of this.")
230 (defvar grep-mode-tool-bar-map
231 (if (display-graphic-p)
232 (let ((map (butlast (copy-keymap tool-bar-map)))
233 (help (last tool-bar-map))) ;; Keep Help last in tool bar
235 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
237 :help "Goto previous match")
239 "right-arrow" 'next-error-no-select 'next-error-no-select map
241 :help "Goto next match")
243 "cancel" 'kill-compilation 'kill-compilation map
244 :enable '(let ((buffer (compilation-find-buffer)))
245 (get-buffer-process buffer))
248 "refresh" 'recompile 'recompile map
249 :help "Restart grep")
252 (defalias 'kill-grep 'kill-compilation)
254 ;;;; TODO --- refine this!!
256 ;; (defcustom grep-use-compilation-buffer t
257 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
258 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
259 ;; can be used to navigate between grep matches (the default).
260 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
261 ;; be used to navigate between grep matches."
265 ;; override compilation-last-buffer
266 (defvar grep-last-buffer nil
267 "The most recent grep buffer.
268 A grep buffer becomes most recent when you select Grep mode in it.
269 Notice that using \\[next-error] or \\[compile-goto-error] modifies
270 `complation-last-buffer' rather than `grep-last-buffer'.")
273 (defvar grep-regexp-alist
274 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
276 ;; Rule to match column numbers is commented out since no known grep
278 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
280 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
281 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
283 ;; Calculate column positions (beg . end) of first grep match on a line
285 (setq compilation-error-screen-columns nil)
286 (- (match-beginning 4) (match-end 1)))
288 (lambda () (- (match-end 5) (match-end 1)
289 (- (match-end 4) (match-beginning 4)))))
291 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
292 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
294 (defvar grep-error "grep hit"
295 "Message to print when no matches are found.")
297 ;; Reverse the colors because grep hits are not errors (though we jump there
298 ;; with `next-error'), and unreadable files can't be gone to.
299 (defvar grep-hit-face compilation-info-face
300 "Face name to use for grep hits.")
302 (defvar grep-error-face 'compilation-error
303 "Face name to use for grep error messages.")
305 (defvar grep-match-face 'match
306 "Face name to use for grep matches.")
308 (defvar grep-context-face 'shadow
309 "Face name to use for grep context lines.")
311 (defvar grep-mode-font-lock-keywords
312 '(;; Command output lines.
313 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
314 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
316 ;; remove match from grep-regexp-alist before fontifying
317 ("^Grep[/a-zA-z]* started.*"
318 (0 '(face nil message nil help-echo nil mouse-face nil) t))
319 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
320 (0 '(face nil message nil help-echo nil mouse-face nil) t)
321 (1 compilation-info-face nil t)
322 (2 compilation-warning-face nil t))
323 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
324 (0 '(face nil message nil help-echo nil mouse-face nil) t)
326 (2 grep-error-face nil t))
327 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
328 ;; Highlight grep matches and delete markers
329 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
330 ;; Refontification does not work after the markers have been
331 ;; deleted. So we use the font-lock-face property here as Font
332 ;; Lock does not clear that.
333 (2 (list 'face nil 'font-lock-face grep-match-face))
336 ;; Delete markers with `replace-match' because it updates
337 ;; the match-data, whereas `delete-region' would render it obsolete.
338 (replace-match "" t t nil 3)
339 (replace-match "" t t nil 1))))
340 ("\\(\033\\[[0-9;]*[mK]\\)"
341 ;; Delete all remaining escape sequences
343 (replace-match "" t t nil 1))))
344 "Additional things to highlight in grep output.
345 This gets tacked on the end of the generated expressions.")
348 (defvar grep-program "grep"
349 "The default grep program for `grep-command' and `grep-find-command'.
350 This variable's value takes effect when `grep-compute-defaults' is called.")
353 (defvar find-program "find"
354 "The default find program for `grep-find-command'.
355 This variable's value takes effect when `grep-compute-defaults' is called.")
358 (defvar xargs-program "xargs"
359 "The default xargs program for `grep-find-command'.
360 See `grep-find-use-xargs'.
361 This variable's value takes effect when `grep-compute-defaults' is called.")
364 (defvar grep-find-use-xargs nil
365 "Non-nil means that `grep-find' uses the `xargs' utility by default.
366 If `exec', use `find -exec'.
367 If `gnu', use `find -print0' and `xargs -0'.
368 Any other non-nil value means to use `find -print' and `xargs'.
370 This variable's value takes effect when `grep-compute-defaults' is called.")
372 ;; History of grep commands.
374 (defvar grep-history nil)
376 (defvar grep-find-history nil)
378 ;; History of lgrep and rgrep regexp and files args.
379 (defvar grep-regexp-history nil)
380 (defvar grep-files-history '("ch" "el"))
382 (defvar grep-host-defaults-alist nil
383 "Default values depending on target host.
384 `grep-compute-defaults' returns default values for every local or
385 remote host `grep' runs. These values can differ from host to
386 host. Once computed, the default values are kept here in order
387 to avoid computing them again.")
390 (defun grep-process-setup ()
391 "Setup compilation variables and buffer for `grep'.
392 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
393 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
394 (grep-compute-defaults))
395 (when (eq grep-highlight-matches t)
396 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
397 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
398 (setenv "TERM" "emacs-grep")
399 ;; `--color=auto' emits escape sequences on a tty rather than on a pipe,
400 ;; thus allowing to use multiple grep filters on the command line
401 ;; and to output escape sequences only on the final grep output
402 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=auto"))
403 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
404 (setenv "GREP_COLOR" "01;31")
405 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
406 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
407 (set (make-local-variable 'compilation-exit-message-function)
408 (lambda (status code msg)
409 (if (eq status 'exit)
411 '("finished (matches found)\n" . "matched"))
413 '("finished with no matches found\n" . "no match"))
417 (run-hooks 'grep-setup-hook))
419 (defun grep-probe (command args &optional func result)
420 (equal (condition-case nil
421 (apply (or func 'process-file) command args)
426 (defun grep-compute-defaults ()
427 ;; Keep default values.
428 (unless grep-host-defaults-alist
430 'grep-host-defaults-alist
432 `((grep-command ,grep-command)
433 (grep-template ,grep-template)
434 (grep-use-null-device ,grep-use-null-device)
435 (grep-find-command ,grep-find-command)
436 (grep-find-template ,grep-find-template)
437 (grep-find-use-xargs ,grep-find-use-xargs)
438 (grep-highlight-matches ,grep-highlight-matches)))))
440 (intern (or (file-remote-p default-directory) "localhost")))
441 (host-defaults (assq host-id grep-host-defaults-alist))
442 (defaults (assq nil grep-host-defaults-alist)))
443 ;; There are different defaults on different hosts. They must be
444 ;; computed for every host once.
446 (or (cadr (assq 'grep-command host-defaults))
447 (cadr (assq 'grep-command defaults)))
450 (or (cadr (assq 'grep-template host-defaults))
451 (cadr (assq 'grep-template defaults)))
454 (or (cadr (assq 'grep-use-null-device host-defaults))
455 (cadr (assq 'grep-use-null-device defaults)))
458 (or (cadr (assq 'grep-find-command host-defaults))
459 (cadr (assq 'grep-find-command defaults)))
462 (or (cadr (assq 'grep-find-template host-defaults))
463 (cadr (assq 'grep-find-template defaults)))
466 (or (cadr (assq 'grep-find-use-xargs host-defaults))
467 (cadr (assq 'grep-find-use-xargs defaults)))
469 grep-highlight-matches
470 (or (cadr (assq 'grep-highlight-matches host-defaults))
471 (cadr (assq 'grep-highlight-matches defaults))))
473 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
474 (setq grep-use-null-device
476 (let ((hello-file (expand-file-name "HELLO" data-directory)))
478 (and (if grep-command
479 ;; `grep-command' is already set, so
480 ;; use that for testing.
481 (grep-probe grep-command
482 `(nil t nil "^English" ,hello-file)
483 #'call-process-shell-command)
484 ;; otherwise use `grep-program'
485 (grep-probe grep-program
486 `(nil t nil "-nH" "^English" ,hello-file)))
488 (goto-char (point-min))
490 (concat (regexp-quote hello-file)
491 ":[0-9]+:English")))))))))
492 (unless (and grep-command grep-find-command
493 grep-template grep-find-template)
495 (concat (if grep-use-null-device "-n" "-nH")
496 (if (grep-probe grep-program
497 `(nil nil nil "-e" "foo" ,null-device)
502 (format "%s %s " grep-program grep-options)))
503 (unless grep-template
505 (format "%s <C> %s <R> <F>" grep-program grep-options)))
506 (unless grep-find-use-xargs
507 (setq grep-find-use-xargs
510 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
511 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
515 (unless grep-find-command
516 (setq grep-find-command
517 (cond ((eq grep-find-use-xargs 'gnu)
518 (format "%s . -type f -print0 | %s -0 -e %s"
519 find-program xargs-program grep-command))
520 ((eq grep-find-use-xargs 'exec)
521 (let ((cmd0 (format "%s . -type f -exec %s"
522 find-program grep-command)))
524 (format "%s {} %s %s"
526 (shell-quote-argument ";"))
527 (1+ (length cmd0)))))
529 (format "%s . -type f -print | %s %s"
530 find-program xargs-program grep-command)))))
531 (unless grep-find-template
532 (setq grep-find-template
533 (let ((gcmd (format "%s <C> %s <R>"
534 grep-program grep-options)))
535 (cond ((eq grep-find-use-xargs 'gnu)
536 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
537 find-program xargs-program gcmd))
538 ((eq grep-find-use-xargs 'exec)
539 (format "%s . <X> -type f <F> -exec %s {} %s %s"
540 find-program gcmd null-device
541 (shell-quote-argument ";")))
543 (format "%s . <X> -type f <F> -print | %s %s"
544 find-program xargs-program gcmd))))))))
545 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
546 (setq grep-highlight-matches
548 (and (grep-probe grep-program '(nil t nil "--help"))
550 (goto-char (point-min))
551 (search-forward "--color" nil t))
554 ;; Save defaults for this host.
555 (setq grep-host-defaults-alist
556 (delete (assq host-id grep-host-defaults-alist)
557 grep-host-defaults-alist))
559 'grep-host-defaults-alist
561 `((grep-command ,grep-command)
562 (grep-template ,grep-template)
563 (grep-use-null-device ,grep-use-null-device)
564 (grep-find-command ,grep-find-command)
565 (grep-find-template ,grep-find-template)
566 (grep-find-use-xargs ,grep-find-use-xargs)
567 (grep-highlight-matches ,grep-highlight-matches))))))
569 (defun grep-tag-default ()
570 (or (and transient-mark-mode mark-active
572 (buffer-substring-no-properties (point) (mark)))
573 (funcall (or find-tag-default-function
574 (get major-mode 'find-tag-default-function)
578 (defun grep-default-command ()
579 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
580 (let ((tag-default (shell-quote-argument (grep-tag-default)))
581 ;; This a regexp to match single shell arguments.
582 ;; Could someone please add comments explaining it?
583 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
584 (grep-default (or (car grep-history) grep-command)))
585 ;; In the default command, find the arg that specifies the pattern.
586 (when (or (string-match
587 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
588 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
590 ;; If the string is not yet complete.
591 (string-match "\\(\\)\\'" grep-default))
592 ;; Maybe we will replace the pattern with the default tag.
593 ;; But first, maybe replace the file name pattern.
595 (unless (or (not (stringp buffer-file-name))
596 (when (match-beginning 2)
600 (file-name-nondirectory
601 (match-string 3 grep-default)))
602 (file-name-nondirectory buffer-file-name)))))
603 (setq grep-default (concat (substring grep-default
604 0 (match-beginning 2))
606 (file-name-extension buffer-file-name))))
607 ;; In case wildcard-to-regexp gets an error
608 ;; from invalid data.
610 ;; Now replace the pattern with the default tag.
611 (replace-match tag-default t t grep-default 1))))
615 (define-compilation-mode grep-mode "Grep"
616 "Sets `grep-last-buffer' and `compilation-window-height'."
617 (setq grep-last-buffer (current-buffer))
618 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
619 (set (make-local-variable 'compilation-error-face)
621 (set (make-local-variable 'compilation-error-regexp-alist)
623 (set (make-local-variable 'compilation-process-setup-function)
625 (set (make-local-variable 'compilation-disable-input) t))
629 (defun grep (command-args)
630 "Run grep, with user-specified args, and collect output in a buffer.
631 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
632 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
633 output buffer, to go to the lines where grep
636 For doing a recursive `grep', see the `rgrep' command. For running
637 `grep' in a specific directory, see `lgrep'.
639 This command uses a special history list for its COMMAND-ARGS, so you
640 can easily repeat a grep command.
642 A prefix argument says to default the argument based upon the current
643 tag the cursor is over, substituting it into the last grep command
644 in the grep command history (or into `grep-command' if that history
648 (grep-compute-defaults)
649 (let ((default (grep-default-command)))
650 (list (read-shell-command "Run grep (like this): "
651 (if current-prefix-arg default grep-command)
653 (if current-prefix-arg nil default))))))
655 ;; Setting process-setup-function makes exit-message-function work
656 ;; even when async processes aren't supported.
657 (compilation-start (if (and grep-use-null-device null-device)
658 (concat command-args " " null-device)
664 (defun grep-find (command-args)
665 "Run grep via find, with user-specified args COMMAND-ARGS.
666 Collect output in a buffer.
667 While find runs asynchronously, you can use the \\[next-error] command
668 to find the text that grep hits refer to.
670 This command uses a special history list for its arguments, so you can
671 easily repeat a find command."
674 (grep-compute-defaults)
675 (if grep-find-command
676 (list (read-shell-command "Run find (like this): "
677 grep-find-command 'grep-find-history))
678 ;; No default was set
680 "compile.el: No `grep-find-command' command available. Press RET.")
683 (let ((null-device nil)) ; see grep
684 (grep command-args))))
687 (defalias 'find-grep 'grep-find)
690 ;; User-friendly interactive API.
692 (defconst grep-expand-keywords
693 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
696 ("<N>" . null-device)
698 ("<R>" . (shell-quote-argument (or regexp ""))))
699 "List of substitutions performed by `grep-expand-template'.
700 If car of an element matches, the cdr is evalled in to get the
701 substitution string. Note dynamic scoping of variables.")
703 (defun grep-expand-template (template &optional regexp files dir excl)
704 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
705 (let ((command template)
706 (cf case-fold-search)
707 (case-fold-search nil))
708 (dolist (kw grep-expand-keywords command)
709 (if (string-match (car kw) command)
712 (or (if (symbolp (cdr kw))
713 (symbol-value (cdr kw))
714 (save-match-data (eval (cdr kw))))
718 (defun grep-read-regexp ()
719 "Read regexp arg for interactive grep."
720 (let ((default (grep-tag-default)))
723 (if (and default (> (length default) 0))
724 (format " (default \"%s\"): " default) ": "))
725 nil 'grep-regexp-history default)))
727 (defun grep-read-files (regexp)
728 "Read files arg for interactive grep."
729 (let* ((bn (or (buffer-file-name) (buffer-name)))
732 (file-name-nondirectory bn)))
735 (let ((aliases grep-files-aliases)
738 (setq alias (car aliases)
739 aliases (cdr aliases))
740 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
745 (let ((ext (file-name-extension fn)))
746 (and ext (concat "*." ext))))
747 (car grep-files-history)
748 (car (car grep-files-aliases))))
750 (concat "Search for \"" regexp
752 (if default (concat " (default " default ")"))
754 nil 'grep-files-history default)))
756 (or (cdr (assoc files grep-files-aliases))
760 (defun lgrep (regexp &optional files dir)
761 "Run grep, searching for REGEXP in FILES in directory DIR.
762 The search is limited to file names matching shell pattern FILES.
763 FILES may use abbreviations defined in `grep-files-aliases', e.g.
764 entering `ch' is equivalent to `*.[ch]'.
766 With \\[universal-argument] prefix, you can edit the constructed shell command line
767 before it is executed.
768 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
770 Collect output in a buffer. While grep runs asynchronously, you
771 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
772 in the grep output buffer,
773 to go to the lines where grep found matches.
775 This command shares argument histories with \\[rgrep] and \\[grep]."
778 (grep-compute-defaults)
780 ((and grep-command (equal current-prefix-arg '(16)))
781 (list (read-from-minibuffer "Run: " grep-command
782 nil nil 'grep-history)
786 (read-string "grep.el: No `grep-template' available. Press RET.")))
787 (t (let* ((regexp (grep-read-regexp))
788 (files (grep-read-files regexp))
789 (dir (read-directory-name "In directory: "
790 nil default-directory t)))
791 (list regexp files dir))))))
792 (when (and (stringp regexp) (> (length regexp) 0))
793 (let ((command regexp))
795 (if (string= command grep-command)
797 (setq dir (file-name-as-directory (expand-file-name dir)))
798 (setq command (grep-expand-template
803 (if (equal current-prefix-arg '(4))
805 (read-from-minibuffer "Confirm: "
806 command nil nil 'grep-history))
807 (add-to-history 'grep-history command))))
809 (let ((default-directory dir))
810 ;; Setting process-setup-function makes exit-message-function work
811 ;; even when async processes aren't supported.
812 (compilation-start (if (and grep-use-null-device null-device)
813 (concat command " " null-device)
816 (if (eq next-error-last-buffer (current-buffer))
817 (setq default-directory dir))))))
820 (defvar find-name-arg) ; autoloaded
823 (defun rgrep (regexp &optional files dir)
824 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
825 The search is limited to file names matching shell pattern FILES.
826 FILES may use abbreviations defined in `grep-files-aliases', e.g.
827 entering `ch' is equivalent to `*.[ch]'.
829 With \\[universal-argument] prefix, you can edit the constructed shell command line
830 before it is executed.
831 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
833 Collect output in a buffer. While find runs asynchronously, you
834 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
835 in the grep output buffer,
836 to go to the lines where grep found matches.
838 This command shares argument histories with \\[lgrep] and \\[grep-find]."
841 (grep-compute-defaults)
843 ((and grep-find-command (equal current-prefix-arg '(16)))
844 (list (read-from-minibuffer "Run: " grep-find-command
845 nil nil 'grep-find-history)
847 ((not grep-find-template)
849 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
850 (t (let* ((regexp (grep-read-regexp))
851 (files (grep-read-files regexp))
852 (dir (read-directory-name "Base directory: "
853 nil default-directory t)))
854 (list regexp files dir))))))
855 (when (and (stringp regexp) (> (length regexp) 0))
857 (if (not (string= regexp grep-find-command))
858 (compilation-start regexp 'grep-mode))
859 (setq dir (file-name-as-directory (expand-file-name dir)))
860 (let ((command (grep-expand-template
863 (concat (shell-quote-argument "(")
864 " " find-name-arg " "
865 (mapconcat #'shell-quote-argument
867 (concat " -o " find-name-arg " "))
869 (shell-quote-argument ")"))
871 (and grep-find-ignored-directories
872 (concat (shell-quote-argument "(")
873 ;; we should use shell-quote-argument here
875 (mapconcat #'(lambda (dir)
876 (shell-quote-argument
878 grep-find-ignored-directories
881 (shell-quote-argument ")")
884 (if current-prefix-arg
886 (read-from-minibuffer "Confirm: "
887 command nil nil 'grep-find-history))
888 (add-to-history 'grep-find-history command))
889 (let ((default-directory dir))
890 (compilation-start command 'grep-mode))
891 ;; Set default-directory if we started rgrep in the *grep* buffer.
892 (if (eq next-error-last-buffer (current-buffer))
893 (setq default-directory dir)))))))
898 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
899 ;;; grep.el ends here