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