4707858649555694ce850a31f0f54fff643b993d
[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://www.namazu.org/
35
36
37 ;;; Install:
38
39 ;; (1) Make index of articles with Namzu before using this module.
40 ;;
41 ;;       % mkdir ~/News/namazu
42 ;;       % cd ~/News/namazu
43 ;;       % mknmz -a -c -h ~/Mail
44 ;;
45 ;; (2) Furthermore, put these expressions to your ~/.emacs, to set the
46 ;;     path of the index files to `gnus-namazu-index-directory' and to
47 ;;     initialize this module.
48 ;;
49 ;;       (setq gnus-namazu-index-directory (expand-file-name "~/Namazu"))
50
51 ;; If you would like to use this module in Gnus (not T-gnus), put this
52 ;; file into the lisp/ directory in the Gnus source tree and run `make
53 ;; install'.  And then, put the following expressions into your ~/.gnus.
54 ;;
55 ;;       (require 'gnus-namazu)
56 ;;       (gnus-namazu-insinuate)
57
58
59 ;;; Usage:
60
61 ;; In group buffer or in summary buffer, type C-c C-n query RET.
62
63
64 ;;; Code:
65
66 (eval-when-compile (require 'cl))
67 (require 'nnoo)
68 (require 'nnheader)
69 (require 'nnmail)
70 (require 'gnus-sum)
71
72
73 (defgroup gnus-namazu nil
74   "Search nnmh and nnml groups in Gnus with Namazu."
75   :group 'namazu
76   :group 'gnus
77   :prefix "gnus-namazu-")
78
79 (defcustom gnus-namazu-indexed-servers nil
80   "*List of servers indexed with Namazu."
81   :type '(repeat gnus-select-method)
82   :group 'gnus-namazu)
83
84 (defcustom gnus-namazu-index-directory
85   (if (boundp 'nnir-namazu-index-directory)
86       (symbol-value 'nnir-namazu-index-directory)
87     (expand-file-name "namazu" gnus-directory))
88   "*Index directory of Namazu."
89   :type 'directory
90   :group 'gnus-namazu)
91
92 (defcustom gnus-namazu-command
93   (cond
94    ((boundp 'namazu-command)
95     (symbol-value 'namazu-command))
96    ((boundp 'nnir-namazu-program)
97     (symbol-value 'nnir-namazu-program))
98    (t "namazu"))
99   "*Name of the executable file of Namazu."
100   :group 'gnus-namazu
101   :type 'string)
102
103 (defcustom gnus-namazu-additional-arguments nil
104   "*Additional arguments of Namazu.
105 The options `-q', `-a', and `-l' are always used, very few other
106 options make any sense in this context."
107   :type '(repeat string)
108   :group 'gnus-namazu)
109
110 (defcustom gnus-namazu-field-keywords
111   '("date" "from" "newsgroups" "size" "subject" "summary" "to" "uri")
112   "*List of keywords to do field-search."
113   :type '(repeat string)
114   :group 'gnus-namazu)
115
116 (defcustom gnus-namazu-coding-system
117   (if (>= emacs-major-version 20) 'euc-japan '*euc-japan*)
118   "*Coding system for Namazu process."
119   :type 'coding-system
120   :group 'gnus-namazu)
121
122
123 (defmacro gnus-namazu/make-article (group number)
124   `(cons ,group ,number))
125 (defmacro gnus-namazu/article-group  (x) `(car ,x))
126 (defmacro gnus-namazu/article-number (x) `(cdr ,x))
127
128
129 (defun gnus-namazu/setup ()
130   (unless gnus-namazu-indexed-servers
131     (setq gnus-namazu-indexed-servers
132           (delq nil
133                 (mapcar (lambda (method)
134                           (when (memq (car method) '(nnml nnmh))
135                             method))
136                         (cons gnus-select-method
137                               gnus-secondary-select-methods)))))
138   (unless gnus-namazu-indexed-servers
139     (error "%s" "Can't find either nnml backend or nnmh backend"))
140   (unless (and (stringp gnus-namazu-index-directory)
141                (file-directory-p gnus-namazu-index-directory)
142                (file-readable-p
143                 (expand-file-name "NMZ.i" gnus-namazu-index-directory)))
144     (error "%s" "Can't find index.  Check `gnus-namazu-index-directory'")))
145
146
147 ;; To suppress byte-compile warning.
148 (eval-when-compile
149   (defvar nnml-directory)
150   (defvar nnmh-directory))
151
152 (defun gnus-namazu/server-directory (server)
153   "Return the top directory of articles in SERVER."
154   (and (memq (car server) '(nnml nnmh))
155        (nnoo-change-server (car server) (nth 1 server) (nthcdr 2 server))
156        (file-name-as-directory
157         (expand-file-name (if (eq 'nnml (car server))
158                               nnml-directory
159                             nnmh-directory)))))
160
161
162 ;;; Functions to call Namazu.
163 (defsubst gnus-namazu/call-namazu (query)
164   (let ((coding-system-for-read gnus-namazu-coding-system)
165         (coding-system-for-write gnus-namazu-coding-system)
166         (default-process-coding-system
167           (cons gnus-namazu-coding-system gnus-namazu-coding-system))
168         (process-environment
169          (copy-sequence process-environment)))
170     ;; Disable locale.
171     (dolist (env process-environment)
172       (when (string-match "\
173 \\`\\(L\\(ANG\\|C_\\(ALL\\|CTYPE\\|COLLATE\\|TIME\\|NUMERIC\\|MONETARY\\|MESSAGES\\)\\)\\)=" env)
174         (setenv (match-string 1 env) nil)))
175     (setenv "LANG" "C")
176     (apply 'call-process
177            `(,gnus-namazu-command
178              nil                        ; input from /dev/null
179              t                          ; output
180              nil                        ; don't redisplay
181              "-q"                       ; don't be verbose
182              "-a"                       ; show all matches
183              "-l"                       ; use list format
184              ,@gnus-namazu-additional-arguments
185              ,query
186              ,gnus-namazu-index-directory))))
187
188 (defun gnus-namazu/search (groups query)
189   (with-temp-buffer
190     (when (zerop (gnus-namazu/call-namazu query))
191       (let* ((articles)
192              (server-alist
193               (delq nil
194                     (let (dir)
195                       (mapcar
196                        (lambda (s)
197                          (when (setq dir (gnus-namazu/server-directory s))
198                            (cons (file-name-as-directory dir) s)))
199                        gnus-namazu-indexed-servers))))
200              (topdir-regexp
201               (regexp-opt (mapcar 'car server-alist) t)))
202         (goto-char (point-min))
203         (while (not (eobp))
204           (let (server group file)
205             (and (looking-at topdir-regexp)
206                  (setq server (cdr (assoc (match-string 1) server-alist))
207                        file (buffer-substring-no-properties
208                              (match-end 0) (point-at-eol)))
209                  (string-match "/\\([0-9]+\\)$" file)
210                  (progn
211                    (setq group (substring file 0 (match-beginning 0))
212                          file (match-string 1 file))
213                    (setq group
214                          (gnus-group-prefixed-name
215                           (nnheader-replace-chars-in-string group ?/ ?.)
216                           server))
217                    (when (or (not groups)
218                              (member group groups))
219                      (push (gnus-namazu/make-article
220                             group (string-to-number file))
221                            articles)))))
222           (forward-line 1))
223         (nreverse articles)))))
224
225
226 (defun gnus-namazu/get-target-groups ()
227   (cond
228    ((eq major-mode 'gnus-group-mode)
229     ;; In Group buffer.
230     (cond
231      (current-prefix-arg
232       (gnus-group-process-prefix current-prefix-arg))
233      (gnus-group-marked
234       (prog1 gnus-group-marked (gnus-group-unmark-all-groups)))))
235    ((eq major-mode 'gnus-summary-mode)
236     ;; In Summary buffer.
237     (if current-prefix-arg
238         (list (gnus-read-group "Group: "))
239       (if (and (gnus-ephemeral-group-p gnus-newsgroup-name)
240                (string-match "^nnvirtual:namazu-search" gnus-newsgroup-name))
241           (cadr (assq 'gnus-namazu-target-groups
242                       (gnus-info-method (gnus-get-info gnus-newsgroup-name))))
243         (list gnus-newsgroup-name))))))
244
245 (defun gnus-namazu/get-current-query ()
246   (and (eq major-mode 'gnus-summary-mode)
247        (gnus-ephemeral-group-p gnus-newsgroup-name)
248        (string-match "^nnvirtual:namazu-search" gnus-newsgroup-name)
249        (cadr (assq 'gnus-namazu-current-query
250                    (gnus-info-method (gnus-get-info gnus-newsgroup-name))))))
251
252 (defvar gnus-namazu/read-query-original-buffer nil)
253 (defvar gnus-namazu/read-query-prompt nil)
254 (defvar gnus-namazu/read-query-history nil)
255
256 (defun gnus-namazu/get-current-subject ()
257   (and gnus-namazu/read-query-original-buffer
258        (bufferp gnus-namazu/read-query-original-buffer)
259        (with-current-buffer gnus-namazu/read-query-original-buffer
260          (when (eq major-mode 'gnus-summary-mode)
261            (let ((s (gnus-summary-article-subject)))
262              ;; Remove typically prefixes of mailing lists.
263              (when (string-match
264                     "^\\(\\[[^]]*[0-9]+\\]\\|([^)]*[0-9]+)\\)\\s-*" s)
265                (setq s (substring s (match-end 0))))
266              (when (string-match
267                     "^\\(Re\\(\\^?\\([0-9]+\\|\\[[0-9]+\\]\\)\\)?:\\s-*\\)+" s)
268                (setq s (substring s (match-end 0))))
269              (when (string-match "\\s-*(\\(re\\|was\\)\\b" s)
270                (setq s (substring s 0 (match-beginning 0))))
271              s)))))
272
273 (defun gnus-namazu/get-current-from ()
274   (and gnus-namazu/read-query-original-buffer
275        (bufferp gnus-namazu/read-query-original-buffer)
276        (with-current-buffer gnus-namazu/read-query-original-buffer
277          (when (eq major-mode 'gnus-summary-mode)
278            (cadr (mail-extract-address-components
279                   (mail-header-from
280                    (gnus-summary-article-header))))))))
281
282 (defmacro gnus-namazu/minibuffer-prompt-end ()
283   (if (fboundp 'minibuffer-prompt-end)
284       '(minibuffer-prompt-end)
285     '(point-min)))
286
287 (defun gnus-namazu/message (string &rest arguments)
288   (let* ((s1 (concat
289               gnus-namazu/read-query-prompt
290               (buffer-substring (gnus-namazu/minibuffer-prompt-end)
291                                 (point-max))))
292          (s2 (apply (function format) string arguments))
293          (w (- (window-width)
294                (string-width s1)
295                (string-width s2)
296                1)))
297     (message (if (>= w 0)
298                  (concat s1 (make-string w ?\ ) s2)
299                s2))
300     (if (sit-for 0.3) (message s1))
301     s2))
302
303 (defun gnus-namazu/complete-query ()
304   (interactive)
305   (let ((pos (point)))
306     (cond
307      ((and (re-search-backward "\\+\\([a-z]*\\)" nil t)
308            (= pos (match-end 0)))
309       (let* ((partial (match-string 1))
310              (completions
311               (all-completions
312                partial
313                (mapcar 'list gnus-namazu-field-keywords))))
314         (cond
315          ((null completions)
316           (gnus-namazu/message "No completions of %s" partial))
317          ((= 1 (length completions))
318           (goto-char (match-beginning 1))
319           (delete-region (match-beginning 1) (match-end 1))
320           (insert (car completions) ":")
321           (setq pos (point))
322           (gnus-namazu/message "Completed"))
323          (t
324           (let ((x (try-completion partial (mapcar 'list completions))))
325             (if (string= x partial)
326                 (if (and (eq last-command
327                              'gnus-namazu/field-keyword-completion)
328                          completion-auto-help)
329                     (with-output-to-temp-buffer "*Completions*"
330                       (display-completion-list completions))
331                   (gnus-namazu/message "Sole completion"))
332               (goto-char (match-beginning 1))
333               (delete-region (match-beginning 1) (match-end 1))
334               (insert x)
335               (setq pos (point))))))))
336      ((and (looking-at "\\+subject:")
337            (= pos (match-end 0)))
338       (let ((s (gnus-namazu/get-current-subject)))
339         (when s
340           (goto-char pos)
341           (insert "\"" s "\"")
342           (setq pos (point)))))
343      ((and (looking-at "\\+from:")
344            (= pos (match-end 0)))
345       (let ((f (gnus-namazu/get-current-from)))
346         (when f
347           (goto-char pos)
348           (insert "\"" f "\"")
349           (setq pos (point))))))
350     (goto-char pos)))
351
352 (defvar gnus-namazu/read-query-map
353   (let ((keymap (copy-keymap minibuffer-local-map)))
354     (define-key keymap "\t" 'gnus-namazu/complete-query)
355     keymap))
356
357 (defun gnus-namazu/read-query (prompt &optional initial)
358   (let ((gnus-namazu/read-query-original-buffer (current-buffer))
359         (gnus-namazu/read-query-prompt prompt))
360     (unless initial
361       (when (setq initial (gnus-namazu/get-current-query))
362         (setq initial (cons initial 0))))
363     (read-from-minibuffer prompt initial gnus-namazu/read-query-map nil
364                           'gnus-namazu/read-query-history)))
365
366 (defun gnus-namazu/truncate-article-list (articles)
367   (let ((hit (length articles)))
368     (when (> hit gnus-large-newsgroup)
369       (let* ((cursor-in-echo-area nil)
370              (input
371               (when (> hit gnus-large-newsgroup)
372                 (read-from-minibuffer
373                  (format
374                   "Too many articles were retrieved.  How many articles (max %d): "
375                   hit)
376                  (cons (number-to-string gnus-large-newsgroup) 0)))))
377         (unless (string-match "^[ \t]*$" input)
378           (setcdr (nthcdr (min (1- (string-to-number input)) hit) articles)
379                   nil))))
380     articles))
381
382 (defun gnus-namazu-search (groups query)
383   "Search QUERY through GROUPS with Namazu,
384 and make a virtual group contains its results."
385   (interactive
386    (list
387     (gnus-namazu/get-target-groups)
388     (gnus-namazu/read-query "Enter Keyword: ")))
389   (gnus-namazu/setup)
390   (let ((articles (gnus-namazu/search groups query)))
391     (if articles
392         (let ((real-groups groups)
393               (vgroup
394                (apply 'format
395                       "nnvirtual:namazu-search?query=%s&groups=%s&id=%d%d%d"
396                       query
397                       (if groups (mapconcat 'identity groups ",") "ALL")
398                       (current-time))))
399           (gnus-namazu/truncate-article-list articles)
400           (unless real-groups
401             (dolist (a articles)
402               (add-to-list 'real-groups (gnus-namazu/article-group a))))
403           ;; Generate virtual group which includes all results.
404           (setq vgroup
405                 (gnus-group-read-ephemeral-group
406                  vgroup
407                  `(nnvirtual ,vgroup
408                              (nnvirtual-component-groups ,real-groups)
409                              (gnus-namazu-target-groups ,groups)
410                              (gnus-namazu-current-query ,query))
411                  t (cons (current-buffer) (current-window-configuration)) t))
412           ;; Generate new summary buffer which contains search results.
413           (gnus-group-read-group
414            t t vgroup
415            (sort (delq nil ;; Ad-hoc fix, to avoid wrong-type-argument error.
416                        (mapcar
417                         (lambda (a)
418                           (nnvirtual-reverse-map-article
419                            (gnus-namazu/article-group a)
420                            (gnus-namazu/article-number a)))
421                         articles))
422                  '<)))
423       (message "No entry."))))
424
425
426 (defun gnus-namazu-insinuate ()
427   (add-hook
428    'gnus-group-mode-hook
429    (lambda ()
430      (define-key gnus-group-mode-map "\C-c\C-n" 'gnus-namazu-search)))
431   (add-hook
432    'gnus-summary-mode-hook
433    (lambda ()
434      (define-key gnus-summary-mode-map "\C-c\C-n" 'gnus-namazu-search))))
435
436
437 (provide 'gnus-namazu)
438 ;; gnus-namazu.el ends here.