Fix typos.
[emacs.git] / lisp / progmodes / grep.el
blob64e7dfdd1741b47a29c1fe3fedfa01370f996625
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, 2009
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 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/>.
26 ;;; Commentary:
28 ;; This package provides the grep facilities documented in the Emacs
29 ;; user's manual.
31 ;;; Code:
33 (require 'compile)
36 (defgroup grep nil
37 "Run grep as inferior of Emacs, parse error messages."
38 :group 'tools
39 :group 'processes)
41 (defvar grep-host-defaults-alist nil
42 "Default values depending on target host.
43 `grep-compute-defaults' returns default values for every local or
44 remote host `grep' runs. These values can differ from host to
45 host. Once computed, the default values are kept here in order
46 to avoid computing them again.")
48 (defun grep-apply-setting (symbol value)
49 "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
50 SYMBOL should be one of `grep-command', `grep-template',
51 `grep-use-null-device', `grep-find-command',
52 `grep-find-template', `grep-find-use-xargs', or
53 `grep-highlight-matches'."
54 (when grep-host-defaults-alist
55 (let* ((host-id
56 (intern (or (file-remote-p default-directory) "localhost")))
57 (host-defaults (assq host-id grep-host-defaults-alist))
58 (defaults (assq nil grep-host-defaults-alist)))
59 (setcar (cdr (assq symbol host-defaults)) value)
60 (setcar (cdr (assq symbol defaults)) value)))
61 (set-default symbol value))
63 ;;;###autoload
64 (defcustom grep-window-height nil
65 "*Number of lines in a grep window. If nil, use `compilation-window-height'."
66 :type '(choice (const :tag "Default" nil)
67 integer)
68 :version "22.1"
69 :group 'grep)
71 (defcustom grep-highlight-matches 'auto-detect
72 "If t, use special markers to highlight grep matches.
74 Some grep programs are able to surround matches with special
75 markers in grep output. Such markers can be used to highlight
76 matches in grep mode.
78 This option sets the environment variable GREP_COLOR to specify
79 markers for highlighting and GREP_OPTIONS to add the --color
80 option in front of any explicit grep options before starting
81 the grep.
83 In interactive usage, the actual value of this variable is set up
84 by `grep-compute-defaults'; to change the default value, use
85 Customize or call the function `grep-apply-setting'."
86 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
87 (const :tag "Highlight matches with grep markers" t)
88 (other :tag "Not Set" auto-detect))
89 :set 'grep-apply-setting
90 :version "22.1"
91 :group 'grep)
93 (defcustom grep-scroll-output nil
94 "*Non-nil to scroll the *grep* buffer window as output appears.
96 Setting it causes the grep commands to put point at the end of their
97 output window so that the end of the output is always visible rather
98 than the begining."
99 :type 'boolean
100 :version "22.1"
101 :group 'grep)
103 ;;;###autoload
104 (defcustom grep-command nil
105 "The default grep command for \\[grep].
106 If the grep program used supports an option to always include file names
107 in its output (such as the `-H' option to GNU grep), it's a good idea to
108 include it when specifying `grep-command'.
110 In interactive usage, the actual value of this variable is set up
111 by `grep-compute-defaults'; to change the default value, use
112 Customize or call the function `grep-apply-setting'."
113 :type '(choice string
114 (const :tag "Not Set" nil))
115 :set 'grep-apply-setting
116 :group 'grep)
118 (defcustom grep-template nil
119 "The default command to run for \\[lgrep].
120 The following place holders should be present in the string:
121 <C> - place to put -i if case insensitive grep.
122 <F> - file names and wildcards to search.
123 <X> - file names and wildcards to exclude.
124 <R> - the regular expression searched for.
125 <N> - place to insert null-device.
127 In interactive usage, the actual value of this variable is set up
128 by `grep-compute-defaults'; to change the default value, use
129 Customize or call the function `grep-apply-setting'."
130 :type '(choice string
131 (const :tag "Not Set" nil))
132 :set 'grep-apply-setting
133 :version "22.1"
134 :group 'grep)
136 (defcustom grep-use-null-device 'auto-detect
137 "If t, append the value of `null-device' to `grep' commands.
138 This is done to ensure that the output of grep includes the filename of
139 any match in the case where only a single file is searched, and is not
140 necessary if the grep program used supports the `-H' option.
142 In interactive usage, the actual value of this variable is set up
143 by `grep-compute-defaults'; to change the default value, use
144 Customize or call the function `grep-apply-setting'."
145 :type '(choice (const :tag "Do Not Append Null Device" nil)
146 (const :tag "Append Null Device" t)
147 (other :tag "Not Set" auto-detect))
148 :set 'grep-apply-setting
149 :group 'grep)
151 ;;;###autoload
152 (defcustom grep-find-command nil
153 "The default find command for \\[grep-find].
154 In interactive usage, the actual value of this variable is set up
155 by `grep-compute-defaults'; to change the default value, use
156 Customize or call the function `grep-apply-setting'."
157 :type '(choice string
158 (const :tag "Not Set" nil))
159 :set 'grep-apply-setting
160 :group 'grep)
162 (defcustom grep-find-template nil
163 "The default command to run for \\[rgrep].
164 The following place holders should be present in the string:
165 <D> - base directory for find
166 <X> - find options to restrict or expand the directory list
167 <F> - find options to limit the files matched
168 <C> - place to put -i if case insensitive grep
169 <R> - the regular expression searched for.
170 In interactive usage, the actual value of this variable is set up
171 by `grep-compute-defaults'; to change the default value, use
172 Customize or call the function `grep-apply-setting'."
173 :type '(choice string
174 (const :tag "Not Set" nil))
175 :set 'grep-apply-setting
176 :version "22.1"
177 :group 'grep)
179 (defcustom grep-files-aliases
180 '(("all" . "* .*")
181 ("el" . "*.el")
182 ("ch" . "*.[ch]")
183 ("c" . "*.c")
184 ("cc" . "*.cc *.cxx *.cpp *.C *.CC *.c++")
185 ("cchh" . "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
186 ("hh" . "*.hxx *.hpp *.[Hh] *.HH *.h++")
187 ("h" . "*.h")
188 ("l" . "[Cc]hange[Ll]og*")
189 ("m" . "[Mm]akefile*")
190 ("tex" . "*.tex")
191 ("texi" . "*.texi")
192 ("asm" . "*.[sS]"))
193 "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
194 :type 'alist
195 :group 'grep)
197 (defcustom grep-find-ignored-directories
198 vc-directory-exclusion-list
199 "*List of names of sub-directories which `rgrep' shall not recurse into.
200 If an element is a cons cell, the car is called on the search directory
201 to determine whether cdr should not be recursed into."
202 :type '(choice (repeat :tag "Ignored directories" string)
203 (const :tag "No ignored directories" nil))
204 :group 'grep)
206 (defcustom grep-find-ignored-files
207 (cons ".#*" (delq nil (mapcar (lambda (s)
208 (unless (string-match-p "/\\'" s)
209 (concat "*" s)))
210 completion-ignored-extensions)))
211 "*List of file names which `rgrep' and `lgrep' shall exclude.
212 If an element is a cons cell, the car is called on the search directory
213 to determine whether cdr should not be excluded."
214 :type '(choice (repeat :tag "Ignored file" string)
215 (const :tag "No ignored files" nil))
216 :group 'grep)
218 (defcustom grep-error-screen-columns nil
219 "*If non-nil, column numbers in grep hits are screen columns.
220 See `compilation-error-screen-columns'"
221 :type '(choice (const :tag "Default" nil)
222 integer)
223 :version "22.1"
224 :group 'grep)
226 ;;;###autoload
227 (defcustom grep-setup-hook nil
228 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
229 :type 'hook
230 :group 'grep)
232 (defvar grep-mode-map
233 (let ((map (make-sparse-keymap)))
234 (set-keymap-parent map compilation-minor-mode-map)
235 (define-key map " " 'scroll-up)
236 (define-key map "\^?" 'scroll-down)
237 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
239 (define-key map "\r" 'compile-goto-error) ;; ?
240 (define-key map "n" 'next-error-no-select)
241 (define-key map "p" 'previous-error-no-select)
242 (define-key map "{" 'compilation-previous-file)
243 (define-key map "}" 'compilation-next-file)
244 (define-key map "\t" 'compilation-next-error)
245 (define-key map [backtab] 'compilation-previous-error)
247 ;; Set up the menu-bar
248 (define-key map [menu-bar grep]
249 (cons "Grep" (make-sparse-keymap "Grep")))
251 (define-key map [menu-bar grep compilation-kill-compilation]
252 '(menu-item "Kill Grep" kill-compilation
253 :help "Kill the currently running grep process"))
254 (define-key map [menu-bar grep compilation-separator2] '("----"))
255 (define-key map [menu-bar grep compilation-compile]
256 '(menu-item "Compile..." compile
257 :help "Compile the program including the current buffer. Default: run `make'"))
258 (define-key map [menu-bar grep compilation-rgrep]
259 '(menu-item "Recursive grep..." rgrep
260 :help "User-friendly recursive grep in directory tree"))
261 (define-key map [menu-bar grep compilation-lgrep]
262 '(menu-item "Local grep..." lgrep
263 :help "User-friendly grep in a directory"))
264 (define-key map [menu-bar grep compilation-grep-find]
265 '(menu-item "Grep via Find..." grep-find
266 :help "Run grep via find, with user-specified args"))
267 (define-key map [menu-bar grep compilation-grep]
268 '(menu-item "Another grep..." grep
269 :help "Run grep, with user-specified args, and collect output in a buffer."))
270 (define-key map [menu-bar grep compilation-recompile]
271 '(menu-item "Repeat grep" recompile
272 :help "Run grep again"))
273 (define-key map [menu-bar grep compilation-separator2] '("----"))
274 (define-key map [menu-bar grep compilation-first-error]
275 '(menu-item "First Match" first-error
276 :help "Restart at the first match, visit corresponding location"))
277 (define-key map [menu-bar grep compilation-previous-error]
278 '(menu-item "Previous Match" previous-error
279 :help "Visit the previous match and corresponding location"))
280 (define-key map [menu-bar grep compilation-next-error]
281 '(menu-item "Next Match" next-error
282 :help "Visit the next match and corresponding location"))
283 map)
284 "Keymap for grep buffers.
285 `compilation-minor-mode-map' is a cdr of this.")
287 (defvar grep-mode-tool-bar-map
288 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
289 ;; so don't do anything.
290 (when (keymapp (butlast tool-bar-map))
291 (let ((map (butlast (copy-keymap tool-bar-map)))
292 (help (last tool-bar-map))) ;; Keep Help last in tool bar
293 (tool-bar-local-item
294 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
295 :rtl "right-arrow"
296 :help "Goto previous match")
297 (tool-bar-local-item
298 "right-arrow" 'next-error-no-select 'next-error-no-select map
299 :rtl "left-arrow"
300 :help "Goto next match")
301 (tool-bar-local-item
302 "cancel" 'kill-compilation 'kill-compilation map
303 :enable '(let ((buffer (compilation-find-buffer)))
304 (get-buffer-process buffer))
305 :help "Stop grep")
306 (tool-bar-local-item
307 "refresh" 'recompile 'recompile map
308 :help "Restart grep")
309 (append map help))))
311 (defalias 'kill-grep 'kill-compilation)
313 ;;;; TODO --- refine this!!
315 ;; (defcustom grep-use-compilation-buffer t
316 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
317 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
318 ;; can be used to navigate between grep matches (the default).
319 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
320 ;; be used to navigate between grep matches."
321 ;; :type 'boolean
322 ;; :group 'grep)
324 ;; override compilation-last-buffer
325 (defvar grep-last-buffer nil
326 "The most recent grep buffer.
327 A grep buffer becomes most recent when you select Grep mode in it.
328 Notice that using \\[next-error] or \\[compile-goto-error] modifies
329 `complation-last-buffer' rather than `grep-last-buffer'.")
331 ;;;###autoload
332 (defvar grep-regexp-alist
333 '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
334 1 3)
335 ;; Rule to match column numbers is commented out since no known grep
336 ;; produces them
337 ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
338 ;; 1 3 (4 . 5))
339 ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
340 \\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
342 ;; Calculate column positions (beg . end) of first grep match on a line
343 ((lambda ()
344 (setq compilation-error-screen-columns nil)
345 (- (match-beginning 4) (match-end 1)))
347 (lambda () (- (match-end 5) (match-end 1)
348 (- (match-end 4) (match-beginning 4)))))
349 nil 1)
350 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
351 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
353 (defvar grep-error "grep hit"
354 "Message to print when no matches are found.")
356 ;; Reverse the colors because grep hits are not errors (though we jump there
357 ;; with `next-error'), and unreadable files can't be gone to.
358 (defvar grep-hit-face compilation-info-face
359 "Face name to use for grep hits.")
361 (defvar grep-error-face 'compilation-error
362 "Face name to use for grep error messages.")
364 (defvar grep-match-face 'match
365 "Face name to use for grep matches.")
367 (defvar grep-context-face 'shadow
368 "Face name to use for grep context lines.")
370 (defvar grep-mode-font-lock-keywords
371 '(;; Command output lines.
372 ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
373 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
374 1 grep-error-face)
375 ;; remove match from grep-regexp-alist before fontifying
376 ("^Grep[/a-zA-z]* started.*"
377 (0 '(face nil message nil help-echo nil mouse-face nil) t))
378 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
379 (0 '(face nil message nil help-echo nil mouse-face nil) t)
380 (1 compilation-info-face nil t)
381 (2 compilation-warning-face nil t))
382 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
383 (0 '(face nil message nil help-echo nil mouse-face nil) t)
384 (1 grep-error-face)
385 (2 grep-error-face nil t))
386 ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
387 ;; Highlight grep matches and delete markers
388 ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
389 ;; Refontification does not work after the markers have been
390 ;; deleted. So we use the font-lock-face property here as Font
391 ;; Lock does not clear that.
392 (2 (list 'face nil 'font-lock-face grep-match-face))
393 ((lambda (bound))
394 (progn
395 ;; Delete markers with `replace-match' because it updates
396 ;; the match-data, whereas `delete-region' would render it obsolete.
397 (replace-match "" t t nil 3)
398 (replace-match "" t t nil 1))))
399 ("\\(\033\\[[0-9;]*[mK]\\)"
400 ;; Delete all remaining escape sequences
401 ((lambda (bound))
402 (replace-match "" t t nil 1))))
403 "Additional things to highlight in grep output.
404 This gets tacked on the end of the generated expressions.")
406 ;;;###autoload
407 (defvar grep-program "grep"
408 "The default grep program for `grep-command' and `grep-find-command'.
409 This variable's value takes effect when `grep-compute-defaults' is called.")
411 ;;;###autoload
412 (defvar find-program "find"
413 "The default find program for `grep-find-command'.
414 This variable's value takes effect when `grep-compute-defaults' is called.")
416 ;;;###autoload
417 (defvar xargs-program "xargs"
418 "The default xargs program for `grep-find-command'.
419 See `grep-find-use-xargs'.
420 This variable's value takes effect when `grep-compute-defaults' is called.")
422 ;;;###autoload
423 (defvar grep-find-use-xargs nil
424 "Non-nil means that `grep-find' uses the `xargs' utility by default.
425 If `exec', use `find -exec'.
426 If `gnu', use `find -print0' and `xargs -0'.
427 Any other non-nil value means to use `find -print' and `xargs'.
429 This variable's value takes effect when `grep-compute-defaults' is called.")
431 ;; History of grep commands.
432 ;;;###autoload
433 (defvar grep-history nil)
434 ;;;###autoload
435 (defvar grep-find-history nil)
437 ;; History of lgrep and rgrep regexp and files args.
438 (defvar grep-regexp-history nil)
439 (defvar grep-files-history nil)
441 ;;;###autoload
442 (defun grep-process-setup ()
443 "Setup compilation variables and buffer for `grep'.
444 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
445 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
446 (grep-compute-defaults))
447 (when (eq grep-highlight-matches t)
448 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
449 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
450 (setenv "TERM" "emacs-grep")
451 ;; `--color=auto' emits escape sequences on a tty rather than on a pipe,
452 ;; thus allowing to use multiple grep filters on the command line
453 ;; and to output escape sequences only on the final grep output
454 (setenv "GREP_OPTIONS"
455 (concat (getenv "GREP_OPTIONS")
456 ;; Windows and DOS pipes fail `isatty' detection in Grep.
457 " --color=" (if (memq system-type '(windows-nt ms-dos))
458 "always" "auto")))
459 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
460 (setenv "GREP_COLOR" "01;31")
461 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
462 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
463 (set (make-local-variable 'compilation-exit-message-function)
464 (lambda (status code msg)
465 (if (eq status 'exit)
466 (cond ((zerop code)
467 '("finished (matches found)\n" . "matched"))
468 ((= code 1)
469 '("finished with no matches found\n" . "no match"))
471 (cons msg code)))
472 (cons msg code))))
473 (run-hooks 'grep-setup-hook))
475 (defun grep-probe (command args &optional func result)
476 (let (process-file-side-effects)
477 (equal (condition-case nil
478 (apply (or func 'process-file) command args)
479 (error nil))
480 (or result 0))))
482 ;;;###autoload
483 (defun grep-compute-defaults ()
484 ;; Keep default values.
485 (unless grep-host-defaults-alist
486 (add-to-list
487 'grep-host-defaults-alist
488 (cons nil
489 `((grep-command ,grep-command)
490 (grep-template ,grep-template)
491 (grep-use-null-device ,grep-use-null-device)
492 (grep-find-command ,grep-find-command)
493 (grep-find-template ,grep-find-template)
494 (grep-find-use-xargs ,grep-find-use-xargs)
495 (grep-highlight-matches ,grep-highlight-matches)))))
496 (let* ((host-id
497 (intern (or (file-remote-p default-directory) "localhost")))
498 (host-defaults (assq host-id grep-host-defaults-alist))
499 (defaults (assq nil grep-host-defaults-alist)))
500 ;; There are different defaults on different hosts. They must be
501 ;; computed for every host once.
502 (dolist (setting '(grep-command grep-template
503 grep-use-null-device grep-find-command
504 grep-find-template grep-find-use-xargs
505 grep-highlight-matches))
506 (set setting
507 (or (cadr (assq setting host-defaults))
508 (cadr (assq setting defaults)))))
510 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
511 (setq grep-use-null-device
512 (with-temp-buffer
513 (let ((hello-file (expand-file-name "HELLO" data-directory)))
514 (not
515 (and (if grep-command
516 ;; `grep-command' is already set, so
517 ;; use that for testing.
518 (grep-probe grep-command
519 `(nil t nil "^English" ,hello-file)
520 #'call-process-shell-command)
521 ;; otherwise use `grep-program'
522 (grep-probe grep-program
523 `(nil t nil "-nH" "^English" ,hello-file)))
524 (progn
525 (goto-char (point-min))
526 (looking-at
527 (concat (regexp-quote hello-file)
528 ":[0-9]+:English")))))))))
529 (unless (and grep-command grep-find-command
530 grep-template grep-find-template)
531 (let ((grep-options
532 (concat (if grep-use-null-device "-n" "-nH")
533 (if (grep-probe grep-program
534 `(nil nil nil "-e" "foo" ,null-device)
535 nil 1)
536 " -e"))))
537 (unless grep-command
538 (setq grep-command
539 (format "%s %s " grep-program grep-options)))
540 (unless grep-template
541 (setq grep-template
542 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
543 (unless grep-find-use-xargs
544 (setq grep-find-use-xargs
545 (cond
546 ((and
547 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
548 (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
549 'gnu)
551 'exec))))
552 (unless grep-find-command
553 (setq grep-find-command
554 (cond ((eq grep-find-use-xargs 'gnu)
555 (format "%s . -type f -print0 | %s -0 -e %s"
556 find-program xargs-program grep-command))
557 ((eq grep-find-use-xargs 'exec)
558 (let ((cmd0 (format "%s . -type f -exec %s"
559 find-program grep-command)))
560 (cons
561 (format "%s {} %s %s"
562 cmd0 null-device
563 (shell-quote-argument ";"))
564 (1+ (length cmd0)))))
566 (format "%s . -type f -print | %s %s"
567 find-program xargs-program grep-command)))))
568 (unless grep-find-template
569 (setq grep-find-template
570 (let ((gcmd (format "%s <C> %s <R>"
571 grep-program grep-options)))
572 (cond ((eq grep-find-use-xargs 'gnu)
573 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
574 find-program xargs-program gcmd))
575 ((eq grep-find-use-xargs 'exec)
576 (format "%s . <X> -type f <F> -exec %s {} %s %s"
577 find-program gcmd null-device
578 (shell-quote-argument ";")))
580 (format "%s . <X> -type f <F> -print | %s %s"
581 find-program xargs-program gcmd))))))))
582 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
583 (setq grep-highlight-matches
584 (with-temp-buffer
585 (and (grep-probe grep-program '(nil t nil "--help"))
586 (progn
587 (goto-char (point-min))
588 (search-forward "--color" nil t))
589 t))))
591 ;; Save defaults for this host.
592 (setq grep-host-defaults-alist
593 (delete (assq host-id grep-host-defaults-alist)
594 grep-host-defaults-alist))
595 (add-to-list
596 'grep-host-defaults-alist
597 (cons host-id
598 `((grep-command ,grep-command)
599 (grep-template ,grep-template)
600 (grep-use-null-device ,grep-use-null-device)
601 (grep-find-command ,grep-find-command)
602 (grep-find-template ,grep-find-template)
603 (grep-find-use-xargs ,grep-find-use-xargs)
604 (grep-highlight-matches ,grep-highlight-matches))))))
606 (defun grep-tag-default ()
607 (or (and transient-mark-mode mark-active
608 (/= (point) (mark))
609 (buffer-substring-no-properties (point) (mark)))
610 (funcall (or find-tag-default-function
611 (get major-mode 'find-tag-default-function)
612 'find-tag-default))
613 ""))
615 (defun grep-default-command ()
616 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
617 (let ((tag-default (shell-quote-argument (grep-tag-default)))
618 ;; This a regexp to match single shell arguments.
619 ;; Could someone please add comments explaining it?
620 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
621 (grep-default (or (car grep-history) grep-command)))
622 ;; In the default command, find the arg that specifies the pattern.
623 (when (or (string-match
624 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
625 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
626 grep-default)
627 ;; If the string is not yet complete.
628 (string-match "\\(\\)\\'" grep-default))
629 ;; Maybe we will replace the pattern with the default tag.
630 ;; But first, maybe replace the file name pattern.
631 (condition-case nil
632 (unless (or (not (stringp buffer-file-name))
633 (when (match-beginning 2)
634 (save-match-data
635 (string-match
636 (wildcard-to-regexp
637 (file-name-nondirectory
638 (match-string 3 grep-default)))
639 (file-name-nondirectory buffer-file-name)))))
640 (setq grep-default (concat (substring grep-default
641 0 (match-beginning 2))
642 " *."
643 (file-name-extension buffer-file-name))))
644 ;; In case wildcard-to-regexp gets an error
645 ;; from invalid data.
646 (error nil))
647 ;; Now replace the pattern with the default tag.
648 (replace-match tag-default t t grep-default 1))))
651 ;;;###autoload
652 (define-compilation-mode grep-mode "Grep"
653 "Sets `grep-last-buffer' and `compilation-window-height'."
654 (setq grep-last-buffer (current-buffer))
655 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
656 (set (make-local-variable 'compilation-error-face)
657 grep-hit-face)
658 (set (make-local-variable 'compilation-error-regexp-alist)
659 grep-regexp-alist)
660 (set (make-local-variable 'compilation-process-setup-function)
661 'grep-process-setup)
662 (set (make-local-variable 'compilation-disable-input) t))
665 ;;;###autoload
666 (defun grep (command-args)
667 "Run grep, with user-specified args, and collect output in a buffer.
668 While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
669 or \\<grep-mode-map>\\[compile-goto-error] in the grep \
670 output buffer, to go to the lines where grep
671 found matches.
673 For doing a recursive `grep', see the `rgrep' command. For running
674 `grep' in a specific directory, see `lgrep'.
676 This command uses a special history list for its COMMAND-ARGS, so you
677 can easily repeat a grep command.
679 A prefix argument says to default the argument based upon the current
680 tag the cursor is over, substituting it into the last grep command
681 in the grep command history (or into `grep-command' if that history
682 list is empty)."
683 (interactive
684 (progn
685 (grep-compute-defaults)
686 (let ((default (grep-default-command)))
687 (list (read-shell-command "Run grep (like this): "
688 (if current-prefix-arg default grep-command)
689 'grep-history
690 (if current-prefix-arg nil default))))))
692 ;; Setting process-setup-function makes exit-message-function work
693 ;; even when async processes aren't supported.
694 (compilation-start (if (and grep-use-null-device null-device)
695 (concat command-args " " null-device)
696 command-args)
697 'grep-mode))
700 ;;;###autoload
701 (defun grep-find (command-args)
702 "Run grep via find, with user-specified args COMMAND-ARGS.
703 Collect output in a buffer.
704 While find runs asynchronously, you can use the \\[next-error] command
705 to find the text that grep hits refer to.
707 This command uses a special history list for its arguments, so you can
708 easily repeat a find command."
709 (interactive
710 (progn
711 (grep-compute-defaults)
712 (if grep-find-command
713 (list (read-shell-command "Run find (like this): "
714 grep-find-command 'grep-find-history))
715 ;; No default was set
716 (read-string
717 "compile.el: No `grep-find-command' command available. Press RET.")
718 (list nil))))
719 (when command-args
720 (let ((null-device nil)) ; see grep
721 (grep command-args))))
723 ;;;###autoload
724 (defalias 'find-grep 'grep-find)
727 ;; User-friendly interactive API.
729 (defconst grep-expand-keywords
730 '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
731 ("<D>" . dir)
732 ("<F>" . files)
733 ("<N>" . null-device)
734 ("<X>" . excl)
735 ("<R>" . (shell-quote-argument (or regexp ""))))
736 "List of substitutions performed by `grep-expand-template'.
737 If car of an element matches, the cdr is evalled in to get the
738 substitution string. Note dynamic scoping of variables.")
740 (defun grep-expand-template (template &optional regexp files dir excl)
741 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
742 (let ((command template)
743 (cf case-fold-search)
744 (case-fold-search nil))
745 (dolist (kw grep-expand-keywords command)
746 (if (string-match (car kw) command)
747 (setq command
748 (replace-match
749 (or (if (symbolp (cdr kw))
750 (symbol-value (cdr kw))
751 (save-match-data (eval (cdr kw))))
753 t t command))))))
755 (defun grep-read-regexp ()
756 "Read regexp arg for interactive grep."
757 (let ((default (grep-tag-default)))
758 (read-string
759 (concat "Search for"
760 (if (and default (> (length default) 0))
761 (format " (default \"%s\"): " default) ": "))
762 nil 'grep-regexp-history default)))
764 (defun grep-read-files (regexp)
765 "Read files arg for interactive grep."
766 (let* ((bn (or (buffer-file-name)
767 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
768 (fn (and bn
769 (stringp bn)
770 (file-name-nondirectory bn)))
771 (default-alias
772 (and fn
773 (let ((aliases grep-files-aliases)
774 alias)
775 (while aliases
776 (setq alias (car aliases)
777 aliases (cdr aliases))
778 (if (string-match (wildcard-to-regexp (cdr alias)) fn)
779 (setq aliases nil)
780 (setq alias nil)))
781 (cdr alias))))
782 (default-extension
783 (and fn
784 (let ((ext (file-name-extension fn)))
785 (and ext (concat "*." ext)))))
786 (default
787 (or default-alias
788 default-extension
789 (car grep-files-history)
790 (car (car grep-files-aliases))))
791 (files (read-string
792 (concat "Search for \"" regexp
793 "\" in files"
794 (if default (concat " (default " default ")"))
795 ": ")
796 nil 'grep-files-history
797 (delete-dups
798 (delq nil (append (list default default-alias default-extension)
799 (mapcar 'car grep-files-aliases)))))))
800 (and files
801 (or (cdr (assoc files grep-files-aliases))
802 files))))
804 ;;;###autoload
805 (defun lgrep (regexp &optional files dir confirm)
806 "Run grep, searching for REGEXP in FILES in directory DIR.
807 The search is limited to file names matching shell pattern FILES.
808 FILES may use abbreviations defined in `grep-files-aliases', e.g.
809 entering `ch' is equivalent to `*.[ch]'.
811 With \\[universal-argument] prefix, you can edit the constructed shell command line
812 before it is executed.
813 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
815 Collect output in a buffer. While grep runs asynchronously, you
816 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
817 in the grep output buffer,
818 to go to the lines where grep found matches.
820 This command shares argument histories with \\[rgrep] and \\[grep]."
821 (interactive
822 (progn
823 (grep-compute-defaults)
824 (cond
825 ((and grep-command (equal current-prefix-arg '(16)))
826 (list (read-from-minibuffer "Run: " grep-command
827 nil nil 'grep-history)))
828 ((not grep-template)
829 (error "grep.el: No `grep-template' available"))
830 (t (let* ((regexp (grep-read-regexp))
831 (files (grep-read-files regexp))
832 (dir (read-directory-name "In directory: "
833 nil default-directory t))
834 (confirm (equal current-prefix-arg '(4))))
835 (list regexp files dir confirm))))))
836 (when (and (stringp regexp) (> (length regexp) 0))
837 (unless (and dir (file-directory-p dir) (file-readable-p dir))
838 (setq dir default-directory))
839 (let ((command regexp))
840 (if (null files)
841 (if (string= command grep-command)
842 (setq command nil))
843 (setq dir (file-name-as-directory (expand-file-name dir)))
844 (setq command (grep-expand-template
845 grep-template
846 regexp
847 files
849 (and grep-find-ignored-files
850 (concat " --exclude="
851 (mapconcat
852 #'(lambda (ignore)
853 (cond ((stringp ignore)
854 (shell-quote-argument ignore))
855 ((consp ignore)
856 (and (funcall (car ignore) dir)
857 (shell-quote-argument
858 (cdr ignore))))))
859 grep-find-ignored-files
860 " --exclude=")))))
861 (when command
862 (if confirm
863 (setq command
864 (read-from-minibuffer "Confirm: "
865 command nil nil 'grep-history))
866 (add-to-history 'grep-history command))))
867 (when command
868 (let ((default-directory dir))
869 ;; Setting process-setup-function makes exit-message-function work
870 ;; even when async processes aren't supported.
871 (compilation-start (if (and grep-use-null-device null-device)
872 (concat command " " null-device)
873 command)
874 'grep-mode))
875 (if (eq next-error-last-buffer (current-buffer))
876 (setq default-directory dir))))))
879 (defvar find-name-arg) ; autoloaded
881 ;;;###autoload
882 (defun rgrep (regexp &optional files dir confirm)
883 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
884 The search is limited to file names matching shell pattern FILES.
885 FILES may use abbreviations defined in `grep-files-aliases', e.g.
886 entering `ch' is equivalent to `*.[ch]'.
888 With \\[universal-argument] prefix, you can edit the constructed shell command line
889 before it is executed.
890 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
892 Collect output in a buffer. While find runs asynchronously, you
893 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
894 in the grep output buffer,
895 to go to the lines where grep found matches.
897 This command shares argument histories with \\[lgrep] and \\[grep-find]."
898 (interactive
899 (progn
900 (grep-compute-defaults)
901 (cond
902 ((and grep-find-command (equal current-prefix-arg '(16)))
903 (list (read-from-minibuffer "Run: " grep-find-command
904 nil nil 'grep-find-history)))
905 ((not grep-find-template)
906 (error "grep.el: No `grep-find-template' available"))
907 (t (let* ((regexp (grep-read-regexp))
908 (files (grep-read-files regexp))
909 (dir (read-directory-name "Base directory: "
910 nil default-directory t))
911 (confirm (equal current-prefix-arg '(4))))
912 (list regexp files dir confirm))))))
913 (when (and (stringp regexp) (> (length regexp) 0))
914 (unless (and dir (file-directory-p dir) (file-readable-p dir))
915 (setq dir default-directory))
916 (if (null files)
917 (if (not (string= regexp grep-find-command))
918 (compilation-start regexp 'grep-mode))
919 (setq dir (file-name-as-directory (expand-file-name dir)))
920 (let ((command (grep-expand-template
921 grep-find-template
922 regexp
923 (concat (shell-quote-argument "(")
924 " " find-name-arg " "
925 (mapconcat #'shell-quote-argument
926 (split-string files)
927 (concat " -o " find-name-arg " "))
929 (shell-quote-argument ")"))
931 (concat
932 (and grep-find-ignored-directories
933 (concat (shell-quote-argument "(")
934 ;; we should use shell-quote-argument here
935 " -path "
936 (mapconcat
937 #'(lambda (ignore)
938 (cond ((stringp ignore)
939 (shell-quote-argument
940 (concat "*/" ignore)))
941 ((consp ignore)
942 (and (funcall (car ignore) dir)
943 (shell-quote-argument
944 (concat "*/"
945 (cdr ignore)))))))
946 grep-find-ignored-directories
947 " -o -path ")
949 (shell-quote-argument ")")
950 " -prune -o "))
951 (and grep-find-ignored-files
952 (concat (shell-quote-argument "(")
953 ;; we should use shell-quote-argument here
954 " -name "
955 (mapconcat
956 #'(lambda (ignore)
957 (cond ((stringp ignore)
958 (shell-quote-argument ignore))
959 ((consp ignore)
960 (and (funcall (car ignore) dir)
961 (shell-quote-argument
962 (cdr ignore))))))
963 grep-find-ignored-files
964 " -o -name ")
966 (shell-quote-argument ")")
967 " -prune -o "))))))
968 (when command
969 (if confirm
970 (setq command
971 (read-from-minibuffer "Confirm: "
972 command nil nil 'grep-find-history))
973 (add-to-history 'grep-find-history command))
974 (let ((default-directory dir))
975 (compilation-start command 'grep-mode))
976 ;; Set default-directory if we started rgrep in the *grep* buffer.
977 (if (eq next-error-last-buffer (current-buffer))
978 (setq default-directory dir)))))))
981 (provide 'grep)
983 ;; arch-tag: 5a5b9169-a79d-4f38-9c38-f69615f39c4d
984 ;;; grep.el ends here