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