New file which is imported from `t-gnus-6_15-quimby' branch.
[elisp/gnus.git-] / lisp / gnus-namazu.el
1 ;;; gnus-namazu.el --- Search mail with Namazu.
2
3 ;; Copyright (C) 2000,2001 Tsuchiya Masatoshi <tsuchiya@namazu.org>
4
5 ;; Author: Tsuchiya Masatoshi <tsuchiya@namazu.org>
6 ;; Keywords: mail searching namazu
7
8 ;;; Copyright:
9
10 ;; This file is a part of Semi-Gnus.
11
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program; if not, you can either send email to this
24 ;; program's maintainer or write to: The Free Software Foundation,
25 ;; Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.
26
27
28 ;;; Commentary:
29
30 ;; This file defines the command to search mails with Namazu and
31 ;; browse its results with Gnus.  This module requires the external
32 ;; command Namazu.  Visit the following page for more information.
33 ;;
34 ;;     http://namazu.org/
35
36
37 ;;; Install:
38
39 ;; Make index of articles with Namzu before using this module.
40 ;;
41 ;;       % mkdir ~/News/namazu
42 ;;       % mknmz -a -h -O ~/News/namazu ~/Mail
43 ;;
44 ;; When you put index files of Namazu into the directory other than
45 ;; the default one (~/News/namazu), it is necessary to put this
46 ;; expression to your ~/.gnus, in order to set the path of index files
47 ;; to `gnus-namazu-index-directories'.
48 ;;
49 ;;      (setq gnus-namazu-index-directories
50 ;;            (list (expand-file-name "~/namazu")))
51 ;;
52 ;; If you would like to use this module in Gnus (not T-gnus), put this
53 ;; file into the lisp/ directory in the Gnus source tree and run `make
54 ;; install'.  And then, put the following expressions into your ~/.gnus.
55 ;;
56 ;;      (require 'gnus-namazu)
57 ;;      (gnus-namazu-insinuate)
58
59
60 ;;; Usage:
61
62 ;; In group buffer or in summary buffer, type C-c C-n query RET.
63
64
65 ;;; Code:
66
67 (eval-when-compile (require 'cl))
68 (require 'nnoo)
69 (require 'nnheader)
70 (require 'nnmail)
71 (require 'gnus-sum)
72
73 ;; It is required for Mule 2.3.  See the file Mule23@1934.en.
74 (eval-and-compile
75   (autoload 'regexp-opt "regexp-opt"))
76
77 ;; To suppress byte-compile warning.
78 (eval-when-compile
79   (defvar nnml-directory)
80   (defvar nnml-group-alist)
81   (defvar nnmh-directory)
82   (defvar nnmh-group-alist))
83
84
85 (defgroup gnus-namazu nil
86   "Search nnmh and nnml groups in Gnus with Namazu."
87   :group 'namazu
88   :group 'gnus
89   :prefix "gnus-namazu-")
90
91 (defcustom gnus-namazu-index-directories
92   (list
93    (or (and (boundp 'gnus-namazu-index-directory)
94             (symbol-value 'gnus-namazu-index-directory))
95        (and (boundp 'nnir-namazu-index-directory)
96             (symbol-value 'nnir-namazu-index-directory))
97        (expand-file-name "namazu" gnus-directory)))
98   "*Index directory of Namazu."
99   :type '(repeat directory)
100   :group 'gnus-namazu)
101
102 (defcustom gnus-namazu-command
103   (or (and (boundp 'namazu-command)
104            (symbol-value 'namazu-command))
105       (and (boundp 'nnir-namazu-program)
106            (symbol-value 'nnir-namazu-program))
107       "namazu")
108   "*Name of the executable file of Namazu."
109   :group 'gnus-namazu
110   :type 'string)
111
112 (defcustom gnus-namazu-additional-arguments nil
113   "*Additional arguments of Namazu.
114 The options `-q', `-a', and `-l' are always used, very few other
115 options make any sense in this context."
116   :type '(repeat string)
117   :group 'gnus-namazu)
118
119 (defcustom gnus-namazu-field-keywords
120   '("date" "from" "newsgroups" "size" "subject" "summary" "to" "uri")
121   "*List of keywords to do field-search."
122   :type '(repeat string)
123   :group 'gnus-namazu)
124
125 (defcustom gnus-namazu-coding-system
126   (if (memq system-type '(windows-nt OS/2 emx))
127       (if (boundp 'MULE) '*sjis* 'shift_jis)
128     (if (boundp 'MULE) '*euc-japan* 'euc-japan))
129   "*Coding system for Namazu process."
130   :type 'coding-system
131   :group 'gnus-namazu)
132
133 (defcustom gnus-namazu-need-path-normalization
134   (eq system-type 'windows-nt)
135   "*Non-nil means that outputs of namazu may contain a not normalized path."
136   :type 'boolean
137   :group 'gnus-namazu)
138
139 (defcustom gnus-namazu-case-sensitive-filesystem
140   (not (eq system-type 'windows-nt))
141   "*Non-nil means that the using file system distinguishes cases of characters."
142   :type 'boolean
143   :group 'gnus-namazu)
144
145
146 ;;; Internal Variable:
147 (defvar gnus-namazu/group-alist nil
148   "Associative list to map groups in lower case to official names.")
149 (defconst gnus-namazu/group-name-regexp "\\`nnvirtual:namazu-search\\?")
150
151
152 (defmacro gnus-namazu/make-article (group number)
153   `(cons ,group ,number))
154 (defmacro gnus-namazu/article-group  (x) `(car ,x))
155 (defmacro gnus-namazu/article-number (x) `(cdr ,x))
156
157 (defsubst gnus-namazu/indexed-servers ()
158   "Choice appropriate servers from opened ones, and return thier list."
159   (append
160    (gnus-servers-using-backend 'nnml)
161    (gnus-servers-using-backend 'nnmh)))
162
163 (defun gnus-namazu/setup ()
164   (add-to-list 'gnus-group-name-charset-group-alist
165                (cons gnus-namazu/group-name-regexp gnus-namazu-coding-system))
166   (unless gnus-namazu-case-sensitive-filesystem
167     ;; FIXME: The alist to map group names in lower case to real names
168     ;; is reconstructed every when gnus-namazu/setup() is called.
169     ;; This reconstruction make gnus-namazu-search() slow.
170     (setq gnus-namazu/group-alist nil)
171     (dolist (server (gnus-namazu/indexed-servers))
172       (dolist (group (gnus-namazu/request-list server))
173         (let ((name (gnus-group-prefixed-name group server)))
174           (unless (assoc name gnus-namazu/group-alist)
175             (push (cons (downcase name) name) gnus-namazu/group-alist)))))))
176
177 (defun gnus-namazu/shutdown ()
178   (setq gnus-namazu/group-alist nil))
179 (add-hook 'gnus-exit-gnus-hook 'gnus-namazu/shutdown)
180
181 (defun gnus-namazu/request-list (server)
182   "Return groups of the server SERVER."
183   (and (memq (car server) '(nnml nnmh))
184        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
185        (gnus-request-list server)
186        (mapcar (function car)
187                (if (eq 'nnml (car server))
188                    nnml-group-alist
189                  nnmh-group-alist))))
190
191 (defun gnus-namazu/server-directory (server)
192   "Return the top directory of the server SERVER."
193   (and (memq (car server) '(nnml nnmh))
194        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
195        (file-name-as-directory
196         (expand-file-name (if (eq 'nnml (car server))
197                               nnml-directory
198                             nnmh-directory)))))
199
200 ;;; Functions to call Namazu.
201 (defsubst gnus-namazu/normalize-results ()
202   "Normalize file names returned by Namazu in this current buffer."
203   (goto-char (point-min))
204   (while (not (eobp))
205     (when (if gnus-namazu-need-path-normalization
206               (or (not (looking-at "/\\(.\\)|/"))
207                   (replace-match "\\1:/"))
208             (eq ?~ (char-after (point))))
209       (insert (expand-file-name
210                (buffer-substring (gnus-point-at-bol) (gnus-point-at-eol))))
211       (delete-region (point) (gnus-point-at-eol)))
212     (forward-line 1)))
213
214 (defsubst gnus-namazu/call-namazu (query)
215   (let ((coding-system-for-read gnus-namazu-coding-system)
216         (coding-system-for-write gnus-namazu-coding-system)
217         (default-process-coding-system
218           (cons gnus-namazu-coding-system gnus-namazu-coding-system))
219         (file-name-coding-system gnus-namazu-coding-system)
220         (pathname-coding-system gnus-namazu-coding-system))
221     (apply 'call-process
222            `(,gnus-namazu-command
223              nil                        ; input from /dev/null
224              t                          ; output
225              nil                        ; don't redisplay
226              "-q"                       ; don't be verbose
227              "-a"                       ; show all matches
228              "-l"                       ; use list format
229              ,@gnus-namazu-additional-arguments
230              ,query
231              ,@gnus-namazu-index-directories))))
232
233 (defsubst gnus-namazu/group-prefixed-name (group method)
234   "Return the whole name from GROUP and METHOD."
235   (if gnus-namazu-case-sensitive-filesystem
236       (gnus-group-prefixed-name group method)
237     (let ((name (gnus-group-prefixed-name group method)))
238       (or (cdr (assoc (downcase name) gnus-namazu/group-alist))
239           name))))
240
241 (defun gnus-namazu/search (groups query)
242   (with-temp-buffer
243     (let ((exit-status (gnus-namazu/call-namazu query)))
244       (unless (zerop exit-status)
245         (error "Namazu finished abnormally: %d" exit-status))
246       (let* ((articles)
247              (server-alist
248               (delq nil
249                     (let (dir)
250                       (mapcar
251                        (lambda (s)
252                          (when (setq dir (gnus-namazu/server-directory s))
253                            (cons (file-name-as-directory dir) s)))
254                        (gnus-namazu/indexed-servers)))))
255              (topdir-regexp (regexp-opt (mapcar 'car server-alist))))
256         (gnus-namazu/normalize-results)
257         (goto-char (point-min))
258         (while (not (eobp))
259           (let (server group file)
260             (and (looking-at topdir-regexp)
261                  ;; Check a discovered file is managed by Gnus servers.
262                  (setq file (buffer-substring-no-properties
263                              (match-end 0) (gnus-point-at-eol))
264                        server (cdr (assoc (match-string-no-properties 0)
265                                           server-alist)))
266                  ;; Check validity of the file name.
267                  (string-match "/\\([0-9]+\\)\\'" file)
268                  (progn
269                    (setq group (substring file 0 (match-beginning 0))
270                          file (match-string 1 file))
271                    (setq group
272                          (gnus-namazu/group-prefixed-name
273                           (nnheader-replace-chars-in-string group ?/ ?.)
274                           server))
275                    (when (or (not groups)
276                              (member group groups))
277                      (push (gnus-namazu/make-article
278                             group (string-to-number file))
279                            articles)))))
280           (forward-line 1))
281         (nreverse articles)))))
282
283
284 ;;; User Interface:
285 (defun gnus-namazu/get-target-groups ()
286   (cond
287    ((eq major-mode 'gnus-group-mode)
288     ;; In Group buffer.
289     (cond
290      (current-prefix-arg
291       (gnus-group-process-prefix current-prefix-arg))
292      (gnus-group-marked
293       (prog1 gnus-group-marked (gnus-group-unmark-all-groups)))))
294    ((eq major-mode 'gnus-summary-mode)
295     ;; In Summary buffer.
296     (if current-prefix-arg
297         (list (gnus-read-group "Group: "))
298       (if (and (gnus-ephemeral-group-p gnus-newsgroup-name)
299                (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name))
300           (cadr (assq 'gnus-namazu-target-groups
301                       (gnus-info-method (gnus-get-info gnus-newsgroup-name))))
302         (list gnus-newsgroup-name))))))
303
304 (defun gnus-namazu/get-current-query ()
305   (and (eq major-mode 'gnus-summary-mode)
306        (gnus-ephemeral-group-p gnus-newsgroup-name)
307        (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name)
308        (cadr (assq 'gnus-namazu-current-query
309                    (gnus-info-method (gnus-get-info gnus-newsgroup-name))))))
310
311 (defvar gnus-namazu/read-query-original-buffer nil)
312 (defvar gnus-namazu/read-query-prompt nil)
313 (defvar gnus-namazu/read-query-history nil)
314
315 (defun gnus-namazu/get-current-subject ()
316   (and gnus-namazu/read-query-original-buffer
317        (bufferp gnus-namazu/read-query-original-buffer)
318        (with-current-buffer gnus-namazu/read-query-original-buffer
319          (when (eq major-mode 'gnus-summary-mode)
320            (let ((s (gnus-summary-article-subject)))
321              ;; Remove typically prefixes of mailing lists.
322              (when (string-match
323                     "^\\(\\[[^]]*[0-9]+\\]\\|([^)]*[0-9]+)\\)\\s-*" s)
324                (setq s (substring s (match-end 0))))
325              (when (string-match
326                     "^\\(Re\\(\\^?\\([0-9]+\\|\\[[0-9]+\\]\\)\\)?:\\s-*\\)+" s)
327                (setq s (substring s (match-end 0))))
328              (when (string-match "\\s-*(\\(re\\|was\\)\\b" s)
329                (setq s (substring s 0 (match-beginning 0))))
330              s)))))
331
332 (defun gnus-namazu/get-current-from ()
333   (and gnus-namazu/read-query-original-buffer
334        (bufferp gnus-namazu/read-query-original-buffer)
335        (with-current-buffer gnus-namazu/read-query-original-buffer
336          (when (eq major-mode 'gnus-summary-mode)
337            (cadr (mail-extract-address-components
338                   (mail-header-from
339                    (gnus-summary-article-header))))))))
340
341 (defmacro gnus-namazu/minibuffer-prompt-end ()
342   (if (fboundp 'minibuffer-prompt-end)
343       '(minibuffer-prompt-end)
344     '(point-min)))
345
346 (defun gnus-namazu/message (string &rest arguments)
347   (let* ((s1 (concat
348               gnus-namazu/read-query-prompt
349               (buffer-substring (gnus-namazu/minibuffer-prompt-end)
350                                 (point-max))))
351          (s2 (apply (function format) string arguments))
352          (w (- (window-width)
353                (string-width s1)
354                (string-width s2)
355                1)))
356     (message (if (>= w 0)
357                  (concat s1 (make-string w ?\ ) s2)
358                s2))
359     (if (sit-for 0.3) (message s1))
360     s2))
361
362 (defun gnus-namazu/complete-query ()
363   (interactive)
364   (let ((pos (point)))
365     (cond
366      ((and (re-search-backward "\\+\\([a-z]*\\)" nil t)
367            (= pos (match-end 0)))
368       (let* ((partial (match-string 1))
369              (completions
370               (all-completions
371                partial
372                (mapcar 'list gnus-namazu-field-keywords))))
373         (cond
374          ((null completions)
375           (gnus-namazu/message "No completions of %s" partial))
376          ((= 1 (length completions))
377           (goto-char (match-beginning 1))
378           (delete-region (match-beginning 1) (match-end 1))
379           (insert (car completions) ":")
380           (setq pos (point))
381           (gnus-namazu/message "Completed"))
382          (t
383           (let ((x (try-completion partial (mapcar 'list completions))))
384             (if (string= x partial)
385                 (if (and (eq last-command
386                              'gnus-namazu/field-keyword-completion)
387                          completion-auto-help)
388                     (with-output-to-temp-buffer "*Completions*"
389                       (display-completion-list completions))
390                   (gnus-namazu/message "Sole completion"))
391               (goto-char (match-beginning 1))
392               (delete-region (match-beginning 1) (match-end 1))
393               (insert x)
394               (setq pos (point))))))))
395      ((and (looking-at "\\+subject:")
396            (= pos (match-end 0)))
397       (let ((s (gnus-namazu/get-current-subject)))
398         (when s
399           (goto-char pos)
400           (insert "\"" s "\"")
401           (setq pos (point)))))
402      ((and (looking-at "\\+from:")
403            (= pos (match-end 0)))
404       (let ((f (gnus-namazu/get-current-from)))
405         (when f
406           (goto-char pos)
407           (insert "\"" f "\"")
408           (setq pos (point))))))
409     (goto-char pos)))
410
411 (defvar gnus-namazu/read-query-map
412   (let ((keymap (copy-keymap minibuffer-local-map)))
413     (define-key keymap "\t" 'gnus-namazu/complete-query)
414     keymap))
415
416 (defun gnus-namazu/read-query (prompt &optional initial)
417   (let ((gnus-namazu/read-query-original-buffer (current-buffer))
418         (gnus-namazu/read-query-prompt prompt))
419     (unless initial
420       (when (setq initial (gnus-namazu/get-current-query))
421         (setq initial (cons initial 0))))
422     (read-from-minibuffer prompt initial gnus-namazu/read-query-map nil
423                           'gnus-namazu/read-query-history)))
424
425 (defun gnus-namazu/truncate-article-list (articles)
426   (let ((hit (length articles)))
427     (when (> hit gnus-large-newsgroup)
428       (let* ((cursor-in-echo-area nil)
429              (input
430               (when (> hit gnus-large-newsgroup)
431                 (read-from-minibuffer
432                  (format
433                   "Too many articles were retrieved.  How many articles (max %d): "
434                   hit)
435                  (cons (number-to-string gnus-large-newsgroup) 0)))))
436         (unless (string-match "\\`[ \t]*\\'" input)
437           (setcdr (nthcdr (min (1- (string-to-number input)) hit) articles)
438                   nil))))
439     articles))
440
441 (defun gnus-namazu-search (groups query)
442   "Search QUERY through GROUPS with Namazu,
443 and make a virtual group contains its results."
444   (interactive
445    (list
446     (gnus-namazu/get-target-groups)
447     (gnus-namazu/read-query "Enter query: ")))
448   (gnus-namazu/setup)
449   (let ((articles (gnus-namazu/search groups query)))
450     (if articles
451         (let ((real-groups groups)
452               (vgroup
453                (apply (function format)
454                       "nnvirtual:namazu-search?query=%s&groups=%s&id=%d%d%d"
455                       query
456                       (if groups (mapconcat 'identity groups ",") "ALL")
457                       (current-time))
458                gnus-namazu-coding-system))
459           (gnus-namazu/truncate-article-list articles)
460           (unless real-groups
461             (dolist (a articles)
462               (add-to-list 'real-groups (gnus-namazu/article-group a))))
463           ;; Generate virtual group which includes all results.
464           (when (fboundp 'gnus-group-decoded-name)
465             (setq vgroup
466                   (encode-coding-string vgroup gnus-namazu-coding-system)))
467           (setq vgroup
468                 (gnus-group-read-ephemeral-group
469                  vgroup
470                  `(nnvirtual ,vgroup
471                              (nnvirtual-component-groups ,real-groups)
472                              (gnus-namazu-target-groups ,groups)
473                              (gnus-namazu-current-query ,query))
474                  t (cons (current-buffer) (current-window-configuration)) t))
475           ;; Generate new summary buffer which contains search results.
476           (gnus-group-read-group
477            t t vgroup
478            (sort (delq nil ;; Ad-hoc fix, to avoid wrong-type-argument error.
479                        (mapcar
480                         (lambda (a)
481                           (nnvirtual-reverse-map-article
482                            (gnus-namazu/article-group a)
483                            (gnus-namazu/article-number a)))
484                         articles))
485                  '<)))
486       (message "No entry."))))
487
488 (defun gnus-namazu-insinuate ()
489   (add-hook
490    'gnus-group-mode-hook
491    (lambda ()
492      (define-key gnus-group-mode-map "\C-c\C-n" 'gnus-namazu-search)))
493   (add-hook
494    'gnus-summary-mode-hook
495    (lambda ()
496      (define-key gnus-summary-mode-map "\C-c\C-n" 'gnus-namazu-search))))
497
498 (provide 'gnus-namazu)
499
500 ;; gnus-namazu.el ends here.