grep.el 37.6 KB
Newer Older
Eli Zaretskii's avatar
Eli Zaretskii committed
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,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
5
;;   Free Software Foundation, Inc.
6 7 8 9 10 11 12

;; Author: Roland McGrath <roland@gnu.org>
;; Maintainer: FSF
;; Keywords: tools, processes

;; 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 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
17 18 19 20 21 22 23

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; 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 27 28 29 30 31 32 33 34

;;; Commentary:

;; This package provides the grep facilities documented in the Emacs
;; user's manual.

;;; Code:

(require 'compile)

35

36
(defgroup grep nil
Kim F. Storm's avatar
Kim F. Storm committed
37
  "Run grep as inferior of Emacs, parse error messages."
38 39 40
  :group 'tools
  :group 'processes)

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
(defvar grep-host-defaults-alist nil
  "Default values depending on target host.
`grep-compute-defaults' returns default values for every local or
remote host `grep' runs.  These values can differ from host to
host.  Once computed, the default values are kept here in order
to avoid computing them again.")

(defun grep-apply-setting (symbol value)
  "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
SYMBOL should be one of `grep-command', `grep-template',
`grep-use-null-device', `grep-find-command',
`grep-find-template', `grep-find-use-xargs', or
`grep-highlight-matches'."
  (when grep-host-defaults-alist
    (let* ((host-id
	    (intern (or (file-remote-p default-directory) "localhost")))
	   (host-defaults (assq host-id grep-host-defaults-alist))
	   (defaults (assq nil grep-host-defaults-alist)))
      (setcar (cdr (assq symbol host-defaults)) value)
      (setcar (cdr (assq symbol defaults)) value)))
  (set-default symbol value))
62 63 64 65 66 67

;;;###autoload
(defcustom grep-window-height nil
  "*Number of lines in a grep window.  If nil, use `compilation-window-height'."
  :type '(choice (const :tag "Default" nil)
		 integer)
68
  :version "22.1"
69 70
  :group 'grep)

71
(defcustom grep-highlight-matches 'auto-detect
72
  "Use special markers to highlight grep matches.
73 74 75 76 77

Some grep programs are able to surround matches with special
markers in grep output.  Such markers can be used to highlight
matches in grep mode.

78
This option sets the environment variable GREP_COLORS to specify
79 80
markers for highlighting and GREP_OPTIONS to add the --color
option in front of any explicit grep options before starting
81 82
the grep.

83 84 85 86 87 88 89 90 91
When this option is `auto', grep uses `--color=auto' to highlight
matches only when it outputs to a terminal (when `grep' is the last
command in the pipe), thus avoiding the use of any potentially-harmful
escape sequences when standard output goes to a file or pipe.

To make grep highlight matches even into a pipe, you need the option
`always' that forces grep to use `--color=always' to unconditionally
output escape sequences.

92
In interactive usage, the actual value of this variable is set up
93 94 95
by `grep-compute-defaults' when the default value is `auto-detect'.
To change the default value, use Customize or call the function
`grep-apply-setting'."
96 97
  :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
		 (const :tag "Highlight matches with grep markers" t)
98 99
		 (const :tag "Use --color=always" always)
		 (const :tag "Use --color=auto" auto)
100
		 (other :tag "Not Set" auto-detect))
101
  :set 'grep-apply-setting
102
  :version "22.1"
103 104
  :group 'grep)

105 106 107 108 109 110 111
(defcustom grep-scroll-output nil
  "*Non-nil to scroll the *grep* buffer window as output appears.

Setting it causes the grep commands to put point at the end of their
output window so that the end of the output is always visible rather
than the begining."
  :type 'boolean
112
  :version "22.1"
113 114
  :group 'grep)

115
;;;###autoload
116 117 118 119 120 121
(defcustom grep-command nil
  "The default grep command for \\[grep].
If the grep program used supports an option to always include file names
in its output (such as the `-H' option to GNU grep), it's a good idea to
include it when specifying `grep-command'.

122 123 124
In interactive usage, the actual value of this variable is set up
by `grep-compute-defaults'; to change the default value, use
Customize or call the function `grep-apply-setting'."
125 126
  :type '(choice string
		 (const :tag "Not Set" nil))
127
  :set 'grep-apply-setting
128 129
  :group 'grep)

Kim F. Storm's avatar
Kim F. Storm committed
130 131 132 133 134
(defcustom grep-template nil
  "The default command to run for \\[lgrep].
The following place holders should be present in the string:
 <C> - place to put -i if case insensitive grep.
 <F> - file names and wildcards to search.
135
 <X> - file names and wildcards to exclude.
Kim F. Storm's avatar
Kim F. Storm committed
136
 <R> - the regular expression searched for.
137 138 139 140 141
 <N> - place to insert null-device.

In interactive usage, the actual value of this variable is set up
by `grep-compute-defaults'; to change the default value, use
Customize or call the function `grep-apply-setting'."
Kim F. Storm's avatar
Kim F. Storm committed
142 143
  :type '(choice string
		 (const :tag "Not Set" nil))
144
  :set 'grep-apply-setting
Kim F. Storm's avatar
Kim F. Storm committed
145 146 147
  :version "22.1"
  :group 'grep)

148 149 150 151 152 153
(defcustom grep-use-null-device 'auto-detect
  "If t, append the value of `null-device' to `grep' commands.
This is done to ensure that the output of grep includes the filename of
any match in the case where only a single file is searched, and is not
necessary if the grep program used supports the `-H' option.

154 155 156
In interactive usage, the actual value of this variable is set up
by `grep-compute-defaults'; to change the default value, use
Customize or call the function `grep-apply-setting'."
157 158 159
  :type '(choice (const :tag "Do Not Append Null Device" nil)
		 (const :tag "Append Null Device" t)
		 (other :tag "Not Set" auto-detect))
160
  :set 'grep-apply-setting
161 162
  :group 'grep)

163
;;;###autoload
164 165
(defcustom grep-find-command nil
  "The default find command for \\[grep-find].
166 167 168
In interactive usage, the actual value of this variable is set up
by `grep-compute-defaults'; to change the default value, use
Customize or call the function `grep-apply-setting'."
169 170
  :type '(choice string
		 (const :tag "Not Set" nil))
171
  :set 'grep-apply-setting
172 173
  :group 'grep)

Kim F. Storm's avatar
Kim F. Storm committed
174 175
(defcustom grep-find-template nil
  "The default command to run for \\[rgrep].
176 177 178 179 180
The following place holders should be present in the string:
 <D> - base directory for find
 <X> - find options to restrict or expand the directory list
 <F> - find options to limit the files matched
 <C> - place to put -i if case insensitive grep
181 182 183 184
 <R> - the regular expression searched for.
In interactive usage, the actual value of this variable is set up
by `grep-compute-defaults'; to change the default value, use
Customize or call the function `grep-apply-setting'."
185 186
  :type '(choice string
		 (const :tag "Not Set" nil))
187
  :set 'grep-apply-setting
188
  :version "22.1"
189 190
  :group 'grep)

191
(defcustom grep-files-aliases
192 193 194
  '(("all" .   "* .*")
    ("el" .    "*.el")
    ("ch" .    "*.[ch]")
195
    ("c" .     "*.c")
196
    ("cc" .    "*.cc *.cxx *.cpp *.C *.CC *.c++")
197
    ("cchh" .  "*.cc *.[ch]xx *.[ch]pp *.[CHh] *.CC *.HH *.[ch]++")
198
    ("hh" .    "*.hxx *.hpp *.[Hh] *.HH *.h++")
199
    ("h" .     "*.h")
200
    ("l" .     "[Cc]hange[Ll]og*")
201
    ("m" .     "[Mm]akefile*")
202 203 204
    ("tex" .   "*.tex")
    ("texi" .  "*.texi")
    ("asm" .   "*.[sS]"))
Kim F. Storm's avatar
Kim F. Storm committed
205
  "*Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
206 207 208
  :type 'alist
  :group 'grep)

209
(defcustom grep-find-ignored-directories
210
  vc-directory-exclusion-list
211 212 213
  "*List of names of sub-directories which `rgrep' shall not recurse into.
If an element is a cons cell, the car is called on the search directory
to determine whether cdr should not be recursed into."
214 215 216 217 218 219 220 221 222 223 224 225 226 227
  :type '(choice (repeat :tag "Ignored directories" string)
		 (const :tag "No ignored directories" nil))
  :group 'grep)

(defcustom grep-find-ignored-files
  (cons ".#*" (delq nil (mapcar (lambda (s)
				  (unless (string-match-p "/\\'" s)
				    (concat "*" s)))
				completion-ignored-extensions)))
  "*List of file names which `rgrep' and `lgrep' shall exclude.
If an element is a cons cell, the car is called on the search directory
to determine whether cdr should not be excluded."
  :type '(choice (repeat :tag "Ignored file" string)
		 (const :tag "No ignored files" nil))
228 229
  :group 'grep)

230 231 232 233 234
(defcustom grep-error-screen-columns nil
  "*If non-nil, column numbers in grep hits are screen columns.
See `compilation-error-screen-columns'"
  :type '(choice (const :tag "Default" nil)
		 integer)
235
  :version "22.1"
236 237
  :group 'grep)

238 239 240 241 242 243 244
;;;###autoload
(defcustom grep-setup-hook nil
  "List of hook functions run by `grep-process-setup' (see `run-hooks')."
  :type 'hook
  :group 'grep)

(defvar grep-mode-map
245 246
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map compilation-minor-mode-map)
247 248
    (define-key map " " 'scroll-up)
    (define-key map "\^?" 'scroll-down)
249
    (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
250 251 252 253 254 255

    (define-key map "\r" 'compile-goto-error)  ;; ?
    (define-key map "n" 'next-error-no-select)
    (define-key map "p" 'previous-error-no-select)
    (define-key map "{" 'compilation-previous-file)
    (define-key map "}" 'compilation-next-file)
256 257
    (define-key map "\t" 'compilation-next-error)
    (define-key map [backtab] 'compilation-previous-error)
258 259 260 261 262 263

    ;; Set up the menu-bar
    (define-key map [menu-bar grep]
      (cons "Grep" (make-sparse-keymap "Grep")))

    (define-key map [menu-bar grep compilation-kill-compilation]
264 265 266
      '(menu-item "Kill Grep" kill-compilation
		  :help "Kill the currently running grep process"))
    (define-key map [menu-bar grep compilation-separator2] '("----"))
267
    (define-key map [menu-bar grep compilation-compile]
268 269
      '(menu-item "Compile..." compile
		  :help "Compile the program including the current buffer.  Default: run `make'"))
270 271 272 273 274 275 276 277 278
    (define-key map [menu-bar grep compilation-rgrep]
      '(menu-item "Recursive grep..." rgrep
		  :help "User-friendly recursive grep in directory tree"))
    (define-key map [menu-bar grep compilation-lgrep]
      '(menu-item "Local grep..." lgrep
		  :help "User-friendly grep in a directory"))
    (define-key map [menu-bar grep compilation-grep-find]
      '(menu-item "Grep via Find..." grep-find
		  :help "Run grep via find, with user-specified args"))
279
    (define-key map [menu-bar grep compilation-grep]
280 281
      '(menu-item "Another grep..." grep
		  :help "Run grep, with user-specified args, and collect output in a buffer."))
282
    (define-key map [menu-bar grep compilation-recompile]
283 284 285
      '(menu-item "Repeat grep" recompile
		  :help "Run grep again"))
    (define-key map [menu-bar grep compilation-separator2] '("----"))
286
    (define-key map [menu-bar grep compilation-first-error]
287 288
      '(menu-item "First Match" first-error
		  :help "Restart at the first match, visit corresponding location"))
289
    (define-key map [menu-bar grep compilation-previous-error]
290 291
      '(menu-item "Previous Match" previous-error
		  :help "Visit the previous match and corresponding location"))
292
    (define-key map [menu-bar grep compilation-next-error]
293 294
      '(menu-item "Next Match" next-error
		  :help "Visit the next match and corresponding location"))
295 296 297 298
    map)
  "Keymap for grep buffers.
`compilation-minor-mode-map' is a cdr of this.")

299
(defvar grep-mode-tool-bar-map
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  ;; When bootstrapping, tool-bar-map is not properly initialized yet,
  ;; so don't do anything.
  (when (keymapp (butlast tool-bar-map))
    (let ((map (butlast (copy-keymap tool-bar-map)))
	  (help (last tool-bar-map))) ;; Keep Help last in tool bar
      (tool-bar-local-item
       "left-arrow" 'previous-error-no-select 'previous-error-no-select map
       :rtl "right-arrow"
       :help "Goto previous match")
      (tool-bar-local-item
       "right-arrow" 'next-error-no-select 'next-error-no-select map
       :rtl "left-arrow"
       :help "Goto next match")
      (tool-bar-local-item
       "cancel" 'kill-compilation 'kill-compilation map
       :enable '(let ((buffer (compilation-find-buffer)))
		  (get-buffer-process buffer))
       :help "Stop grep")
      (tool-bar-local-item
       "refresh" 'recompile 'recompile map
       :help "Restart grep")
      (append map help))))
322

323 324
(defalias 'kill-grep 'kill-compilation)

325 326
;;;; TODO --- refine this!!

Stefan Monnier's avatar
Stefan Monnier committed
327 328 329 330 331 332 333 334
;; (defcustom grep-use-compilation-buffer t
;;   "When non-nil, grep specific commands update `compilation-last-buffer'.
;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
;; can be used to navigate between grep matches (the default).
;; Otherwise, the grep specific commands like \\[grep-next-match] must
;; be used to navigate between grep matches."
;;   :type 'boolean
;;   :group 'grep)
335 336 337 338

;; override compilation-last-buffer
(defvar grep-last-buffer nil
  "The most recent grep buffer.
339
A grep buffer becomes most recent when you select Grep mode in it.
340 341 342
Notice that using \\[next-error] or \\[compile-goto-error] modifies
`complation-last-buffer' rather than `grep-last-buffer'.")

343
;;;###autoload
344
(defconst grep-regexp-alist
345
  '(("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2"
346 347 348
     1 3)
    ;; Rule to match column numbers is commented out since no known grep
    ;; produces them
349
    ;; ("^\\(.+?\\)\\(:[ \t]*\\)\\([0-9]+\\)\\2\\(?:\\([0-9]+\\)\\(?:-\\([0-9]+\\)\\)?\\2\\)?"
350
    ;;  1 3 (4 . 5))
351
    ("^\\(\\(.+?\\):\\([0-9]+\\):\\).*?\
Juri Linkov's avatar
Juri Linkov committed
352
\\(\033\\[01;31m\\(?:\033\\[K\\)?\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
353
     2 3
354
     ;; Calculate column positions (beg . end) of first grep match on a line
355
     ((lambda ()
Juri Linkov's avatar
Juri Linkov committed
356 357
	(setq compilation-error-screen-columns nil)
        (- (match-beginning 4) (match-end 1)))
358
      .
Juri Linkov's avatar
Juri Linkov committed
359 360
      (lambda () (- (match-end 5) (match-end 1)
		    (- (match-end 4) (match-beginning 4)))))
361
     nil 1)
362
    ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
363 364
  "Regexp used to match grep hits.  See `compilation-error-regexp-alist'.")

365 366 367 368 369 370 371 372
(defvar grep-error "grep hit"
  "Message to print when no matches are found.")

;; Reverse the colors because grep hits are not errors (though we jump there
;; with `next-error'), and unreadable files can't be gone to.
(defvar grep-hit-face	compilation-info-face
  "Face name to use for grep hits.")

373
(defvar grep-error-face	'compilation-error
374 375
  "Face name to use for grep error messages.")

Juri Linkov's avatar
Juri Linkov committed
376 377 378
(defvar grep-match-face	'match
  "Face name to use for grep matches.")

379 380 381
(defvar grep-context-face 'shadow
  "Face name to use for grep context lines.")

382 383 384 385 386 387
(defvar grep-mode-font-lock-keywords
   '(;; Command output lines.
     ("^\\([A-Za-z_0-9/\.+-]+\\)[ \t]*:" 1 font-lock-function-name-face)
     (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
      1 grep-error-face)
     ;; remove match from grep-regexp-alist before fontifying
388
     ("^Grep[/a-zA-z]* started.*"
389
      (0 '(face nil message nil help-echo nil mouse-face nil) t))
390
     ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
391
      (0 '(face nil message nil help-echo nil mouse-face nil) t)
392 393
      (1 compilation-info-face nil t)
      (2 compilation-warning-face nil t))
394
     ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
395
      (0 '(face nil message nil help-echo nil mouse-face nil) t)
396
      (1 grep-error-face)
397
      (2 grep-error-face nil t))
398
     ("^.+?-[0-9]+-.*\n" (0 grep-context-face))
399
     ;; Highlight grep matches and delete markers
Juri Linkov's avatar
Juri Linkov committed
400
     ("\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)"
401 402 403 404
      ;; Refontification does not work after the markers have been
      ;; deleted.  So we use the font-lock-face property here as Font
      ;; Lock does not clear that.
      (2 (list 'face nil 'font-lock-face grep-match-face))
Juri Linkov's avatar
Juri Linkov committed
405
      ((lambda (bound))
406 407 408 409
       (progn
	 ;; Delete markers with `replace-match' because it updates
	 ;; the match-data, whereas `delete-region' would render it obsolete.
	 (replace-match "" t t nil 3)
Juri Linkov's avatar
Juri Linkov committed
410 411 412 413 414
	 (replace-match "" t t nil 1))))
     ("\\(\033\\[[0-9;]*[mK]\\)"
      ;; Delete all remaining escape sequences
      ((lambda (bound))
       (replace-match "" t t nil 1))))
415 416 417
   "Additional things to highlight in grep output.
This gets tacked on the end of the generated expressions.")

418
;;;###autoload
419
(defvar grep-program (purecopy "grep")
420 421 422
  "The default grep program for `grep-command' and `grep-find-command'.
This variable's value takes effect when `grep-compute-defaults' is called.")

423
;;;###autoload
424
(defvar find-program (purecopy "find")
425 426 427
  "The default find program for `grep-find-command'.
This variable's value takes effect when `grep-compute-defaults' is called.")

428
;;;###autoload
429
(defvar xargs-program (purecopy "xargs")
430 431 432 433
  "The default xargs program for `grep-find-command'.
See `grep-find-use-xargs'.
This variable's value takes effect when `grep-compute-defaults' is called.")

434
;;;###autoload
435
(defvar grep-find-use-xargs nil
436 437 438 439
  "Non-nil means that `grep-find' uses the `xargs' utility by default.
If `exec', use `find -exec'.
If `gnu', use `find -print0' and `xargs -0'.
Any other non-nil value means to use `find -print' and `xargs'.
440 441 442 443

This variable's value takes effect when `grep-compute-defaults' is called.")

;; History of grep commands.
444
;;;###autoload
445
(defvar grep-history nil)
446
;;;###autoload
447 448
(defvar grep-find-history nil)

Kim F. Storm's avatar
Kim F. Storm committed
449 450
;; History of lgrep and rgrep regexp and files args.
(defvar grep-regexp-history nil)
451
(defvar grep-files-history nil)
Kim F. Storm's avatar
Kim F. Storm committed
452

453
;;;###autoload
454 455
(defun grep-process-setup ()
  "Setup compilation variables and buffer for `grep'.
456
Set up `compilation-exit-message-function' and run `grep-setup-hook'."
457
  (when (eq grep-highlight-matches 'auto-detect)
458
    (grep-compute-defaults))
459 460
  (unless (or (eq grep-highlight-matches 'auto-detect)
	      (null grep-highlight-matches))
461 462 463
    ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
    ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
    (setenv "TERM" "emacs-grep")
464 465
    (setenv "GREP_OPTIONS"
	    (concat (getenv "GREP_OPTIONS")
466
		    " --color=" (if (eq grep-highlight-matches 'always)
467
				    "always" "auto")))
468
    ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
Juri Linkov's avatar
Juri Linkov committed
469
    (setenv "GREP_COLOR" "01;31")
470
    ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
Juri Linkov's avatar
Juri Linkov committed
471
    (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
472 473 474 475 476 477 478 479 480 481 482 483
  (set (make-local-variable 'compilation-exit-message-function)
       (lambda (status code msg)
	 (if (eq status 'exit)
	     (cond ((zerop code)
		    '("finished (matches found)\n" . "matched"))
		   ((= code 1)
		    '("finished with no matches found\n" . "no match"))
		   (t
		    (cons msg code)))
	   (cons msg code))))
  (run-hooks 'grep-setup-hook))

Kim F. Storm's avatar
Kim F. Storm committed
484
(defun grep-probe (command args &optional func result)
485 486 487 488 489
  (let (process-file-side-effects)
    (equal (condition-case nil
	       (apply (or func 'process-file) command args)
	     (error nil))
	   (or result 0))))
Kim F. Storm's avatar
Kim F. Storm committed
490

491
;;;###autoload
492
(defun grep-compute-defaults ()
493 494 495 496 497 498 499 500 501 502 503 504 505
  ;; Keep default values.
  (unless grep-host-defaults-alist
    (add-to-list
     'grep-host-defaults-alist
     (cons nil
	   `((grep-command ,grep-command)
	     (grep-template ,grep-template)
	     (grep-use-null-device ,grep-use-null-device)
	     (grep-find-command ,grep-find-command)
	     (grep-find-template ,grep-find-template)
	     (grep-find-use-xargs ,grep-find-use-xargs)
	     (grep-highlight-matches ,grep-highlight-matches)))))
  (let* ((host-id
Stefan Monnier's avatar
Stefan Monnier committed
506
	  (intern (or (file-remote-p default-directory) "localhost")))
507 508
	 (host-defaults (assq host-id grep-host-defaults-alist))
	 (defaults (assq nil grep-host-defaults-alist)))
509
    ;; There are different defaults on different hosts.  They must be
510
    ;; computed for every host once.
511 512 513 514 515 516 517
    (dolist (setting '(grep-command grep-template
		       grep-use-null-device grep-find-command
		       grep-find-template grep-find-use-xargs
		       grep-highlight-matches))
      (set setting
	   (or (cadr (assq setting host-defaults))
	       (cadr (assq setting defaults)))))
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

    (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
      (setq grep-use-null-device
	    (with-temp-buffer
	      (let ((hello-file (expand-file-name "HELLO" data-directory)))
		(not
		 (and (if grep-command
			  ;; `grep-command' is already set, so
			  ;; use that for testing.
			  (grep-probe grep-command
				      `(nil t nil "^English" ,hello-file)
				      #'call-process-shell-command)
			;; otherwise use `grep-program'
			(grep-probe grep-program
				    `(nil t nil "-nH" "^English" ,hello-file)))
		      (progn
			(goto-char (point-min))
			(looking-at
			 (concat (regexp-quote hello-file)
				 ":[0-9]+:English")))))))))
    (unless (and grep-command grep-find-command
		 grep-template grep-find-template)
      (let ((grep-options
	     (concat (if grep-use-null-device "-n" "-nH")
		     (if (grep-probe grep-program
				     `(nil nil nil "-e" "foo" ,null-device)
				     nil 1)
			 " -e"))))
	(unless grep-command
	  (setq grep-command
		(format "%s %s " grep-program grep-options)))
	(unless grep-template
	  (setq grep-template
551
		(format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
552 553 554 555 556
	(unless grep-find-use-xargs
	  (setq grep-find-use-xargs
		(cond
		 ((and
		   (grep-probe find-program `(nil nil nil ,null-device "-print0"))
557
		   (grep-probe xargs-program `(nil nil nil "-0" "-e" "echo")))
558 559 560 561 562
		  'gnu)
		 (t
		  'exec))))
	(unless grep-find-command
	  (setq grep-find-command
Kim F. Storm's avatar
Kim F. Storm committed
563
		(cond ((eq grep-find-use-xargs 'gnu)
564 565
		       (format "%s . -type f -print0 | %s -0 -e %s"
			       find-program xargs-program grep-command))
566
		      ((eq grep-find-use-xargs 'exec)
567 568 569 570 571 572 573
		       (let ((cmd0 (format "%s . -type f -exec %s"
					   find-program grep-command)))
			 (cons
			  (format "%s {} %s %s"
				  cmd0 null-device
				  (shell-quote-argument ";"))
			  (1+ (length cmd0)))))
574
		      (t
575 576
		       (format "%s . -type f -print | %s %s"
			       find-program xargs-program grep-command)))))
577 578 579 580 581
	(unless grep-find-template
	  (setq grep-find-template
		(let ((gcmd (format "%s <C> %s <R>"
				    grep-program grep-options)))
		  (cond ((eq grep-find-use-xargs 'gnu)
582 583
			 (format "%s . <X> -type f <F> -print0 | %s -0 -e %s"
				 find-program xargs-program gcmd))
584 585 586 587 588
			((eq grep-find-use-xargs 'exec)
			 (format "%s . <X> -type f <F> -exec %s {} %s %s"
				 find-program gcmd null-device
				 (shell-quote-argument ";")))
			(t
589 590
			 (format "%s . <X> -type f <F> -print | %s %s"
				 find-program xargs-program gcmd))))))))
591
    (when (eq grep-highlight-matches 'auto-detect)
592 593 594 595 596 597
      (setq grep-highlight-matches
	    (with-temp-buffer
	      (and (grep-probe grep-program '(nil t nil "--help"))
		   (progn
		     (goto-char (point-min))
		     (search-forward "--color" nil t))
598 599 600
		   ;; Windows and DOS pipes fail `isatty' detection in Grep.
		   (if (memq system-type '(windows-nt ms-dos))
		       'always 'auto)))))
601 602

    ;; Save defaults for this host.
603 604 605 606 607 608 609 610 611 612 613 614 615
    (setq grep-host-defaults-alist
	  (delete (assq host-id grep-host-defaults-alist)
		  grep-host-defaults-alist))
    (add-to-list
     'grep-host-defaults-alist
     (cons host-id
	   `((grep-command ,grep-command)
	     (grep-template ,grep-template)
	     (grep-use-null-device ,grep-use-null-device)
	     (grep-find-command ,grep-find-command)
	     (grep-find-template ,grep-find-template)
	     (grep-find-use-xargs ,grep-find-use-xargs)
	     (grep-highlight-matches ,grep-highlight-matches))))))
616

617 618 619 620 621 622 623 624 625
(defun grep-tag-default ()
  (or (and transient-mark-mode mark-active
	   (/= (point) (mark))
	   (buffer-substring-no-properties (point) (mark)))
      (funcall (or find-tag-default-function
		   (get major-mode 'find-tag-default-function)
		   'find-tag-default))
      ""))

626
(defun grep-default-command ()
627
  "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
628
  (let ((tag-default (shell-quote-argument (grep-tag-default)))
629 630
	;; This a regexp to match single shell arguments.
	;; Could someone please add comments explaining it?
631 632
	(sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
	(grep-default (or (car grep-history) grep-command)))
633
    ;; In the default command, find the arg that specifies the pattern.
634 635 636 637 638 639
    (when (or (string-match
	       (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
		       sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
	       grep-default)
	      ;; If the string is not yet complete.
	      (string-match "\\(\\)\\'" grep-default))
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
      ;; Maybe we will replace the pattern with the default tag.
      ;; But first, maybe replace the file name pattern.
      (condition-case nil
	  (unless (or (not (stringp buffer-file-name))
		      (when (match-beginning 2)
			(save-match-data
			  (string-match
			   (wildcard-to-regexp
			    (file-name-nondirectory
			     (match-string 3 grep-default)))
			   (file-name-nondirectory buffer-file-name)))))
	    (setq grep-default (concat (substring grep-default
						  0 (match-beginning 2))
				       " *."
				       (file-name-extension buffer-file-name))))
	;; In case wildcard-to-regexp gets an error
	;; from invalid data.
	(error nil))
      ;; Now replace the pattern with the default tag.
659
      (replace-match tag-default t t grep-default 1))))
660

Kim F. Storm's avatar
Kim F. Storm committed
661

662
;;;###autoload
Kim F. Storm's avatar
Kim F. Storm committed
663 664 665
(define-compilation-mode grep-mode "Grep"
  "Sets `grep-last-buffer' and `compilation-window-height'."
  (setq grep-last-buffer (current-buffer))
666
  (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
Kim F. Storm's avatar
Kim F. Storm committed
667 668 669 670 671 672 673 674 675 676 677
  (set (make-local-variable 'compilation-error-face)
       grep-hit-face)
  (set (make-local-variable 'compilation-error-regexp-alist)
       grep-regexp-alist)
  (set (make-local-variable 'compilation-process-setup-function)
       'grep-process-setup)
  (set (make-local-variable 'compilation-disable-input) t))


;;;###autoload
(defun grep (command-args)
678 679
  "Run grep, with user-specified args, and collect output in a buffer.
While grep runs asynchronously, you can use \\[next-error] (M-x next-error),
Luc Teirlinck's avatar
Luc Teirlinck committed
680
or \\<grep-mode-map>\\[compile-goto-error] in the grep \
681 682
output buffer, to go to the lines where grep
found matches.
683

684
For doing a recursive `grep', see the `rgrep' command.  For running
685
`grep' in a specific directory, see `lgrep'.
686

687 688
This command uses a special history list for its COMMAND-ARGS, so you
can easily repeat a grep command.
689 690 691

A prefix argument says to default the argument based upon the current
tag the cursor is over, substituting it into the last grep command
692 693
in the grep command history (or into `grep-command' if that history
list is empty)."
694 695
  (interactive
   (progn
Kim F. Storm's avatar
Kim F. Storm committed
696
     (grep-compute-defaults)
697
     (let ((default (grep-default-command)))
698 699 700 701
       (list (read-shell-command "Run grep (like this): "
                                 (if current-prefix-arg default grep-command)
                                 'grep-history
                                 (if current-prefix-arg nil default))))))
702 703 704

  ;; Setting process-setup-function makes exit-message-function work
  ;; even when async processes aren't supported.
705 706 707
  (compilation-start (if (and grep-use-null-device null-device)
			 (concat command-args " " null-device)
		       command-args)
Kim F. Storm's avatar
Kim F. Storm committed
708
		     'grep-mode))
709

710 711 712 713 714 715 716 717 718 719 720 721

;;;###autoload
(defun grep-find (command-args)
  "Run grep via find, with user-specified args COMMAND-ARGS.
Collect output in a buffer.
While find runs asynchronously, you can use the \\[next-error] command
to find the text that grep hits refer to.

This command uses a special history list for its arguments, so you can
easily repeat a find command."
  (interactive
   (progn
Kim F. Storm's avatar
Kim F. Storm committed
722
     (grep-compute-defaults)
723
     (if grep-find-command
724 725
	 (list (read-shell-command "Run find (like this): "
                                   grep-find-command 'grep-find-history))
726 727 728 729
       ;; No default was set
       (read-string
        "compile.el: No `grep-find-command' command available. Press RET.")
       (list nil))))
730
  (when command-args
731 732
    (let ((null-device nil))		; see grep
      (grep command-args))))
733

734 735 736
;;;###autoload
(defalias 'find-grep 'grep-find)

Kim F. Storm's avatar
Kim F. Storm committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

;; User-friendly interactive API.

(defconst grep-expand-keywords
  '(("<C>" . (and cf (isearch-no-upper-case-p regexp t) "-i"))
    ("<D>" . dir)
    ("<F>" . files)
    ("<N>" . null-device)
    ("<X>" . excl)
    ("<R>" . (shell-quote-argument (or regexp ""))))
  "List of substitutions performed by `grep-expand-template'.
If car of an element matches, the cdr is evalled in to get the
substitution string.  Note dynamic scoping of variables.")

(defun grep-expand-template (template &optional regexp files dir excl)
  "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
  (let ((command template)
	(cf case-fold-search)
	(case-fold-search nil))
    (dolist (kw grep-expand-keywords command)
      (if (string-match (car kw) command)
758 759 760
	  (setq command
		(replace-match
		 (or (if (symbolp (cdr kw))
761
			 (symbol-value (cdr kw))
762 763 764
		       (save-match-data (eval (cdr kw))))
		     "")
		 t t command))))))
Kim F. Storm's avatar
Kim F. Storm committed
765 766 767

(defun grep-read-regexp ()
  "Read regexp arg for interactive grep."
768
  (let ((default (grep-tag-default)))
Kim F. Storm's avatar
Kim F. Storm committed
769 770 771
    (read-string
     (concat "Search for"
	     (if (and default (> (length default) 0))
772
		 (format " (default \"%s\"): " default) ": "))
Kim F. Storm's avatar
Kim F. Storm committed
773 774 775 776
     nil 'grep-regexp-history default)))

(defun grep-read-files (regexp)
  "Read files arg for interactive grep."
777 778
  (let* ((bn (or (buffer-file-name)
		 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
779 780 781
	 (fn (and bn
		  (stringp bn)
		  (file-name-nondirectory bn)))
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
	 (default-alias
	   (and fn
		(let ((aliases grep-files-aliases)
		      alias)
		  (while aliases
		    (setq alias (car aliases)
			  aliases (cdr aliases))
		    (if (string-match (wildcard-to-regexp (cdr alias)) fn)
			(setq aliases nil)
		      (setq alias nil)))
		  (cdr alias))))
	 (default-extension
	   (and fn
		(let ((ext (file-name-extension fn)))
		  (and ext (concat "*." ext)))))
797
	 (default
798 799
	   (or default-alias
	       default-extension
800 801
	       (car grep-files-history)
	       (car (car grep-files-aliases))))
802
	 (files (completing-read
Kim F. Storm's avatar
Kim F. Storm committed
803
		 (concat "Search for \"" regexp
804 805 806
			 "\" in files"
			 (if default (concat " (default " default ")"))
			 ": ")
807 808
		 'read-file-name-internal
		 nil nil nil 'grep-files-history
809 810 811
		 (delete-dups
		  (delq nil (append (list default default-alias default-extension)
				    (mapcar 'car grep-files-aliases)))))))
Kim F. Storm's avatar
Kim F. Storm committed
812 813 814
    (and files
	 (or (cdr (assoc files grep-files-aliases))
	     files))))
815 816

;;;###autoload
Juri Linkov's avatar
Juri Linkov committed
817
(defun lgrep (regexp &optional files dir confirm)
818
  "Run grep, searching for REGEXP in FILES in directory DIR.
819
The search is limited to file names matching shell pattern FILES.
Kim F. Storm's avatar
Kim F. Storm committed
820
FILES may use abbreviations defined in `grep-files-aliases', e.g.
821 822
entering `ch' is equivalent to `*.[ch]'.

Kim F. Storm's avatar
Kim F. Storm committed
823 824 825
With \\[universal-argument] prefix, you can edit the constructed shell command line
before it is executed.
With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
826

Kim F. Storm's avatar
Kim F. Storm committed
827
Collect output in a buffer.  While grep runs asynchronously, you
828 829 830
can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
in the grep output buffer,
to go to the lines where grep found matches.
831

Kim F. Storm's avatar
Kim F. Storm committed
832
This command shares argument histories with \\[rgrep] and \\[grep]."
833
  (interactive
Kim F. Storm's avatar
Kim F. Storm committed
834 835 836 837 838
   (progn
     (grep-compute-defaults)
     (cond
      ((and grep-command (equal current-prefix-arg '(16)))
       (list (read-from-minibuffer "Run: " grep-command
Juri Linkov's avatar
Juri Linkov committed
839
				   nil nil 'grep-history)))
Kim F. Storm's avatar
Kim F. Storm committed
840
      ((not grep-template)
Juanma Barranquero's avatar
Juanma Barranquero committed
841
       (error "grep.el: No `grep-template' available"))
Kim F. Storm's avatar
Kim F. Storm committed
842
      (t (let* ((regexp (grep-read-regexp))
843 844
		(files (grep-read-files regexp))
		(dir (read-directory-name "In directory: "
Juri Linkov's avatar
Juri Linkov committed
845 846 847
					  nil default-directory t))
		(confirm (equal current-prefix-arg '(4))))
	   (list regexp files dir confirm))))))
Kim F. Storm's avatar
Kim F. Storm committed
848
  (when (and (stringp regexp) (> (length regexp) 0))
Juri Linkov's avatar
Juri Linkov committed
849 850
    (unless (and dir (file-directory-p dir) (file-readable-p dir))
      (setq dir default-directory))
Kim F. Storm's avatar
Kim F. Storm committed
851 852 853 854
    (let ((command regexp))
      (if (null files)
	  (if (string= command grep-command)
	      (setq command nil))
855
	(setq dir (file-name-as-directory (expand-file-name dir)))
Kim F. Storm's avatar
Kim F. Storm committed
856 857 858
	(setq command (grep-expand-template
		       grep-template
		       regexp
859 860 861 862 863 864 865 866 867 868 869 870 871 872
		       files
		       nil
		       (and grep-find-ignored-files
			    (concat " --exclude="
				    (mapconcat
				     #'(lambda (ignore)
					 (cond ((stringp ignore)
						(shell-quote-argument ignore))
					       ((consp ignore)
						(and (funcall (car ignore) dir)
						     (shell-quote-argument
						      (cdr ignore))))))
				     grep-find-ignored-files
				     " --exclude=")))))
Kim F. Storm's avatar
Kim F. Storm committed
873
	(when command
Juri Linkov's avatar
Juri Linkov committed
874
	  (if confirm
Kim F. Storm's avatar
Kim F. Storm committed
875 876 877
	      (setq command
		    (read-from-minibuffer "Confirm: "
					  command nil nil 'grep-history))
878
	    (add-to-history 'grep-history command))))
Kim F. Storm's avatar
Kim F. Storm committed
879
      (when command
Juri Linkov's avatar
Juri Linkov committed
880
	(let ((default-directory dir))
881 882 883 884
	  ;; Setting process-setup-function makes exit-message-function work
	  ;; even when async processes aren't supported.
	  (compilation-start (if (and grep-use-null-device null-device)
				 (concat command " " null-device)
Richard M. Stallman's avatar
Richard M. Stallman committed
885 886
			       command)
			     'grep-mode))
887 888 889
	(if (eq next-error-last-buffer (current-buffer))
	    (setq default-directory dir))))))

Kim F. Storm's avatar
Kim F. Storm committed
890

891
(defvar find-name-arg)	    ; not autoloaded but defined in find-dired
Kim F. Storm's avatar
Kim F. Storm committed
892 893

;;;###autoload
Juri Linkov's avatar
Juri Linkov committed
894
(defun rgrep (regexp &optional files dir confirm)
Kim F. Storm's avatar
Kim F. Storm committed
895
  "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
Kim F. Storm's avatar
Kim F. Storm committed
896 897 898 899
The search is limited to file names matching shell pattern FILES.
FILES may use abbreviations defined in `grep-files-aliases', e.g.
entering `ch' is equivalent to `*.[ch]'.

Kim F. Storm's avatar
Kim F. Storm committed
900 901 902
With \\[universal-argument] prefix, you can edit the constructed shell command line
before it is executed.
With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
Kim F. Storm's avatar
Kim F. Storm committed
903 904

Collect output in a buffer.  While find runs asynchronously, you
905 906 907
can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
in the grep output buffer,
to go to the lines where grep found matches.
Kim F. Storm's avatar
Kim F. Storm committed
908 909 910 911 912 913 914 915

This command shares argument histories with \\[lgrep] and \\[grep-find]."
  (interactive
   (progn
     (grep-compute-defaults)
     (cond
      ((and grep-find-command (equal current-prefix-arg '(16)))
       (list (read-from-minibuffer "Run: " grep-find-command
Juri Linkov's avatar
Juri Linkov committed
916
				   nil nil 'grep-find-history)))
Kim F. Storm's avatar
Kim F. Storm committed
917
      ((not grep-find-template)
Juanma Barranquero's avatar
Juanma Barranquero committed
918
       (error "grep.el: No `grep-find-template' available"))
Kim F. Storm's avatar
Kim F. Storm committed
919 920 921
      (t (let* ((regexp (grep-read-regexp))
		(files (grep-read-files regexp))
		(dir (read-directory-name "Base directory: "
Juri Linkov's avatar
Juri Linkov committed
922 923 924
					  nil default-directory t))
		(confirm (equal current-prefix-arg '(4))))
	   (list regexp files dir confirm))))))
Kim F. Storm's avatar
Kim F. Storm committed
925
  (when (and (stringp regexp) (> (length regexp) 0))
Juri Linkov's avatar
Juri Linkov committed
926 927
    (unless (and dir (file-directory-p dir) (file-readable-p dir))
      (setq dir default-directory))
Kim F. Storm's avatar
Kim F. Storm committed
928 929 930
    (if (null files)
	(if (not (string= regexp grep-find-command))
	    (compilation-start regexp 'grep-mode))
931
      (setq dir (file-name-as-directory (expand-file-name dir)))
932
      (require 'find-dired)		; for `find-name-arg'
933 934 935
      (let ((command (grep-expand-template
		      grep-find-template
		      regexp
936
		      (concat (shell-quote-argument "(")
Jason Rumney's avatar
Jason Rumney committed
937
			      " " find-name-arg " "
938 939
			      (mapconcat #'shell-quote-argument
					 (split-string files)
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
940
					 (concat " -o " find-name-arg " "))
941 942
			      " "
			      (shell-quote-argument ")"))
943 944
		      dir
		      (concat
Kim F. Storm's avatar
Kim F. Storm committed
945
		       (and grep-find-ignored-directories
946 947 948
			    (concat (shell-quote-argument "(")
				    ;; we should use shell-quote-argument here
				    " -path "
949
				    (mapconcat
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
				     #'(lambda (ignore)
					 (cond ((stringp ignore)
						(shell-quote-argument
						 (concat "*/" ignore)))
					       ((consp ignore)
						(and (funcall (car ignore) dir)
						     (shell-quote-argument
						      (concat "*/"
							      (cdr ignore)))))))
				     grep-find-ignored-directories
				     " -o -path ")
				    " "
				    (shell-quote-argument ")")
				    " -prune -o "))
		       (and grep-find-ignored-files
			    (concat (shell-quote-argument "(")
				    ;; we should use shell-quote-argument here
				    " -name "
				    (mapconcat
				     #'(lambda (ignore)
					 (cond ((stringp ignore)
						(shell-quote-argument ignore))
					       ((consp ignore)
						(and (funcall (car ignore) dir)
						     (shell-quote-argument
						      (cdr ignore))))))
				     grep-find-ignored-files
				     " -o -name ")
978 979
				    " "
				    (shell-quote-argument ")")
980
				    " -prune -o "))))))
Kim F. Storm's avatar
Kim F. Storm committed
981
	(when command
Juri Linkov's avatar
Juri Linkov committed
982
	  (if confirm
Kim F. Storm's avatar
Kim F. Storm committed
983 984 985
	      (setq command
		    (read-from-minibuffer "Confirm: "
					  command nil nil 'grep-find-history))