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