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