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