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