* progmodes/grep.el (grep-find-ignored-directories): Initialize
[emacs.git] / lisp / progmodes / grep.el
blob101e8f12e3f44d67cb77c13295f82a9e4aa150ff
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 Free Software Foundation, Inc.
6 ;; Author: Roland McGrath <roland@gnu.org>
7 ;; Maintainer: FSF
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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; This package provides the grep facilities documented in the Emacs
30 ;; user's manual.
32 ;;; Code:
34 (require 'compile)
37 (defgroup grep nil
38 "Run grep as inferior of Emacs, parse error messages."
39 :group 'tools
40 :group 'processes)
43 ;;;###autoload
44 (defcustom grep-window-height nil
45 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
46 :type '(choice (const :tag "Default" nil)
47 integer)
48 :version "22.1"
49 :group 'grep)
51 (defcustom grep-highlight-matches 'auto-detect
52 "If t, use special markers to highlight grep matches.
54 Some grep programs are able to surround matches with special
55 markers in grep output. Such markers can be used to highlight
56 matches in grep mode.
58 This option sets the environment variable GREP_COLOR to specify
59 markers for highlighting and GREP_OPTIONS to add the --color
60 option in front of any explicit grep options before starting
61 the grep.
63 The default value of this variable is set up by `grep-compute-defaults';
64 call that function before using this variable in your program."
65 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
66 (const :tag "Highlight matches with grep markers" t)
67 (other :tag "Not Set" auto-detect))
68 :version "22.1"
69 :group 'grep)
71 (defcustom grep-scroll-output nil
72 "*Non-nil to scroll the *grep* buffer window as output appears.
74 Setting it causes the grep commands to put point at the end of their
75 output window so that the end of the output is always visible rather
76 than the begining."
77 :type 'boolean
78 :version "22.1"
79 :group 'grep)
81 ;;;###autoload
82 (defcustom grep-command nil
83 "The default grep command for \\[grep].
84 If the grep program used supports an option to always include file names
85 in its output (such as the `-H' option to GNU grep), it's a good idea to
86 include it when specifying `grep-command'.
88 The default value of this variable is set up by `grep-compute-defaults';
89 call that function before using this variable in your program."
90 :type '(choice string
91 (const :tag "Not Set" nil))
92 :group 'grep)
94 (defcustom grep-template nil
95 "The default command to run for \\[lgrep].
96 The default value of this variable is set up by `grep-compute-defaults';
97 call that function before using this variable in your program.
98 The following place holders should be present in the string:
99 <C> - place to put -i if case insensitive grep.
100 <F> - file names and wildcards to search.
101 <R> - the regular expression searched for.
102 <N> - place to insert null-device."
103 :type '(choice string
104 (const :tag "Not Set" nil))
105 :version "22.1"
106 :group 'grep)
108 (defcustom grep-use-null-device 'auto-detect
109 "If t, append the value of `null-device' to `grep' commands.
110 This is done to ensure that the output of grep includes the filename of
111 any match in the case where only a single file is searched, and is not
112 necessary if the grep program used supports the `-H' option.
114 The default value of this variable is set up by `grep-compute-defaults';
115 call that function before using this variable in your program."
116 :type '(choice (const :tag "Do Not Append Null Device" nil)
117 (const :tag "Append Null Device" t)
118 (other :tag "Not Set" auto-detect))
119 :group 'grep)
121 ;;;###autoload
122 (defcustom grep-find-command nil
123 "The default find command for \\[grep-find].
124 The default value of this variable is set up by `grep-compute-defaults';
125 call that function before using this variable in your program."
126 :type '(choice string
127 (const :tag "Not Set" nil))
128 :group 'grep)
130 (defcustom grep-find-template nil
131 "The default command to run for \\[rgrep].
132 The default value of this variable is set up by `grep-compute-defaults';
133 call that function before using this variable in your program.
134 The following place holders should be present in the string:
135 <D> - base directory for find
136 <X> - find options to restrict or expand the directory list
137 <F> - find options to limit the files matched
138 <C> - place to put -i if case insensitive grep
139 <R> - the regular expression searched for."
140 :type '(choice string
141 (const :tag "Not Set" nil))
142 :version "22.1"
143 :group 'grep)
145 (defcustom grep-files-aliases
146 '(("asm" . "*.[sS]")
147 ("c" . "*.c")
148 ("cc" . "*.cc")
149 ("ch" . "*.[ch]")
150 ("el" . "*.el")
151 ("h" . "*.h")
152 ("l" . "[Cc]hange[Ll]og*")
153 ("m" . "[Mm]akefile*")
154 ("tex" . "*.tex")
155 ("texi" . "*.texi"))
156 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
157 :type 'alist
158 :group 'grep)
160 (defcustom grep-find-ignored-directories
161 vc-directory-exclusion-list
162 "*List of names of sub-directories which `rgrep' shall not recurse into."
163 :type '(repeat string)
164 :group 'grep)
166 (defcustom grep-error-screen-columns nil
167 "*If non-nil, column numbers in grep hits are screen columns.
168 See `compilation-error-screen-columns'"
169 :type '(choice (const :tag "Default" nil)
170 integer)
171 :version "22.1"
172 :group 'grep)
174 ;;;###autoload
175 (defcustom grep-setup-hook nil
176 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
177 :type 'hook
178 :group 'grep)
180 (defvar grep-mode-map
181 (let ((map (cons 'keymap compilation-minor-mode-map)))
182 (define-key map " " 'scroll-up)
183 (define-key map "\^?" 'scroll-down)
184 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
186 (define-key map "\r" 'compile-goto-error) ;; ?
187 (define-key map "n" 'next-error-no-select)
188 (define-key map "p" 'previous-error-no-select)
189 (define-key map "{" 'compilation-previous-file)
190 (define-key map "}" 'compilation-next-file)
191 (define-key map "\t" 'compilation-next-error)
192 (define-key map [backtab] 'compilation-previous-error)
194 ;; Set up the menu-bar
195 (define-key map [menu-bar grep]
196 (cons "Grep" (make-sparse-keymap "Grep")))
198 (define-key map [menu-bar grep compilation-kill-compilation]
199 '("Kill Grep" . kill-compilation))
200 (define-key map [menu-bar grep compilation-separator2]
201 '("----" . nil))
202 (define-key map [menu-bar grep compilation-compile]
203 '("Compile..." . compile))
204 (define-key map [menu-bar grep compilation-grep]
205 '("Another grep..." . grep))
206 (define-key map [menu-bar grep compilation-grep-find]
207 '("Recursive grep..." . grep-find))
208 (define-key map [menu-bar grep compilation-recompile]
209 '("Repeat grep" . recompile))
210 (define-key map [menu-bar grep compilation-separator2]
211 '("----" . nil))
212 (define-key map [menu-bar grep compilation-first-error]
213 '("First Match" . first-error))
214 (define-key map [menu-bar grep compilation-previous-error]
215 '("Previous Match" . previous-error))
216 (define-key map [menu-bar grep compilation-next-error]
217 '("Next Match" . next-error))
218 map)
219 "Keymap for grep buffers.
220 `compilation-minor-mode-map' is a cdr of this.")
222 (defalias 'kill-grep 'kill-compilation)
224 ;;;; TODO --- refine this!!
226 ;;; (defcustom grep-use-compilation-buffer t
227 ;;; "When non-nil, grep specific commands update `compilation-last-buffer'.
228 ;;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
229 ;;; can be used to navigate between grep matches (the default).
230 ;;; Otherwise, the grep specific commands like \\[grep-next-match] must
231 ;;; be used to navigate between grep matches."
232 ;;; :type 'boolean
233 ;;; :group 'grep)
235 ;; override compilation-last-buffer
236 (defvar grep-last-buffer nil
237 "The most recent grep buffer.
238 A grep buffer becomes most recent when you select Grep mode in it.
239 Notice that using \\[next-error] or \\[compile-goto-error] modifies
240 `complation-last-buffer' rather than `grep-last-buffer'.")
242 ;;;###autoload
243 (defvar grep-regexp-alist
244 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
245 1 3)
246 ;; Rule to match column numbers is commented out since no known grep
247 ;; produces them
248 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
249 ;; 1 3 (4 . 5))
250 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
251 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
253 ;; Calculate column positions (beg . end) of first grep match on a line
254 ((lambda ()
255 (setq compilation-error-screen-columns nil)
256 (- (match-beginning 4) (match-end 1)))
258 (lambda () (- (match-end 5) (match-end 1)
259 (- (match-end 4) (match-beginning 4)))))
260 nil 1)
261 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
262 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
264 (defvar grep-error "grep hit"
265 "Message to print when no matches are found.")
267 ;; Reverse the colors because grep hits are not errors (though we jump there
268 ;; with `next-error'), and unreadable files can't be gone to.
269 (defvar grep-hit-face compilation-info-face
270 "Face name to use for grep hits.")
272 (defvar grep-error-face 'compilation-error
273 "Face name to use for grep error messages.")
275 (defvar grep-match-face 'match
276 "Face name to use for grep matches.")
278 (defvar grep-context-face 'shadow
279 "Face name to use for grep context lines.")
281 (defvar grep-mode-font-lock-keywords
282 '(;; Command output lines.
283 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
284 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
285 1 grep-error-face)
286 ;; remove match from grep-regexp-alist before fontifying
287 ("^Grep[/a-zA-z]* started.*"
288 (0 '(face nil message nil help-echo nil mouse-face nil) t))
289 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
290 (0 '(face nil message nil help-echo nil mouse-face nil) t)
291 (1 compilation-info-face nil t)
292 (2 compilation-warning-face nil t))
293 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
294 (0 '(face nil message nil help-echo nil mouse-face nil) t)
295 (1 grep-error-face)
296 (2 grep-error-face nil t))
297 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
298 ;; Highlight grep matches and delete markers
299 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
300 ;; Refontification does not work after the markers have been
301 ;; deleted. So we use the font-lock-face property here as Font
302 ;; Lock does not clear that.
303 (2 (list 'face nil 'font-lock-face grep-match-face))
304 ((lambda (bound))
305 (progn
306 ;; Delete markers with `replace-match' because it updates
307 ;; the match-data, whereas `delete-region' would render it obsolete.
308 (replace-match "" t t nil 3)
309 (replace-match "" t t nil 1))))
310 ("\\(\033\\[[0-9;]*[mK]\\)"
311 ;; Delete all remaining escape sequences
312 ((lambda (bound))
313 (replace-match "" t t nil 1))))
314 "Additional things to highlight in grep output.
315 This gets tacked on the end of the generated expressions.")
317 ;;;###autoload
318 (defvar grep-program "grep"
319 "The default grep program for `grep-command' and `grep-find-command'.
320 This variable's value takes effect when `grep-compute-defaults' is called.")
322 ;;;###autoload
323 (defvar find-program "find"
324 "The default find program for `grep-find-command'.
325 This variable's value takes effect when `grep-compute-defaults' is called.")
327 ;;;###autoload
328 (defvar xargs-program "xargs"
329 "The default xargs program for `grep-find-command'.
330 See `grep-find-use-xargs'.
331 This variable's value takes effect when `grep-compute-defaults' is called.")
333 ;;;###autoload
334 (defvar grep-find-use-xargs nil
335 "Non-nil means that `grep-find' uses the `xargs' utility by default.
336 If `exec', use `find -exec'.
337 If `gnu', use `find -print0' and `xargs -0'.
338 Any other non-nil value means to use `find -print' and `xargs'.
340 This variable's value takes effect when `grep-compute-defaults' is called.")
342 ;; History of grep commands.
343 ;;;###autoload
344 (defvar grep-history nil)
345 ;;;###autoload
346 (defvar grep-find-history nil)
348 ;; History of lgrep and rgrep regexp and files args.
349 (defvar grep-regexp-history nil)
350 (defvar grep-files-history '("ch" "el"))
352 (defvar grep-host-defaults-alist nil
353 "Default values depending on target host.
354 `grep-compute-defaults' returns default values for every local or
355 remote host `grep' runs. These values can differ from host to
356 host. Once computed, the default values are kept here in order
357 to avoid computing them again.")
359 ;;;###autoload
360 (defun grep-process-setup ()
361 "Setup compilation variables and buffer for `grep'.
362 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
363 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
364 (grep-compute-defaults))
365 (when (eq grep-highlight-matches t)
366 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
367 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
368 (setenv "TERM" "emacs-grep")
369 ;; `--color=auto' emits escape sequences on a tty rather than on a pipe,
370 ;; thus allowing to use multiple grep filters on the command line
371 ;; and to output escape sequences only on the final grep output
372 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=auto"))
373 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
374 (setenv "GREP_COLOR" "01;31")
375 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
376 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
377 (set (make-local-variable 'compilation-exit-message-function)
378 (lambda (status code msg)
379 (if (eq status 'exit)
380 (cond ((zerop code)
381 '("finished (matches found)\n" . "matched"))
382 ((= code 1)
383 '("finished with no matches found\n" . "no match"))
385 (cons msg code)))
386 (cons msg code))))
387 (run-hooks 'grep-setup-hook))
389 (defun grep-probe (command args &optional func result)
390 (equal (condition-case nil
391 (apply (or func 'process-file) command args)
392 (error nil))
393 (or result 0)))
395 ;;;###autoload
396 (defun grep-compute-defaults ()
397 ;; Keep default values.
398 (unless grep-host-defaults-alist
399 (add-to-list
400 'grep-host-defaults-alist
401 (cons nil
402 `((grep-command ,grep-command)
403 (grep-template ,grep-template)
404 (grep-use-null-device ,grep-use-null-device)
405 (grep-find-command ,grep-find-command)
406 (grep-find-template ,grep-find-template)
407 (grep-find-use-xargs ,grep-find-use-xargs)
408 (grep-highlight-matches ,grep-highlight-matches)))))
409 (let* ((host-id
410 (intern (or (file-remote-p default-directory 'host) "localhost")))
411 (host-defaults (assq host-id grep-host-defaults-alist))
412 (defaults (assq nil grep-host-defaults-alist)))
413 ;; There are different defaults on different hosts. They must be
414 ;; computed for every host once.
415 (setq grep-command
416 (or (cadr (assq 'grep-command host-defaults))
417 (cadr (assq 'grep-command defaults)))
419 grep-template
420 (or (cadr (assq 'grep-template host-defaults))
421 (cadr (assq 'grep-template defaults)))
423 grep-use-null-device
424 (or (cadr (assq 'grep-use-null-device host-defaults))
425 (cadr (assq 'grep-use-null-device defaults)))
427 grep-find-command
428 (or (cadr (assq 'grep-find-command host-defaults))
429 (cadr (assq 'grep-find-command defaults)))
431 grep-find-template
432 (or (cadr (assq 'grep-find-template host-defaults))
433 (cadr (assq 'grep-find-template defaults)))
435 grep-find-use-xargs
436 (or (cadr (assq 'grep-find-use-xargs host-defaults))
437 (cadr (assq 'grep-find-use-xargs defaults)))
439 grep-highlight-matches
440 (or (cadr (assq 'grep-highlight-matches host-defaults))
441 (cadr (assq 'grep-highlight-matches defaults))))
443 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
444 (setq grep-use-null-device
445 (with-temp-buffer
446 (let ((hello-file (expand-file-name "HELLO" data-directory)))
447 (not
448 (and (if grep-command
449 ;; `grep-command' is already set, so
450 ;; use that for testing.
451 (grep-probe grep-command
452 `(nil t nil "^English" ,hello-file)
453 #'call-process-shell-command)
454 ;; otherwise use `grep-program'
455 (grep-probe grep-program
456 `(nil t nil "-nH" "^English" ,hello-file)))
457 (progn
458 (goto-char (point-min))
459 (looking-at
460 (concat (regexp-quote hello-file)
461 ":[0-9]+:English")))))))))
462 (unless (and grep-command grep-find-command
463 grep-template grep-find-template)
464 (let ((grep-options
465 (concat (if grep-use-null-device "-n" "-nH")
466 (if (grep-probe grep-program
467 `(nil nil nil "-e" "foo" ,null-device)
468 nil 1)
469 " -e"))))
470 (unless grep-command
471 (setq grep-command
472 (format "%s %s " grep-program grep-options)))
473 (unless grep-template
474 (setq grep-template
475 (format "%s <C> %s <R> <F>" grep-program grep-options)))
476 (unless grep-find-use-xargs
477 (setq grep-find-use-xargs
478 (cond
479 ((and
480 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
481 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
482 'gnu)
484 'exec))))
485 (unless grep-find-command
486 (setq grep-find-command
487 (cond ((eq grep-find-use-xargs 'gnu)
488 (format "%s . -type f -print0 | %s -0 -e %s"
489 find-program xargs-program grep-command))
490 ((eq grep-find-use-xargs 'exec)
491 (let ((cmd0 (format "%s . -type f -exec %s"
492 find-program grep-command)))
493 (cons
494 (format "%s {} %s %s"
495 cmd0 null-device
496 (shell-quote-argument ";"))
497 (1+ (length cmd0)))))
499 (format "%s . -type f -print | %s %s"
500 find-program xargs-program grep-command)))))
501 (unless grep-find-template
502 (setq grep-find-template
503 (let ((gcmd (format "%s <C> %s <R>"
504 grep-program grep-options)))
505 (cond ((eq grep-find-use-xargs 'gnu)
506 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
507 find-program xargs-program gcmd))
508 ((eq grep-find-use-xargs 'exec)
509 (format "%s . <X> -type f <F> -exec %s {} %s %s"
510 find-program gcmd null-device
511 (shell-quote-argument ";")))
513 (format "%s . <X> -type f <F> -print | %s %s"
514 find-program xargs-program gcmd))))))))
515 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
516 (setq grep-highlight-matches
517 (with-temp-buffer
518 (and (grep-probe grep-program '(nil t nil "--help"))
519 (progn
520 (goto-char (point-min))
521 (search-forward "--color" nil t))
522 t))))
524 ;; Save defaults for this host.
525 (setq grep-host-defaults-alist
526 (delete (assq host-id grep-host-defaults-alist)
527 grep-host-defaults-alist))
528 (add-to-list
529 'grep-host-defaults-alist
530 (cons host-id
531 `((grep-command ,grep-command)
532 (grep-template ,grep-template)
533 (grep-use-null-device ,grep-use-null-device)
534 (grep-find-command ,grep-find-command)
535 (grep-find-template ,grep-find-template)
536 (grep-find-use-xargs ,grep-find-use-xargs)
537 (grep-highlight-matches ,grep-highlight-matches))))))
539 (defun grep-tag-default ()
540 (or (and transient-mark-mode mark-active
541 (/= (point) (mark))
542 (buffer-substring-no-properties (point) (mark)))
543 (funcall (or find-tag-default-function
544 (get major-mode 'find-tag-default-function)
545 'find-tag-default))
546 ""))
548 (defun grep-default-command ()
549 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
550 (let ((tag-default (shell-quote-argument (grep-tag-default)))
551 ;; This a regexp to match single shell arguments.
552 ;; Could someone please add comments explaining it?
553 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
554 (grep-default (or (car grep-history) grep-command)))
555 ;; In the default command, find the arg that specifies the pattern.
556 (when (or (string-match
557 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
558 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
559 grep-default)
560 ;; If the string is not yet complete.
561 (string-match "\\(\\)\\'" grep-default))
562 ;; Maybe we will replace the pattern with the default tag.
563 ;; But first, maybe replace the file name pattern.
564 (condition-case nil
565 (unless (or (not (stringp buffer-file-name))
566 (when (match-beginning 2)
567 (save-match-data
568 (string-match
569 (wildcard-to-regexp
570 (file-name-nondirectory
571 (match-string 3 grep-default)))
572 (file-name-nondirectory buffer-file-name)))))
573 (setq grep-default (concat (substring grep-default
574 0 (match-beginning 2))
575 " *."
576 (file-name-extension buffer-file-name))))
577 ;; In case wildcard-to-regexp gets an error
578 ;; from invalid data.
579 (error nil))
580 ;; Now replace the pattern with the default tag.
581 (replace-match tag-default t t grep-default 1))))
584 ;;;###autoload
585 (define-compilation-mode grep-mode "Grep"
586 "Sets `grep-last-buffer' and `compilation-window-height'."
587 (setq grep-last-buffer (current-buffer))
588 (set (make-local-variable 'compilation-error-face)
589 grep-hit-face)
590 (set (make-local-variable 'compilation-error-regexp-alist)
591 grep-regexp-alist)
592 (set (make-local-variable 'compilation-process-setup-function)
593 'grep-process-setup)
594 (set (make-local-variable 'compilation-disable-input) t))
597 ;;;###autoload
598 (defun grep (command-args)
599 "Run grep, with user-specified args, and collect output in a buffer.
600 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
601 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
602 output buffer, to go to the lines where grep
603 found matches.
605 For doing a recursive `grep', see the `rgrep' command. For running
606 `grep' in a specific directory, see `lgrep'.
608 This command uses a special history list for its COMMAND-ARGS, so you
609 can easily repeat a grep command.
611 A prefix argument says to default the argument based upon the current
612 tag the cursor is over, substituting it into the last grep command
613 in the grep command history (or into `grep-command' if that history
614 list is empty)."
615 (interactive
616 (progn
617 (grep-compute-defaults)
618 (let ((default (grep-default-command)))
619 (list (read-from-minibuffer "Run grep (like this): "
620 (if current-prefix-arg
621 default grep-command)
622 nil nil 'grep-history
623 (if current-prefix-arg nil default))))))
625 ;; Setting process-setup-function makes exit-message-function work
626 ;; even when async processes aren't supported.
627 (compilation-start (if (and grep-use-null-device null-device)
628 (concat command-args " " null-device)
629 command-args)
630 'grep-mode))
633 ;;;###autoload
634 (defun grep-find (command-args)
635 "Run grep via find, with user-specified args COMMAND-ARGS.
636 Collect output in a buffer.
637 While find runs asynchronously, you can use the \\[next-error] command
638 to find the text that grep hits refer to.
640 This command uses a special history list for its arguments, so you can
641 easily repeat a find command."
642 (interactive
643 (progn
644 (grep-compute-defaults)
645 (if grep-find-command
646 (list (read-from-minibuffer "Run find (like this): "
647 grep-find-command nil nil
648 'grep-find-history))
649 ;; No default was set
650 (read-string
651 "compile.el: No `grep-find-command' command available. Press RET.")
652 (list nil))))
653 (when command-args
654 (let ((null-device nil)) ; see grep
655 (grep command-args))))
657 ;;;###autoload
658 (defalias 'find-grep 'grep-find)
661 ;; User-friendly interactive API.
663 (defconst grep-expand-keywords
664 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
665 ("<D>" . dir)
666 ("<F>" . files)
667 ("<N>" . null-device)
668 ("<X>" . excl)
669 ("<R>" . (shell-quote-argument (or regexp ""))))
670 "List of substitutions performed by `grep-expand-template'.
671 If car of an element matches, the cdr is evalled in to get the
672 substitution string. Note dynamic scoping of variables.")
674 (defun grep-expand-template (template &optional regexp files dir excl)
675 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
676 (let ((command template)
677 (cf case-fold-search)
678 (case-fold-search nil))
679 (dolist (kw grep-expand-keywords command)
680 (if (string-match (car kw) command)
681 (setq command
682 (replace-match
683 (or (if (symbolp (cdr kw))
684 (symbol-value (cdr kw))
685 (save-match-data (eval (cdr kw))))
687 t t command))))))
689 (defun grep-read-regexp ()
690 "Read regexp arg for interactive grep."
691 (let ((default (grep-tag-default)))
692 (read-string
693 (concat "Search for"
694 (if (and default (> (length default) 0))
695 (format " (default \"%s\"): " default) ": "))
696 nil 'grep-regexp-history default)))
698 (defun grep-read-files (regexp)
699 "Read files arg for interactive grep."
700 (let* ((bn (or (buffer-file-name) (buffer-name)))
701 (fn (and bn
702 (stringp bn)
703 (file-name-nondirectory bn)))
704 (default
705 (or (and fn
706 (let ((aliases grep-files-aliases)
707 alias)
708 (while aliases
709 (setq alias (car aliases)
710 aliases (cdr aliases))
711 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
712 (setq aliases nil)
713 (setq alias nil)))
714 (cdr alias)))
715 (and fn
716 (let ((ext (file-name-extension fn)))
717 (and ext (concat "*." ext))))
718 (car grep-files-history)
719 (car (car grep-files-aliases))))
720 (files (read-string
721 (concat "Search for \"" regexp
722 "\" in files"
723 (if default (concat " (default " default ")"))
724 ": ")
725 nil 'grep-files-history default)))
726 (and files
727 (or (cdr (assoc files grep-files-aliases))
728 files))))
730 ;;;###autoload
731 (defun lgrep (regexp &optional files dir)
732 "Run grep, searching for REGEXP in FILES in directory DIR.
733 The search is limited to file names matching shell pattern FILES.
734 FILES may use abbreviations defined in `grep-files-aliases', e.g.
735 entering `ch' is equivalent to `*.[ch]'.
737 With \\[universal-argument] prefix, you can edit the constructed shell command line
738 before it is executed.
739 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
741 Collect output in a buffer. While grep runs asynchronously, you
742 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
743 in the grep output buffer,
744 to go to the lines where grep found matches.
746 This command shares argument histories with \\[rgrep] and \\[grep]."
747 (interactive
748 (progn
749 (grep-compute-defaults)
750 (cond
751 ((and grep-command (equal current-prefix-arg '(16)))
752 (list (read-from-minibuffer "Run: " grep-command
753 nil nil 'grep-history)
754 nil))
755 ((not grep-template)
756 (list nil
757 (read-string "grep.el: No `grep-template' available. Press RET.")))
758 (t (let* ((regexp (grep-read-regexp))
759 (files (grep-read-files regexp))
760 (dir (read-directory-name "In directory: "
761 nil default-directory t)))
762 (list regexp files dir))))))
763 (when (and (stringp regexp) (> (length regexp) 0))
764 (let ((command regexp))
765 (if (null files)
766 (if (string= command grep-command)
767 (setq command nil))
768 (setq dir (file-name-as-directory (expand-file-name dir)))
769 (setq command (grep-expand-template
770 grep-template
771 regexp
772 files))
773 (when command
774 (if (equal current-prefix-arg '(4))
775 (setq command
776 (read-from-minibuffer "Confirm: "
777 command nil nil 'grep-history))
778 (add-to-history 'grep-history command))))
779 (when command
780 (let ((default-directory dir))
781 ;; Setting process-setup-function makes exit-message-function work
782 ;; even when async processes aren't supported.
783 (compilation-start (if (and grep-use-null-device null-device)
784 (concat command " " null-device)
785 command)
786 'grep-mode))
787 (if (eq next-error-last-buffer (current-buffer))
788 (setq default-directory dir))))))
792 ;;;###autoload
793 (defun rgrep (regexp &optional files dir)
794 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
795 The search is limited to file names matching shell pattern FILES.
796 FILES may use abbreviations defined in `grep-files-aliases', e.g.
797 entering `ch' is equivalent to `*.[ch]'.
799 With \\[universal-argument] prefix, you can edit the constructed shell command line
800 before it is executed.
801 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
803 Collect output in a buffer. While find runs asynchronously, you
804 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
805 in the grep output buffer,
806 to go to the lines where grep found matches.
808 This command shares argument histories with \\[lgrep] and \\[grep-find]."
809 (interactive
810 (progn
811 (grep-compute-defaults)
812 (cond
813 ((and grep-find-command (equal current-prefix-arg '(16)))
814 (list (read-from-minibuffer "Run: " grep-find-command
815 nil nil 'grep-find-history)
816 nil))
817 ((not grep-find-template)
818 (list nil nil
819 (read-string "grep.el: No `grep-find-template' available. Press RET.")))
820 (t (let* ((regexp (grep-read-regexp))
821 (files (grep-read-files regexp))
822 (dir (read-directory-name "Base directory: "
823 nil default-directory t)))
824 (list regexp files dir))))))
825 (when (and (stringp regexp) (> (length regexp) 0))
826 (if (null files)
827 (if (not (string= regexp grep-find-command))
828 (compilation-start regexp 'grep-mode))
829 (setq dir (file-name-as-directory (expand-file-name dir)))
830 (let ((command (grep-expand-template
831 grep-find-template
832 regexp
833 (concat (shell-quote-argument "(")
834 " " find-name-arg " "
835 (mapconcat #'shell-quote-argument
836 (split-string files)
837 (concat " -o " find-name-arg " "))
839 (shell-quote-argument ")"))
841 (and grep-find-ignored-directories
842 (concat (shell-quote-argument "(")
843 ;; we should use shell-quote-argument here
844 " -path "
845 (mapconcat #'(lambda (dir)
846 (shell-quote-argument
847 (concat "*/" dir)))
848 grep-find-ignored-directories
849 " -o -path ")
851 (shell-quote-argument ")")
852 " -prune -o ")))))
853 (when command
854 (if current-prefix-arg
855 (setq command
856 (read-from-minibuffer "Confirm: "
857 command nil nil 'grep-find-history))
858 (add-to-history 'grep-find-history command))
859 (let ((default-directory dir))
860 (compilation-start command 'grep-mode))
861 ;; Set default-directory if we started rgrep in the *grep* buffer.
862 (if (eq next-error-last-buffer (current-buffer))
863 (setq default-directory dir)))))))
866 (provide 'grep)
868 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
869 ;;; grep.el ends here