]> code.delx.au - gnu-emacs/blob - lisp/progmodes/grep.el
Add `r'/`l' grep command history commands
[gnu-emacs] / lisp / progmodes / grep.el
1 ;;; grep.el --- run `grep' and display the results -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1985-1987, 1993-1999, 2001-2016 Free Software
4 ;; Foundation, Inc.
5
6 ;; Author: Roland McGrath <roland@gnu.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: tools, processes
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides the grep facilities documented in the Emacs
28 ;; user's manual.
29
30 ;;; Code:
31
32 (require 'compile)
33
34
35 (defgroup grep nil
36 "Run `grep' and display the results."
37 :group 'tools
38 :group 'processes)
39
40 (defvar grep-host-defaults-alist nil
41 "Default values depending on target host.
42 `grep-compute-defaults' returns default values for every local or
43 remote host `grep' runs. These values can differ from host to
44 host. Once computed, the default values are kept here in order
45 to avoid computing them again.")
46
47 (defun grep-apply-setting (symbol value)
48 "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
49 SYMBOL should be one of `grep-command', `grep-template',
50 `grep-use-null-device', `grep-find-command',
51 `grep-find-template', `grep-find-use-xargs', or
52 `grep-highlight-matches'."
53 (when grep-host-defaults-alist
54 (let* ((host-id
55 (intern (or (file-remote-p default-directory) "localhost")))
56 (host-defaults (assq host-id grep-host-defaults-alist))
57 (defaults (assq nil grep-host-defaults-alist)))
58 (setcar (cdr (assq symbol host-defaults)) value)
59 (setcar (cdr (assq symbol defaults)) value)))
60 (set-default symbol value))
61
62 ;;;###autoload
63 (defcustom grep-window-height nil
64 "Number of lines in a grep window. If nil, use `compilation-window-height'."
65 :type '(choice (const :tag "Default" nil)
66 integer)
67 :version "22.1"
68 :group 'grep)
69
70 (defcustom grep-highlight-matches 'auto-detect
71 "Use special markers to highlight grep matches.
72
73 Some grep programs are able to surround matches with special
74 markers in grep output. Such markers can be used to highlight
75 matches in grep mode. This requires `font-lock-mode' to be active
76 in grep buffers, so if you have globally disabled font-lock-mode,
77 you will not get highlighting.
78
79 This option sets the environment variable GREP_COLORS to specify
80 markers for highlighting and adds the --color option in front of
81 any explicit grep options before starting the grep.
82
83 When this option is `auto', grep uses `--color' to highlight
84 matches only when it outputs to a terminal (when `grep' is the last
85 command in the pipe), thus avoiding the use of any potentially-harmful
86 escape sequences when standard output goes to a file or pipe.
87
88 To make grep highlight matches even into a pipe, you need the option
89 `always' that forces grep to use `--color=always' to unconditionally
90 output escape sequences.
91
92 In interactive usage, the actual value of this variable is set up
93 by `grep-compute-defaults' when the default value is `auto-detect'.
94 To change the default value, use Customize or call the function
95 `grep-apply-setting'."
96 :type '(choice (const :tag "Do not highlight matches with grep markers" nil)
97 (const :tag "Highlight matches with grep markers" t)
98 (const :tag "Use --color=always" always)
99 (const :tag "Use --color" auto)
100 (other :tag "Not Set" auto-detect))
101 :set 'grep-apply-setting
102 :version "22.1"
103 :group 'grep)
104
105 (defcustom grep-scroll-output nil
106 "Non-nil to scroll the *grep* buffer window as output appears.
107
108 Setting it causes the grep commands to put point at the end of their
109 output window so that the end of the output is always visible rather
110 than the beginning."
111 :type 'boolean
112 :version "22.1"
113 :group 'grep)
114
115 ;;;###autoload
116 (defcustom grep-command nil
117 "The default grep command for \\[grep].
118 If the grep program used supports an option to always include file names
119 in its output (such as the `-H' option to GNU grep), it's a good idea to
120 include it when specifying `grep-command'.
121
122 In interactive usage, the actual value of this variable is set up
123 by `grep-compute-defaults'; to change the default value, use
124 Customize or call the function `grep-apply-setting'."
125 :type '(choice string
126 (const :tag "Not Set" nil))
127 :set 'grep-apply-setting
128 :group 'grep)
129
130 (defcustom grep-template nil
131 "The default command to run for \\[lgrep].
132 The following place holders should be present in the string:
133 <C> - place to put the options like -i and --color.
134 <F> - file names and wildcards to search.
135 <X> - file names and wildcards to exclude.
136 <R> - the regular expression searched for.
137 <N> - place to insert null-device.
138
139 In interactive usage, the actual value of this variable is set up
140 by `grep-compute-defaults'; to change the default value, use
141 Customize or call the function `grep-apply-setting'."
142 :type '(choice string
143 (const :tag "Not Set" nil))
144 :set 'grep-apply-setting
145 :version "22.1"
146 :group 'grep)
147
148 (defcustom grep-use-null-device 'auto-detect
149 "If t, append the value of `null-device' to `grep' commands.
150 This is done to ensure that the output of grep includes the filename of
151 any match in the case where only a single file is searched, and is not
152 necessary if the grep program used supports the `-H' option.
153
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 (const :tag "Do Not Append Null Device" nil)
158 (const :tag "Append Null Device" t)
159 (other :tag "Not Set" auto-detect))
160 :set 'grep-apply-setting
161 :group 'grep)
162
163 ;;;###autoload
164 (defcustom grep-find-command nil
165 "The default find command for \\[grep-find].
166 In interactive usage, the actual value of this variable is set up
167 by `grep-compute-defaults'; to change the default value, use
168 Customize or call the function `grep-apply-setting'."
169 :type '(choice string
170 (const :tag "Not Set" nil))
171 :set 'grep-apply-setting
172 :group 'grep)
173
174 (defcustom grep-find-template nil
175 "The default command to run for \\[rgrep].
176 The following place holders should be present in the string:
177 <D> - base directory for find
178 <X> - find options to restrict or expand the directory list
179 <F> - find options to limit the files matched
180 <C> - place to put the grep options like -i and --color
181 <R> - the regular expression searched for.
182 In interactive usage, the actual value of this variable is set up
183 by `grep-compute-defaults'; to change the default value, use
184 Customize or call the function `grep-apply-setting'."
185 :type '(choice string
186 (const :tag "Not Set" nil))
187 :set 'grep-apply-setting
188 :version "22.1"
189 :group 'grep)
190
191 (defcustom grep-files-aliases
192 '(("all" . "* .[!.]* ..?*") ;; Don't match `..'. See bug#22577
193 ("el" . "*.el")
194 ("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 ("tex" . "*.tex")
203 ("texi" . "*.texi")
204 ("asm" . "*.[sS]"))
205 "Alist of aliases for the FILES argument to `lgrep' and `rgrep'."
206 :type 'alist
207 :group 'grep)
208
209 (defcustom grep-find-ignored-directories
210 vc-directory-exclusion-list
211 "List of names of sub-directories which `rgrep' shall not recurse into.
212 If an element is a cons cell, the car is called on the search directory
213 to determine whether cdr should not be recursed into."
214 :type '(choice (repeat :tag "Ignored directories" string)
215 (const :tag "No ignored directories" nil))
216 :group 'grep)
217
218 (defcustom grep-find-ignored-files
219 (cons ".#*" (delq nil (mapcar (lambda (s)
220 (unless (string-match-p "/\\'" s)
221 (concat "*" s)))
222 completion-ignored-extensions)))
223 "List of file names which `rgrep' and `lgrep' shall exclude.
224 If an element is a cons cell, the car is called on the search directory
225 to determine whether cdr should not be excluded."
226 :type '(choice (repeat :tag "Ignored file" string)
227 (const :tag "No ignored files" nil))
228 :group 'grep)
229
230 (defcustom grep-save-buffers 'ask
231 "If non-nil, save buffers before running the grep commands.
232 If `ask', ask before saving. If a function, call it with no arguments
233 with each buffer current, as a predicate to determine whether that
234 buffer should be saved or not. E.g., one can set this to
235 (lambda ()
236 (string-prefix-p my-grep-root (file-truename (buffer-file-name))))
237 to limit saving to files located under `my-grep-root'."
238 :version "25.2"
239 :type '(choice
240 (const :tag "Ask before saving" ask)
241 (const :tag "Don't save buffers" nil)
242 function
243 (other :tag "Save all buffers" t))
244 :group 'grep)
245
246 (defcustom grep-error-screen-columns nil
247 "If non-nil, column numbers in grep hits are screen columns.
248 See `compilation-error-screen-columns'"
249 :type '(choice (const :tag "Default" nil)
250 integer)
251 :version "22.1"
252 :group 'grep)
253
254 ;;;###autoload
255 (defcustom grep-setup-hook nil
256 "List of hook functions run by `grep-process-setup' (see `run-hooks')."
257 :type 'hook
258 :group 'grep)
259
260 (defvar grep-mode-map
261 (let ((map (make-sparse-keymap)))
262 (set-keymap-parent map compilation-minor-mode-map)
263 (define-key map " " 'scroll-up-command)
264 (define-key map [?\S-\ ] 'scroll-down-command)
265 (define-key map "\^?" 'scroll-down-command)
266 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
267
268 (define-key map "\r" 'compile-goto-error) ;; ?
269 (define-key map "n" 'next-error-no-select)
270 (define-key map "p" 'previous-error-no-select)
271 (define-key map "{" 'compilation-previous-file)
272 (define-key map "}" 'compilation-next-file)
273 (define-key map "\t" 'compilation-next-error)
274 (define-key map "r" 'grep-forward-history)
275 (define-key map "l" 'grep-backward-history)
276 (define-key map [backtab] 'compilation-previous-error)
277
278 ;; Set up the menu-bar
279 (define-key map [menu-bar grep]
280 (cons "Grep" (make-sparse-keymap "Grep")))
281
282 (define-key map [menu-bar grep compilation-kill-compilation]
283 '(menu-item "Kill Grep" kill-compilation
284 :help "Kill the currently running grep process"))
285 (define-key map [menu-bar grep compilation-separator2] '("----"))
286 (define-key map [menu-bar grep compilation-compile]
287 '(menu-item "Compile..." compile
288 :help "Compile the program including the current buffer. Default: run `make'"))
289 (define-key map [menu-bar grep compilation-rgrep]
290 '(menu-item "Recursive grep..." rgrep
291 :help "User-friendly recursive grep in directory tree"))
292 (define-key map [menu-bar grep compilation-lgrep]
293 '(menu-item "Local grep..." lgrep
294 :help "User-friendly grep in a directory"))
295 (define-key map [menu-bar grep compilation-grep-find]
296 '(menu-item "Grep via Find..." grep-find
297 :help "Run grep via find, with user-specified args"))
298 (define-key map [menu-bar grep compilation-grep]
299 '(menu-item "Another grep..." grep
300 :help "Run grep, with user-specified args, and collect output in a buffer."))
301 (define-key map [menu-bar grep compilation-recompile]
302 '(menu-item "Repeat grep" recompile
303 :help "Run grep again"))
304 (define-key map [menu-bar grep compilation-separator2] '("----"))
305 (define-key map [menu-bar grep compilation-first-error]
306 '(menu-item "First Match" first-error
307 :help "Restart at the first match, visit corresponding location"))
308 (define-key map [menu-bar grep compilation-previous-error]
309 '(menu-item "Previous Match" previous-error
310 :help "Visit the previous match and corresponding location"))
311 (define-key map [menu-bar grep compilation-next-error]
312 '(menu-item "Next Match" next-error
313 :help "Visit the next match and corresponding location"))
314 (define-key map [menu-bar grep grep-backward-history]
315 '(menu-item "Previous Command" grep-backward-history
316 :help "Run the previous grep command from the command history"))
317 (define-key map [menu-bar grep grep-forward-history]
318 '(menu-item "Next Command" grep-forward-history
319 :help "Run the next grep command from the command history"))
320 map)
321 "Keymap for grep buffers.
322 `compilation-minor-mode-map' is a cdr of this.")
323
324 (defvar grep-mode-tool-bar-map
325 ;; When bootstrapping, tool-bar-map is not properly initialized yet,
326 ;; so don't do anything.
327 (when (keymapp (butlast tool-bar-map))
328 (let ((map (butlast (copy-keymap tool-bar-map)))
329 (help (last tool-bar-map))) ;; Keep Help last in tool bar
330 (tool-bar-local-item
331 "left-arrow" 'previous-error-no-select 'previous-error-no-select map
332 :rtl "right-arrow"
333 :help "Goto previous match")
334 (tool-bar-local-item
335 "right-arrow" 'next-error-no-select 'next-error-no-select map
336 :rtl "left-arrow"
337 :help "Goto next match")
338 (tool-bar-local-item
339 "cancel" 'kill-compilation 'kill-compilation map
340 :enable '(let ((buffer (compilation-find-buffer)))
341 (get-buffer-process buffer))
342 :help "Stop grep")
343 (tool-bar-local-item
344 "refresh" 'recompile 'recompile map
345 :help "Restart grep")
346 (append map help))))
347
348 (defalias 'kill-grep 'kill-compilation)
349
350 ;;;; TODO --- refine this!!
351
352 ;; (defcustom grep-use-compilation-buffer t
353 ;; "When non-nil, grep specific commands update `compilation-last-buffer'.
354 ;; This means that standard compile commands like \\[next-error] and \\[compile-goto-error]
355 ;; can be used to navigate between grep matches (the default).
356 ;; Otherwise, the grep specific commands like \\[grep-next-match] must
357 ;; be used to navigate between grep matches."
358 ;; :type 'boolean
359 ;; :group 'grep)
360
361 ;; override compilation-last-buffer
362 (defvar grep-last-buffer nil
363 "The most recent grep buffer.
364 A grep buffer becomes most recent when you select Grep mode in it.
365 Notice that using \\[next-error] or \\[compile-goto-error] modifies
366 `compilation-last-buffer' rather than `grep-last-buffer'.")
367
368 ;;;###autoload
369 (defconst grep-regexp-alist
370 '(
371 ;; Use a tight regexp to handle weird file names (with colons
372 ;; in them) as well as possible. E.g., use [1-9][0-9]* rather
373 ;; than [0-9]+ so as to accept ":034:" in file names.
374 ("^\\(.*?[^/\n]\\):[ \t]*\\([1-9][0-9]*\\)[ \t]*:"
375 1 2
376 ;; Calculate column positions (col . end-col) of first grep match on a line
377 ((lambda ()
378 (when grep-highlight-matches
379 (let* ((beg (match-end 0))
380 (end (save-excursion (goto-char beg) (line-end-position)))
381 (mbeg (text-property-any beg end 'font-lock-face grep-match-face)))
382 (when mbeg
383 (- mbeg beg)))))
384 .
385 (lambda ()
386 (when grep-highlight-matches
387 (let* ((beg (match-end 0))
388 (end (save-excursion (goto-char beg) (line-end-position)))
389 (mbeg (text-property-any beg end 'font-lock-face grep-match-face))
390 (mend (and mbeg (next-single-property-change mbeg 'font-lock-face nil end))))
391 (when mend
392 (- mend beg)))))))
393 ("^Binary file \\(.+\\) matches$" 1 nil nil 0 1))
394 "Regexp used to match grep hits. See `compilation-error-regexp-alist'.")
395
396 (defvar grep-first-column 0 ; bug#10594
397 "Value to use for `compilation-first-column' in grep buffers.")
398
399 (defvar grep-error "grep hit"
400 "Message to print when no matches are found.")
401
402 ;; Reverse the colors because grep hits are not errors (though we jump there
403 ;; with `next-error'), and unreadable files can't be gone to.
404 (defvar grep-hit-face compilation-info-face
405 "Face name to use for grep hits.")
406
407 (defvar grep-error-face 'compilation-error
408 "Face name to use for grep error messages.")
409
410 (defvar grep-match-face 'match
411 "Face name to use for grep matches.")
412
413 (defvar grep-context-face 'shadow
414 "Face name to use for grep context lines.")
415
416 (defvar grep-mode-font-lock-keywords
417 '(;; Command output lines.
418 (": \\(.+\\): \\(?:Permission denied\\|No such \\(?:file or directory\\|device or address\\)\\)$"
419 1 grep-error-face)
420 ;; remove match from grep-regexp-alist before fontifying
421 ("^Grep[/a-zA-z]* started.*"
422 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t))
423 ("^Grep[/a-zA-z]* finished \\(?:(\\(matches found\\))\\|with \\(no matches found\\)\\).*"
424 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
425 (1 compilation-info-face nil t)
426 (2 compilation-warning-face nil t))
427 ("^Grep[/a-zA-z]* \\(exited abnormally\\|interrupt\\|killed\\|terminated\\)\\(?:.*with code \\([0-9]+\\)\\)?.*"
428 (0 '(face nil compilation-message nil help-echo nil mouse-face nil) t)
429 (1 grep-error-face)
430 (2 grep-error-face nil t))
431 ;; "filename-linenumber-" format is used for context lines in GNU grep,
432 ;; "filename=linenumber=" for lines with function names in "git grep -p".
433 ("^.+?[-=][0-9]+[-=].*\n" (0 grep-context-face)))
434 "Additional things to highlight in grep output.
435 This gets tacked on the end of the generated expressions.")
436
437 ;;;###autoload
438 (defvar grep-program (purecopy "grep")
439 "The default grep program for `grep-command' and `grep-find-command'.
440 This variable's value takes effect when `grep-compute-defaults' is called.")
441
442 ;;;###autoload
443 (defvar find-program (purecopy "find")
444 "The default find program.
445 This is used by commands like `grep-find-command', `find-dired'
446 and others.")
447
448 ;;;###autoload
449 (defvar xargs-program (purecopy "xargs")
450 "The default xargs program for `grep-find-command'.
451 See `grep-find-use-xargs'.
452 This variable's value takes effect when `grep-compute-defaults' is called.")
453
454 ;;;###autoload
455 (defvar grep-find-use-xargs nil
456 "How to invoke find and grep.
457 If `exec', use `find -exec {} ;'.
458 If `exec-plus' use `find -exec {} +'.
459 If `gnu', use `find -print0' and `xargs -0'.
460 Any other value means to use `find -print' and `xargs'.
461
462 This variable's value takes effect when `grep-compute-defaults' is called.")
463
464 ;; History of grep commands.
465 ;;;###autoload
466 (defvar grep-history nil "History list for grep.")
467 ;;;###autoload
468 (defvar grep-find-history nil "History list for grep-find.")
469
470 ;; History of lgrep and rgrep regexp and files args.
471 (defvar grep-regexp-history nil)
472 (defvar grep-files-history nil)
473
474 ;;;###autoload
475 (defun grep-process-setup ()
476 "Setup compilation variables and buffer for `grep'.
477 Set up `compilation-exit-message-function' and run `grep-setup-hook'."
478 (when (eq grep-highlight-matches 'auto-detect)
479 (grep-compute-defaults))
480 (unless (or (eq grep-highlight-matches 'auto-detect)
481 (null grep-highlight-matches)
482 ;; Don't output color escapes if they can't be
483 ;; highlighted with `font-lock-face' by `grep-filter'.
484 (null font-lock-mode))
485 ;; `setenv' modifies `process-environment' let-bound in `compilation-start'
486 ;; Any TERM except "dumb" allows GNU grep to use `--color=auto'
487 (setenv "TERM" "emacs-grep")
488 ;; GREP_COLOR is used in GNU grep 2.5.1, but deprecated in later versions
489 (setenv "GREP_COLOR" "01;31")
490 ;; GREP_COLORS is used in GNU grep 2.5.2 and later versions
491 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:sl=:cx=:ne"))
492 (set (make-local-variable 'compilation-exit-message-function)
493 (lambda (status code msg)
494 (if (eq status 'exit)
495 ;; This relies on the fact that `compilation-start'
496 ;; sets buffer-modified to nil before running the command,
497 ;; so the buffer is still unmodified if there is no output.
498 (cond ((and (zerop code) (buffer-modified-p))
499 '("finished (matches found)\n" . "matched"))
500 ((not (buffer-modified-p))
501 '("finished with no matches found\n" . "no match"))
502 (t
503 (cons msg code)))
504 (cons msg code))))
505 (run-hooks 'grep-setup-hook))
506
507 (defun grep-filter ()
508 "Handle match highlighting escape sequences inserted by the grep process.
509 This function is called from `compilation-filter-hook'."
510 (save-excursion
511 (forward-line 0)
512 (let ((end (point)) beg)
513 (goto-char compilation-filter-start)
514 (forward-line 0)
515 (setq beg (point))
516 ;; Only operate on whole lines so we don't get caught with part of an
517 ;; escape sequence in one chunk and the rest in another.
518 (when (< (point) end)
519 (setq end (copy-marker end))
520 ;; Highlight grep matches and delete marking sequences.
521 (while (re-search-forward "\033\\[0?1;31m\\(.*?\\)\033\\[[0-9]*m" end 1)
522 (replace-match (propertize (match-string 1)
523 'face nil 'font-lock-face grep-match-face)
524 t t))
525 ;; Delete all remaining escape sequences
526 (goto-char beg)
527 (while (re-search-forward "\033\\[[0-9;]*[mK]" end 1)
528 (replace-match "" t t))))))
529
530 (defun grep-probe (command args &optional func result)
531 (let (process-file-side-effects)
532 (equal (condition-case nil
533 (apply (or func 'process-file) command args)
534 (error nil))
535 (or result 0))))
536
537 ;;;###autoload
538 (defun grep-compute-defaults ()
539 ;; Keep default values.
540 (unless grep-host-defaults-alist
541 (add-to-list
542 'grep-host-defaults-alist
543 (cons nil
544 `((grep-command ,grep-command)
545 (grep-template ,grep-template)
546 (grep-use-null-device ,grep-use-null-device)
547 (grep-find-command ,grep-find-command)
548 (grep-find-template ,grep-find-template)
549 (grep-find-use-xargs ,grep-find-use-xargs)
550 (grep-highlight-matches ,grep-highlight-matches)))))
551 (let* ((host-id
552 (intern (or (file-remote-p default-directory) "localhost")))
553 (host-defaults (assq host-id grep-host-defaults-alist))
554 (defaults (assq nil grep-host-defaults-alist)))
555 ;; There are different defaults on different hosts. They must be
556 ;; computed for every host once.
557 (dolist (setting '(grep-command grep-template
558 grep-use-null-device grep-find-command
559 grep-find-template grep-find-use-xargs
560 grep-highlight-matches))
561 (set setting
562 (cadr (or (assq setting host-defaults)
563 (assq setting defaults)))))
564
565 (unless (or (not grep-use-null-device) (eq grep-use-null-device t))
566 (setq grep-use-null-device
567 (with-temp-buffer
568 (let ((hello-file (expand-file-name "HELLO" data-directory)))
569 (not
570 (and (if grep-command
571 ;; `grep-command' is already set, so
572 ;; use that for testing.
573 (grep-probe grep-command
574 `(nil t nil "^English" ,hello-file)
575 #'call-process-shell-command)
576 ;; otherwise use `grep-program'
577 (grep-probe grep-program
578 `(nil t nil "-nH" "^English" ,hello-file)))
579 (progn
580 (goto-char (point-min))
581 (looking-at
582 (concat (regexp-quote hello-file)
583 ":[0-9]+:English")))))))))
584
585 (when (eq grep-highlight-matches 'auto-detect)
586 (setq grep-highlight-matches
587 (with-temp-buffer
588 (and (grep-probe grep-program '(nil t nil "--help"))
589 (progn
590 (goto-char (point-min))
591 (search-forward "--color" nil t))
592 ;; Windows and DOS pipes fail `isatty' detection in Grep.
593 (if (memq system-type '(windows-nt ms-dos))
594 'always 'auto)))))
595
596 (unless (and grep-command grep-find-command
597 grep-template grep-find-template)
598 (let ((grep-options
599 (concat (if grep-use-null-device "-n" "-nH")
600 (if (grep-probe grep-program
601 `(nil nil nil "-e" "foo" ,null-device)
602 nil 1)
603 " -e"))))
604 (unless grep-command
605 (setq grep-command
606 (format "%s %s %s " grep-program
607 (or
608 (and grep-highlight-matches
609 (grep-probe grep-program
610 `(nil nil nil "--color" "x" ,null-device)
611 nil 1)
612 (if (eq grep-highlight-matches 'always)
613 "--color=always" "--color"))
614 "")
615 grep-options)))
616 (unless grep-template
617 (setq grep-template
618 (format "%s <X> <C> %s <R> <F>" grep-program grep-options)))
619 (unless grep-find-use-xargs
620 (setq grep-find-use-xargs
621 (cond
622 ((grep-probe find-program
623 `(nil nil nil ,null-device "-exec" "echo"
624 "{}" "+"))
625 'exec-plus)
626 ((and
627 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
628 (grep-probe xargs-program `(nil nil nil "-0" "echo")))
629 'gnu)
630 (t
631 'exec))))
632 (unless grep-find-command
633 (setq grep-find-command
634 (cond ((eq grep-find-use-xargs 'gnu)
635 ;; Windows shells need the program file name
636 ;; after the pipe symbol be quoted if they use
637 ;; forward slashes as directory separators.
638 (format "%s . -type f -print0 | \"%s\" -0 %s"
639 find-program xargs-program grep-command))
640 ((memq grep-find-use-xargs '(exec exec-plus))
641 (let ((cmd0 (format "%s . -type f -exec %s"
642 find-program grep-command))
643 (null (if grep-use-null-device
644 (format "%s " null-device)
645 "")))
646 (cons
647 (if (eq grep-find-use-xargs 'exec-plus)
648 (format "%s %s{} +" cmd0 null)
649 (format "%s {} %s%s" cmd0 null
650 (shell-quote-argument ";")))
651 (1+ (length cmd0)))))
652 (t
653 (format "%s . -type f -print | \"%s\" %s"
654 find-program xargs-program grep-command)))))
655 (unless grep-find-template
656 (setq grep-find-template
657 (let ((gcmd (format "%s <C> %s <R>"
658 grep-program grep-options))
659 (null (if grep-use-null-device
660 (format "%s " null-device)
661 "")))
662 (cond ((eq grep-find-use-xargs 'gnu)
663 (format "%s <D> <X> -type f <F> -print0 | \"%s\" -0 %s"
664 find-program xargs-program gcmd))
665 ((eq grep-find-use-xargs 'exec)
666 (format "%s <D> <X> -type f <F> -exec %s {} %s%s"
667 find-program gcmd null
668 (shell-quote-argument ";")))
669 ((eq grep-find-use-xargs 'exec-plus)
670 (format "%s <D> <X> -type f <F> -exec %s %s{} +"
671 find-program gcmd null))
672 (t
673 (format "%s <D> <X> -type f <F> -print | \"%s\" %s"
674 find-program xargs-program gcmd))))))))
675
676 ;; Save defaults for this host.
677 (setq grep-host-defaults-alist
678 (delete (assq host-id grep-host-defaults-alist)
679 grep-host-defaults-alist))
680 (add-to-list
681 'grep-host-defaults-alist
682 (cons host-id
683 `((grep-command ,grep-command)
684 (grep-template ,grep-template)
685 (grep-use-null-device ,grep-use-null-device)
686 (grep-find-command ,grep-find-command)
687 (grep-find-template ,grep-find-template)
688 (grep-find-use-xargs ,grep-find-use-xargs)
689 (grep-highlight-matches ,grep-highlight-matches))))))
690
691 (defun grep-tag-default ()
692 (or (and transient-mark-mode mark-active
693 (/= (point) (mark))
694 (buffer-substring-no-properties (point) (mark)))
695 (funcall (or find-tag-default-function
696 (get major-mode 'find-tag-default-function)
697 'find-tag-default))
698 ""))
699
700 (defun grep-default-command ()
701 "Compute the default grep command for \\[universal-argument] \\[grep] to offer."
702 (let ((tag-default (shell-quote-argument (grep-tag-default)))
703 ;; This a regexp to match single shell arguments.
704 ;; Could someone please add comments explaining it?
705 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
706 (grep-default (or (car grep-history) grep-command)))
707 ;; In the default command, find the arg that specifies the pattern.
708 (when (or (string-match
709 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
710 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
711 grep-default)
712 ;; If the string is not yet complete.
713 (string-match "\\(\\)\\'" grep-default))
714 ;; Maybe we will replace the pattern with the default tag.
715 ;; But first, maybe replace the file name pattern.
716 (condition-case nil
717 (unless (or (not (stringp buffer-file-name))
718 (when (match-beginning 2)
719 (save-match-data
720 (string-match
721 (wildcard-to-regexp
722 (file-name-nondirectory
723 (match-string 3 grep-default)))
724 (file-name-nondirectory buffer-file-name)))))
725 (setq grep-default (concat (substring grep-default
726 0 (match-beginning 2))
727 " *."
728 (file-name-extension buffer-file-name))))
729 ;; In case wildcard-to-regexp gets an error
730 ;; from invalid data.
731 (error nil))
732 ;; Now replace the pattern with the default tag.
733 (replace-match tag-default t t grep-default 1))))
734
735
736 ;;;###autoload
737 (define-compilation-mode grep-mode "Grep"
738 "Sets `grep-last-buffer' and `compilation-window-height'."
739 (setq grep-last-buffer (current-buffer))
740 (set (make-local-variable 'tool-bar-map) grep-mode-tool-bar-map)
741 (set (make-local-variable 'compilation-error-face)
742 grep-hit-face)
743 (set (make-local-variable 'compilation-error-regexp-alist)
744 grep-regexp-alist)
745 ;; compilation-directory-matcher can't be nil, so we set it to a regexp that
746 ;; can never match.
747 (set (make-local-variable 'compilation-directory-matcher) '("\\`a\\`"))
748 (set (make-local-variable 'compilation-process-setup-function)
749 'grep-process-setup)
750 (set (make-local-variable 'compilation-disable-input) t)
751 (set (make-local-variable 'compilation-error-screen-columns)
752 grep-error-screen-columns)
753 (add-hook 'compilation-filter-hook 'grep-filter nil t))
754
755 (defvar grep--command-history nil)
756 (defvar grep--history-inhibit nil)
757 (defvar grep--history-place 0)
758
759 (defun grep--save-history (command)
760 (unless grep--history-inhibit
761 (push (cons default-directory command) grep--command-history)
762 (setq grep--history-place 0)
763 ;; Don't let the history grow without bounds.
764 (when (> (length grep--command-history) 100)
765 (setcdr (nthcdr 100 grep--command-history) nil))))
766
767 (defun grep-forward-history ()
768 "Go to the next result in the grep command history.
769 Also see `grep-backward-history'."
770 (interactive)
771 (let ((elem (and (> grep--history-place 0)
772 (nth (1- grep--history-place) grep--command-history)))
773 (grep--history-inhibit t))
774 (unless elem
775 (error "Nothing further in the command history"))
776 (cl-decf grep--history-place)
777 (let ((default-directory (car elem)))
778 (grep (cdr elem)))))
779
780 (defun grep-backward-history ()
781 "Go to the previous result in the grep command history.
782 Also see `grep-forward-history'."
783 (interactive)
784 (let ((elem (nth (1+ grep--history-place) grep--command-history))
785 (grep--history-inhibit t))
786 (unless elem
787 (error "Nothing further in the command history"))
788 (cl-incf grep--history-place)
789 (let ((default-directory (car elem)))
790 (grep (cdr elem)))))
791
792 (defun grep--save-buffers ()
793 (when grep-save-buffers
794 (save-some-buffers (and (not (eq grep-save-buffers 'ask))
795 (not (functionp grep-save-buffers)))
796 (and (functionp grep-save-buffers)
797 grep-save-buffers))))
798
799 ;;;###autoload
800 (defun grep (command-args)
801 "Run Grep with user-specified COMMAND-ARGS, collect output in a buffer.
802 While Grep runs asynchronously, you can use \\[next-error] (M-x next-error),
803 or \\<grep-mode-map>\\[compile-goto-error] in the *grep* \
804 buffer, to go to the lines where Grep found
805 matches. To kill the Grep job before it finishes, type \\[kill-compilation].
806
807 Noninteractively, COMMAND-ARGS should specify the Grep command-line
808 arguments.
809
810 For doing a recursive `grep', see the `rgrep' command. For running
811 Grep in a specific directory, see `lgrep'.
812
813 This command uses a special history list for its COMMAND-ARGS, so you
814 can easily repeat a grep command.
815
816 A prefix argument says to default the COMMAND-ARGS based on the current
817 tag the cursor is over, substituting it into the last Grep command
818 in the Grep command history (or into `grep-command' if that history
819 list is empty)."
820 (interactive
821 (progn
822 (grep-compute-defaults)
823 (let ((default (grep-default-command)))
824 (list (read-shell-command "Run grep (like this): "
825 (if current-prefix-arg default grep-command)
826 'grep-history
827 (if current-prefix-arg nil default))))))
828 (grep--save-history command-args)
829 (grep--save-buffers)
830 ;; Setting process-setup-function makes exit-message-function work
831 ;; even when async processes aren't supported.
832 (compilation-start (if (and grep-use-null-device null-device)
833 (concat command-args " " null-device)
834 command-args)
835 'grep-mode))
836
837
838 ;;;###autoload
839 (defun grep-find (command-args)
840 "Run grep via find, with user-specified args COMMAND-ARGS.
841 Collect output in a buffer.
842 While find runs asynchronously, you can use the \\[next-error] command
843 to find the text that grep hits refer to.
844
845 This command uses a special history list for its arguments, so you can
846 easily repeat a find command."
847 (interactive
848 (progn
849 (grep-compute-defaults)
850 (if grep-find-command
851 (list (read-shell-command "Run find (like this): "
852 grep-find-command 'grep-find-history))
853 ;; No default was set
854 (read-string
855 "compile.el: No `grep-find-command' command available. Press RET.")
856 (list nil))))
857 (when command-args
858 (let ((null-device nil)) ; see grep
859 (grep command-args))))
860
861 ;;;###autoload
862 (defalias 'find-grep 'grep-find)
863
864
865 ;; User-friendly interactive API.
866
867 (defconst grep-expand-keywords
868 '(("<C>" . (mapconcat #'identity opts " "))
869 ("<D>" . (or dir "."))
870 ("<F>" . files)
871 ("<N>" . null-device)
872 ("<X>" . excl)
873 ("<R>" . (shell-quote-argument (or regexp ""))))
874 "List of substitutions performed by `grep-expand-template'.
875 If car of an element matches, the cdr is evalled in to get the
876 substitution string. Note dynamic scoping of variables.")
877
878 (defun grep-expand-template (template &optional regexp files dir excl)
879 "Patch grep COMMAND string replacing <C>, <D>, <F>, <R>, and <X>."
880 (let* ((command template)
881 (env `((opts . ,(let (opts)
882 (when (and case-fold-search
883 (isearch-no-upper-case-p regexp t))
884 (push "-i" opts))
885 (cond
886 ((eq grep-highlight-matches 'always)
887 (push "--color=always" opts))
888 ((eq grep-highlight-matches 'auto)
889 (push "--color" opts)))
890 opts))
891 (excl . ,excl)
892 (dir . ,dir)
893 (files . ,files)
894 (regexp . ,regexp)))
895 (case-fold-search nil))
896 (dolist (kw grep-expand-keywords command)
897 (if (string-match (car kw) command)
898 (setq command
899 (replace-match
900 (or (if (symbolp (cdr kw))
901 (eval (cdr kw) env)
902 (save-match-data (eval (cdr kw) env)))
903 "")
904 t t command))))))
905
906 (defun grep-read-regexp ()
907 "Read regexp arg for interactive grep using `read-regexp'."
908 (read-regexp "Search for" 'grep-tag-default 'grep-regexp-history))
909
910 (defun grep-read-files (regexp)
911 "Read files arg for interactive grep."
912 (let* ((bn (or (buffer-file-name)
913 (replace-regexp-in-string "<[0-9]+>\\'" "" (buffer-name))))
914 (fn (and bn
915 (stringp bn)
916 (file-name-nondirectory bn)))
917 (default-alias
918 (and fn
919 (let ((aliases (remove (assoc "all" grep-files-aliases)
920 grep-files-aliases))
921 alias)
922 (while aliases
923 (setq alias (car aliases)
924 aliases (cdr aliases))
925 (if (string-match (mapconcat
926 'wildcard-to-regexp
927 (split-string (cdr alias) nil t)
928 "\\|")
929 fn)
930 (setq aliases nil)
931 (setq alias nil)))
932 (cdr alias))))
933 (default-extension
934 (and fn
935 (let ((ext (file-name-extension fn)))
936 (and ext (concat "*." ext)))))
937 (default
938 (or default-alias
939 default-extension
940 (car grep-files-history)
941 (car (car grep-files-aliases))))
942 (files (completing-read
943 (concat "Search for \"" regexp
944 "\" in files"
945 (if default (concat " (default " default ")"))
946 ": ")
947 'read-file-name-internal
948 nil nil nil 'grep-files-history
949 (delete-dups
950 (delq nil (append (list default default-alias default-extension)
951 (mapcar 'car grep-files-aliases)))))))
952 (and files
953 (or (cdr (assoc files grep-files-aliases))
954 files))))
955
956 ;;;###autoload
957 (defun lgrep (regexp &optional files dir confirm)
958 "Run grep, searching for REGEXP in FILES in directory DIR.
959 The search is limited to file names matching shell pattern FILES.
960 FILES may use abbreviations defined in `grep-files-aliases', e.g.
961 entering `ch' is equivalent to `*.[ch]'.
962
963 With \\[universal-argument] prefix, you can edit the constructed shell command line
964 before it is executed.
965 With two \\[universal-argument] prefixes, directly edit and run `grep-command'.
966
967 Collect output in a buffer. While grep runs asynchronously, you
968 can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
969 in the grep output buffer,
970 to go to the lines where grep found matches.
971
972 This command shares argument histories with \\[rgrep] and \\[grep]."
973 (interactive
974 (progn
975 (grep-compute-defaults)
976 (cond
977 ((and grep-command (equal current-prefix-arg '(16)))
978 (list (read-from-minibuffer "Run: " grep-command
979 nil nil 'grep-history)))
980 ((not grep-template)
981 (error "grep.el: No `grep-template' available"))
982 (t (let* ((regexp (grep-read-regexp))
983 (files (grep-read-files regexp))
984 (dir (read-directory-name "In directory: "
985 nil default-directory t))
986 (confirm (equal current-prefix-arg '(4))))
987 (list regexp files dir confirm))))))
988 (when (and (stringp regexp) (> (length regexp) 0))
989 (unless (and dir (file-accessible-directory-p dir))
990 (setq dir default-directory))
991 (let ((command regexp))
992 (if (null files)
993 (if (string= command grep-command)
994 (setq command nil))
995 (setq dir (file-name-as-directory (expand-file-name dir)))
996 (setq command (grep-expand-template
997 grep-template
998 regexp
999 files
1000 nil
1001 (and grep-find-ignored-files
1002 (concat " --exclude="
1003 (mapconcat
1004 #'(lambda (ignore)
1005 (cond ((stringp ignore)
1006 (shell-quote-argument ignore))
1007 ((consp ignore)
1008 (and (funcall (car ignore) dir)
1009 (shell-quote-argument
1010 (cdr ignore))))))
1011 grep-find-ignored-files
1012 " --exclude=")))))
1013 (when command
1014 (if confirm
1015 (setq command
1016 (read-from-minibuffer "Confirm: "
1017 command nil nil 'grep-history))
1018 (add-to-history 'grep-history command))))
1019 (when command
1020 (let ((default-directory dir))
1021 ;; Setting process-setup-function makes exit-message-function work
1022 ;; even when async processes aren't supported.
1023 (grep--save-buffers)
1024 (compilation-start (if (and grep-use-null-device null-device)
1025 (concat command " " null-device)
1026 command)
1027 'grep-mode))
1028 (if (eq next-error-last-buffer (current-buffer))
1029 (setq default-directory dir))))))
1030
1031
1032 (defvar find-name-arg) ; not autoloaded but defined in find-dired
1033
1034 ;;;###autoload
1035 (defun rgrep (regexp &optional files dir confirm)
1036 "Recursively grep for REGEXP in FILES in directory tree rooted at DIR.
1037 The search is limited to file names matching shell pattern FILES.
1038 FILES may use abbreviations defined in `grep-files-aliases', e.g.
1039 entering `ch' is equivalent to `*.[ch]'.
1040
1041 With \\[universal-argument] prefix, you can edit the constructed shell command line
1042 before it is executed.
1043 With two \\[universal-argument] prefixes, directly edit and run `grep-find-command'.
1044
1045 Collect output in a buffer. While the recursive grep is running,
1046 you can use \\[next-error] (M-x next-error), or \\<grep-mode-map>\\[compile-goto-error] \
1047 in the grep output buffer,
1048 to visit the lines where matches were found. To kill the job
1049 before it finishes, type \\[kill-compilation].
1050
1051 This command shares argument histories with \\[lgrep] and \\[grep-find].
1052
1053 When called programmatically and FILES is nil, REGEXP is expected
1054 to specify a command to run."
1055 (interactive
1056 (progn
1057 (grep-compute-defaults)
1058 (cond
1059 ((and grep-find-command (equal current-prefix-arg '(16)))
1060 (list (read-from-minibuffer "Run: " grep-find-command
1061 nil nil 'grep-find-history)))
1062 ((not grep-find-template)
1063 (error "grep.el: No `grep-find-template' available"))
1064 (t (let* ((regexp (grep-read-regexp))
1065 (files (grep-read-files regexp))
1066 (dir (read-directory-name "Base directory: "
1067 nil default-directory t))
1068 (confirm (equal current-prefix-arg '(4))))
1069 (list regexp files dir confirm))))))
1070 (when (and (stringp regexp) (> (length regexp) 0))
1071 (unless (and dir (file-accessible-directory-p dir))
1072 (setq dir default-directory))
1073 (if (null files)
1074 (if (not (string= regexp (if (consp grep-find-command)
1075 (car grep-find-command)
1076 grep-find-command)))
1077 (compilation-start regexp 'grep-mode))
1078 (setq dir (file-name-as-directory (expand-file-name dir)))
1079 (let ((command (rgrep-default-command regexp files nil)))
1080 (when command
1081 (if confirm
1082 (setq command
1083 (read-from-minibuffer "Confirm: "
1084 command nil nil 'grep-find-history))
1085 (add-to-history 'grep-find-history command))
1086 (grep--save-buffers)
1087 (let ((default-directory dir))
1088 (compilation-start command 'grep-mode))
1089 ;; Set default-directory if we started rgrep in the *grep* buffer.
1090 (if (eq next-error-last-buffer (current-buffer))
1091 (setq default-directory dir)))))))
1092
1093 (defun rgrep-default-command (regexp files dir)
1094 "Compute the command for \\[rgrep] to use by default."
1095 (require 'find-dired) ; for `find-name-arg'
1096 (grep-expand-template
1097 grep-find-template
1098 regexp
1099 (concat (shell-quote-argument "(")
1100 " " find-name-arg " "
1101 (mapconcat
1102 #'shell-quote-argument
1103 (split-string files)
1104 (concat " -o " find-name-arg " "))
1105 " "
1106 (shell-quote-argument ")"))
1107 dir
1108 (concat
1109 (and grep-find-ignored-directories
1110 (concat "-type d "
1111 (shell-quote-argument "(")
1112 ;; we should use shell-quote-argument here
1113 " -path "
1114 (mapconcat
1115 'identity
1116 (delq nil (mapcar
1117 #'(lambda (ignore)
1118 (cond ((stringp ignore)
1119 (shell-quote-argument
1120 (concat "*/" ignore)))
1121 ((consp ignore)
1122 (and (funcall (car ignore) dir)
1123 (shell-quote-argument
1124 (concat "*/"
1125 (cdr ignore)))))))
1126 grep-find-ignored-directories))
1127 " -o -path ")
1128 " "
1129 (shell-quote-argument ")")
1130 " -prune -o "))
1131 (and grep-find-ignored-files
1132 (concat (shell-quote-argument "!") " -type d "
1133 (shell-quote-argument "(")
1134 ;; we should use shell-quote-argument here
1135 " -name "
1136 (mapconcat
1137 #'(lambda (ignore)
1138 (cond ((stringp ignore)
1139 (shell-quote-argument ignore))
1140 ((consp ignore)
1141 (and (funcall (car ignore) dir)
1142 (shell-quote-argument
1143 (cdr ignore))))))
1144 grep-find-ignored-files
1145 " -o -name ")
1146 " "
1147 (shell-quote-argument ")")
1148 " -prune -o ")))))
1149
1150 ;;;###autoload
1151 (defun zrgrep (regexp &optional files dir confirm template)
1152 "Recursively grep for REGEXP in gzipped FILES in tree rooted at DIR.
1153 Like `rgrep' but uses `zgrep' for `grep-program', sets the default
1154 file name to `*.gz', and sets `grep-highlight-matches' to `always'."
1155 (interactive
1156 (progn
1157 ;; Compute standard default values.
1158 (grep-compute-defaults)
1159 ;; Compute the default zrgrep command by running `grep-compute-defaults'
1160 ;; for grep program "zgrep", but not changing global values.
1161 (let ((grep-program "zgrep")
1162 ;; Don't change global values for variables computed
1163 ;; by `grep-compute-defaults'.
1164 (grep-find-template nil)
1165 (grep-find-command nil)
1166 (grep-host-defaults-alist nil)
1167 ;; Use for `grep-read-files'
1168 (grep-files-aliases '(("all" . "* .*")
1169 ("gz" . "*.gz"))))
1170 ;; Recompute defaults using let-bound values above.
1171 (grep-compute-defaults)
1172 (cond
1173 ((and grep-find-command (equal current-prefix-arg '(16)))
1174 (list (read-from-minibuffer "Run: " grep-find-command
1175 nil nil 'grep-find-history)))
1176 ((not grep-find-template)
1177 (error "grep.el: No `grep-find-template' available"))
1178 (t (let* ((regexp (grep-read-regexp))
1179 (files (grep-read-files regexp))
1180 (dir (read-directory-name "Base directory: "
1181 nil default-directory t))
1182 (confirm (equal current-prefix-arg '(4))))
1183 (list regexp files dir confirm grep-find-template)))))))
1184 (let ((grep-find-template template)
1185 ;; Set `grep-highlight-matches' to `always'
1186 ;; since `zgrep' puts filters in the grep output.
1187 (grep-highlight-matches 'always))
1188 (rgrep regexp files dir confirm)))
1189
1190 ;;;###autoload
1191 (defalias 'rzgrep 'zrgrep)
1192
1193 (provide 'grep)
1194
1195 ;;; grep.el ends here