Cancel the last change.
[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 ;; Multibyte group name:
152 (add-to-list 'gnus-group-name-charset-group-alist
153              (cons gnus-namazu/group-name-regexp gnus-namazu-coding-system))
154 (and
155  (fboundp 'gnus-group-decoded-name)
156  (let ((group
157         (concat "nnvirtual:namazu-search?query="
158                 (decode-coding-string
159                  (string 27 36 66 52 65 59 122 27 40 66)
160                  (if (boundp 'MULE) '*iso-2022-jp* 'iso-2022-7bit)))))
161    (/= (length (string-to-char-list (concat "*Summary " group "*")))
162        (length
163         (string-to-char-list
164          (gnus-summary-buffer-name
165           (encode-coding-string group gnus-namazu-coding-system))))))
166  (let (current-load-list)
167    (defadvice gnus-summary-buffer-name
168      (before gnus-namazu-summary-buffer-name activate compile)
169      "Advised by `gnus-namazu' to handle encoded group names."
170      (ad-set-arg 0 (gnus-group-decoded-name (ad-get-arg 0))))))
171
172 (defmacro gnus-namazu/make-article (group number)
173   `(cons ,group ,number))
174 (defmacro gnus-namazu/article-group  (x) `(car ,x))
175 (defmacro gnus-namazu/article-number (x) `(cdr ,x))
176
177 (defsubst gnus-namazu/indexed-servers ()
178   "Choice appropriate servers from opened ones, and return thier list."
179   (append
180    (gnus-servers-using-backend 'nnml)
181    (gnus-servers-using-backend 'nnmh)))
182
183 (defun gnus-namazu/setup ()
184   (unless gnus-namazu-case-sensitive-filesystem
185     ;; FIXME: The alist to map group names in lower case to real names
186     ;; is reconstructed every when gnus-namazu/setup() is called.
187     ;; This reconstruction make gnus-namazu-search() slow.
188     (setq gnus-namazu/group-alist nil)
189     (dolist (server (gnus-namazu/indexed-servers))
190       (dolist (group (gnus-namazu/request-list server))
191         (let ((name (gnus-group-prefixed-name group server)))
192           (unless (assoc name gnus-namazu/group-alist)
193             (push (cons (downcase name) name) gnus-namazu/group-alist)))))))
194
195 (defun gnus-namazu/shutdown ()
196   (setq gnus-namazu/group-alist nil))
197 (add-hook 'gnus-exit-gnus-hook 'gnus-namazu/shutdown)
198
199 (defun gnus-namazu/request-list (server)
200   "Return groups of the server SERVER."
201   (and (memq (car server) '(nnml nnmh))
202        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
203        (gnus-request-list server)
204        (mapcar (function car)
205                (if (eq 'nnml (car server))
206                    nnml-group-alist
207                  nnmh-group-alist))))
208
209 (defun gnus-namazu/server-directory (server)
210   "Return the top directory of the server SERVER."
211   (and (memq (car server) '(nnml nnmh))
212        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
213        (file-name-as-directory
214         (expand-file-name (if (eq 'nnml (car server))
215                               nnml-directory
216                             nnmh-directory)))))
217
218 ;;; Functions to call Namazu.
219 (defsubst gnus-namazu/normalize-results ()
220   "Normalize file names returned by Namazu in this current buffer."
221   (goto-char (point-min))
222   (while (not (eobp))
223     (when (if gnus-namazu-need-path-normalization
224               (or (not (looking-at "/\\(.\\)|/"))
225                   (replace-match "\\1:/"))
226             (eq ?~ (char-after (point))))
227       (insert (expand-file-name
228                (buffer-substring (gnus-point-at-bol) (gnus-point-at-eol))))
229       (delete-region (point) (gnus-point-at-eol)))
230     (forward-line 1)))
231
232 (defsubst gnus-namazu/call-namazu (query)
233   (let ((coding-system-for-read gnus-namazu-coding-system)
234         (coding-system-for-write gnus-namazu-coding-system)
235         (default-process-coding-system
236           (cons gnus-namazu-coding-system gnus-namazu-coding-system))
237         (file-name-coding-system gnus-namazu-coding-system)
238         (pathname-coding-system gnus-namazu-coding-system))
239     (apply 'call-process
240            `(,gnus-namazu-command
241              nil                        ; input from /dev/null
242              t                          ; output
243              nil                        ; don't redisplay
244              "-q"                       ; don't be verbose
245              "-a"                       ; show all matches
246              "-l"                       ; use list format
247              ,@gnus-namazu-additional-arguments
248              ,query
249              ,@gnus-namazu-index-directories))))
250
251 (defsubst gnus-namazu/group-prefixed-name (group method)
252   "Return the whole name from GROUP and METHOD."
253   (if gnus-namazu-case-sensitive-filesystem
254       (gnus-group-prefixed-name group method)
255     (let ((name (gnus-group-prefixed-name group method)))
256       (or (cdr (assoc (downcase name) gnus-namazu/group-alist))
257           name))))
258
259 (defun gnus-namazu/search (groups query)
260   (with-temp-buffer
261     (let ((exit-status (gnus-namazu/call-namazu query)))
262       (unless (zerop exit-status)
263         (error "Namazu finished abnormally: %d" exit-status))
264       (let* ((articles)
265              (server-alist
266               (delq nil
267                     (let (dir)
268                       (mapcar
269                        (lambda (s)
270                          (when (setq dir (gnus-namazu/server-directory s))
271                            (cons (file-name-as-directory dir) s)))
272                        (gnus-namazu/indexed-servers)))))
273              (topdir-regexp (regexp-opt (mapcar 'car server-alist))))
274         (gnus-namazu/normalize-results)
275         (goto-char (point-min))
276         (while (not (eobp))
277           (let (server group file)
278             (and (looking-at topdir-regexp)
279                  ;; Check a discovered file is managed by Gnus servers.
280                  (setq file (buffer-substring-no-properties
281                              (match-end 0) (gnus-point-at-eol))
282                        server (cdr (assoc (match-string-no-properties 0)
283                                           server-alist)))
284                  ;; Check validity of the file name.
285                  (string-match "/\\([0-9]+\\)\\'" file)
286                  (progn
287                    (setq group (substring file 0 (match-beginning 0))
288                          file (match-string 1 file))
289                    (setq group
290                          (gnus-namazu/group-prefixed-name
291                           (nnheader-replace-chars-in-string group ?/ ?.)
292                           server))
293                    (when (or (not groups)
294                              (member group groups))
295                      (push (gnus-namazu/make-article
296                             group (string-to-number file))
297                            articles)))))
298           (forward-line 1))
299         (nreverse articles)))))
300
301
302 ;;; User Interface:
303 (defun gnus-namazu/get-target-groups ()
304   (cond
305    ((eq major-mode 'gnus-group-mode)
306     ;; In Group buffer.
307     (cond
308      (current-prefix-arg
309       (gnus-group-process-prefix current-prefix-arg))
310      (gnus-group-marked
311       (prog1 gnus-group-marked (gnus-group-unmark-all-groups)))))
312    ((eq major-mode 'gnus-summary-mode)
313     ;; In Summary buffer.
314     (if current-prefix-arg
315         (list (gnus-read-group "Group: "))
316       (if (and (gnus-ephemeral-group-p gnus-newsgroup-name)
317                (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name))
318           (cadr (assq 'gnus-namazu-target-groups
319                       (gnus-info-method (gnus-get-info gnus-newsgroup-name))))
320         (list gnus-newsgroup-name))))))
321
322 (defun gnus-namazu/get-current-query ()
323   (and (eq major-mode 'gnus-summary-mode)
324        (gnus-ephemeral-group-p gnus-newsgroup-name)
325        (string-match gnus-namazu/group-name-regexp gnus-newsgroup-name)
326        (cadr (assq 'gnus-namazu-current-query
327                    (gnus-info-method (gnus-get-info gnus-newsgroup-name))))))
328
329 (defvar gnus-namazu/read-query-original-buffer nil)
330 (defvar gnus-namazu/read-query-prompt nil)
331 (defvar gnus-namazu/read-query-history nil)
332
333 (defun gnus-namazu/get-current-subject ()
334   (and gnus-namazu/read-query-original-buffer
335        (bufferp gnus-namazu/read-query-original-buffer)
336        (with-current-buffer gnus-namazu/read-query-original-buffer
337          (when (eq major-mode 'gnus-summary-mode)
338            (let ((s (gnus-summary-article-subject)))
339              ;; Remove typically prefixes of mailing lists.
340              (when (string-match
341                     "^\\(\\[[^]]*[0-9]+\\]\\|([^)]*[0-9]+)\\)\\s-*" s)
342                (setq s (substring s (match-end 0))))
343              (when (string-match
344                     "^\\(Re\\(\\^?\\([0-9]+\\|\\[[0-9]+\\]\\)\\)?:\\s-*\\)+" s)
345                (setq s (substring s (match-end 0))))
346              (when (string-match "\\s-*(\\(re\\|was\\)\\b" s)
347                (setq s (substring s 0 (match-beginning 0))))
348              s)))))
349
350 (defun gnus-namazu/get-current-from ()
351   (and gnus-namazu/read-query-original-buffer
352        (bufferp gnus-namazu/read-query-original-buffer)
353        (with-current-buffer gnus-namazu/read-query-original-buffer
354          (when (eq major-mode 'gnus-summary-mode)
355            (cadr (mail-extract-address-components
356                   (mail-header-from
357                    (gnus-summary-article-header))))))))
358
359 (defmacro gnus-namazu/minibuffer-prompt-end ()
360   (if (fboundp 'minibuffer-prompt-end)
361       '(minibuffer-prompt-end)
362     '(point-min)))
363
364 (defun gnus-namazu/message (string &rest arguments)
365   (let* ((s1 (concat
366               gnus-namazu/read-query-prompt
367               (buffer-substring (gnus-namazu/minibuffer-prompt-end)
368                                 (point-max))))
369          (s2 (apply (function format) string arguments))
370          (w (- (window-width)
371                (string-width s1)
372                (string-width s2)
373                1)))
374     (message (if (>= w 0)
375                  (concat s1 (make-string w ?\ ) s2)
376                s2))
377     (if (sit-for 0.3) (message s1))
378     s2))
379
380 (defun gnus-namazu/complete-query ()
381   (interactive)
382   (let ((pos (point)))
383     (cond
384      ((and (re-search-backward "\\+\\([a-z]*\\)" nil t)
385            (= pos (match-end 0)))
386       (let* ((partial (match-string 1))
387              (completions
388               (all-completions
389                partial
390                (mapcar 'list gnus-namazu-field-keywords))))
391         (cond
392          ((null completions)
393           (gnus-namazu/message "No completions of %s" partial))
394          ((= 1 (length completions))
395           (goto-char (match-beginning 1))
396           (delete-region (match-beginning 1) (match-end 1))
397           (insert (car completions) ":")
398           (setq pos (point))
399           (gnus-namazu/message "Completed"))
400          (t
401           (let ((x (try-completion partial (mapcar 'list completions))))
402             (if (string= x partial)
403                 (if (and (eq last-command
404                              'gnus-namazu/field-keyword-completion)
405                          completion-auto-help)
406                     (with-output-to-temp-buffer "*Completions*"
407                       (display-completion-list completions))
408                   (gnus-namazu/message "Sole completion"))
409               (goto-char (match-beginning 1))
410               (delete-region (match-beginning 1) (match-end 1))
411               (insert x)
412               (setq pos (point))))))))
413      ((and (looking-at "\\+subject:")
414            (= pos (match-end 0)))
415       (let ((s (gnus-namazu/get-current-subject)))
416         (when s
417           (goto-char pos)
418           (insert "\"" s "\"")
419           (setq pos (point)))))
420      ((and (looking-at "\\+from:")
421            (= pos (match-end 0)))
422       (let ((f (gnus-namazu/get-current-from)))
423         (when f
424           (goto-char pos)
425           (insert "\"" f "\"")
426           (setq pos (point))))))
427     (goto-char pos)))
428
429 (defvar gnus-namazu/read-query-map
430   (let ((keymap (copy-keymap minibuffer-local-map)))
431     (define-key keymap "\t" 'gnus-namazu/complete-query)
432     keymap))
433
434 (defun gnus-namazu/read-query (prompt &optional initial)
435   (let ((gnus-namazu/read-query-original-buffer (current-buffer))
436         (gnus-namazu/read-query-prompt prompt))
437     (unless initial
438       (when (setq initial (gnus-namazu/get-current-query))
439         (setq initial (cons initial 0))))
440     (read-from-minibuffer prompt initial gnus-namazu/read-query-map nil
441                           'gnus-namazu/read-query-history)))
442
443 (defun gnus-namazu/truncate-article-list (articles)
444   (let ((hit (length articles)))
445     (when (> hit gnus-large-newsgroup)
446       (let* ((cursor-in-echo-area nil)
447              (input
448               (when (> hit gnus-large-newsgroup)
449                 (read-from-minibuffer
450                  (format
451                   "Too many articles were retrieved.  How many articles (max %d): "
452                   hit)
453                  (cons (number-to-string gnus-large-newsgroup) 0)))))
454         (unless (string-match "\\`[ \t]*\\'" input)
455           (setcdr (nthcdr (min (1- (string-to-number input)) hit) articles)
456                   nil))))
457     articles))
458
459 ;;;###autoload
460 (defun gnus-namazu-search (groups query)
461   "Search QUERY through GROUPS with Namazu,
462 and make a virtual group contains its results."
463   (interactive
464    (list
465     (gnus-namazu/get-target-groups)
466     (gnus-namazu/read-query "Enter query: ")))
467   (gnus-namazu/setup)
468   (let ((articles (gnus-namazu/search groups query)))
469     (if articles
470         (let ((real-groups groups)
471               (vgroup
472                (apply (function format)
473                       "nnvirtual:namazu-search?query=%s&groups=%s&id=%d%d%d"
474                       query
475                       (if groups (mapconcat 'identity groups ",") "ALL")
476                       (current-time))))
477           (gnus-namazu/truncate-article-list articles)
478           (unless real-groups
479             (dolist (a articles)
480               (add-to-list 'real-groups (gnus-namazu/article-group a))))
481           ;; Generate virtual group which includes all results.
482           (when (fboundp 'gnus-group-decoded-name)
483             (setq vgroup
484                   (encode-coding-string vgroup gnus-namazu-coding-system)))
485           (setq vgroup
486                 (gnus-group-read-ephemeral-group
487                  vgroup
488                  `(nnvirtual ,vgroup
489                              (nnvirtual-component-groups ,real-groups)
490                              (gnus-namazu-target-groups ,groups)
491                              (gnus-namazu-current-query ,query))
492                  t (cons (current-buffer) (current-window-configuration)) t))
493           ;; Generate new summary buffer which contains search results.
494           (gnus-group-read-group
495            t t vgroup
496            (sort (delq nil ;; Ad-hoc fix, to avoid wrong-type-argument error.
497                        (mapcar
498                         (lambda (a)
499                           (nnvirtual-reverse-map-article
500                            (gnus-namazu/article-group a)
501                            (gnus-namazu/article-number a)))
502                         articles))
503                  '<)))
504       (message "No entry."))))
505
506 (defun gnus-namazu-insinuate ()
507   (add-hook
508    'gnus-group-mode-hook
509    (lambda ()
510      (define-key gnus-group-mode-map "\C-c\C-n" 'gnus-namazu-search)))
511   (add-hook
512    'gnus-summary-mode-hook
513    (lambda ()
514      (define-key gnus-summary-mode-map "\C-c\C-n" 'gnus-namazu-search))))
515
516 (provide 'gnus-namazu)
517
518 ;; gnus-namazu.el ends here.