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