file uu-decode.pbm was added on branch t-gnus-6_17 on 2005-05-01 23:25:48 +0000
[elisp/gnus.git-] / lisp / gnus-namazu.el
1 ;;; gnus-namazu.el --- Search mail with Namazu -*- coding: iso-2022-7bit; -*-
2
3 ;; Copyright (C) 2000, 2001, 2002, 2003, 2004
4 ;; TSUCHIYA Masatoshi <tsuchiya@namazu.org>
5
6 ;; Author: TSUCHIYA Masatoshi <tsuchiya@namazu.org>
7 ;; Keywords: mail searching namazu
8
9 ;; This file is a part of Semi-Gnus.
10
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program; if not, you can either send email to this
23 ;; program's maintainer or write to: The Free Software Foundation,
24 ;; Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.
25
26
27 ;;; Commentary:
28
29 ;; This file defines the command to search mails and persistent
30 ;; articles with Namazu and to browse its results with Gnus.
31 ;;
32 ;; Namazu is a full-text search engine intended for easy use.  For
33 ;; more detail about Namazu, visit the following page:
34 ;;
35 ;;     http://namazu.org/
36
37
38 ;;; Quick Start:
39
40 ;; If this module has already been installed, only 3 steps are
41 ;; required to search articles with this module.
42 ;;
43 ;;   (1) Install Namazu.
44 ;;   (2) Start Gnus and type M-x gnus-namazu-create-index RET to make
45 ;;       index of articles.
46 ;;   (3) In group buffer or in summary buffer, type C-c C-n query RET.
47
48
49 ;;; Install:
50
51 ;; Before installing this module, you must install Namazu.
52 ;;
53 ;; This file is a part of T-gnus but is not *YET* a part of Gnus.
54 ;; When you would like to use this module in Gnus (not T-gnus), put
55 ;; this file into the lisp/ directory in the Gnus source tree and run
56 ;; `make install'.  And then, put the following expression into your
57 ;; ~/.gnus.
58 ;;
59 ;;      (require 'gnus-namazu)
60 ;;      (gnus-namazu-insinuate)
61 ;;
62 ;; In order to make index of articles with Namazu before using this
63 ;; module, type M-x gnus-namazu-create-index RET.  Otherwise, you can
64 ;; create index by yourself with the following commands:
65 ;;
66 ;;      % mkdir ~/News/namazu
67 ;;      % mknmz -a -h -O ~/News/namazu ~/Mail ~/News/cache
68 ;;
69 ;; The first command makes the directory for index files, and the
70 ;; second command generates index files of mails and persistent
71 ;; articles.
72 ;;
73 ;; In order to update indices for incoming articles, this module
74 ;; automatically runs mknmz, the indexer of Namazu, at an interval of
75 ;; 3 days; this period is set to `gnus-namazu-index-update-interval'.
76 ;;
77 ;; Indices will be updated when `gnus-namazu-search' is called.  If
78 ;; you want to update indices everywhen Gnus is started, you can put
79 ;; the following expression to your ~/.gnus.
80 ;;
81 ;;      (add-hook 'gnus-startup-hook 'gnus-namazu-update-all-indices)
82 ;;
83 ;; In order to control mknmz closely, disable the automatic updating
84 ;; feature and run mknmz by yourself.  In this case, set nil to the
85 ;; above option.
86 ;;
87 ;;      (setq gnus-namazu-index-update-interval nil)
88 ;;
89 ;; When your index is put into the directory other than the default
90 ;; one (~/News/namazu), it is necessary to set its place to
91 ;; `gnus-namazu-index-directories' as follows:
92 ;;
93 ;;      (setq gnus-namazu-index-directories
94 ;;            (list (expand-file-name "~/namazu")))
95
96
97 ;;; Code:
98
99 (eval-when-compile (require 'cl))
100 (require 'nnoo)
101 (require 'nnheader)
102 (require 'nnmail)
103 (require 'gnus-sum)
104
105 ;; To suppress byte-compile warning.
106 (eval-when-compile
107   (defvar nnml-directory)
108   (defvar nnmh-directory))
109
110
111 (defgroup gnus-namazu nil
112   "Search nnmh and nnml groups in Gnus with Namazu."
113   :group 'namazu
114   :group 'gnus
115   :prefix "gnus-namazu-")
116
117 (defconst gnus-namazu-default-index-directory
118   (expand-file-name "namazu" gnus-directory)
119   "Default place of Namazu index files.")
120
121 (defcustom gnus-namazu-index-directories
122   (list
123    (or (and (boundp 'gnus-namazu-index-directory)
124             (symbol-value 'gnus-namazu-index-directory))
125        (and (boundp 'nnir-namazu-index-directory)
126             (symbol-value 'nnir-namazu-index-directory))
127        gnus-namazu-default-index-directory))
128   "*Places of Namazu index files."
129   :type '(repeat directory)
130   :group 'gnus-namazu)
131
132 (defcustom gnus-namazu-command
133   (or (and (boundp 'namazu-command)
134            (symbol-value 'namazu-command))
135       (and (boundp 'nnir-namazu-program)
136            (symbol-value 'nnir-namazu-program))
137       "namazu")
138   "*Name of the executable file of Namazu."
139   :type 'string
140   :group 'gnus-namazu)
141
142 (defcustom gnus-namazu-additional-arguments nil
143   "*Additional arguments of Namazu.
144 The options `-q', `-a', and `-l' are always used, very few other
145 options make any sense in this context."
146   :type '(repeat string)
147   :group 'gnus-namazu)
148
149 (defcustom gnus-namazu-index-update-interval
150   259200                                ; 3 days == 259200 seconds.
151   "*Number of seconds between running the indexer of Namazu."
152   :type '(choice (const :tag "Never run the indexer" nil)
153                  (integer :tag "Number of seconds"))
154   :group 'gnus-namazu)
155
156 (defcustom gnus-namazu-make-index-command "mknmz"
157   "*Name of the executable file of the indexer of Namazu."
158   :type 'string
159   :group 'gnus-namazu)
160
161 (defcustom gnus-namazu-make-index-arguments
162   (nconc
163    (list "--all" "--mailnews" "--deny=^.*[^0-9].*$")
164    (when (and (boundp 'current-language-environment)
165               (string= "Japanese"
166                        (symbol-value 'current-language-environment)))
167      (list "--indexing-lang=ja")))
168   "*Arguments of the indexer of Namazu."
169   :type '(repeat string)
170   :group 'gnus-namazu)
171
172 (defcustom gnus-namazu-field-keywords
173   '("date" "from" "newsgroups" "size" "subject" "summary" "to" "uri")
174   "*List of keywords to do field-search."
175   :type '(repeat string)
176   :group 'gnus-namazu)
177
178 (defcustom gnus-namazu-coding-system
179   (if (memq system-type '(windows-nt OS/2 emx))
180       'shift_jis
181     'euc-japan)
182   "*Coding system for Namazu process."
183   :type 'coding-system
184   :group 'gnus-namazu)
185
186 (defcustom gnus-namazu-need-path-normalization
187   (and (memq system-type '(windows-nt OS/2 emx)) t)
188   "*Non-nil means that outputs of namazu may contain drive letters."
189   :type 'boolean
190   :group 'gnus-namazu)
191
192 (defcustom gnus-namazu-case-sensitive-filesystem
193   (not (eq system-type 'windows-nt))
194   "*Non-nil means that the using file system distinguishes cases of characters."
195   :type 'boolean
196   :group 'gnus-namazu)
197
198 (defcustom gnus-namazu-query-highlight t
199   "Non-nil means that queried words is highlighted."
200   :type 'boolean
201   :group 'gnus-namazu)
202
203 (defface gnus-namazu-query-highlight-face
204   '((((type tty pc) (class color))
205      (:background "magenta4" :foreground "cyan1"))
206     (((class color) (background light))
207      (:background "magenta4" :foreground "lightskyblue1"))
208     (((class color) (background dark))
209      (:background "palevioletred2" :foreground "brown4"))
210     (t (:inverse-video t)))
211   "Face used for namazu query matching words."
212   :group 'gnus-namazu)
213
214 (defcustom gnus-namazu-command-prefix nil
215   "*Prefix command, 
216 if set '(\"ssh\" \"-x\" \"host\"),
217 then execute \"ssh -x host namazu ...\""
218   :type '(repeat string)
219   :group 'gnus-namazu)
220
221 (defcustom gnus-namazu-imap-group-prefix nil
222   "*Prefix of imap group name.
223 ex. nnimap+server:INBOX."
224   :type 'string
225   :group 'gnus-namazu)
226
227 (defcustom gnus-namazu-imap-maildir nil
228   "*Maildir directory name."
229   :type 'string
230   :group 'gnus-namazu)
231
232 ;;; Internal Variable:
233 (defconst gnus-namazu/group-name-regexp "\\`nnvirtual:namazu-search\\?")
234
235 ;; Multibyte group name:
236 (and
237  (fboundp 'gnus-group-decoded-name)
238  (let ((gnus-group-name-charset-group-alist
239         (list (cons gnus-namazu/group-name-regexp gnus-namazu-coding-system)))
240        (query (decode-coding-string (string 27 36 66 52 65 59 122 27 40 66)
241                                     'iso-2022-7bit)))
242    (not (string-match query
243                       (gnus-summary-buffer-name
244                        (encode-coding-string
245                         (concat "nnvirtual:namazu-search?query=" query)
246                         gnus-namazu-coding-system)))))
247  (let (current-load-list)
248    (defadvice gnus-summary-buffer-name
249      (before gnus-namazu-summary-buffer-name activate compile)
250      "Advised by `gnus-namazu' to handle encoded group names."
251      (ad-set-arg 0 (gnus-group-decoded-name (ad-get-arg 0))))))
252
253 (defmacro gnus-namazu/make-article (group number)
254   `(cons ,group ,number))
255 (defmacro gnus-namazu/article-group  (x) `(car ,x))
256 (defmacro gnus-namazu/article-number (x) `(cdr ,x))
257
258 (defsubst gnus-namazu/indexed-servers ()
259   "Choice appropriate servers from opened ones, and return thier list."
260   (append
261    (gnus-servers-using-backend 'nnml)
262    (gnus-servers-using-backend 'nnmh)))
263
264 (defsubst gnus-namazu/default-index-directory ()
265   (if (member gnus-namazu-default-index-directory
266               gnus-namazu-index-directories)
267       gnus-namazu-default-index-directory
268     (car gnus-namazu-index-directories)))
269
270 (defun gnus-namazu/setup ()
271   (and (boundp 'gnus-group-name-charset-group-alist)
272        (not (member (cons gnus-namazu/group-name-regexp
273                           gnus-namazu-coding-system)
274                     gnus-group-name-charset-group-alist))
275        (let ((pair (assoc gnus-namazu/group-name-regexp
276                           gnus-group-name-charset-group-alist)))
277          (if pair
278              (setcdr pair gnus-namazu-coding-system)
279            (push (cons gnus-namazu/group-name-regexp
280                        gnus-namazu-coding-system)
281                  gnus-group-name-charset-group-alist))))
282   (gnus-namazu-update-all-indices))
283
284 (defun gnus-namazu/server-directory (server)
285   "Return the top directory of the server SERVER."
286   (and (memq (car server) '(nnml nnmh))
287        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
288        (file-name-as-directory
289         (expand-file-name (if (eq 'nnml (car server))
290                               nnml-directory
291                             nnmh-directory)))))
292
293 ;;; Functions to call Namazu.
294 (defsubst gnus-namazu/normalize-results ()
295   "Normalize file names returned by Namazu in this current buffer."
296   (goto-char (point-min))
297   (while (not (eobp))
298     (when (looking-at "file://")
299       (delete-region (point) (match-end 0)))
300     (when (if gnus-namazu-need-path-normalization
301               (or (not (looking-at "/\\(.\\)|/"))
302                   (replace-match "\\1:/"))
303             (eq ?~ (char-after (point))))
304       (insert (expand-file-name
305                (buffer-substring (point-at-bol) (point-at-eol))))
306       (delete-region (point) (point-at-eol)))
307     (forward-line 1)))
308
309 (defsubst gnus-namazu/call-namazu (query)
310   (let ((coding-system-for-read gnus-namazu-coding-system)
311         (coding-system-for-write gnus-namazu-coding-system)
312         (default-process-coding-system
313           (cons gnus-namazu-coding-system gnus-namazu-coding-system))
314         program-coding-system-alist
315         (file-name-coding-system gnus-namazu-coding-system))
316     (if gnus-namazu-command-prefix
317         (apply 'call-process
318                (append
319                 (list (car gnus-namazu-command-prefix))
320                 '(nil t nil)
321                 (cdr gnus-namazu-command-prefix)
322                 `(,gnus-namazu-command
323                   "-q"                  ; don't be verbose
324                   "-a"                  ; show all matches
325                   "-l"                  ; use list format
326                   ,@gnus-namazu-additional-arguments
327                   ,query
328                   ,@gnus-namazu-index-directories)))
329       (apply 'call-process
330              `(,gnus-namazu-command
331                nil                      ; input from /dev/null
332                t                        ; output
333                nil                      ; don't redisplay
334                "-q"                     ; don't be verbose
335                "-a"                     ; show all matches
336                "-l"                     ; use list format
337                ,@gnus-namazu-additional-arguments
338                ,query
339                ,@gnus-namazu-index-directories)))))
340
341 (defvar gnus-namazu/directory-table nil)
342 (defun gnus-namazu/make-directory-table (&optional force)
343   (interactive (list t))
344   (unless (and (not force)
345                gnus-namazu/directory-table
346                (eq gnus-namazu-case-sensitive-filesystem
347                    (car gnus-namazu/directory-table)))
348     (let ((table (make-vector (length gnus-newsrc-hashtb) 0))
349           cache agent alist dir method)
350       (mapatoms
351        (lambda (group)
352          (unless (gnus-ephemeral-group-p (setq group (symbol-name group)))
353            (when (file-directory-p
354                   (setq dir (file-name-as-directory
355                              (gnus-cache-file-name group ""))))
356              (push (cons dir group) cache))
357            (when (file-directory-p
358                   (setq dir (gnus-agent-group-pathname group)))
359              (push (cons dir group) agent))
360            (when (memq (car (setq method (gnus-find-method-for-group group)))
361                        '(nnml nnmh))
362              (when (file-directory-p
363                     (setq dir (nnmail-group-pathname
364                                (gnus-group-short-name group)
365                                (gnus-namazu/server-directory method))))
366                (push (cons dir group) alist)))))
367        gnus-newsrc-hashtb)
368       (dolist (pair (nconc agent cache alist))
369         (set (intern (if gnus-namazu-case-sensitive-filesystem
370                          (car pair)
371                        (downcase (car pair)))
372                      table)
373              (cdr pair)))
374       (setq gnus-namazu/directory-table
375             (cons gnus-namazu-case-sensitive-filesystem table)))))
376
377 (defun gnus-namazu/search (groups query)
378   (gnus-namazu/make-directory-table)
379   (with-temp-buffer
380     (let ((exit-status (gnus-namazu/call-namazu query)))
381       (unless (zerop exit-status)
382         (error "Namazu finished abnormally: %d" exit-status)))
383     (gnus-namazu/normalize-results)
384     (goto-char (point-min))
385     (let (articles group)
386       (while (not (eobp))
387         (setq group (buffer-substring-no-properties
388                      (point)
389                      (progn
390                        (end-of-line)
391                        ;; NOTE: Only numeric characters are permitted
392                        ;; as file names of articles.
393                        (skip-chars-backward "0-9")
394                        (point))))
395         (and (if (not gnus-namazu-imap-maildir)
396                  (setq group
397                        (symbol-value
398                         (intern-soft (if gnus-namazu-case-sensitive-filesystem
399                                          group
400                                        (downcase group))
401                                      (cdr gnus-namazu/directory-table))))
402                ;; FIXME:
403                ;; gnus-select-method is '(nnimap "server")
404                ;; nnimap+server:INBOX.group = ~/Maildir/.group 
405                ;; Namazu resault: ~/Maildir/.group/123
406                (setq group (and (string-match 
407                                  (concat gnus-namazu-imap-maildir
408                                          "/\\.\\(.*\\)/") group)
409                                 (concat gnus-namazu-imap-group-prefix 
410                                         (match-string 1 group)))))
411              (or (not groups)
412                  (member group groups))
413              (push (gnus-namazu/make-article
414                     group
415                     (string-to-number
416                      (buffer-substring-no-properties (point)
417                                                      (point-at-eol))))
418                    articles))
419         (forward-line 1))
420       (nreverse articles))))
421
422 ;;; User Interface:
423 (defun gnus-namazu/get-target-groups ()
424   (cond
425    ((eq major-mode 'gnus-group-mode)
426     ;; In Group buffer.
427     (cond
428      (current-prefix-arg
429       (gnus-group-process-prefix current-prefix-arg))
430      (gnus-group-marked
431       (prog1 gnus-group-marked (gnus-group-unmark-all-groups)))))
432    ((eq major-mode 'gnus-summary-mode)
433     ;; In Summary buffer.
434     (if current-prefix-arg
435         (list (gnus-read-group "Group: "))
436       (if (and
437            (gnus-ephemeral-group-p gnus-newsgroup-name)
438            (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name))
439           (cadr (assq 'gnus-namazu-target-groups
440                       (gnus-info-method (gnus-get-info gnus-newsgroup-name))))
441         (list gnus-newsgroup-name))))))
442
443 (defun gnus-namazu/get-current-query ()
444   (and (eq major-mode 'gnus-summary-mode)
445        (gnus-ephemeral-group-p gnus-newsgroup-name)
446        (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name)
447        (cadr (assq 'gnus-namazu-current-query
448                    (gnus-info-method (gnus-get-info gnus-newsgroup-name))))))
449
450 (defvar gnus-namazu/read-query-original-buffer nil)
451 (defvar gnus-namazu/read-query-prompt nil)
452 (defvar gnus-namazu/read-query-history nil)
453
454 (defun gnus-namazu/get-current-subject ()
455   (and gnus-namazu/read-query-original-buffer
456        (bufferp gnus-namazu/read-query-original-buffer)
457        (with-current-buffer gnus-namazu/read-query-original-buffer
458          (when (eq major-mode 'gnus-summary-mode)
459            (let ((s (gnus-summary-article-subject)))
460              ;; Remove typically prefixes of mailing lists.
461              (when (string-match
462                     "^\\(\\[[^]]*[0-9]+\\]\\|([^)]*[0-9]+)\\)\\s-*" s)
463                (setq s (substring s (match-end 0))))
464              (when (string-match
465                     "^\\(Re\\(\\^?\\([0-9]+\\|\\[[0-9]+\\]\\)\\)?:\\s-*\\)+" s)
466                (setq s (substring s (match-end 0))))
467              (when (string-match "\\s-*(\\(re\\|was\\)\\b" s)
468                (setq s (substring s 0 (match-beginning 0))))
469              s)))))
470
471 (defun gnus-namazu/get-current-from ()
472   (and gnus-namazu/read-query-original-buffer
473        (bufferp gnus-namazu/read-query-original-buffer)
474        (with-current-buffer gnus-namazu/read-query-original-buffer
475          (when (eq major-mode 'gnus-summary-mode)
476            (cadr (mail-extract-address-components
477                   (mail-header-from
478                    (gnus-summary-article-header))))))))
479
480 (defun gnus-namazu/get-current-to ()
481   (and gnus-namazu/read-query-original-buffer
482        (bufferp gnus-namazu/read-query-original-buffer)
483        (with-current-buffer gnus-namazu/read-query-original-buffer
484          (when (eq major-mode 'gnus-summary-mode)
485            (cadr (mail-extract-address-components
486                   (cdr (assq 'To (mail-header-extra
487                                   (gnus-summary-article-header))))))))))
488
489 (defmacro gnus-namazu/minibuffer-prompt-end ()
490   (if (fboundp 'minibuffer-prompt-end)
491       '(minibuffer-prompt-end)
492     '(point-min)))
493
494 (defun gnus-namazu/message (string &rest arguments)
495   (let* ((s1 (concat
496               gnus-namazu/read-query-prompt
497               (buffer-substring (gnus-namazu/minibuffer-prompt-end)
498                                 (point-max))))
499          (s2 (apply (function format) string arguments))
500          (w (- (window-width)
501                (string-width s1)
502                (string-width s2)
503                1)))
504     (message (if (>= w 0)
505                  (concat s1 (make-string w ?\ ) s2)
506                s2))
507     (if (sit-for 0.3) (message s1))
508     s2))
509
510 (defun gnus-namazu/complete-query ()
511   (interactive)
512   (let ((pos (point)))
513     (cond
514      ((and (re-search-backward "\\+\\([-a-z]*\\)" nil t)
515            (= pos (match-end 0)))
516       (let* ((partial (match-string 1))
517              (completions
518               (all-completions
519                partial
520                (mapcar 'list gnus-namazu-field-keywords))))
521         (cond
522          ((null completions)
523           (gnus-namazu/message "No completions of %s" partial))
524          ((= 1 (length completions))
525           (goto-char (match-beginning 1))
526           (delete-region (match-beginning 1) (match-end 1))
527           (insert (car completions) ":")
528           (setq pos (point))
529           (gnus-namazu/message "Completed"))
530          (t
531           (let ((x (try-completion partial (mapcar 'list completions))))
532             (if (string= x partial)
533                 (if (and (eq last-command
534                              'gnus-namazu/field-keyword-completion)
535                          completion-auto-help)
536                     (with-output-to-temp-buffer "*Completions*"
537                       (display-completion-list completions))
538                   (gnus-namazu/message "Sole completion"))
539               (goto-char (match-beginning 1))
540               (delete-region (match-beginning 1) (match-end 1))
541               (insert x)
542               (setq pos (point))))))))
543      ((and (looking-at "\\+subject:")
544            (= pos (match-end 0)))
545       (let ((s (gnus-namazu/get-current-subject)))
546         (when s
547           (goto-char pos)
548           (insert "\"" s "\"")
549           (setq pos (point)))))
550      ((and (looking-at "\\+from:")
551            (= pos (match-end 0)))
552       (let ((f (gnus-namazu/get-current-from)))
553         (when f
554           (goto-char pos)
555           (insert "\"" f "\"")
556           (setq pos (point)))))
557      ((and (looking-at "\\+to:")
558            (= pos (match-end 0)))
559       (let ((to (gnus-namazu/get-current-to)))
560         (when to
561           (goto-char pos)
562           (insert "\"" to "\"")
563           (setq pos (point))))))
564     (goto-char pos)))
565
566 (defvar gnus-namazu/read-query-map
567   (let ((keymap (copy-keymap minibuffer-local-map)))
568     (define-key keymap "\t" 'gnus-namazu/complete-query)
569     keymap))
570
571 (defun gnus-namazu/read-query (prompt &optional initial)
572   (let ((gnus-namazu/read-query-original-buffer (current-buffer))
573         (gnus-namazu/read-query-prompt prompt))
574     (unless initial
575       (when (setq initial (gnus-namazu/get-current-query))
576         (setq initial (cons initial 0))))
577     (read-from-minibuffer prompt initial gnus-namazu/read-query-map nil
578                           'gnus-namazu/read-query-history)))
579
580 (defun gnus-namazu/highlight-words (query)
581   (with-temp-buffer
582     (insert " " query)
583     ;; Remove tokens for NOT search
584     (goto-char (point-min))
585     (while (re-search-forward "[\e$B!!\e(B \t\r\f\n]+not[\e$B!!\e(B \t\r\f\n]+\
586 \\([^\e$B!!\e(B \t\r\f\n\"{(/]+\\|\"[^\"]+\"\\|{[^}]+}\\|([^)]+)\\|/[^/]+/\\)+" nil t)
587       (delete-region (match-beginning 0) (match-end 0)))
588     ;; Remove tokens for Field search
589     (goto-char (point-min))
590     (while (re-search-forward "[\e$B!!\e(B \t\r\f\n]+\\+[^\e$B!!\e(B \t\r\f\n:]+:\
591 \\([^\e$B!!\e(B \t\r\f\n\"{(/]+\\|\"[^\"]+\"\\|{[^}]+}\\|([^)]+)\\|/[^/]+/\\)+" nil t)
592       (delete-region (match-beginning 0) (match-end 0)))
593     ;; Remove tokens for Regexp search
594     (goto-char (point-min))
595     (while (re-search-forward "/[^/]+/" nil t)
596       (delete-region (match-beginning 0) (match-end 0)))
597     ;; Remove brackets, double quote, asterisk and operators
598     (goto-char (point-min))
599     (while (re-search-forward "\\([(){}\"*]\\|\\b\\(and\\|or\\)\\b\\)" nil t)
600       (delete-region (match-beginning 0) (match-end 0)))
601     ;; Collect all keywords
602     (setq query nil)
603     (goto-char (point-min))
604     (while (re-search-forward "[^\e$B!!\e(B \t\r\f\n]+" nil t)
605       (push (match-string 0) query))
606     (when query
607       (let (en ja)
608         (dolist (q query)
609           (if (string-match "\\cj" q)
610               (push q ja)
611             (push q en)))
612         (append
613          (when en
614            (list (list (concat "\\b\\(" (regexp-opt en) "\\)\\b")
615                        0 0 'gnus-namazu-query-highlight-face)))
616          (when ja
617            (list (list (regexp-opt ja)
618                        0 0 'gnus-namazu-query-highlight-face))))))))
619
620 (defun gnus-namazu/truncate-article-list (articles)
621   (let ((hit (length articles)))
622     (when (and gnus-large-newsgroup
623                (> hit gnus-large-newsgroup))
624       (let* ((cursor-in-echo-area nil)
625              (input (read-from-minibuffer
626                      (format "\
627 Too many articles were retrieved.  How many articles (max %d): "
628                              hit)
629                      (cons (number-to-string gnus-large-newsgroup) 0))))
630         (unless (string-match "\\`[ \t]*\\'" input)
631           (setcdr (nthcdr (min (1- (string-to-number input)) hit) articles)
632                   nil)))))
633   articles)
634
635 ;;;###autoload
636 (defun gnus-namazu-search (groups query)
637   "Search QUERY through GROUPS with Namazu,
638 and make a virtual group contains its results."
639   (interactive
640    (list
641     (gnus-namazu/get-target-groups)
642     (gnus-namazu/read-query "Enter query: ")))
643   (gnus-namazu/setup)
644   (let ((articles (gnus-namazu/search groups query)))
645     (if articles
646         (let ((real-groups groups)
647               (vgroup
648                (apply (function format)
649                       "nnvirtual:namazu-search?query=%s&groups=%s&id=%d%d%d"
650                       query
651                       (if groups (mapconcat 'identity groups ",") "ALL")
652                       (current-time))))
653           (gnus-namazu/truncate-article-list articles)
654           (unless real-groups
655             (dolist (a articles)
656               (add-to-list 'real-groups (gnus-namazu/article-group a))))
657           ;; Generate virtual group which includes all results.
658           (when (fboundp 'gnus-group-decoded-name)
659             (setq vgroup
660                   (encode-coding-string vgroup gnus-namazu-coding-system)))
661           (setq vgroup
662                 (gnus-group-read-ephemeral-group
663                  vgroup
664                  `(nnvirtual ,vgroup
665                              (nnvirtual-component-groups ,real-groups)
666                              (gnus-namazu-target-groups ,groups)
667                              (gnus-namazu-current-query ,query))
668                  t (cons (current-buffer) (current-window-configuration)) t))
669           (when gnus-namazu-query-highlight
670             (gnus-group-set-parameter vgroup 'highlight-words
671                                       (gnus-namazu/highlight-words query)))
672           ;; Generate new summary buffer which contains search results.
673           (gnus-group-read-group
674            t t vgroup
675            (sort (delq nil ;; Ad-hoc fix, to avoid wrong-type-argument error.
676                        (mapcar
677                         (lambda (a)
678                           (nnvirtual-reverse-map-article
679                            (gnus-namazu/article-group a)
680                            (gnus-namazu/article-number a)))
681                         articles))
682                  '<)))
683       (message "No entry."))))
684
685 (defmacro gnus-namazu/lock-file-name (&optional directory)
686   `(expand-file-name "NMZ.lock2" ,directory))
687
688 (defmacro gnus-namazu/status-file-name (&optional directory)
689   `(expand-file-name "NMZ.status" ,directory))
690
691 (defmacro gnus-namazu/index-file-name (&optional directory)
692   `(expand-file-name "NMZ.i" ,directory))
693
694 (defun gnus-namazu/mknmz-cleanup (directory)
695   (let ((lockfile (gnus-namazu/lock-file-name directory)))
696     (when (file-exists-p lockfile)
697       (delete-file lockfile)
698       (dolist (tmpfile (directory-files directory t "\\`NMZ\\..*\\.tmp\\'" t))
699         (delete-file tmpfile)))))
700
701 ;;;###autoload
702 (defun gnus-namazu-create-index (directory &optional target-directories force)
703   "Create index under DIRECTORY."
704   (interactive
705    (list
706     (if (and current-prefix-arg (> (length gnus-namazu-index-directories) 1))
707         (completing-read "Directory: "
708                          (mapcar 'list gnus-namazu-index-directories) nil t)
709       (gnus-namazu/default-index-directory))
710     nil t))
711   (setq directory (file-name-as-directory (expand-file-name directory)))
712   (unless target-directories
713     (setq target-directories
714           (delq nil
715                 (mapcar (lambda (dir)
716                           (when (file-directory-p dir) dir))
717                         (append
718                          (mapcar 'gnus-namazu/server-directory
719                                  (gnus-namazu/indexed-servers))
720                          (list
721                           (expand-file-name gnus-cache-directory)
722                           (expand-file-name gnus-agent-directory)))))))
723   (if (file-exists-p (gnus-namazu/lock-file-name directory))
724       (when force
725         (error "Found lock file: %s" (gnus-namazu/lock-file-name directory)))
726     (with-current-buffer
727         (get-buffer-create (concat " *mknmz*" directory))
728       (erase-buffer)
729       (unless (file-directory-p directory)
730         (make-directory directory t))
731       (setq default-directory directory)
732       (let ((args (append gnus-namazu-make-index-arguments
733                           target-directories)))
734         (insert "% " gnus-namazu-make-index-command " "
735                 (mapconcat 'identity args " ") "\n")
736         (goto-char (point-max))
737         (when force
738           (pop-to-buffer (current-buffer)))
739         (message "Make index at %s..." directory)
740         (unwind-protect
741             (apply 'call-process gnus-namazu-make-index-command nil t t args)
742           (gnus-namazu/mknmz-cleanup directory))
743         (message "Make index at %s...done" directory)
744         (unless force
745           (kill-buffer (current-buffer)))))
746     (gnus-namazu/make-directory-table t)))
747
748 (defun gnus-namazu/lapse-seconds (start end)
749   "Return lapse seconds from START to END.
750 START and END are lists which represent time in Emacs-style."
751   (+ (* (- (car end) (car start)) 65536)
752      (cadr end)
753      (- (cadr start))))
754
755 (defun gnus-namazu/index-old-p (directory)
756   "Return non-nil value when the index under the DIRECTORY is older
757 than the period that is set to `gnus-namazu-index-update-interval'"
758   (let ((file (gnus-namazu/index-file-name directory)))
759     (or (not (file-exists-p file))
760         (and (integerp gnus-namazu-index-update-interval)
761              (>= (gnus-namazu/lapse-seconds
762                   (nth 5 (file-attributes file))
763                   (current-time))
764                  gnus-namazu-index-update-interval)))))
765
766 (defvar gnus-namazu/update-directories nil)
767 (defvar gnus-namazu/update-process nil)
768
769 (defun gnus-namazu/update-p (directory &optional force)
770   "Return the DIRECTORY when the index undef the DIRECTORY should be updated."
771   (setq directory (file-name-as-directory (expand-file-name directory)))
772   (labels ((error-message (format &rest args)
773                           (apply (if force 'error 'message) format args)
774                           nil))
775     (if gnus-namazu/update-process
776         (error-message "%s" "Can not run two update processes simultaneously")
777       (and (or force
778                (gnus-namazu/index-old-p directory))
779            (let ((status-file (gnus-namazu/status-file-name directory)))
780              (or (file-exists-p status-file)
781                  (error-message "Can not find status file: %s" status-file)))
782            (let ((lock-file (gnus-namazu/lock-file-name directory)))
783              (or (not (file-exists-p lock-file))
784                  (error-message "Found lock file: %s" lock-file)))
785            directory))))
786
787 ;;;###autoload
788 (defun gnus-namazu-update-index (directory &optional force)
789   "Update the index under the DIRECTORY."
790   (interactive
791    (list
792     (if (and current-prefix-arg (> (length gnus-namazu-index-directories) 1))
793         (completing-read "Directory: "
794                          (mapcar 'list gnus-namazu-index-directories) nil t)
795       (gnus-namazu/default-index-directory))
796     t))
797   (when (and (not gnus-namazu-imap-maildir)
798              (setq directory (gnus-namazu/update-p directory force)))
799     (with-current-buffer (get-buffer-create (concat " *mknmz*" directory))
800       (buffer-disable-undo)
801       (erase-buffer)
802       (unless (file-directory-p directory)
803         (make-directory directory t))
804       (setq default-directory directory)
805       (let ((proc (start-process gnus-namazu-make-index-command
806                                  (current-buffer)
807                                  gnus-namazu-make-index-command
808                                  (format "--update=%s" directory))))
809         (if (processp proc)
810             (prog1 (setq gnus-namazu/update-process proc)
811               (process-kill-without-query proc)
812               (set-process-sentinel proc 'gnus-namazu/update-sentinel)
813               (add-hook 'kill-emacs-hook 'gnus-namazu-stop-update)
814               (message "Update index at %s..." directory))
815           (goto-char (point-min))
816           (if (re-search-forward "^ERROR:.*$" nil t)
817               (progn
818                 (pop-to-buffer (current-buffer))
819                 (funcall (if force 'error 'message)
820                          "Update index at %s...%s" directory (match-string 0)))
821             (kill-buffer (current-buffer))
822             (funcall (if force 'error 'message)
823                      "Can not start %s" gnus-namazu-make-index-command))
824           nil)))))
825
826 ;;;###autoload
827 (defun gnus-namazu-update-all-indices (&optional force)
828   "Update all indices which is set to `gnus-namazu-index-directories'."
829   (interactive (list t))
830   (gnus-namazu-update-indices gnus-namazu-index-directories force))
831
832 (defun gnus-namazu-update-indices (&optional directories force)
833   (when (and (not gnus-namazu-imap-maildir)
834              (setq directories
835                    (delq nil (mapcar (lambda (d) 
836                                        (gnus-namazu/update-p d force)) 
837                                      directories))))
838     (setq gnus-namazu/update-directories (cons force (cdr directories)))
839     (gnus-namazu-update-index (car directories) force)))
840
841 (defun gnus-namazu/update-sentinel (process event)
842   (let ((buffer (process-buffer process)))
843     (when (buffer-name buffer)
844       (with-current-buffer buffer
845         (gnus-namazu/mknmz-cleanup default-directory)
846         (goto-char (point-min))
847         (cond
848          ((re-search-forward "^ERROR:.*$" nil t)
849           (pop-to-buffer (current-buffer))
850           (message "Update index at %s...%s"
851                    default-directory (match-string 0))
852           (setq gnus-namazu/update-directories nil))
853          ((and (eq 'exit (process-status process))
854                (zerop (process-exit-status process)))
855           (message "Update index at %s...done" default-directory)
856           (unless (or debug-on-error debug-on-quit)
857             (kill-buffer buffer)))))))
858   (setq gnus-namazu/update-process nil)
859   (unless (gnus-namazu-update-indices (cdr gnus-namazu/update-directories)
860                                       (car gnus-namazu/update-directories))
861     (gnus-namazu/make-directory-table t)))
862
863 ;;;###autoload
864 (defun gnus-namazu-stop-update ()
865   "Stop the running indexer of Namazu."
866   (interactive)
867   (setq gnus-namazu/update-directories nil)
868   (and gnus-namazu/update-process
869        (processp gnus-namazu/update-process)
870        (kill-process gnus-namazu/update-process)))
871
872 (let (current-load-list)
873   (defadvice gnus-offer-save-summaries
874     (before gnus-namazu-kill-summary-buffers activate compile)
875     "Advised by `gnus-namazu'.
876 In order to avoid annoying questions, kill summary buffers which
877 generated by `gnus-namazu' itself before `gnus-offer-save-summaries'
878 is called."
879     (let ((buffers (buffer-list)))
880       (while buffers
881         (when (with-current-buffer (car buffers)
882                 (and (eq major-mode 'gnus-summary-mode)
883                      (gnus-ephemeral-group-p gnus-newsgroup-name)
884                      (string-match gnus-namazu/group-name-regexp
885                                    gnus-newsgroup-name)))
886           (kill-buffer (car buffers)))
887         (setq buffers (cdr buffers))))))
888
889 ;;;###autoload
890 (defun gnus-namazu-insinuate ()
891   (add-hook
892    'gnus-group-mode-hook
893    (lambda ()
894      (define-key gnus-group-mode-map "\C-c\C-n" 'gnus-namazu-search)))
895   (add-hook
896    'gnus-summary-mode-hook
897    (lambda ()
898      (define-key gnus-summary-mode-map "\C-c\C-n" 'gnus-namazu-search))))
899
900 (provide 'gnus-namazu)
901
902 ;; gnus-namazu.el ends here.