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