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