Initial Commit
[packages] / xemacs-packages / dired / dired-grep.el
1 ;; -*-Emacs-Lisp-*-
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;
4 ;; File:           dired-grep.el
5 ;; RCS:
6 ;; Dired Version: 7.17
7 ;; Description:    Support for running grep on marked files in a dired buffer.
8 ;; Author:         Sandy Rutherford <sandy@ibm550.sissa.it>
9 ;; Created:        Tue Jul 13 22:59:37 1993 by sandy on ibm550
10 ;;
11 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
12
13 ;;; Copyright (C) 1993 Sandy Rutherford
14
15 ;;; This program is free software; you can redistribute it and/or modify
16 ;;; it under the terms of the GNU General Public License as published by
17 ;;; the Free Software Foundation; either version 1, or (at your option)
18 ;;; any later version.
19 ;;;
20 ;;; This program is distributed in the hope that it will be useful,
21 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;;; GNU General Public License for more details.
24 ;;;
25 ;;; A copy of the GNU General Public License can be obtained from this
26 ;;; program's author (send electronic mail to sandy@ibm550.sissa.it) or
27 ;;; from the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
28 ;;; MA 02139, USA.
29
30 ;;; The user-level command in this file is dired-grep-file. The command
31 ;;; grep is defined in compile.el. This file does not change that command.
32
33 ;;; Requirements and provisions
34
35 (provide 'dired-grep)
36 (or (fboundp 'file-local-copy) (require 'emacs-19))
37 (or (fboundp 'generate-new-buffer) (require 'emacs-19))
38 (require 'dired)
39
40 ;;; Variables
41
42 (defvar dired-grep-program "grep"
43   "Name of program to use to grep files.
44 When used with the \"-n\" flag, program must precede each match with \"###:\",
45 where \"###\" is the line number of the match.
46 If there are grep programs which don't do this, we'll try to think of
47 some way to accomodate them.")
48
49 (defvar dired-grep-switches nil
50   "*Switches to pass to the grep program.
51 This may be either a string or a list of strings.  It is not necessary to 
52 include \"-n\" as that switch is always used.")
53
54 (defvar dired-grep-zcat-program "zcat"
55   "Name of program to cat compressed files.")
56
57 (defvar dired-grep-compressed-file ".\\.\\(gz\\|[zZ]\\)$"
58   "Regexp to match names of compressed files.")
59
60 (defvar dired-grep-pop-up-buffer t
61   "*If non-nil, the grep output is displayed in the other window upon
62 completion of the grep process.")
63
64 (defvar dired-grep-results-buffer "*Dired Grep*"
65   "Name of buffer where grep results are logged.")
66
67 (defvar dired-grep-mode-hook nil
68   "Hook run after going into grep-mode")
69
70 (defvar grep-history nil
71   "History of previous grep patterns used.")
72
73 (defvar dired-grep-parse-flags-cache nil)
74 (defvar dired-grep-parse-flags-cache-result nil)
75
76 (defvar dired-grep-mode-map nil
77   "Keymap for dired-grep-mode buffers.")
78
79 (if dired-grep-mode-map
80     ()
81   (setq dired-grep-mode-map (make-keymap))
82   (suppress-keymap dired-grep-mode-map)
83   (define-key dired-grep-mode-map "[" 'backward-page)
84   (define-key dired-grep-mode-map "]" 'forward-page)
85   (define-key dired-grep-mode-map ">" 'dired-grep-next-hit)
86   (define-key dired-grep-mode-map "<" 'dired-grep-previous-hit)
87   (define-key dired-grep-mode-map "n" 'dired-grep-advertized-next-hit)
88   (define-key dired-grep-mode-map "p" 'dired-grep-advertized-previous-hit)
89   (define-key dired-grep-mode-map "k" 'dired-grep-delete-line)
90   (define-key dired-grep-mode-map "d" 'dired-grep-delete-page)
91   (define-key dired-grep-mode-map "^" 'dired-grep-delete-preceding-pages)
92   (define-key dired-grep-mode-map "f" 'dired-grep-find-file)
93   (define-key dired-grep-mode-map "e" 'dired-grep-find-file)
94   (define-key dired-grep-mode-map "m" 'dired-grep-delete-misses)
95   (define-key dired-grep-mode-map "o" 'dired-grep-find-file-other-window)
96   (define-key dired-grep-mode-map "v" 'dired-grep-view-file)
97   (define-key dired-grep-mode-map "w" 'dired-grep-delete-grep-for)
98   (define-key dired-grep-mode-map "\C-_" 'dired-grep-undo)
99   (define-key dired-grep-mode-map "\C-xu" 'dired-grep-undo))
100
101 ;;; Entry functions from dired.el
102
103 (defun dired-grep (pattern flags)
104   ;; grep the file on the current line for PATTERN, using grep flags FLAGS.
105   ;; Return nil on success. Offending filename otherwise.
106   (let* ((file (dired-get-filename))
107          (result (dired-grep-file pattern file flags)))
108     (and result
109          (progn
110            (dired-log (buffer-name (current-buffer)) (concat result "\n"))
111            file))))
112
113 ;;;###autoload
114 (defun dired-do-grep (pattern &optional flags arg)
115   "Grep marked files for a pattern. With a \C-u prefix prompts for grep flags."
116   (interactive
117    (let* ((switches (if (consp current-prefix-arg)
118                         (read-string "Switches for grep: ")
119                       dired-grep-switches))
120           (prompt (format "grep %sfor pattern"
121                           (if (stringp switches)
122                               (if (string-equal switches "")
123                                   switches
124                                 (concat switches " "))
125                             (if switches
126                                 (concat (mapconcat 'identity switches " ") " ")
127                               ""))))
128           (pattern (dired-read-with-history (concat prompt ": ")
129                                             nil 'grep-history)))
130      (list pattern switches
131            (and (not (consp current-prefix-arg)) current-prefix-arg))))
132   (dired-map-over-marks-check
133    (function
134     (lambda ()
135       (dired-grep pattern flags)))
136    arg 'grep (concat "grep " flags (if flags " \"" "\"") pattern "\"") t))
137
138 ;;; Utility functions
139
140 (defun dired-grep-get-results-buffer ()
141   ;; Return the buffer object of the dired-grep-results-buffer, creating and
142   ;; initializing it if necessary.
143   (let ((buffer (get-buffer dired-grep-results-buffer)))
144     (or buffer
145          (save-excursion
146            (set-buffer (setq buffer (get-buffer-create dired-grep-results-buffer)))
147            (dired-grep-mode)
148            buffer))))
149
150 ;; Only define if undefined, in case efs has got to it already.
151 (or (fboundp 'dired-grep-delete-local-temp-file)
152     (defun dired-grep-delete-local-temp-file (file)
153       (condition-case nil (delete-file file) (error nil))))
154
155 ;;; Commands in the dired-grep-results-buffer buffer.
156
157 (defun dired-grep-mode ()
158   "\\<dired-grep-mode-map>Mode for perusing grep output generated from dired.
159 The output is divided into pages, one page per grepped file.
160
161 Summary of commands:
162
163 Move to next grep hit                     \\[dired-grep-advertized-next-hit], \\[dired-grep-next-hit]
164 Move to previous grep hit                 \\[dired-grep-advertized-previous-hit], \\[dired-grep-previous-hit]
165 Move to output for next file              \\[forward-page]
166 Move to output for previous file          \\[backward-page]
167
168 Delete the current grep line              \\[dired-grep-delete-line]
169 Delete all output for current file        \\[dired-grep-delete-page]
170 Delete all preceding pages                \\[dired-grep-delete-preceding-pages]
171 Delete all pages for files with no hits   \\[dired-grep-delete-misses]
172 Delete all pages which grep for the 
173   same pattern as the current page        \\[dired-grep-delete-grep-for]
174
175 Find current grep hit in file             \\[dired-grep-find-file]
176 Find current grep hit in other window     \\[dired-grep-find-file-other-window]
177 View current grep hit                     \\[dired-grep-view-file]
178
179 Undo changes to the grep buffer           \\[dired-grep-undo]
180
181 Keybindings:
182 \\{dired-grep-mode-map}"
183   (kill-all-local-variables)
184   (use-local-map dired-grep-mode-map)
185   (setq major-mode 'dired-grep-mode
186         mode-name "Dired-Grep"
187         buffer-read-only t)
188   (set (make-local-variable 'page-delimiter) "\n\n")
189   (run-hooks 'dired-grep-mode-hook))
190
191 (defun dired-grep-current-file-and-line ()
192   ;; Returns a list \(FILENAME . LINE\) corresponding to the filename
193   ;; and line number associated with the position of the point in a
194   ;; grep buffer. Returns nil if there is none.
195   (save-excursion
196     (let (file line)
197       (and
198        (progn
199          (beginning-of-line)
200          (looking-at "[0-9]+:"))
201        (progn
202          (setq line (string-to-int (buffer-substring (point)
203                                                      (1- (match-end 0)))))
204          (if (search-backward "\n\n" nil 'move) (forward-char 2))
205          (looking-at "Hits for "))
206        (progn
207          (forward-line 1)
208          (looking-at "   "))
209        (progn
210          (setq file (buffer-substring (match-end 0)
211                                       (progn (end-of-line) (1- (point)))))
212          (cons file line))))))
213
214 (defun dired-grep-find-file ()
215   (interactive)
216   (let ((file (dired-grep-current-file-and-line)))
217     (if file
218         (progn
219           (find-file (car file))
220           (goto-line (cdr file))
221           (recenter '(4)))
222       (error "No file specified by this line."))))
223
224 (defun dired-grep-find-file-other-window ()
225   (interactive)
226   (let ((file (dired-grep-current-file-and-line)))
227     (if file
228         (progn
229           (find-file-other-window (car file))
230           (goto-line (cdr  file))
231           (recenter '(4)))
232       (error "No file specified by this line."))))
233
234 (defun dired-grep-view-file ()
235   (interactive)
236   (let ((file (dired-grep-current-file-and-line)))
237     (if file
238         (let* ((fun (function
239                      (lambda () (goto-line (cdr file)) (recenter '(4)))))
240                (view-hook
241                 (if (boundp 'view-hook)
242                     (if (and (listp view-hook)
243                              (not (eq (car view-hook) 'lambda)))
244                         (cons fun view-hook)
245                       (list fun view-hook))
246                   fun)))
247           (view-file (car file)))
248       (error "No file specified by this line."))))
249
250 (defun dired-grep-next-hit (arg)
251   "Moves to the next, or next ARGth, grep hit."
252   (interactive "p")
253   (forward-line 1)
254   (if (re-search-forward "^[0-9]" nil 'move arg)
255       (goto-char (match-beginning 0))
256     (error "No further grep hits")))
257
258 (defun dired-grep-previous-hit (arg)
259   "Moves to the previous, or previous ARGth, grep hit."
260   (interactive "p")
261   (beginning-of-line)
262   (or (re-search-backward "^[0-9]" nil 'move arg)
263       (error "No further grep hits")))
264
265 ;; These are only so we can get a decent looking help buffer.
266 (fset 'dired-grep-advertized-next-hit 'dired-grep-next-hit)
267 (fset 'dired-grep-advertized-previous-hit 'dired-grep-previous-hit)
268
269 (defun dired-grep-delete-page (arg)
270   "Deletes the current and ARG - 1 following grep output pages.
271 If ARG is negative, deletes preceding pages."
272   (interactive "p")
273   (let ((done 0)
274         (buffer-read-only nil)
275         (backward (< arg 0))
276         start)
277     (if backward (setq arg (- arg)))
278     (while (and (< done arg) (not (if backward (bobp) (eobp))))
279       (or (looking-at "^\n")
280           (if (search-backward "\n\n" nil 'move) (forward-char 1)))
281       (setq start (point))
282       (if (search-forward "\n\n" nil 'move) (forward-char -1))
283       (delete-region start (point))
284       (and (bobp) (not (eobp)) (delete-char 1))
285       (if backward (skip-chars-backward "\n"))
286       (setq done (1+ done)))))
287
288 (defun dired-grep-delete-preceding-pages ()
289   "Deletes the current, and all preceding pages from the grep buffer."
290   (interactive)
291   (let ((buffer-read-only nil))
292     (if (looking-at "^\n")
293         (forward-char 1)
294       (search-forward "\n\n" nil 'move))
295     (delete-region (point-min) (point))))
296
297 (defun dired-grep-delete-line (arg)
298   "Deletes the current line and ARG following lines from the grep buffer.
299 Only operates on lines which correspond to file lines for grep hits."
300   (interactive "p")
301   (let ((opoint (point))
302         (buffer-read-only nil)
303         (backward (< arg 0))
304         (done 0))
305     (beginning-of-line)
306     (if backward (setq arg (- arg)))
307     (if (looking-at "[0-9]+:")
308         (while (< done arg)
309           (delete-region (point) (progn (forward-line 1) (point)))
310           (if backward (forward-line -1))
311           (if (looking-at "[0-9]+:")
312               (setq done (1+ done))
313             (setq done arg)))
314       ;; Do nothing.
315       (goto-char opoint))))
316
317 (defun dired-grep-delete-grep-for ()
318   "Deletes all pages which grep some file for the pattern of the current page."
319   (interactive)
320   (save-excursion
321     ;; In case we happen to be right at the beginning of a page.
322     (or (eobp) (eolp) (forward-char 1))
323     (forward-page -1) ; gets to the beginning of the page.
324     (let* ((eol (save-excursion (end-of-line) (point)))
325            (line (and (search-forward " grep " eol t)
326                       (buffer-substring (point) eol))))
327       (if line
328           (progn
329             (goto-char (point-min))
330             (while (not (eobp))
331               (let* ((eol (save-excursion (end-of-line) (point)))
332                      (this-line (and (search-forward " grep " eol t)
333                                      (buffer-substring (point) eol))))
334                 (if (equal line this-line)
335                     (progn
336                       (dired-grep-delete-page 1)
337                       (skip-chars-forward "\n"))
338                   (or (eobp) (forward-page 1))))))))))
339
340 (defun dired-grep-delete-misses ()
341   "Delete all pages for which there were no grep hits.
342 Deletes pages for which grep failed because of an error too."
343   (interactive)
344   (save-excursion
345     (goto-char (point-min))
346     (while (not (eobp))
347       (if (looking-at "Grep failed \\|No hits ")
348           (progn
349             (dired-grep-delete-page 1)
350             (skip-chars-forward "\n"))
351         (forward-page 1)))))
352
353 (defun dired-grep-undo ()
354   "Undoes deletions in a grep buffer."
355   (interactive)
356   (let (buffer-read-only)
357     (undo)))
358
359 ;;; Commands for grepping files.
360
361 (defun dired-grep-parse-flags (string)
362   ;; Breaks a string of switches into a list.
363   (if (equal dired-grep-parse-flags-cache string)
364       dired-grep-parse-flags-cache-result
365     (let ((length (length string))
366           (pointer 0)
367           (start 0)
368           (result nil))
369       (while (and (< pointer length) (= (aref string pointer) ?\ ))
370         (setq pointer (1+ pointer)))
371     (while (< pointer length)
372       (setq start pointer)
373       (while (and (< pointer length) (/= (aref string pointer) ?\ ))
374         (setq pointer (1+ pointer)))
375       (setq result (cons (substring string start pointer) result))
376       (while (and (< pointer length) (= (aref string pointer) ?\ ))
377         (setq pointer (1+ pointer))))
378     (setq dired-grep-parse-flags-cache string
379           dired-grep-parse-flags-cache-result (nreverse result)))))
380   
381 (defun dired-grep-file (pattern file &optional flags)
382   "Grep for PATTERN in FILE.
383 Optional FLAGS are flags to pass to the grep program.
384 When used interactively, will prompt for FLAGS if a prefix argument is used."
385   (interactive 
386    (let* ((switches (if (consp current-prefix-arg)
387                         (read-string "Switches for grep: ")
388                       dired-grep-switches))
389           (prompt (format "grep %sfor pattern"
390                           (if (stringp switches)
391                               (if (string-match switches "^ *$")
392                                   ""
393                                 (concat switches " "))
394                             (if switches
395                                 (concat (mapconcat 'identity switches " ") " ")
396                               ""))))
397           (pattern (dired-read-with-history (concat prompt ": ")
398                                             nil 'grep-history))
399           (file (read-file-name (concat prompt " \"" pattern "\" in file :"))))
400      (list pattern file switches)))
401   (setq file (expand-file-name file))
402   (if (listp flags)
403       (setq flags (mapconcat 'identity flags " "))
404     (if (string-match "^ +$" flags)
405         (setq flags "")))
406   (let ((file-buff (get-file-buffer file)))
407     (if (and file-buff (buffer-modified-p file-buff))
408         (if (y-or-n-p (format "Save buffer %s? " (buffer-name file-buff)))
409             (save-excursion
410               (set-buffer file-buff)
411               (save-buffer)))))
412   (let ((buffer (dired-grep-get-results-buffer))
413         (compressed (string-match dired-grep-compressed-file file))
414         failed temp-file jka-compr-compression-info-list)
415     (setq temp-file
416           (condition-case err
417               (file-local-copy file)
418             (error (progn (setq failed (format "%s" err)) nil))))
419     (or failed
420         (save-excursion
421           (set-buffer buffer)
422           (goto-char (point-max))
423           (let ((buffer-read-only nil)
424                 pos-1 pos-2)
425             (or (bobp) (insert "\n"))
426             (setq pos-1 (point))
427             (insert "Hits for grep ")
428             (or (string-equal flags "") (insert flags " "))
429             (insert "\"" pattern "\" in\n   " file ":\n")
430             (setq pos-2 (point))
431             (condition-case err
432                 (apply
433                  'call-process
434                  (if compressed "sh" dired-grep-program)
435                  (or temp-file file)
436                  buffer t
437                  (if compressed
438                      (list "-c" (concat dired-grep-zcat-program
439                                         " |" dired-grep-program
440                                         " " flags " -n '" pattern "'"))
441                    (append (dired-grep-parse-flags flags)
442                            (list "-n" pattern))))
443               (error (setq failed (format "%s" err))))
444             (if failed
445                 (progn
446                   (if (= pos-2 (point-max))
447                       (progn
448                         (goto-char (1- pos-2))
449                         (delete-char -1)
450                         (insert ".")))
451                   (goto-char pos-1)
452                   (delete-char 4)
453                   (insert "Grep failed")
454                   failed)
455               (if (= pos-2 (point-max))
456                   (progn
457                     (goto-char pos-1)
458                     (delete-char 1)
459                     (insert "No h")
460                     (forward-line 1)
461                     (end-of-line)
462                     (delete-char -1)
463                     (insert "."))
464                 (goto-char pos-2)
465                 (or (looking-at "[0-9]+:")
466                     (setq failed (buffer-substring pos-2
467                                                    (progn (end-of-line)
468                                                           (point))))))))))
469     (let ((curr-wind (selected-window)))
470       (unwind-protect
471           (progn
472             (pop-to-buffer buffer)
473             (goto-char (point-max)))
474         (select-window curr-wind)))
475     (if temp-file
476         (dired-grep-delete-local-temp-file temp-file))
477     failed))
478
479 ;;; Run the load hook
480
481 (run-hooks 'dired-grep-load-hook)
482
483 ;;; end of dired-grep.el