6230143069add72adaa18efb21dbba8ca0230ba5
[elisp/gnus.git-] / lisp / nnir.el
1 ;;; nnir.el --- search mail with various search engines
2 ;; Copyright (C) 1998 Kai Großjohann
3
4 ;; $Id: nnir.el,v 1.68 2001/05/26 23:34:07 grossjoh Exp $
5
6 ;; Author: Kai Großjohann <grossjohann@ls6.cs.uni-dortmund.de>
7 ;; Keywords: news, mail, searching, ir, glimpse, wais
8
9 ;; This file is not part of GNU Emacs.
10
11 ;; This is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; The most recent version of this can always be fetched from the
29 ;; following FTP site:
30 ;; ls6-ftp.cs.uni-dortmund.de:/pub/src/emacs
31
32 ;; This code is still in the development stage but I'd like other
33 ;; people to have a look at it.  Please do not hesitate to contact me
34 ;; with your ideas.
35
36 ;; What does it do?  Well, it allows you to index your mail using some
37 ;; search engine (freeWAIS-sf and Glimpse are currently supported),
38 ;; then type `G G' in the Group buffer and issue a query to the search
39 ;; engine.  You will then get a buffer which shows all articles
40 ;; matching the query, sorted by Retrieval Status Value (score).
41
42 ;; When looking at the retrieval result (in the Summary buffer) you
43 ;; can type `G T' (aka M-x gnus-summary-nnir-goto-thread RET) on an
44 ;; article.  You will be teleported into the group this article came
45 ;; from, showing the thread this article is part of.  (See below for
46 ;; restrictions.)
47
48 ;; The Lisp installation is simple: just put this file on your
49 ;; load-path, byte-compile it, and load it from ~/.gnus or something.
50 ;; This will install a new command `G G' in your Group buffer for
51 ;; searching your mail.  Note that you also need to configure a number
52 ;; of variables, as described below.
53
54 ;; Restrictions:
55 ;;
56 ;; * Currently, this expects that you use nnml or another
57 ;;   one-file-per-message backend.
58 ;; * It can only search one mail backend.
59 ;; * There are restrictions to the Glimpse setup.
60 ;; * There are restrictions to the Wais setup.
61 ;; * gnus-summary-nnir-goto-thread: Fetches whole group first, before
62 ;;   limiting to the right articles.  This is much too slow, of
63 ;;   course.  May issue a query for number of articles to fetch; you
64 ;;   must accept the default of all articles at this point or things
65 ;;   may break.
66
67 ;; The Lisp setup involves setting a few variables and setting up the
68 ;; search engine.  The first variable to set is `nnir-mail-backend'.
69 ;; For me, `gnus-secondary-select-methods' contains just one select
70 ;; method, and this is also what I put in `nnir-mail-backend'.  Type
71 ;; `C-h v nnir-mail-backend RET' for more information -- the variable
72 ;; documentation includes more details and a few examples.  The second
73 ;; variable to set is `nnir-search-engine'.  Choose one of the engines
74 ;; listed in `nnir-engines'.  (Actually `nnir-engines' is an alist,
75 ;; type `C-h v nnir-engines RET' for more information; this includes
76 ;; examples for setting `nnir-search-engine', too.)
77
78 ;; You must also set up a search engine.  I'll tell you about the two
79 ;; search engines currently supported:
80
81 ;; 1. freeWAIS-sf
82 ;;
83 ;; As always with freeWAIS-sf, you need a so-called `format file'.  I
84 ;; use the following file:
85 ;;
86 ;; ,-----
87 ;; | # Kai's format file for freeWAIS-sf for indexing mails.
88 ;; | # Each mail is in a file, much like the MH format.
89 ;; |
90 ;; | # Document separator should never match -- each file is a document.
91 ;; | record-sep: /^@this regex should never match@$/
92 ;; |
93 ;; | # Searchable fields specification.
94 ;; |
95 ;; | region: /^[sS]ubject:/ /^[sS]ubject: */
96 ;; |         subject "Subject header" stemming TEXT BOTH
97 ;; | end: /^[^ \t]/
98 ;; |
99 ;; | region: /^([tT][oO]|[cC][cC]):/ /^([tT][oO]|[cC][cC]): */
100 ;; |         to "To and Cc headers" SOUNDEX BOTH
101 ;; | end: /^[^ \t]/
102 ;; |
103 ;; | region: /^[fF][rR][oO][mM]:/ /^[fF][rR][oO][mM]: */
104 ;; |         from "From header" SOUNDEX BOTH
105 ;; | end: /^[^ \t]/
106 ;; |
107 ;; | region: /^$/
108 ;; |         stemming TEXT GLOBAL
109 ;; | end: /^@this regex should never match@$/
110 ;; `-----
111 ;;
112 ;; 1998-07-22: waisindex would dump core on me for large articles with
113 ;; the above settings.  I used /^$/ as the end regex for the global
114 ;; field.  That seemed to work okay.
115
116 ;; There is a Perl module called `WAIS.pm' which is available from
117 ;; CPAN as well as ls6-ftp.cs.uni-dortmund.de:/pub/wais/Perl.  This
118 ;; module comes with a nifty tool called `makedb', which I use for
119 ;; indexing.  Here's my `makedb.conf':
120 ;;
121 ;; ,-----
122 ;; | # Config file for makedb
123 ;; |
124 ;; | # Global options
125 ;; | waisindex = /usr/local/bin/waisindex
126 ;; | wais_opt  = -stem -t fields
127 ;; | # `-stem' option necessary when `stemming' is specified for the
128 ;; | # global field in the *.fmt file
129 ;; |
130 ;; | # Own variables
131 ;; | homedir = /home/kai
132 ;; |
133 ;; | # The mail database.
134 ;; | database        = mail
135 ;; | files           = `find $homedir/Mail -name \*[0-9] -print`
136 ;; | dbdir           = $homedir/.wais
137 ;; | limit           = 100
138 ;; `-----
139 ;;
140 ;; The Lisp setup involves the `nnir-wais-*' variables.  The most
141 ;; difficult to understand variable is probably
142 ;; `nnir-wais-remove-prefix'.  Here's what it does: the output of
143 ;; `waissearch' basically contains the file name and the (full)
144 ;; directory name.  As Gnus works with group names rather than
145 ;; directory names, the directory name is transformed into a group
146 ;; name as follows: first, a prefix is removed from the (full)
147 ;; directory name, then all `/' are replaced with `.'.  The variable
148 ;; `nnir-wais-remove-prefix' should contain a regex matching exactly
149 ;; this prefix.  It defaults to `$HOME/Mail/' (note the trailing
150 ;; slash).
151
152 ;; 2. Glimpse
153 ;;
154 ;; The code expects you to have one Glimpse index which contains all
155 ;; your mail files.  The Lisp setup involves setting the
156 ;; `nnir-glimpse-*' variables.  The most difficult to understand
157 ;; variable is probably `nnir-glimpse-remove-prefix', it corresponds
158 ;; to `nnir-wais-remove-prefix', see above.  The `nnir-glimpse-home'
159 ;; variable should be set to the value of the `-H' option which allows
160 ;; one to search this Glimpse index.  I have indexed my whole home
161 ;; directory with Glimpse, so I assume a default of `$HOME'.
162
163 ;; Developer information:
164
165 ;; I have tried to make the code expandable.  Basically, it is divided
166 ;; into two layers.  The upper layer is somewhat like the `nnvirtual'
167 ;; or `nnkiboze' backends: given a specification of what articles to
168 ;; show from another backend, it creates a group containing exactly
169 ;; those articles.  The lower layer issues a query to a search engine
170 ;; and produces such a specification of what articles to show from the
171 ;; other backend.
172
173 ;; The interface between the two layers consists of the single
174 ;; function `nnir-run-query', which just selects the appropriate
175 ;; function for the search engine one is using.  The input to
176 ;; `nnir-run-query' is a string, representing the query as input by
177 ;; the user.  The output of `nnir-run-query' is supposed to be a
178 ;; vector, each element of which should in turn be a three-element
179 ;; vector.  The first element should be group name of the article, the
180 ;; second element should be the article number, and the third element
181 ;; should be the Retrieval Status Value (RSV) as returned from the
182 ;; search engine.  An RSV is the score assigned to the document by the
183 ;; search engine.  For Boolean search engines like Glimpse, the RSV is
184 ;; always 1000 (or 1 or 100, or whatever you like).
185
186 ;; The sorting order of the articles in the summary buffer created by
187 ;; nnir is based on the order of the articles in the above mentioned
188 ;; vector, so that's where you can do the sorting you'd like.  Maybe
189 ;; it would be nice to have a way of displaying the search result
190 ;; sorted differently?
191
192 ;; So what do you need to do when you want to add another search
193 ;; engine?  You write a function that executes the query.  Temporary
194 ;; data from the search engine can be put in `nnir-tmp-buffer'.  This
195 ;; function should return the list of articles as a vector, as
196 ;; described above.  Then, you need to register this backend in
197 ;; `nnir-engines'.  Then, users can choose the backend by setting
198 ;; `nnir-search-engine'.
199
200 ;; Todo, or future ideas:
201
202 ;; * Make it so that Glimpse can also be called without `-F'.
203 ;;
204 ;; * It should be possible to restrict search to certain groups.
205 ;;
206 ;; * There is currently no error checking.
207 ;;
208 ;; * The summary buffer display is currently really ugly, with all the
209 ;;   added information in the subjects.  How could I make this
210 ;;   prettier?
211 ;;
212 ;; * A function which can be called from an nnir summary buffer which
213 ;;   teleports you into the group the current article came from and
214 ;;   shows you the whole thread this article is part of.
215 ;;   Implementation suggestions?
216 ;;   (1998-07-24: There is now a preliminary implementation, but
217 ;;   it is much too slow and quite fragile.)
218 ;;
219 ;; * Support other mail backends.  In particular, probably quite a few
220 ;;   people use nnfolder.  How would one go about searching nnfolders
221 ;;   and producing the right data needed?  The group name and the RSV
222 ;;   are simple, but what about the article number?
223 ;;
224 ;; * Support compressed mail files.  Probably, just stripping off the
225 ;;   `.gz' or `.Z' file name extension is sufficient.
226 ;;
227 ;; * Support a find/grep combination.
228 ;;
229 ;; * At least for imap, the query is performed twice.
230 ;;
231 ;; * Support multiple mail backends.  The information that is needed
232 ;;   by nnir could be put in the server parameters.  (Use sensible
233 ;;   default values, though: include the name of the backend in the
234 ;;   default value such that people do not have to mess with the
235 ;;   server parameters if they don't want to.)  It is not clear how to
236 ;;   do the user interface, though.  Hm.  Maybe offer the user a
237 ;;   completable list of backends to search?  Or use the
238 ;;   process-marked groups to find out which backends to search?  Or
239 ;;   always search all backends?
240 ;;
241
242 ;; Have you got other ideas?
243
244 ;;; Setup Code:
245
246 (defconst nnir-version "$Id: nnir.el,v 1.68 2001/05/26 23:34:07 grossjoh Exp $"
247   "Version of NNIR.")
248
249 (require 'cl)
250 (require 'nnoo)
251 (require 'gnus-group)
252 (require 'gnus-sum)
253 (eval-and-compile
254   (require 'gnus-util))
255
256 (nnoo-declare nnir)
257 (nnoo-define-basics nnir)
258
259 (gnus-declare-backend "nnir" 'mail)
260
261 ;;; Developer Extension Variable:
262
263 (defvar nnir-engines
264   '((glimpse nnir-run-glimpse
265              ((group . "Group spec: ")))
266     (wais    nnir-run-waissearch
267              ())
268     (excite  nnir-run-excite-search
269              ())
270     (imap    nnir-run-imap
271              ())
272     (swish++ nnir-run-swish++
273              ((group . "Group spec: ")))
274     (swish-e nnir-run-swish-e
275              ((group . "Group spec: "))))
276 "Alist of supported search engines.
277 Each element in the alist is a three-element list (ENGINE FUNCTION ARGS).
278 ENGINE is a symbol designating the searching engine.  FUNCTION is also
279 a symbol, giving the function that does the search.  The third element
280 ARGS is a list of cons pairs (PARAM . PROMPT).  When issuing a query,
281 the FUNCTION will issue a query for each of the PARAMs, using PROMPT.
282
283 The value of `nnir-search-engine' must be one of the ENGINE symbols.
284 For example, use the following line for searching using freeWAIS-sf:
285     (setq nnir-search-engine 'wais)
286 Use the following line if you read your mail via IMAP and your IMAP
287 server supports searching:
288     (setq nnir-search-engine 'imap)
289 Note that you have to set additional variables for most backends.  For
290 example, the `wais' backend needs the variables `nnir-wais-program',
291 `nnir-wais-database' and `nnir-wais-remove-prefix'.
292
293 Add an entry here when adding a new search engine.")
294
295 ;;; User Customizable Variables:
296
297 (defgroup nnir nil
298   "Search nnmh and nnml groups in Gnus with Glimpse, freeWAIS-sf, or EWS.")
299
300 ;; Mail backend.
301
302 ;; TODO:
303 ;; If `nil', use server parameters to find out which server to search. CCC
304 ;;
305 (defcustom nnir-mail-backend '(nnml "")
306   "*Specifies which backend should be searched.
307 More precisely, this is used to determine from which backend to fetch the
308 messages found.
309
310 This must be equal to an existing server, so maybe it is best to use
311 something like the following:
312     (setq nnir-mail-backend (nth 0 gnus-secondary-select-methods))
313 The above line works fine if the mail backend you want to search is
314 the first element of gnus-secondary-select-methods (`nth' starts counting
315 at zero)."
316   :type '(sexp)
317   :group 'nnir)
318
319 ;; Search engine to use.
320
321 (defcustom nnir-search-engine 'wais
322   "*The search engine to use.  Must be a symbol.
323 See `nnir-engines' for a list of supported engines, and for example
324 settings of `nnir-search-engine'."
325   :type '(sexp)
326   :group 'nnir)
327
328 ;; Glimpse engine.
329
330 (defcustom nnir-glimpse-program "glimpse"
331   "*Name of Glimpse executable."
332   :type '(string)
333   :group 'nnir)
334
335 (defcustom nnir-glimpse-home (getenv "HOME")
336   "*Value of `-H' glimpse option.
337 `~' and environment variables must be expanded, see the functions
338 `expand-file-name' and `substitute-in-file-name'."
339   :type '(directory)
340   :group 'nnir)
341
342 (defcustom nnir-glimpse-remove-prefix (concat (getenv "HOME") "/Mail/")
343   "*The prefix to remove from each file name returned by Glimpse
344 in order to get a group name (albeit with / instead of .).
345
346 For example, suppose that Glimpse returns file names such as
347 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
348 setting:  (setq nnir-glimpse-remove-prefix \"/home/john/Mail/\")
349 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
350 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
351 arrive at the correct group name, \"mail.misc\"."
352   :type '(directory)
353   :group 'nnir)
354
355 (defcustom nnir-glimpse-additional-switches '("-i")
356   "*A list of strings, to be given as additional arguments to glimpse.
357 The switches `-H', `-W', `-l' and `-y' are always used -- calling
358 glimpse without them does not make sense in our situation.
359 Suggested elements to put here are `-i' and `-w'.
360
361 Note that this should be a list.  Ie, do NOT use the following:
362     (setq nnir-glimpse-additional-switches \"-i -w\") ; wrong!
363 Instead, use this:
364     (setq nnir-glimpse-additional-switches '(\"-i\" \"-w\"))"
365   :type '(repeat (string))
366   :group 'nnir)
367
368 ;; freeWAIS-sf.
369
370 (defcustom nnir-wais-program "waissearch"
371   "*Name of waissearch executable."
372   :type '(string)
373   :group 'nnir)
374
375 (defcustom nnir-wais-database (expand-file-name "~/.wais/mail")
376   "*Name of Wais database containing the mail.
377
378 Note that this should be a file name without extension.  For example,
379 if you have a file /home/john/.wais/mail.fmt, use this:
380     (setq nnir-wais-database \"/home/john/.wais/mail\")
381 The string given here is passed to `waissearch -d' as-is."
382   :type '(file)
383   :group 'nnir)
384
385 (defcustom nnir-wais-remove-prefix (concat (getenv "HOME") "/Mail/")
386   "*The prefix to remove from each directory name returned by waissearch
387 in order to get a group name (albeit with / instead of .).
388
389 This variable is similar to `nnir-glimpse-remove-prefix', only for Wais,
390 not Glimpse."
391   :type '(directory)
392   :group 'nnir)
393
394 ;; EWS (Excite for Web Servers) engine.
395
396 (defcustom nnir-excite-aquery-program "aquery.pl"
397   "*Name of the EWS query program.  Should be `aquery.pl' or a path to same."
398   :type '(string)
399   :group 'nnir)
400
401 (defcustom nnir-excite-collection "Mail"
402   "*Name of the EWS collection to search."
403   :type '(string)
404   :group 'nnir)
405
406 (defcustom nnir-excite-remove-prefix (concat (getenv "HOME") "/Mail/")
407   "*The prefix to remove from each file name returned by EWS
408 in order to get a group name (albeit with / instead of .).
409
410 This variable is very similar to `nnir-glimpse-remove-prefix', except
411 that it is for EWS, not Glimpse."
412   :type '(directory)
413   :group 'nnir)
414
415 ;; Swish++.  Next three variables Copyright (C) 2000, 2001 Christoph
416 ;; Conrad <christoph.conrad@gmx.de>.
417 ;; Swish++ home page: http://homepage.mac.com/pauljlucas/software/swish/
418
419 (defcustom nnir-swish++-configuration-file
420   (expand-file-name "~/Mail/swish++.conf")
421   "*Configuration file for swish++."
422   :type '(file)
423   :group 'nnir)
424
425 (defcustom nnir-swish++-program "search"
426   "*Name of swish++ search executable."
427   :type '(string)
428   :group 'nnir)
429
430 (defcustom nnir-swish++-additional-switches '()
431     "*A list of strings, to be given as additional arguments to swish++.
432
433 Note that this should be a list.  Ie, do NOT use the following:
434     (setq nnir-swish++-additional-switches \"-i -w\") ; wrong
435 Instead, use this:
436     (setq nnir-swish++-additional-switches '(\"-i\" \"-w\"))"
437   :type '(repeat (string))
438   :group 'nnir)
439
440 (defcustom nnir-swish++-remove-prefix (concat (getenv "HOME") "/Mail/")
441   "*The prefix to remove from each file name returned by swish++
442 in order to get a group name (albeit with / instead of .).
443
444 This variable is very similar to `nnir-glimpse-remove-prefix', except
445 that it is for swish++, not Glimpse."
446   :type '(directory)
447   :group 'nnir)
448
449 ;; Swish-E.  Next three variables Copyright (C) 2000 Christoph Conrad
450 ;; <christoph.conrad@gmx.de>.
451 ;; URL: http://sunsite.berkeley.edu/SWISH-E/
452 ;; New version: http://www.boe.es/swish-e
453
454 (defcustom nnir-swish-e-index-file
455   (expand-file-name "~/Mail/index.swish-e")
456   "*Index file for swish-e."
457   :type '(file)
458   :group 'nnir)
459
460 (defcustom nnir-swish-e-program "swish-e"
461   "*Name of swish-e search executable."
462   :type '(string)
463   :group 'nnir)
464
465 (defcustom nnir-swish-e-additional-switches '()
466   "*A list of strings, to be given as additional arguments to swish-e.
467
468 Note that this should be a list.  Ie, do NOT use the following:
469     (setq nnir-swish-e-additional-switches \"-i -w\") ; wrong
470 Instead, use this:
471     (setq nnir-swish-e-additional-switches '(\"-i\" \"-w\"))"
472   :type '(repeat (string))
473   :group 'nnir)
474
475 (defcustom nnir-swish-e-remove-prefix (concat (getenv "HOME") "/Mail/")
476   "*The prefix to remove from each file name returned by swish-e
477 in order to get a group name (albeit with / instead of .).
478
479 This variable is very similar to `nnir-glimpse-remove-prefix', except
480 that it is for swish-e, not Glimpse."
481   :type '(directory)
482   :group 'nnir)
483
484 ;;; Internal Variables:
485
486 (defvar nnir-current-query nil
487   "Internal: stores current query (= group name).")
488
489 (defvar nnir-current-server nil
490   "Internal: stores current server (does it ever change?).")
491
492 (defvar nnir-current-group-marked nil
493   "Internal: stores current list of process-marked groups.")
494
495 (defvar nnir-artlist nil
496   "Internal: stores search result.")
497
498 (defvar nnir-tmp-buffer " *nnir*"
499   "Internal: temporary buffer.")
500
501 ;;; Code:
502
503 ;; Gnus glue.
504
505 (defun gnus-group-make-nnir-group (extra-parms query)
506   "Create an nnir group.  Asks for query."
507   (interactive "P\nsQuery: ")
508   (let ((parms nil))
509     (if extra-parms
510         (setq parms (nnir-read-parms query))
511       (setq parms (list (cons 'query query))))
512     (gnus-group-read-ephemeral-group
513      (concat "nnir:" (prin1-to-string parms)) '(nnir "") t
514      (cons (current-buffer)
515            gnus-current-window-configuration)
516      nil)))
517
518 ;; Emacs 19 compatibility?
519 (or (fboundp 'kbd) (defalias 'kbd 'read-kbd-macro))
520
521 (defun nnir-group-mode-hook ()
522   (define-key gnus-group-mode-map
523     (if (fboundp 'read-kbd-macro)
524         (kbd "G G")
525       "GG")                             ; XEmacs 19 compat
526     'gnus-group-make-nnir-group))
527 (add-hook 'gnus-group-mode-hook 'nnir-group-mode-hook)
528
529
530
531 ;; Summary mode commands.
532
533 (defun gnus-summary-nnir-goto-thread ()
534   "Only applies to nnir groups.  Go to group this article came from
535 and show thread that contains this article."
536   (interactive)
537   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
538     (error "Can't execute this command unless in nnir group."))
539   (let* ((cur (gnus-summary-article-number))
540          (backend-group (nnir-artlist-artitem-group nnir-artlist cur))
541          (backend-number (nnir-artlist-artitem-number nnir-artlist cur)))
542     (gnus-group-read-ephemeral-group
543      backend-group
544      nnir-mail-backend
545      t                                  ; activate
546      (cons (current-buffer)
547            'summary)                    ; window config
548      nil
549      (list backend-number))
550     (gnus-summary-limit (list backend-number))
551     (gnus-summary-refer-thread)))
552
553 (if (fboundp 'eval-after-load)
554     (eval-after-load "gnus-sum"
555       '(define-key gnus-summary-goto-map
556          "T" 'gnus-summary-nnir-goto-thread))
557   (add-hook 'gnus-summary-mode-hook
558             (function (lambda ()
559                         (define-key gnus-summary-goto-map
560                           "T" 'gnus-summary-nnir-goto-thread)))))
561
562
563
564 ;; Gnus backend interface functions.
565
566 (deffoo nnir-open-server (server &optional definitions)
567   ;; Just set the server variables appropriately.
568   (nnoo-change-server 'nnir server definitions))
569
570 (deffoo nnir-request-group (group &optional server fast)
571   "GROUP is the query string."
572   (nnir-possibly-change-server server)
573   ;; Check for cache and return that if appropriate.
574   (if (and (equal group nnir-current-query)
575            (equal gnus-group-marked nnir-current-group-marked)
576            (or (null server)
577                (equal server nnir-current-server)))
578       nnir-artlist
579     ;; Cache miss.
580     (setq nnir-artlist (nnir-run-query group))
581     (save-excursion
582       (set-buffer nntp-server-buffer)
583       (if (zerop (length nnir-artlist))
584           (progn
585             (setq nnir-current-query nil
586                   nnir-current-server nil
587                   nnir-current-group-marked nil
588                   nnir-artlist nil)
589             (nnheader-report 'nnir "Search produced empty results."))
590         ;; Remember data for cache.
591         (setq nnir-current-query group)
592         (when server (setq nnir-current-server server))
593         (setq nnir-current-group-marked gnus-group-marked)
594         (nnheader-insert "211 %d %d %d %s\n"
595                          (nnir-artlist-length nnir-artlist) ; total #
596                          1              ; first #
597                          (nnir-artlist-length nnir-artlist) ; last #
598                          group)))))     ; group name
599
600 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
601   (save-excursion
602     (let ((artlist (copy-sequence articles))
603           (idx 1)
604           (art nil)
605           (artitem nil)
606           (artgroup nil) (artno nil)
607           (artrsv nil)
608           (artfullgroup nil)
609           (novitem nil)
610           (novdata nil)
611           (foo nil))
612       (while (not (null artlist))
613         (setq art (car artlist))
614         (or (numberp art)
615             (nnheader-report
616              "nnir-retrieve-headers doesn't grok message ids: %s"
617              art))
618         (setq artitem (nnir-artlist-article nnir-artlist art))
619         (setq artrsv (nnir-artitem-rsv artitem))
620         (setq artgroup (nnir-artitem-group artitem))
621         (setq artno (nnir-artitem-number artitem))
622         (setq artfullgroup (nnir-group-full-name artgroup))
623         ;; retrieve NOV or HEAD data for this article, transform into
624         ;; NOV data and prepend to `novdata'
625         (set-buffer nntp-server-buffer)
626         (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
627           (nov
628            (goto-char (point-min))
629            (setq novitem (nnheader-parse-nov))
630            (unless novitem
631              (pop-to-buffer nntp-server-buffer)
632              (error
633               "nnheader-parse-nov returned nil for article %s in group %s"
634               artno artfullgroup)))
635           (headers
636            (goto-char (point-min))
637            (setq novitem (nnheader-parse-head))
638            (unless novitem
639              (pop-to-buffer nntp-server-buffer)
640              (error
641               "nnheader-parse-head returned nil for article %s in group %s"
642               artno artfullgroup)))
643           (t (nnheader-report "Don't support header type %s." foo)))
644         ;; replace article number in original group with article number
645         ;; in nnir group
646         (mail-header-set-number novitem idx)
647         (mail-header-set-from novitem
648                               (mail-header-from novitem))
649         (mail-header-set-subject
650          novitem
651          (format "[%d: %s/%d] %s"
652                  artrsv artgroup artno
653                  (mail-header-subject novitem)))
654         ;;-(mail-header-set-extra novitem nil)
655         (push novitem novdata)
656         (setq artlist (cdr artlist))
657         (setq idx (1+ idx)))
658       (setq novdata (nreverse novdata))
659       (set-buffer nntp-server-buffer) (erase-buffer)
660       (mapcar 'nnheader-insert-nov novdata)
661       'nov)))
662
663 (deffoo nnir-request-article (article
664                               &optional group server to-buffer)
665   (save-excursion
666     (let* ((artitem (nnir-artlist-article nnir-artlist
667                                           article))
668            (artgroup (nnir-artitem-group artitem))
669            (artno (nnir-artitem-number artitem))
670            ;; Bug?
671            ;; Why must we bind nntp-server-buffer here?  It won't
672            ;; work if `buf' is used, say.  (Of course, the set-buffer
673            ;; line below must then be updated, too.)
674            (nntp-server-buffer (or to-buffer nntp-server-buffer)))
675       (set-buffer nntp-server-buffer)
676       (erase-buffer)
677       (message "Requesting article %d from group %s"
678                artno
679                (nnir-group-full-name artgroup))
680       (gnus-request-article artno (nnir-group-full-name artgroup)
681                             nntp-server-buffer)
682       (cons artgroup artno))))
683
684
685 (nnoo-define-skeleton nnir)
686
687 ;;; Search Engine Interfaces:
688
689 ;; Glimpse interface.
690 (defun nnir-run-glimpse (query &optional group)
691   "Run given query against glimpse.  Returns a vector of (group name, file name)
692 pairs (also vectors, actually)."
693   (save-excursion
694     (let ((artlist nil)
695           (groupspec (cdr (assq 'group query)))
696           (qstring (cdr (assq 'query query))))
697       (when (and group groupspec)
698         (error (concat "It does not make sense to use a group spec"
699                        " with process-marked groups.")))
700       (when group
701         (setq groupspec (gnus-group-real-name group)))
702       (set-buffer (get-buffer-create nnir-tmp-buffer))
703       (erase-buffer)
704       (if groupspec
705           (message "Doing glimpse query %s on %s..." query groupspec)
706         (message "Doing glimpse query %s..." query))
707       (let* ((cp-list
708               `( ,nnir-glimpse-program
709                  nil                    ; input from /dev/null
710                  t                      ; output
711                  nil                    ; don't redisplay
712                  "-H" ,nnir-glimpse-home ; search home dir
713                  "-W"                   ; match pattern in file
714                  "-l" "-y"              ; misc options
715                  ,@nnir-glimpse-additional-switches
716                  "-F" ,nnir-glimpse-remove-prefix ; restrict output to mail
717                  ,qstring               ; the query, in glimpse format
718                 ))
719              (exitstatus
720               (progn
721                 (message "%s args: %s" nnir-glimpse-program
722                          (mapconcat 'identity (cddddr cp-list) " "))
723                 (apply 'call-process cp-list))))
724         (unless (or (null exitstatus)
725                     (zerop exitstatus))
726           (nnheader-report "Couldn't run glimpse: %s" exitstatus)
727           ;; Glimpse failure reason is in this buffer, show it if
728           ;; the user wants it.
729           (when (> gnus-verbose 6)
730             (display-buffer nnir-tmp-buffer))))
731       (when groupspec
732         (keep-lines groupspec))
733       (if groupspec
734           (message "Doing glimpse query %s on %s...done" query groupspec)
735         (message "Doing glimpse query %s...done" query))
736       (sit-for 0)
737       ;; CCC: The following work of extracting group name and article
738       ;; number from the Glimpse output can probably better be done by
739       ;; just going through the buffer once, and plucking out the
740       ;; right information from each line.
741       ;; remove superfluous stuff from glimpse output
742       (goto-char (point-min))
743       (delete-non-matching-lines "/[0-9]+$")
744       ;;(delete-matching-lines "\\.overview~?$")
745       (goto-char (point-min))
746       (while (re-search-forward (concat "^" nnir-glimpse-remove-prefix) nil t)
747         (replace-match ""))
748       ;; separate group name from article number with \t
749       ;; XEmacs compatible version
750       (goto-char (point-max))
751       (while (re-search-backward "/[0-9]+$" nil t)
752         (delete-char 1 nil)
753         (insert-char ?\t 1))
754 ; Emacs compatible version
755 ;      (goto-char (point-min))
756 ;      (while (re-search-forward "\\(/\\)[0-9]+$" nil t)
757 ;        (replace-match "\t" t t nil 1))
758       ;; replace / with . in group names
759       (subst-char-in-region (point-min) (point-max) ?/ ?. t)
760       ;; massage buffer to contain some Lisp;
761       ;; this depends on the artlist encoding internals
762       ;; maybe this dependency should be removed?
763       (goto-char (point-min))
764       (while (not (eobp))
765         (insert "[\"")
766         (skip-chars-forward "^\t")
767         (insert "\" ")
768         (end-of-line)
769         (insert " 1000 ]")              ; 1000 = score
770         (forward-line 1))
771       (insert "])\n")
772       (goto-char (point-min))
773       (insert "(setq artlist [\n")
774       (eval-buffer)
775       (sort* artlist
776              (function (lambda (x y)
777                          (if (string-lessp (nnir-artitem-group x)
778                                            (nnir-artitem-group y))
779                              t
780                            (< (nnir-artitem-number x)
781                               (nnir-artitem-number y))))))
782       )))
783
784 ;; freeWAIS-sf interface.
785 (defun nnir-run-waissearch (query &optional group)
786   "Run given query agains waissearch.  Returns vector of (group name, file name)
787 pairs (also vectors, actually)."
788   (when group
789     (error "The freeWAIS-sf backend cannot search specific groups."))
790   (save-excursion
791     (let ((qstring (cdr (assq 'query query)))
792           (artlist nil)
793           (score nil) (artno nil) (dirnam nil) (group nil))
794       (set-buffer (get-buffer-create nnir-tmp-buffer))
795       (erase-buffer)
796       (message "Doing WAIS query %s..." query)
797       (call-process nnir-wais-program
798                     nil                 ; input from /dev/null
799                     t                   ; output to current buffer
800                     nil                 ; don't redisplay
801                     "-d" nnir-wais-database ; database to search
802                     qstring)
803       (message "Massaging waissearch output...")
804       ;; remove superfluous lines
805       (keep-lines "Score:")
806       ;; extract data from result lines
807       (goto-char (point-min))
808       (while (re-search-forward
809               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
810         (setq score (match-string 1)
811               artno (match-string 2)
812               dirnam (match-string 3))
813         (unless (string-match nnir-wais-remove-prefix dirnam)
814           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
815                            dirnam nnir-wais-remove-prefix))
816         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
817         (push (vector group
818                       (string-to-int artno)
819                       (string-to-int score))
820               artlist))
821       (message "Massaging waissearch output...done")
822       (apply 'vector
823              (sort* artlist
824                     (function (lambda (x y)
825                                 (> (nnir-artitem-rsv x)
826                                    (nnir-artitem-rsv y)))))))))
827
828 ;; EWS (Excite for Web Servers) interface
829 (defun nnir-run-excite-search (query &optional group)
830   "Run a given query against EWS.  Returns vector of (group name, file name)
831 pairs (also vectors, actually)."
832   (when group
833     (error "Searching specific groups not implemented for EWS."))
834   (save-excursion
835     (let ((qstring (cdr (assq 'query query)))
836           artlist group article-num article)
837       (setq nnir-current-query query)
838       (set-buffer (get-buffer-create nnir-tmp-buffer))
839       (erase-buffer)
840       (message "Doing EWS query %s..." qstring)
841       (call-process nnir-excite-aquery-program
842                     nil                 ; input from /dev/null
843                     t                   ; output to current buffer
844                     nil                 ; don't redisplay
845                     nnir-excite-collection
846                     (if (string= (substring qstring 0 1) "(")
847                         qstring
848                       (format "(concept %s)" qstring)))
849       (message "Gathering query output...")
850
851       (goto-char (point-min))
852       (while (re-search-forward
853               "^[0-9]+\\s-[0-9]+\\s-[0-9]+\\s-\\(\\S-*\\)" nil t)
854         (setq article (match-string 1))
855         (unless (string-match
856                  (concat "^" (regexp-quote nnir-excite-remove-prefix)
857                          "\\(.*\\)/\\([0-9]+\\)") article)
858           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
859                            article nnir-excite-remove-prefix))
860         (setq group (substitute ?. ?/ (match-string 1 article)))
861         (setq article-num (match-string 2 article))
862         (setq artlist (vconcat artlist (vector (vector group
863                                                        (string-to-int article-num)
864                                                        1000)))))
865       (message "Gathering query output...done")
866       artlist)))
867
868 ;; IMAP interface.  The following function is Copyright (C) 1998 Simon
869 ;; Josefsson <jas@pdc.kth.se>.
870 ;; todo:
871 ;; nnir invokes this two (2) times???!
872 ;; we should not use nnimap at all but open our own server connection
873 ;; we should not LIST * but use nnimap-list-pattern from defs
874 ;; send queries as literals
875 ;; handle errors
876
877 (defun nnir-run-imap (query &optional group)
878   (require 'imap)
879   (require 'nnimap)
880   (unless group
881     (error "Must specify groups for IMAP searching."))
882   (save-excursion
883     (let ((qstring (cdr (assq 'query query)))
884           (server (cadr nnir-mail-backend))
885           (defs (caddr nnir-mail-backend))
886           artlist buf)
887       (message "Opening server %s" server)
888       (condition-case ()
889           (when (nnimap-open-server server defs) ;; xxx
890             (setq buf nnimap-server-buffer) ;; xxx
891             (message "Searching %s..." group)
892             (let ((arts 0)
893                   (mbx (gnus-group-real-name group)))
894               (when (imap-mailbox-select mbx nil buf)
895                 (mapcar
896                  (lambda (artnum)
897                    (push (vector mbx artnum 1) artlist)
898                    (setq arts (1+ arts)))
899                  (imap-search (concat "TEXT \"" qstring "\"") buf))
900                 (message "Searching %s... %d matches" mbx arts)))
901             (message "Searching %s...done" group))
902         (quit nil))
903       (reverse artlist))))
904
905 ;; Swish++ interface.  The following function is Copyright (C) 2000,
906 ;; 2001 Christoph Conrad <christoph.conrad@gmx.de>.
907 ;; -cc- Todo
908 ;; Search by
909 ;; - group
910 ;; Sort by
911 ;; - rank (default)
912 ;; - article number
913 ;; - file size
914 ;; - group
915 (defun nnir-run-swish++ (query &optional group)
916   "Run given query against swish++.
917 Returns a vector of (group name, file name) pairs (also vectors,
918 actually).
919
920 Tested with swish++ 4.7 on GNU/Linux and with with swish++ 5.0b2 on
921 Windows NT 4.0."
922
923   (when group
924     (error "The swish++ backend cannot search specific groups."))
925
926   (save-excursion
927     (let ( (qstring (cdr (assq 'query query)))
928            (artlist nil)
929            (score nil) (artno nil) (dirnam nil) (group nil) )
930
931       (when (equal "" qstring)
932         (error "swish++: You didn't enter anything."))
933
934       (set-buffer (get-buffer-create nnir-tmp-buffer))
935       (erase-buffer)
936
937       (message "Doing swish++ query %s..." query)
938       (let* ((cp-list `( ,nnir-swish++-program
939                          nil            ; input from /dev/null
940                          t              ; output
941                          nil            ; don't redisplay
942                          "--config-file" ,nnir-swish++-configuration-file
943                          ,@nnir-swish++-additional-switches
944                          ,qstring       ; the query, in swish++ format
945                          ))
946              (exitstatus
947               (progn
948                 (message "%s args: %s" nnir-swish++-program
949                          (mapconcat 'identity (cddddr cp-list) " "));; ???
950                 (apply 'call-process cp-list))))
951         (unless (or (null exitstatus)
952                     (zerop exitstatus))
953           (nnheader-report "Couldn't run swish++: %s" exitstatus)
954           ;; swish++ failure reason is in this buffer, show it if
955           ;; the user wants it.
956           (when (> gnus-verbose 6)
957             (display-buffer nnir-tmp-buffer))))
958
959       ;; The results are output in the format of:
960       ;; V 4.7 Linux
961       ;; rank relative-path-name file-size file-title
962       ;; V 5.0b2:
963       ;; rank relative-path-name file-size topic??
964       ;; where rank is an integer from from 1 to 100.
965       (goto-char (point-min))
966       (while (re-search-forward
967               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
968         (setq score (match-string 1)
969               artno (file-name-nondirectory (match-string 2))
970               dirnam (file-name-directory (match-string 2)))
971
972         ;; don't match directories
973         (when (string-match "^[0-9]+$" artno)
974           (when (not (null dirnam))
975
976             ;; remove nnir-swish++-remove-prefix from beginning of dirname
977             (when (string-match (concat "^" nnir-swish++-remove-prefix)
978                                 dirnam)
979               (setq dirnam (replace-match "" t t dirnam)))
980
981             (setq dirnam (substring dirnam 0 -1))
982             ;; eliminate all ".", "/", "\" from beginning. Always matches.
983             (string-match "^[./\\]*\\(.*\\)$" dirnam)
984             ;; "/" -> "."
985             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
986             ;; "\\" -> "."
987             (setq group (substitute ?. ?\\ group))
988
989             (push (vector group
990                           (string-to-int artno)
991                           (string-to-int score))
992                   artlist))))
993
994       (message "Massaging swish++ output...done")
995
996       ;; Sort by score
997       (apply 'vector
998              (sort* artlist
999                     (function (lambda (x y)
1000                                 (> (nnir-artitem-rsv x)
1001                                    (nnir-artitem-rsv y)))))))))
1002
1003 ;; Swish-E interface.  The following function is Copyright (C) 2000,
1004 ;; 2001 by Christoph Conrad <christoph.conrad@gmx.de>.
1005 (defun nnir-run-swish-e (query &optional group)
1006   "Run given query against swish-e.
1007 Returns a vector of (group name, file name) pairs (also vectors,
1008 actually).
1009
1010 Tested with swish-e-2.0.1 on Windows NT 4.0."
1011
1012   ;; swish-e crashes with empty parameter to "-w" on commandline...
1013   (when group
1014     (error "The swish-e backend cannot search specific groups."))
1015
1016   (save-excursion
1017     (let ( (qstring (cdr (assq 'query query)))
1018            (artlist nil)
1019            (score nil) (artno nil) (dirnam nil) (group nil) )
1020
1021       (when (equal "" qstring)
1022         (error "swish-e: You didn't enter anything."))
1023
1024       (set-buffer (get-buffer-create nnir-tmp-buffer))
1025       (erase-buffer)
1026
1027       (message "Doing swish-e query %s..." query)
1028       (let* ((cp-list `( ,nnir-swish-e-program
1029                          nil            ; input from /dev/null
1030                          t              ; output
1031                          nil            ; don't redisplay
1032                          "-f" ,nnir-swish-e-index-file
1033                          ,@nnir-swish-e-additional-switches
1034                          "-w"
1035                          ,qstring       ; the query, in swish-e format
1036                          ))
1037              (exitstatus
1038               (progn
1039                 (message "%s args: %s" nnir-swish-e-program
1040                          (mapconcat 'identity (cddddr cp-list) " "))
1041                 (apply 'call-process cp-list))))
1042         (unless (or (null exitstatus)
1043                     (zerop exitstatus))
1044           (nnheader-report "Couldn't run swish-e: %s" exitstatus)
1045           ;; swish-e failure reason is in this buffer, show it if
1046           ;; the user wants it.
1047           (when (> gnus-verbose 6)
1048             (display-buffer nnir-tmp-buffer))))
1049
1050       ;; The results are output in the format of:
1051       ;; rank path-name file-title file-size
1052       (goto-char (point-min))
1053       (while (re-search-forward
1054               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1055         (setq score (match-string 1)
1056               artno (match-string 3)
1057               dirnam (file-name-directory (match-string 2)))
1058
1059         ;; don't match directories
1060         (when (string-match "^[0-9]+$" artno)
1061           (when (not (null dirnam))
1062
1063             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1064             (when (string-match (concat "^" nnir-swish-e-remove-prefix)
1065                                 dirnam)
1066               (setq dirnam (replace-match "" t t dirnam)))
1067
1068             (setq dirnam (substring dirnam 0 -1))
1069             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1070             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1071             ;; "/" -> "."
1072             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1073             ;; Windows "\\" -> "."
1074             (setq group (substitute ?. ?\\ group))
1075
1076             (push (vector group
1077                           (string-to-int artno)
1078                           (string-to-int score))
1079                   artlist))))
1080
1081       (message "Massaging swish-e output...done")
1082
1083       ;; Sort by score
1084       (apply 'vector
1085              (sort* artlist
1086                     (function (lambda (x y)
1087                                 (> (nnir-artitem-rsv x)
1088                                    (nnir-artitem-rsv y)))))))))
1089
1090 ;;; Util Code:
1091
1092 (defun nnir-read-parms (query)
1093   "Reads additional search parameters according to `nnir-engines'."
1094   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1095     (cons (cons 'query query)
1096           (mapcar 'nnir-read-parm parmspec))))
1097
1098 (defun nnir-read-parm (parmspec)
1099   "Reads a single search parameter.
1100 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1101   (let ((sym (car parmspec))
1102         (prompt (cdr parmspec)))
1103     (cons sym (read-string prompt))))
1104
1105 (defun nnir-run-query (query)
1106   "Invoke appropriate search engine function (see `nnir-engines').
1107 If some groups were process-marked, run the query for each of the groups
1108 and concat the results."
1109   (let ((search-func (cadr (assoc nnir-search-engine nnir-engines)))
1110         (q (car (read-from-string query))))
1111     (if gnus-group-marked
1112         (apply 'append
1113                (mapcar (lambda (x)
1114                          (funcall search-func q x))
1115                        gnus-group-marked))
1116       (funcall search-func q nil))))
1117
1118 (defun nnir-group-full-name (shortname)
1119   "For the given group name, return a full Gnus group name.
1120 The Gnus backend/server information is added."
1121   (gnus-group-prefixed-name shortname nnir-mail-backend))
1122
1123 (defun nnir-possibly-change-server (server)
1124   (unless (and server (nnir-server-opened server))
1125     (nnir-open-server server)))
1126
1127
1128 ;; Data type article list.
1129
1130 (defun nnir-artlist-length (artlist)
1131   "Returns number of articles in artlist."
1132   (length artlist))
1133
1134 (defun nnir-artlist-article (artlist n)
1135   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1136   (elt artlist (1- n)))
1137
1138 (defun nnir-artitem-group (artitem)
1139   "Returns the group from the ARTITEM."
1140   (elt artitem 0))
1141
1142 (defun nnir-artlist-artitem-group (artlist n)
1143   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1144   (nnir-artitem-group (nnir-artlist-article artlist n)))
1145
1146 (defun nnir-artitem-number (artitem)
1147   "Returns the number from the ARTITEM."
1148   (elt artitem 1))
1149
1150 (defun nnir-artlist-artitem-number (artlist n)
1151   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1152   (nnir-artitem-number (nnir-artlist-article artlist n)))
1153
1154 (defun nnir-artitem-rsv (artitem)
1155   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1156   (elt artitem 2))
1157
1158 (defun nnir-artlist-artitem-rsv (artlist n)
1159   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1160 (counting from 1)."
1161   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1162
1163 ;; unused?
1164 (defun nnir-artlist-groups (artlist)
1165   "Returns a list of all groups in the given ARTLIST."
1166   (let ((res nil)
1167         (with-dups nil))
1168     ;; from each artitem, extract group component
1169     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1170     ;; remove duplicates from above
1171     (mapcar (function (lambda (x) (add-to-list 'res x)))
1172             with-dups)
1173     res))
1174
1175
1176 ;; The end.
1177 (provide 'nnir)