* contrib/anything-grep.el (agrep-goto): If lineno is unavailable, just open file
[anything-config.git] / contrib / anything-grep.el
blobc0945d32dfbc9dd3de278858144b2568a9e87582
1 ;;; anything-grep.el --- search refinement of grep result with anything
2 ;; $Id: anything-grep.el,v 1.27 2010-03-21 11:31:04 rubikitch Exp $
4 ;; Copyright (C) 2008, 2009, 2010 rubikitch
6 ;; Author: rubikitch <rubikitch@ruby-lang.org>
7 ;; Keywords: convenience, unix
8 ;; URL: http://www.emacswiki.org/cgi-bin/wiki/download/anything-grep.el
10 ;; This file is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
15 ;; This file is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to
22 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
25 ;;; Commentary:
27 ;; Do grep in anything buffer. When we search information with grep,
28 ;; we often narrow the candidates. Let's use `anything' to do it.
30 ;;; Commands:
32 ;; Below are complete command list:
34 ;; `anything-grep'
35 ;; Run grep in `anything' buffer to narrow results.
36 ;; `anything-grep-by-name'
37 ;; Do `anything-grep' from predefined location.
38 ;; `anything-grep-by-name-reversed'
39 ;; Do `anything-grep' from predefined location.
41 ;;; Customizable Options:
43 ;; Below are customizable option list:
46 ;; `anything-grep' is simple interface to grep a query. It asks
47 ;; directory to grep. The grep process is synchronous process. You may
48 ;; have to wait when you grep the target for the first time. But once
49 ;; the target is on the disk cache, queries are grepped at lightning
50 ;; speed. Even if older Pentium4 computer, grepping from 180MB takes
51 ;; only 0.2s! GNU grep is amazingly fast.
53 ;; `anything-grep-by-name' asks query and predefined location. It is
54 ;; good idea to have ack (ack-grep), grep implemented in Perl, to
55 ;; exclude unneeded files. Such as RCS, .svn and so on.
57 ;; ack -- better than grep, a power search tool for programmers
58 ;; http://petdance.com/ack/
62 ;;; History:
64 ;; $Log: anything-grep.el,v $
65 ;; Revision 1.27 2010-03-21 11:31:04 rubikitch
66 ;; Resume bug fix
68 ;; Revision 1.26 2010/03/21 11:13:30 rubikitch
69 ;; `anything-grep' works asynchronously
71 ;; Revision 1.25 2010/03/21 06:34:25 rubikitch
72 ;; New function: `anything-grep-by-name-reversed'
74 ;; Revision 1.24 2010/03/21 06:28:42 rubikitch
75 ;; update copyright
77 ;; Revision 1.23 2010/03/21 06:28:32 rubikitch
78 ;; refactoring
80 ;; Revision 1.22 2009/12/28 08:56:56 rubikitch
81 ;; `anything-grep-by-name': INCOMPATIBLE!!! swap optional arguments
82 ;; `anything-grep-by-name' can utilize `repeat-complex-command'.
84 ;; Revision 1.21 2009/12/18 11:01:11 rubikitch
85 ;; `agrep-real-to-display': erase "nil" message
87 ;; Revision 1.20 2009/06/25 03:36:38 rubikitch
88 ;; `agrep-real-to-display': avoid error
89 ;; auto-document
91 ;; Revision 1.19 2009/02/03 21:06:49 rubikitch
92 ;; fontify file name and line number.
93 ;; New variable: `anything-grep-fontify-file-name'
95 ;; Revision 1.18 2009/02/03 20:48:12 rubikitch
96 ;; multi-line support.
97 ;; New variable: `anything-grep-multiline'
99 ;; Revision 1.17 2009/02/03 20:35:03 rubikitch
100 ;; Use `anything-quit-if-no-candidate' not to open *anything* buffer when no matches found.
102 ;; Revision 1.16 2009/01/20 09:56:19 rubikitch
103 ;; New variable: `anything-grep-filter-command'
105 ;; Revision 1.15 2009/01/03 07:04:30 rubikitch
106 ;; copyright
108 ;; Revision 1.14 2009/01/02 16:00:07 rubikitch
109 ;; * Fixed invalid value of `anything-grep-alist'.
110 ;; * Implemented functionality to search all buffers with `buffer-file-name'.
111 ;; See `anything-grep-alist'.
113 ;; Revision 1.13 2008/12/29 09:43:59 rubikitch
114 ;; Rename variables:
115 ;; `agrep-goto-hook' => `anything-grep-goto-hook'
116 ;; `agrep-find-file-function' => `anything-grep-find-file-function'
118 ;; Revision 1.12 2008/12/29 09:40:23 rubikitch
119 ;; document
121 ;; Revision 1.11 2008/12/29 07:58:37 rubikitch
122 ;; refactoring
124 ;; Revision 1.10 2008/10/21 18:02:02 rubikitch
125 ;; use *anything grep* buffer instead.
127 ;; Revision 1.9 2008/10/12 17:17:23 rubikitch
128 ;; `anything-grep-by-name': swapped query order
130 ;; Revision 1.8 2008/10/09 00:33:40 rubikitch
131 ;; New variable: `anything-grep-save-buffers-before-grep'
133 ;; Revision 1.7 2008/10/09 00:26:00 rubikitch
134 ;; `anything-grep-by-name': nil argument
136 ;; Revision 1.6 2008/10/05 15:43:09 rubikitch
137 ;; changed spec: `anything-grep-alist'
139 ;; Revision 1.5 2008/10/02 18:27:55 rubikitch
140 ;; Use original fontify code instead of font-lock.
141 ;; New variable: `agrep-find-file-function'
143 ;; Revision 1.4 2008/10/01 18:18:18 rubikitch
144 ;; use ack-grep command to select files for search.
146 ;; Revision 1.3 2008/10/01 17:18:59 rubikitch
147 ;; silence byte compiler
149 ;; Revision 1.2 2008/10/01 17:17:59 rubikitch
150 ;; many bug fix
151 ;; New command: `anything-grep-by-name'
153 ;; Revision 1.1 2008/10/01 10:58:59 rubikitch
154 ;; Initial revision
157 ;;; Code:
159 (defvar anything-grep-version "$Id: anything-grep.el,v 1.27 2010-03-21 11:31:04 rubikitch Exp $")
160 (require 'anything-config)
161 (require 'grep)
163 (defvar anything-grep-save-buffers-before-grep nil
164 "Do `save-some-buffers' before performing `anything-grep'.")
166 (defvar anything-grep-goto-hook nil
167 "List of functions to be called after `agrep-goto' opens file.")
169 (defvar anything-grep-find-file-function 'find-file
170 "Function to visit a file with.
171 It takes one argument, a file name to visit.")
173 (defvar anything-grep-multiline t
174 "If non-nil, use multi-line display. It is prettier.
175 Use anything.el v1.147 or newer.")
177 (defvar anything-grep-fontify-file-name t
178 "If non-nil, fontify file name and line number of matches.")
180 (defvar anything-grep-sh-program
181 (or (executable-find "zsh")
182 (executable-find "sh")))
184 (defvar anything-grep-alist
185 '(("buffers" ("egrep -Hin %s $buffers" "/"))
186 ("memo" ("ack-grep -af | xargs egrep -Hin %s" "~/memo"))
187 ("PostgreSQL" ("egrep -Hin %s *.txt" "~/doc/postgresql-74/"))
188 ("~/bin and ~/ruby"
189 ("ack-grep -afG 'rb$' | xargs egrep -Hin %s" "~/ruby")
190 ("ack-grep -af | xargs egrep -Hin %s" "~/bin")))
191 "Mapping of location and command/pwd used by `anything-grep-by-name'.
192 The command is grep command line. Note that %s is replaced by query.
193 The command is typically \"ack-grep -af | xargs egrep -Hin %s\", which means
194 regexp/case-insensitive search for all files (including subdirectories)
195 except unneeded files.
196 The occurrence of $file in command is replaced with `buffer-file-name' of
197 all buffers.
199 The pwd is current directory to grep.
201 The format is:
203 ((LOCATION1
204 (COMMAND1-1 PWD1-1)
205 (COMMAND1-2 PWD1-2)
206 ...)
207 (LOCATION2
208 (COMMAND2-1 PWD2-1)
209 (COMMAND2-2 PWD2-2)
210 ...)
211 ...)
214 (defvar anything-grep-filter-command nil
215 "If non-nil, filter the result of grep command.
217 For example, normalizing many Japanese encodings to EUC-JP,
218 set this variable to \"ruby -rkconv -pe '$_.replace $_.toeuc'\".
219 The command is converting standard input to EUC-JP line by line. ")
222 ;; (@* "core")
223 (defvar anything-grep-sources nil
224 "`anything-sources' for last invoked `anything-grep'.")
225 (defvar anything-grep-buffer-name nil)
226 (defun anything-grep-base (sources &optional bufname)
227 "Invoke `anything' for `anything-grep'."
228 (and anything-grep-save-buffers-before-grep
229 (save-some-buffers (not compilation-ask-about-save) nil))
230 (setq anything-grep-sources sources)
231 (setq anything-grep-buffer-name (or bufname "*anything grep*"))
232 (let ((anything-quit-if-no-candidate t)
233 (anything-compile-source-functions
234 (cons 'anything-compile-source--agrep-init anything-compile-source-functions)))
235 (anything sources nil nil nil nil bufname)))
237 ;; (anything (list (agrep-source "grep -Hin agrep anything-grep.el" default-directory) (agrep-source "grep -Hin pwd anything-grep.el" default-directory)))
239 (defun agrep-source (command pwd)
240 "Anything Source of `anything-grep'."
241 `((command . ,command)
242 (pwd . ,pwd)
243 (name . ,(format "%s [%s]" command pwd))
244 (action . agrep-goto)
245 (anything-grep)
246 (candidate-number-limit . 9999)
247 (migemo)
248 ;; to inherit faces
249 (candidates-in-buffer)
250 (get-line . buffer-substring)
251 ,@(when anything-grep-multiline
252 '((multiline)
253 (real-to-display . agrep-real-to-display)))))
255 (defun anything-compile-source--agrep-init (source)
256 (if (assq 'anything-grep source)
257 (append '((init . agrep-init)
258 (candidates)) source)
259 source))
261 (defun agrep-init ()
262 (agrep-create-buffer (anything-attr 'command) (anything-attr 'pwd)))
264 (defun agrep-real-to-display (file-line-content)
265 (if (string-match ":\\([0-9]+\\):" file-line-content)
266 (format "%s:%s\n %s"
267 (substring file-line-content 0 (match-beginning 0))
268 (match-string 1 file-line-content)
269 (substring file-line-content (match-end 0)))
270 file-line-content))
272 (defvar agrep-source-local nil)
273 (defvar agrep-waiting-source nil
274 "`anything' sources to get together in `agrep-sentinel'.")
275 (defun agrep-do-grep (command pwd)
276 "Insert result of COMMAND. The current directory is PWD.
277 GNU grep is expected for COMMAND. The grep result is colorized."
278 (let ((process-environment process-environment))
279 (when (eq grep-highlight-matches t)
280 ;; Modify `process-environment' locally bound in `call-process-shell-command'.
281 (setenv "GREP_OPTIONS" (concat (getenv "GREP_OPTIONS") " --color=always"))
282 ;; for GNU grep 2.5.1
283 (setenv "GREP_COLOR" "01;31")
284 ;; for GNU grep 2.5.1-cvs
285 (setenv "GREP_COLORS" "mt=01;31:fn=:ln=:bn=:se=:ml=:cx=:ne"))
286 (set (make-local-variable 'agrep-source-local) (anything-get-current-source))
287 (add-to-list 'agrep-waiting-source agrep-source-local)
288 (set-process-sentinel
289 (start-process "anything-grep" (current-buffer)
290 anything-grep-sh-program "-c"
291 (format "cd %s; %s" pwd command))
292 'agrep-sentinel)))
294 (defvar agrep-do-after-minibuffer-exit nil)
295 (defun agrep-minibuffer-exit-hook ()
296 (when agrep-do-after-minibuffer-exit
297 (run-at-time 1 nil agrep-do-after-minibuffer-exit)
298 (setq agrep-do-after-minibuffer-exit nil)))
299 (add-hook 'minibuffer-exit-hook 'agrep-minibuffer-exit-hook)
301 (defun agrep-highlight-line-after-persistent-action ()
302 (when anything-in-persistent-action
303 (anything-persistent-highlight-point (point-at-bol) (point-at-eol))))
304 (add-hook 'anything-grep-goto-hook 'agrep-highlight-line-after-persistent-action)
306 (defun agrep-show (func)
307 (if (active-minibuffer-window)
308 (setq agrep-do-after-minibuffer-exit func)
309 (funcall func)))
310 ;; (anything-grep "sleep 1; grep -Hin grep anything-grep.el" "~/src/anything-config/extensions/")
312 (defun agrep-sentinel (proc stat)
313 (with-current-buffer (process-buffer proc)
314 (setq agrep-waiting-source (delete agrep-source-local agrep-waiting-source))
315 (agrep-fontify))
316 (unless agrep-waiting-source
317 ;; call anything
318 (agrep-show
319 (lambda ()
320 (let ((anything-quit-if-no-candidate (lambda () (message "No matches"))))
321 (anything anything-grep-sources nil nil nil nil anything-grep-buffer-name))))))
323 (defun agrep-fontify ()
324 "Fontify the result of `agrep-do-grep'."
325 ;; Color matches.
326 (goto-char 1)
327 (while (re-search-forward "\\(\033\\[01;31m\\)\\(.*?\\)\\(\033\\[[0-9]*m\\)" nil t)
328 (put-text-property (match-beginning 2) (match-end 2) 'face grep-match-face)
329 (replace-match "" t t nil 1)
330 (replace-match "" t t nil 3))
331 ;; Delete other escape sequences.
332 (goto-char 1)
333 (while (re-search-forward "\\(\033\\[[0-9;]*[mK]\\)" nil t)
334 (replace-match "" t t nil 0))
335 (when anything-grep-fontify-file-name
336 (goto-char 1)
337 (while (re-search-forward ":\\([0-9]+\\):" nil t)
338 (put-text-property (point-at-bol) (match-beginning 0) 'face compilation-info-face)
339 (put-text-property (match-beginning 1) (match-end 1) 'face compilation-line-face)
340 (forward-line 1))))
341 ;; (anything-grep "grep -n grep *.el" "~/emacs/init.d")
343 (defun agrep-create-buffer (command pwd)
344 "Create candidate buffer for `anything-grep'.
345 Its contents is fontified grep result."
346 (with-current-buffer (anything-candidate-buffer 'global)
347 (setq default-directory pwd)
348 (agrep-do-grep command pwd)
349 (current-buffer)))
350 ;; (display-buffer (agrep-create-buffer "grep --color=always -Hin agrep anything-grep.el" default-directory))
351 ;; (anything '(((name . "test") (init . (lambda () (anything-candidate-buffer (get-buffer " *anything grep:grep --color=always -Hin agrep anything-grep.el*")) )) (candidates-in-buffer) (get-line . buffer-substring))))
353 (defun agrep-goto (file-line-content)
354 "Visit the source for the grep result at point."
355 (if (not (string-match ":\\([0-9]+\\):" file-line-content))
356 ;; If lineno is unavailable, just open file
357 (funcall anything-grep-find-file-function
358 (expand-file-name file-line-content (anything-attr 'pwd)))
359 (save-match-data
360 (funcall anything-grep-find-file-function
361 (expand-file-name (substring file-line-content
362 0 (match-beginning 0))
363 (anything-attr 'pwd))))
364 (goto-line (string-to-number (match-string 1 file-line-content))))
365 (run-hooks 'anything-grep-goto-hook))
367 ;; (@* "simple grep interface")
368 (defun anything-grep (command pwd)
369 "Run grep in `anything' buffer to narrow results.
370 It asks COMMAND for grep command line and PWD for current directory."
371 (interactive
372 (progn
373 (grep-compute-defaults)
374 (let ((default (grep-default-command)))
375 (list (read-from-minibuffer "Run grep (like this): "
376 (if current-prefix-arg
377 default grep-command)
378 nil nil 'grep-history
379 (if current-prefix-arg nil default))
380 (read-directory-name "Directory: " default-directory default-directory t)))))
381 (anything-grep-base (list (agrep-source (agrep-preprocess-command command) pwd))
382 (format "*anything grep:%s [%s]*" command (abbreviate-file-name pwd))))
383 ;; (anything-grep "grep -Hin agrep anything-grep.el" default-directory)
385 (defun agrep-preprocess-command (command)
386 (with-temp-buffer
387 (insert command)
388 (goto-char 1)
389 (when (search-forward "$buffers" nil t)
390 (delete-region (match-beginning 0) (match-end 0))
391 (insert (mapconcat 'shell-quote-argument
392 (delq nil (mapcar 'buffer-file-name (buffer-list))) " ")))
393 (when anything-grep-filter-command
394 (goto-char (point-max))
395 (insert "|" anything-grep-filter-command))
396 (buffer-string)))
398 ;; (@* "grep in predefined files")
399 (defvar agbn-last-name nil
400 "The last used name by `anything-grep-by-name'.")
402 (defun agrep-by-name-read-info (&rest kinds)
403 (let* ((default (or (thing-at-point 'symbol) ""))
404 (result (mapcar (lambda (kind)
405 (case kind
406 ('query (read-string
407 (format "Grep query (default:%s): " default)
408 nil nil default))
409 ('name (completing-read
410 "Grep by name: "
411 anything-grep-alist
412 nil t nil nil agbn-last-name))))
413 kinds)))
414 (if (cdr result) ; length >= 1
415 result
416 (car result))))
418 (defun anything-grep-by-name (&optional query name)
419 "Do `anything-grep' from predefined location.
420 It asks NAME for location name and QUERY."
421 (interactive (agrep-by-name-read-info 'query 'name))
422 (setq query (or query (agrep-by-name-read-info 'query)))
423 (setq name (or name (agrep-by-name-read-info 'name)))
424 (setq agbn-last-name name)
425 (anything-aif (assoc-default name anything-grep-alist)
426 (progn
427 (grep-compute-defaults)
428 (anything-grep-base
429 (mapcar (lambda (args)
430 (destructuring-bind (cmd dir) args
431 (agrep-source (format (agrep-preprocess-command cmd)
432 (shell-quote-argument query)) dir)))
434 (format "*anything grep:%s [%s]" query name)))
435 (error "no such name %s" name)))
437 (defun anything-grep-by-name-reversed (&optional name query)
438 "Do `anything-grep' from predefined location.
439 It asks QUERY and NAME for location name.
441 Difference with `anything-grep-by-name' is prompt order."
442 (interactive (agrep-by-name-read-info (quote name) (quote query)))
443 (anything-grep-by-name query name))
445 ;;;; unit test
446 ;; (install-elisp "http://www.emacswiki.org/cgi-bin/wiki/download/el-expectations.el")
447 ;; (install-elisp "http://www.emacswiki.org/cgi-bin/wiki/download/el-mock.el")
448 (dont-compile
449 (when (fboundp 'expectations)
450 (expectations
451 (desc "agrep-by-name-read-info")
452 (expect "query1"
453 (stub read-string => "query1")
454 (agrep-by-name-read-info 'query))
455 (expect "elinit"
456 (stub completing-read => "elinit")
457 (agrep-by-name-read-info 'name))
458 (expect '("query1" "elinit")
459 (stub read-string => "query1")
460 (stub completing-read => "elinit")
461 (agrep-by-name-read-info 'query 'name))
462 (expect '("elinit" "query1")
463 (stub read-string => "query1")
464 (stub completing-read => "elinit")
465 (agrep-by-name-read-info 'name 'query))
468 (provide 'anything-grep)
470 ;; How to save (DO NOT REMOVE!!)
471 ;; (progn (magit-push) (emacswiki-post "anything-grep.el"))
472 ;;; anything-grep.el ends here