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