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