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