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