* gnus.el (gnus-find-method-for-group): On killed/unknown groups, try
[gnus] / contrib / nnir.el
1 ;;; nnir.el --- search mail with various search engines -*- coding: iso-8859-1 -*-
2 ;; Copyright (C) 1998 Kai Großjohann
3
4 ;; Author: Kai Großjohann <grossjohann@ls6.cs.uni-dortmund.de>
5 ;; Keywords: news, mail, searching, ir, glimpse, wais, hyrex
6
7 ;; This file is not part of GNU Emacs.
8
9 ;; This is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;; The most recent version of this can always be fetched from the Gnus
27 ;; CVS repository.  See http://www.gnus.org/ for more information.
28
29 ;; This code is still in the development stage but I'd like other
30 ;; people to have a look at it.  Please do not hesitate to contact me
31 ;; with your ideas.
32
33 ;; What does it do?  Well, it allows you to index your mail using some
34 ;; search engine (freeWAIS-sf, Glimpse and others -- see later),
35 ;; then type `G G' in the Group buffer and issue a query to the search
36 ;; engine.  You will then get a buffer which shows all articles
37 ;; matching the query, sorted by Retrieval Status Value (score).
38
39 ;; When looking at the retrieval result (in the Summary buffer) you
40 ;; can type `G T' (aka M-x gnus-summary-nnir-goto-thread RET) on an
41 ;; article.  You will be teleported into the group this article came
42 ;; from, showing the thread this article is part of.  (See below for
43 ;; restrictions.)
44
45 ;; The Lisp installation is simple: just put this file on your
46 ;; load-path, byte-compile it, and load it from ~/.gnus or something.
47 ;; This will install a new command `G G' in your Group buffer for
48 ;; searching your mail.  Note that you also need to configure a number
49 ;; of variables, as described below.
50
51 ;; Restrictions:
52 ;;
53 ;; * If you don't use HyREX as your search engine, this expects that
54 ;;   you use nnml or another one-file-per-message backend, because the
55 ;;   others doesn't support nnfolder.
56 ;; * It can only search the mail backend's which are supported by one
57 ;;   search engine, because of different query languages.
58 ;; * There are restrictions to the Glimpse setup.
59 ;; * There are restrictions to the Wais setup.
60 ;; * There are restrictions to the imap 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. You can define the variables in the server definition
69 ;; like this :
70 ;;   (setq gnus-secondary-select-methods '(
71 ;;       (nnimap "" (nnimap-address "localhost")
72 ;;                  (nnir-search-engine hyrex)
73 ;;                  (nnir-hyrex-additional-switches ("-d" "ddl-nnimap.xml"))
74 ;;       )))
75 ;; Or you can define the global ones. The variables set in the mailer-
76 ;; definition will be used first.
77 ;; The variable to set is `nnir-search-engine'.  Choose one of the engines
78 ;; listed in `nnir-engines'.  (Actually `nnir-engines' is an alist,
79 ;; type `C-h v nnir-engines RET' for more information; this includes
80 ;; examples for setting `nnir-search-engine', too.)
81 ;;
82 ;; The variable nnir-mail-backend isn't used anymore.
83 ;;
84
85 ;; You must also set up a search engine.  I'll tell you about the two
86 ;; search engines currently supported:
87
88 ;; 1. freeWAIS-sf
89 ;;
90 ;; As always with freeWAIS-sf, you need a so-called `format file'.  I
91 ;; use the following file:
92 ;;
93 ;; ,-----
94 ;; | # Kai's format file for freeWAIS-sf for indexing mails.
95 ;; | # Each mail is in a file, much like the MH format.
96 ;; |
97 ;; | # Document separator should never match -- each file is a document.
98 ;; | record-sep: /^@this regex should never match@$/
99 ;; |
100 ;; | # Searchable fields specification.
101 ;; |
102 ;; | region: /^[sS]ubject:/ /^[sS]ubject: */
103 ;; |         subject "Subject header" stemming TEXT BOTH
104 ;; | end: /^[^ \t]/
105 ;; |
106 ;; | region: /^([tT][oO]|[cC][cC]):/ /^([tT][oO]|[cC][cC]): */
107 ;; |         to "To and Cc headers" SOUNDEX BOTH
108 ;; | end: /^[^ \t]/
109 ;; |
110 ;; | region: /^[fF][rR][oO][mM]:/ /^[fF][rR][oO][mM]: */
111 ;; |         from "From header" SOUNDEX BOTH
112 ;; | end: /^[^ \t]/
113 ;; |
114 ;; | region: /^$/
115 ;; |         stemming TEXT GLOBAL
116 ;; | end: /^@this regex should never match@$/
117 ;; `-----
118 ;;
119 ;; 1998-07-22: waisindex would dump core on me for large articles with
120 ;; the above settings.  I used /^$/ as the end regex for the global
121 ;; field.  That seemed to work okay.
122
123 ;; There is a Perl module called `WAIS.pm' which is available from
124 ;; CPAN as well as ls6-ftp.cs.uni-dortmund.de:/pub/wais/Perl.  This
125 ;; module comes with a nifty tool called `makedb', which I use for
126 ;; indexing.  Here's my `makedb.conf':
127 ;;
128 ;; ,-----
129 ;; | # Config file for makedb
130 ;; |
131 ;; | # Global options
132 ;; | waisindex = /usr/local/bin/waisindex
133 ;; | wais_opt  = -stem -t fields
134 ;; | # `-stem' option necessary when `stemming' is specified for the
135 ;; | # global field in the *.fmt file
136 ;; |
137 ;; | # Own variables
138 ;; | homedir = /home/kai
139 ;; |
140 ;; | # The mail database.
141 ;; | database        = mail
142 ;; | files           = `find $homedir/Mail -name \*[0-9] -print`
143 ;; | dbdir           = $homedir/.wais
144 ;; | limit           = 100
145 ;; `-----
146 ;;
147 ;; The Lisp setup involves the `nnir-wais-*' variables.  The most
148 ;; difficult to understand variable is probably
149 ;; `nnir-wais-remove-prefix'.  Here's what it does: the output of
150 ;; `waissearch' basically contains the file name and the (full)
151 ;; directory name.  As Gnus works with group names rather than
152 ;; directory names, the directory name is transformed into a group
153 ;; name as follows: first, a prefix is removed from the (full)
154 ;; directory name, then all `/' are replaced with `.'.  The variable
155 ;; `nnir-wais-remove-prefix' should contain a regex matching exactly
156 ;; this prefix.  It defaults to `$HOME/Mail/' (note the trailing
157 ;; slash).
158
159 ;; 2. Glimpse
160 ;;
161 ;; The code expects you to have one Glimpse index which contains all
162 ;; your mail files.  The Lisp setup involves setting the
163 ;; `nnir-glimpse-*' variables.  The most difficult to understand
164 ;; variable is probably `nnir-glimpse-remove-prefix', it corresponds
165 ;; to `nnir-wais-remove-prefix', see above.  The `nnir-glimpse-home'
166 ;; variable should be set to the value of the `-H' option which allows
167 ;; one to search this Glimpse index.  I have indexed my whole home
168 ;; directory with Glimpse, so I assume a default of `$HOME'.
169
170 ;; 3. Namazu
171 ;;
172 ;; The Namazu backend requires you to have one directory containing all
173 ;; index files, this is controlled by the `nnir-namazu-index-directory'
174 ;; variable.  To function the `nnir-namazu-remove-prefix' variable must
175 ;; also be correct, see the documentation for `nnir-wais-remove-prefix'
176 ;; above.
177 ;;
178 ;; It is particularly important not to pass any any switches to namazu
179 ;; that will change the output format.  Good switches to use include
180 ;; `--sort', `--ascending', `--early' and `--late'.  Refer to the Namazu
181 ;; documentation for further information on valid switches.
182 ;;
183 ;; To index my mail with the `mknmz' program I use the following
184 ;; configuration file:
185 ;;
186 ;; ,----
187 ;; | package conf;  # Don't remove this line!
188 ;; |
189 ;; | # Paths which will not be indexed. Don't use `^' or `$' anchors.
190 ;; | $EXCLUDE_PATH = "spam|sent";
191 ;; |
192 ;; | # Header fields which should be searchable. case-insensitive
193 ;; | $REMAIN_HEADER = "from|date|message-id|subject";
194 ;; |
195 ;; | # Searchable fields. case-insensitive
196 ;; | $SEARCH_FIELD = "from|date|message-id|subject";
197 ;; |
198 ;; | # The max length of a word.
199 ;; | $WORD_LENG_MAX = 128;
200 ;; |
201 ;; | # The max length of a field.
202 ;; | $MAX_FIELD_LENGTH = 256;
203 ;; `----
204 ;;
205 ;; My mail is stored in the directories ~/Mail/mail/, ~/Mail/lists/ and
206 ;; ~/Mail/archive/, so to index them I go to the directory set in
207 ;; `nnir-namazu-index-directory' and issue the following command.
208 ;;
209 ;;      mknmz --mailnews ~/Mail/archive/ ~/Mail/mail/ ~/Mail/lists/
210 ;;
211 ;; For maximum searching efficiency I have a cron job set to run this
212 ;; command every four hours.
213
214 ;; 4. HyREX
215 ;;
216 ;; The HyREX backend requires you to have one directory from where all
217 ;; your relative paths are to, if you use them. This directory must be
218 ;; set in the `nnir-hyrex-index-directory' variable, which defaults to
219 ;; your home directory. You must also pass the base, class and
220 ;; directory options or simply your dll to the `nnir-hyrex-programm' by
221 ;; setting the `nnir-hyrex-additional-switches' variable accordently.
222 ;; To function the `nnir-hyrex-remove-prefix' variable must also be
223 ;; correct, see the documentation for `nnir-wais-remove-prefix' above.
224
225 ;; Developer information:
226
227 ;; I have tried to make the code expandable.  Basically, it is divided
228 ;; into two layers.  The upper layer is somewhat like the `nnvirtual'
229 ;; or `nnkiboze' backends: given a specification of what articles to
230 ;; show from another backend, it creates a group containing exactly
231 ;; those articles.  The lower layer issues a query to a search engine
232 ;; and produces such a specification of what articles to show from the
233 ;; other backend.
234
235 ;; The interface between the two layers consists of the single
236 ;; function `nnir-run-query', which just selects the appropriate
237 ;; function for the search engine one is using.  The input to
238 ;; `nnir-run-query' is a string, representing the query as input by
239 ;; the user.  The output of `nnir-run-query' is supposed to be a
240 ;; vector, each element of which should in turn be a three-element
241 ;; vector.  The first element should be full group name of the article,
242 ;; the second element should be the article number, and the third
243 ;; element should be the Retrieval Status Value (RSV) as returned from
244 ;; the search engine.  An RSV is the score assigned to the document by
245 ;; the search engine.  For Boolean search engines like Glimpse, the
246 ;; RSV is always 1000 (or 1 or 100, or whatever you like).
247
248 ;; The sorting order of the articles in the summary buffer created by
249 ;; nnir is based on the order of the articles in the above mentioned
250 ;; vector, so that's where you can do the sorting you'd like.  Maybe
251 ;; it would be nice to have a way of displaying the search result
252 ;; sorted differently?
253
254 ;; So what do you need to do when you want to add another search
255 ;; engine?  You write a function that executes the query.  Temporary
256 ;; data from the search engine can be put in `nnir-tmp-buffer'.  This
257 ;; function should return the list of articles as a vector, as
258 ;; described above.  Then, you need to register this backend in
259 ;; `nnir-engines'.  Then, users can choose the backend by setting
260 ;; `nnir-search-engine'.
261
262 ;; Todo, or future ideas:
263
264 ;; * Make it so that Glimpse can also be called without `-F'.
265 ;;
266 ;; * It should be possible to restrict search to certain groups.
267 ;;
268 ;; * There is currently no error checking.
269 ;;
270 ;; * The summary buffer display is currently really ugly, with all the
271 ;;   added information in the subjects.  How could I make this
272 ;;   prettier?
273 ;;
274 ;; * A function which can be called from an nnir summary buffer which
275 ;;   teleports you into the group the current article came from and
276 ;;   shows you the whole thread this article is part of.
277 ;;   Implementation suggestions?
278 ;;   (1998-07-24: There is now a preliminary implementation, but
279 ;;   it is much too slow and quite fragile.)
280 ;;
281 ;; * Support other mail backends.  In particular, probably quite a few
282 ;;   people use nnfolder.  How would one go about searching nnfolders
283 ;;   and producing the right data needed?  The group name and the RSV
284 ;;   are simple, but what about the article number?
285 ;;   - The article number is encoded in the `X-Gnus-Article-Number'
286 ;;     header of each mail.
287 ;;   - The HyREX engine supports nnfolder.
288 ;;
289 ;; * Support compressed mail files.  Probably, just stripping off the
290 ;;   `.gz' or `.Z' file name extension is sufficient.
291 ;;
292 ;; * Support a find/grep combination.
293 ;;
294 ;; * At least for imap, the query is performed twice.
295 ;;
296
297 ;; Have you got other ideas?
298
299 ;;; Setup Code:
300
301 (require 'cl)
302 (require 'nnoo)
303 (require 'gnus-group)
304 (require 'gnus-sum)
305 (eval-and-compile
306   (require 'gnus-util))
307 (eval-when-compile
308   (require 'nnimap)
309   (autoload 'read-kbd-macro "edmacro" nil t))
310
311 (nnoo-declare nnir)
312 (nnoo-define-basics nnir)
313
314 (gnus-declare-backend "nnir" 'mail)
315
316 (defvar nnir-imap-search-field "TEXT"
317   "The IMAP search item when doing an nnir search")
318
319 (defvar nnir-imap-search-arguments
320   '(("Whole message" . "TEXT")
321     ("Subject" . "SUBJECT")
322     ("To" . "TO")
323     ("From" . "FROM")
324     (nil . "HEADER \"%s\""))
325   "Mapping from user readable strings to IMAP search items for use in nnir")
326
327 (defvar nnir-imap-search-argument-history ()
328   "The history for querying search options in nnir")
329
330 ;;; Developer Extension Variable:
331
332 (defvar nnir-engines
333   `((glimpse nnir-run-glimpse
334              ((group . "Group spec: ")))
335     (wais    nnir-run-waissearch
336              ())
337     (excite  nnir-run-excite-search
338              ())
339     (imap    nnir-run-imap
340              ((criteria 
341                "Search in: "                      ; Prompt
342                ,nnir-imap-search-arguments        ; alist for completing
343                nil                                ; no filtering
344                nil                                ; allow any user input
345                nil                                ; initial value
346                nnir-imap-search-argument-history  ; the history to use
347                ,nnir-imap-search-field            ; default
348                )))
349     (swish++ nnir-run-swish++
350              ((group . "Group spec: ")))
351     (swish-e nnir-run-swish-e
352              ((group . "Group spec: ")))
353     (namazu  nnir-run-namazu
354              ())
355     (hyrex   nnir-run-hyrex
356              ((group . "Group spec: "))))
357   "Alist of supported search engines.
358 Each element in the alist is a three-element list (ENGINE FUNCTION ARGS).
359 ENGINE is a symbol designating the searching engine.  FUNCTION is also
360 a symbol, giving the function that does the search.  The third element
361 ARGS is a list of cons pairs (PARAM . PROMPT).  When issuing a query,
362 the FUNCTION will issue a query for each of the PARAMs, using PROMPT.
363
364 The value of `nnir-search-engine' must be one of the ENGINE symbols.
365 For example, use the following line for searching using freeWAIS-sf:
366     (setq nnir-search-engine 'wais)
367 Use the following line if you read your mail via IMAP and your IMAP
368 server supports searching:
369     (setq nnir-search-engine 'imap)
370 Note that you have to set additional variables for most backends.  For
371 example, the `wais' backend needs the variables `nnir-wais-program',
372 `nnir-wais-database' and `nnir-wais-remove-prefix'.
373
374 Add an entry here when adding a new search engine.")
375
376 ;;; User Customizable Variables:
377
378 (defgroup nnir nil
379   "Search nnmh and nnml groups in Gnus with Glimpse, freeWAIS-sf, or EWS."
380   :group 'gnus)
381
382 ;; Mail backend.
383
384 ;; TODO:
385 ;; If `nil', use server parameters to find out which server to search. CCC
386 ;;
387 (defcustom nnir-mail-backend '(nnml "")
388   "*Specifies which backend should be searched.
389 More precisely, this is used to determine from which backend to fetch the
390 messages found.
391
392 This must be equal to an existing server, so maybe it is best to use
393 something like the following:
394     (setq nnir-mail-backend (nth 0 gnus-secondary-select-methods))
395 The above line works fine if the mail backend you want to search is
396 the first element of gnus-secondary-select-methods (`nth' starts counting
397 at zero)."
398   :type '(sexp)
399   :group 'nnir)
400
401 ;; Search engine to use.
402
403 (defcustom nnir-search-engine 'wais
404   "*The search engine to use.  Must be a symbol.
405 See `nnir-engines' for a list of supported engines, and for example
406 settings of `nnir-search-engine'."
407   :type '(sexp)
408   :group 'nnir)
409
410 ;; Glimpse engine.
411
412 (defcustom nnir-glimpse-program "glimpse"
413   "*Name of Glimpse executable."
414   :type '(string)
415   :group 'nnir)
416
417 (defcustom nnir-glimpse-home (getenv "HOME")
418   "*Value of `-H' glimpse option.
419 `~' and environment variables must be expanded, see the functions
420 `expand-file-name' and `substitute-in-file-name'."
421   :type '(directory)
422   :group 'nnir)
423
424 (defcustom nnir-glimpse-remove-prefix (concat (getenv "HOME") "/Mail/")
425   "*The prefix to remove from each file name returned by Glimpse
426 in order to get a group name (albeit with / instead of .).  This is a
427 regular expression.
428
429 For example, suppose that Glimpse returns file names such as
430 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
431 setting:  (setq nnir-glimpse-remove-prefix \"/home/john/Mail/\")
432 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
433 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
434 arrive at the correct group name, \"mail.misc\"."
435   :type '(regexp)
436   :group 'nnir)
437
438 (defcustom nnir-glimpse-additional-switches '("-i")
439   "*A list of strings, to be given as additional arguments to glimpse.
440 The switches `-H', `-W', `-l' and `-y' are always used -- calling
441 glimpse without them does not make sense in our situation.
442 Suggested elements to put here are `-i' and `-w'.
443
444 Note that this should be a list.  Ie, do NOT use the following:
445     (setq nnir-glimpse-additional-switches \"-i -w\") ; wrong!
446 Instead, use this:
447     (setq nnir-glimpse-additional-switches '(\"-i\" \"-w\"))"
448   :type '(repeat (string))
449   :group 'nnir)
450
451 ;; freeWAIS-sf.
452
453 (defcustom nnir-wais-program "waissearch"
454   "*Name of waissearch executable."
455   :type '(string)
456   :group 'nnir)
457
458 (defcustom nnir-wais-database (expand-file-name "~/.wais/mail")
459   "*Name of Wais database containing the mail.
460
461 Note that this should be a file name without extension.  For example,
462 if you have a file /home/john/.wais/mail.fmt, use this:
463     (setq nnir-wais-database \"/home/john/.wais/mail\")
464 The string given here is passed to `waissearch -d' as-is."
465   :type '(file)
466   :group 'nnir)
467
468 (defcustom nnir-wais-remove-prefix (concat (getenv "HOME") "/Mail/")
469   "*The prefix to remove from each directory name returned by waissearch
470 in order to get a group name (albeit with / instead of .).  This is a
471 regular expression.
472
473 This variable is similar to `nnir-glimpse-remove-prefix', only for Wais,
474 not Glimpse."
475   :type '(regexp)
476   :group 'nnir)
477
478 ;; EWS (Excite for Web Servers) engine.
479
480 (defcustom nnir-excite-aquery-program "aquery.pl"
481   "*Name of the EWS query program.  Should be `aquery.pl' or a path to same."
482   :type '(string)
483   :group 'nnir)
484
485 (defcustom nnir-excite-collection "Mail"
486   "*Name of the EWS collection to search."
487   :type '(string)
488   :group 'nnir)
489
490 (defcustom nnir-excite-remove-prefix (concat (getenv "HOME") "/Mail/")
491   "*The prefix to remove from each file name returned by EWS
492 in order to get a group name (albeit with / instead of .).  This is a
493 regular expression.
494
495 This variable is very similar to `nnir-glimpse-remove-prefix', except
496 that it is for EWS, not Glimpse."
497   :type '(regexp)
498   :group 'nnir)
499
500 ;; Swish++.  Next three variables Copyright (C) 2000, 2001 Christoph
501 ;; Conrad <christoph.conrad@gmx.de>.
502 ;; Swish++ home page: http://homepage.mac.com/pauljlucas/software/swish/
503
504 (defcustom nnir-swish++-configuration-file
505   (expand-file-name "~/Mail/swish++.conf")
506   "*Configuration file for swish++."
507   :type '(file)
508   :group 'nnir)
509
510 (defcustom nnir-swish++-program "search"
511   "*Name of swish++ search executable."
512   :type '(string)
513   :group 'nnir)
514
515 (defcustom nnir-swish++-additional-switches '()
516   "*A list of strings, to be given as additional arguments to swish++.
517
518 Note that this should be a list.  Ie, do NOT use the following:
519     (setq nnir-swish++-additional-switches \"-i -w\") ; wrong
520 Instead, use this:
521     (setq nnir-swish++-additional-switches '(\"-i\" \"-w\"))"
522   :type '(repeat (string))
523   :group 'nnir)
524
525 (defcustom nnir-swish++-remove-prefix (concat (getenv "HOME") "/Mail/")
526   "*The prefix to remove from each file name returned by swish++
527 in order to get a group name (albeit with / instead of .).  This is a
528 regular expression.
529
530 This variable is very similar to `nnir-glimpse-remove-prefix', except
531 that it is for swish++, not Glimpse."
532   :type '(regexp)
533   :group 'nnir)
534
535 ;; Swish-E.
536 ;; URL: http://sunsite.berkeley.edu/SWISH-E/
537 ;; New version: http://www.boe.es/swish-e
538 ;; Variables `nnir-swish-e-index-file', `nnir-swish-e-program' and
539 ;; `nnir-swish-e-additional-switches'
540 ;; Copyright (C) 2000 Christoph Conrad <christoph.conrad@gmx.de>.
541
542 (make-obsolete-variable 'nnir-swish-e-index-file
543                         'nnir-swish-e-index-files)
544 (defcustom nnir-swish-e-index-file
545   (expand-file-name "~/Mail/index.swish-e")
546   "*Index file for swish-e.
547 This could be a server parameter.
548 It is never consulted once `nnir-swish-e-index-files', which should be
549 used instead, has been customized."
550   :type '(file)
551   :group 'nnir)
552
553 (defcustom nnir-swish-e-index-files
554   (list nnir-swish-e-index-file)
555   "*List of index files for swish-e.
556 This could be a server parameter."
557   :type '(repeat (file))
558   :group 'nnir)
559
560 (defcustom nnir-swish-e-program "swish-e"
561   "*Name of swish-e search executable.
562 This cannot be a server parameter."
563   :type '(string)
564   :group 'nnir)
565
566 (defcustom nnir-swish-e-additional-switches '()
567   "*A list of strings, to be given as additional arguments to swish-e.
568
569 Note that this should be a list.  Ie, do NOT use the following:
570     (setq nnir-swish-e-additional-switches \"-i -w\") ; wrong
571 Instead, use this:
572     (setq nnir-swish-e-additional-switches '(\"-i\" \"-w\"))
573
574 This could be a server parameter."
575   :type '(repeat (string))
576   :group 'nnir)
577
578 (defcustom nnir-swish-e-remove-prefix (concat (getenv "HOME") "/Mail/")
579   "*The prefix to remove from each file name returned by swish-e
580 in order to get a group name (albeit with / instead of .).  This is a
581 regular expression.
582
583 This variable is very similar to `nnir-glimpse-remove-prefix', except
584 that it is for swish-e, not Glimpse.
585
586 This could be a server parameter."
587   :type '(regexp)
588   :group 'nnir)
589
590 ;; HyREX engine, see <URL:http://ls6-www.cs.uni-dortmund.de/>
591
592 (defcustom nnir-hyrex-program "nnir-search"
593   "*Name of the nnir-search executable."
594   :type '(string)
595   :group 'nnir)
596
597 (defcustom nnir-hyrex-additional-switches '()
598   "*A list of strings, to be given as additional arguments for nnir-search.
599 Note that this should be a list. Ie, do NOT use the following:
600     (setq nnir-hyrex-additional-switches \"-ddl ddl.xml -c nnir\") ; wrong !
601 Instead, use this:
602     (setq nnir-hyrex-additional-switches '(\"-ddl\" \"ddl.xml\" \"-c\" \"nnir\"))"
603   :type '(repeat (string))
604   :group 'nnir)
605
606 (defcustom nnir-hyrex-index-directory (getenv "HOME")
607   "*Index directory for HyREX."
608   :type '(directory)
609   :group 'nnir)
610
611 (defcustom nnir-hyrex-remove-prefix (concat (getenv "HOME") "/Mail/")
612   "*The prefix to remove from each file name returned by HyREX
613 in order to get a group name (albeit with / instead of .).
614
615 For example, suppose that HyREX returns file names such as
616 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
617 setting:  (setq nnir-hyrex-remove-prefix \"/home/john/Mail/\")
618 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
619 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
620 arrive at the correct group name, \"mail.misc\"."
621   :type '(directory)
622   :group 'nnir)
623
624 ;; Namazu engine, see <URL:http://ww.namazu.org/>
625
626 (defcustom nnir-namazu-program "namazu"
627   "*Name of Namazu search executable."
628   :type '(string)
629   :group 'nnir)
630
631 (defcustom nnir-namazu-index-directory (expand-file-name "~/Mail/namazu/")
632   "*Index directory for Namazu."
633   :type '(directory)
634   :group 'nnir)
635
636 (defcustom nnir-namazu-additional-switches '()
637   "*A list of strings, to be given as additional arguments to namazu.
638 The switches `-q', `-a', and `-s' are always used, very few other switches
639 make any sense in this context.
640
641 Note that this should be a list.  Ie, do NOT use the following:
642     (setq nnir-namazu-additional-switches \"-i -w\") ; wrong
643 Instead, use this:
644     (setq nnir-namazu-additional-switches '(\"-i\" \"-w\"))"
645   :type '(repeat (string))
646   :group 'nnir)
647
648 (defcustom nnir-namazu-remove-prefix (concat (getenv "HOME") "/Mail/")
649   "*The prefix to remove from each file name returned by Namazu
650 in order to get a group name (albeit with / instead of .).
651
652 This variable is very similar to `nnir-glimpse-remove-prefix', except
653 that it is for Namazu, not Glimpse."
654   :type '(directory)
655   :group 'nnir)
656
657 ;;; Internal Variables:
658
659 (defvar nnir-current-query nil
660   "Internal: stores current query (= group name).")
661
662 (defvar nnir-current-server nil
663   "Internal: stores current server (does it ever change?).")
664
665 (defvar nnir-current-group-marked nil
666   "Internal: stores current list of process-marked groups.")
667
668 (defvar nnir-artlist nil
669   "Internal: stores search result.")
670
671 (defvar nnir-tmp-buffer " *nnir*"
672   "Internal: temporary buffer.")
673
674 ;;; Code:
675
676 ;; Gnus glue.
677
678 (defun gnus-group-make-nnir-group (extra-parms query)
679   "Create an nnir group.  Asks for query."
680   (interactive "P\nsQuery: ")
681   (setq nnir-current-query nil
682         nnir-current-server nil
683         nnir-current-group-marked nil
684         nnir-artlist nil)
685   (let ((parms nil))
686     (if extra-parms
687         (setq parms (nnir-read-parms query))
688       (setq parms (list (cons 'query query))))
689     (gnus-group-read-ephemeral-group
690      (concat "nnir:" (prin1-to-string parms)) '(nnir "") t
691      (cons (current-buffer)
692            gnus-current-window-configuration)
693      nil)))
694
695 ;; Emacs 19 compatibility?
696 (or (fboundp 'kbd) (defalias 'kbd 'read-kbd-macro))
697
698 (defun nnir-group-mode-hook ()
699   (define-key gnus-group-mode-map
700     (if (fboundp 'read-kbd-macro)
701         (kbd "G G")
702       "GG")                             ; XEmacs 19 compat
703     'gnus-group-make-nnir-group))
704 (add-hook 'gnus-group-mode-hook 'nnir-group-mode-hook)
705
706 (defmacro nnir-group-server (group)
707   "Return the server for a newsgroup GROUP.
708 The returned format is as `gnus-server-to-method' needs it.  See
709 `gnus-group-real-prefix' and `gnus-group-real-name'."
710   `(let ((gname ,group))
711      (if (string-match "^\\([^:]+\\):" gname)
712          (progn
713            (setq gname (match-string 1 gname))
714            (if (string-match "^\\([^+]+\\)\\+\\(.+\\)$" gname)
715                (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
716              (concat gname ":")))
717        "native")))
718
719 ;; Summary mode commands.
720
721 (defun gnus-summary-nnir-goto-thread ()
722   "Only applies to nnir groups.  Go to group this article came from
723 and show thread that contains this article."
724   (interactive)
725   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
726     (error "Can't execute this command unless in nnir group."))
727   (let* ((cur (gnus-summary-article-number))
728          (group (nnir-artlist-artitem-group nnir-artlist cur))
729          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
730          server backend-group)
731     (setq server (nnir-group-server group))
732     (setq backend-group (gnus-group-real-name group))
733     (gnus-group-read-ephemeral-group
734      backend-group
735      (gnus-server-to-method server)
736      t                                  ; activate
737      (cons (current-buffer)
738            'summary)                    ; window config
739      nil
740      (list backend-number))
741     (gnus-summary-limit (list backend-number))
742     (gnus-summary-refer-thread)))
743
744 (if (fboundp 'eval-after-load)
745     (eval-after-load "gnus-sum"
746       '(define-key gnus-summary-goto-map
747          "T" 'gnus-summary-nnir-goto-thread))
748   (add-hook 'gnus-summary-mode-hook
749             (function (lambda ()
750                         (define-key gnus-summary-goto-map
751                           "T" 'gnus-summary-nnir-goto-thread)))))
752
753
754
755 ;; Gnus backend interface functions.
756
757 (deffoo nnir-open-server (server &optional definitions)
758   ;; Just set the server variables appropriately.
759   (nnoo-change-server 'nnir server definitions))
760
761 (deffoo nnir-request-group (group &optional server fast)
762   "GROUP is the query string."
763   (nnir-possibly-change-server server)
764   ;; Check for cache and return that if appropriate.
765   (if (and (equal group nnir-current-query)
766            (equal gnus-group-marked nnir-current-group-marked)
767            (or (null server)
768                (equal server nnir-current-server)))
769       nnir-artlist
770     ;; Cache miss.
771     (setq nnir-artlist (nnir-run-query group)))
772   (save-excursion
773     (set-buffer nntp-server-buffer)
774     (if (zerop (length nnir-artlist))
775         (progn
776           (setq nnir-current-query nil
777                 nnir-current-server nil
778                 nnir-current-group-marked nil
779                 nnir-artlist nil)
780           (nnheader-report 'nnir "Search produced empty results."))
781       ;; Remember data for cache.
782       (setq nnir-current-query group)
783       (when server (setq nnir-current-server server))
784       (setq nnir-current-group-marked gnus-group-marked)
785       (nnheader-insert "211 %d %d %d %s\n"
786                        (nnir-artlist-length nnir-artlist) ; total #
787                        1              ; first #
788                        (nnir-artlist-length nnir-artlist) ; last #
789                        group))))     ; group name
790
791 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
792   (save-excursion
793     (let ((artlist (copy-sequence articles))
794           (art nil)
795           (artitem nil)
796           (artgroup nil) (artno nil)
797           (artrsv nil)
798           (artfullgroup nil)
799           (novitem nil)
800           (novdata nil)
801           (foo nil)
802           server)
803       (while (not (null artlist))
804         (setq art (car artlist))
805         (or (numberp art)
806             (nnheader-report
807              'nnir
808              "nnir-retrieve-headers doesn't grok message ids: %s"
809              art))
810         (setq artitem (nnir-artlist-article nnir-artlist art))
811         (setq artrsv (nnir-artitem-rsv artitem))
812         (setq artfullgroup (nnir-artitem-group artitem))
813         (setq artno (nnir-artitem-number artitem))
814         (setq artgroup (gnus-group-real-name artfullgroup))
815         (setq server (nnir-group-server artfullgroup))
816         ;; retrieve NOV or HEAD data for this article, transform into
817         ;; NOV data and prepend to `novdata'
818         (set-buffer nntp-server-buffer)
819         (nnir-possibly-change-server server)
820         (let ((gnus-override-method
821                (gnus-server-to-method server)))
822           (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
823             (nov
824              (goto-char (point-min))
825              (setq novitem (nnheader-parse-nov))
826              (unless novitem
827                (pop-to-buffer nntp-server-buffer)
828                (error
829                 "nnheader-parse-nov returned nil for article %s in group %s"
830                 artno artfullgroup)))
831             (headers
832              (goto-char (point-min))
833              (setq novitem (nnheader-parse-head))
834              (unless novitem
835                (pop-to-buffer nntp-server-buffer)
836                (error
837                 "nnheader-parse-head returned nil for article %s in group %s"
838                 artno artfullgroup)))
839             (t (error "Unknown header type %s while requesting article %s of group %s"
840                       foo artno artfullgroup))))
841         ;; replace article number in original group with article number
842         ;; in nnir group
843         (mail-header-set-number novitem art)
844         (mail-header-set-from novitem
845                               (mail-header-from novitem))
846         (mail-header-set-subject
847          novitem
848          (format "[%d: %s/%d] %s"
849                  artrsv artgroup artno
850                  (mail-header-subject novitem)))
851         ;;-(mail-header-set-extra novitem nil)
852         (push novitem novdata)
853         (setq artlist (cdr artlist)))
854       (setq novdata (nreverse novdata))
855       (set-buffer nntp-server-buffer) (erase-buffer)
856       (mapcar 'nnheader-insert-nov novdata)
857       'nov)))
858
859 (deffoo nnir-request-article (article
860                               &optional group server to-buffer)
861   (if (stringp article)
862       (nnheader-report
863        'nnir
864        "nnir-retrieve-headers doesn't grok message ids: %s"
865        article)
866     (save-excursion
867       (let* ((artitem (nnir-artlist-article nnir-artlist
868                                             article))
869              (artfullgroup (nnir-artitem-group artitem))
870              (artno (nnir-artitem-number artitem))
871              ;; Bug?
872              ;; Why must we bind nntp-server-buffer here?  It won't
873              ;; work if `buf' is used, say.  (Of course, the set-buffer
874              ;; line below must then be updated, too.)
875              (nntp-server-buffer (or to-buffer nntp-server-buffer)))
876         (set-buffer nntp-server-buffer)
877         (erase-buffer)
878         (message "Requesting article %d from group %s"
879                  artno artfullgroup)
880         (gnus-request-article artno artfullgroup nntp-server-buffer)
881         (cons artfullgroup artno)))))
882
883
884 (nnoo-define-skeleton nnir)
885
886 ;;; Search Engine Interfaces:
887
888 ;; Glimpse interface.
889 (defun nnir-run-glimpse (query server &optional group)
890   "Run given query against glimpse.  Returns a vector of (group name, file name)
891 pairs (also vectors, actually)."
892   (save-excursion
893     (let ((artlist nil)
894           (groupspec (cdr (assq 'group query)))
895           (qstring (cdr (assq 'query query)))
896           (prefix (nnir-read-server-parm 'nnir-glimpse-remove-prefix server))
897           artno dirnam)
898       (when (and group groupspec)
899         (error (concat "It does not make sense to use a group spec"
900                        " with process-marked groups.")))
901       (when group
902         (setq groupspec (gnus-group-real-name group)))
903       (set-buffer (get-buffer-create nnir-tmp-buffer))
904       (erase-buffer)
905       (if groupspec
906           (message "Doing glimpse query %s on %s..." query groupspec)
907         (message "Doing glimpse query %s..." query))
908       (let* ((cp-list
909               `( ,nnir-glimpse-program
910                  nil                    ; input from /dev/null
911                  t                      ; output
912                  nil                    ; don't redisplay
913                  "-H" ,(nnir-read-server-parm 'nnir-glimpse-home server) ; search home dir
914                  "-W"                   ; match pattern in file
915                  "-l" "-y"              ; misc options
916                  ,@(nnir-read-server-parm 'nnir-glimpse-additional-switches server)
917                  "-F" ,prefix           ; restrict output to mail
918                  ,qstring               ; the query, in glimpse format
919                  ))
920              (exitstatus
921               (progn
922                 (message "%s args: %s" nnir-glimpse-program
923                          (mapconcat 'identity (cddddr cp-list) " "))
924                 (apply 'call-process cp-list))))
925         (unless (or (null exitstatus)
926                     (zerop exitstatus))
927           (nnheader-report 'nnir "Couldn't run glimpse: %s" exitstatus)
928           ;; Glimpse failure reason is in this buffer, show it if
929           ;; the user wants it.
930           (when (> gnus-verbose 6)
931             (display-buffer nnir-tmp-buffer))))
932       (when groupspec
933         (keep-lines groupspec))
934       (if groupspec
935           (message "Doing glimpse query %s on %s...done" query groupspec)
936         (message "Doing glimpse query %s...done" query))
937       (sit-for 0)
938       ;; remove superfluous stuff from glimpse output
939       (goto-char (point-min))
940       (delete-non-matching-lines "/[0-9]+$")
941       ;;(delete-matching-lines "\\.overview~?$")
942       (goto-char (point-min))
943       (while (re-search-forward (concat "^" prefix "\\(.+\\)" "/\\([0-9]\\)+$") nil t)
944         ;; replace / with . in group names
945         (setq dirnam (substitute ?. ?/ (match-string 1))
946               artno  (match-string 2))
947         (push (vector (nnir-group-full-name dirnam server)
948                       (string-to-int artno)) artlist))
949
950       (sort* artlist
951              (function (lambda (x y)
952                          (if (string-lessp (nnir-artitem-group x)
953                                            (nnir-artitem-group y))
954                              t
955                            (< (nnir-artitem-number x)
956                               (nnir-artitem-number y))))))
957       )))
958
959 ;; freeWAIS-sf interface.
960 (defun nnir-run-waissearch (query server &optional group)
961   "Run given query agains waissearch.  Returns vector of (group name, file name)
962 pairs (also vectors, actually)."
963   (when group
964     (error "The freeWAIS-sf backend cannot search specific groups."))
965   (save-excursion
966     (let ((qstring (cdr (assq 'query query)))
967           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
968           (artlist nil)
969           (score nil) (artno nil) (dirnam nil) (group nil))
970       (set-buffer (get-buffer-create nnir-tmp-buffer))
971       (erase-buffer)
972       (message "Doing WAIS query %s..." query)
973       (call-process nnir-wais-program
974                     nil                 ; input from /dev/null
975                     t                   ; output to current buffer
976                     nil                 ; don't redisplay
977                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
978                     qstring)
979       (message "Massaging waissearch output...")
980       ;; remove superfluous lines
981       (keep-lines "Score:")
982       ;; extract data from result lines
983       (goto-char (point-min))
984       (while (re-search-forward
985               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
986         (setq score (match-string 1)
987               artno (match-string 2)
988               dirnam (match-string 3))
989         (unless (string-match prefix dirnam)
990           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
991                            dirnam prefix))
992         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
993         (push (vector (nnir-group-full-name group server)
994                       (string-to-int artno)
995                       (string-to-int score))
996               artlist))
997       (message "Massaging waissearch output...done")
998       (apply 'vector
999              (sort* artlist
1000                     (function (lambda (x y)
1001                                 (> (nnir-artitem-rsv x)
1002                                    (nnir-artitem-rsv y)))))))))
1003
1004 ;; EWS (Excite for Web Servers) interface
1005 (defun nnir-run-excite-search (query server &optional group)
1006   "Run a given query against EWS.  Returns vector of (group name, file name)
1007 pairs (also vectors, actually)."
1008   (when group
1009     (error "Searching specific groups not implemented for EWS."))
1010   (save-excursion
1011     (let ((qstring (cdr (assq 'query query)))
1012           (prefix (nnir-read-server-parm 'nnir-excite-remove-prefix server))
1013           artlist group article-num article)
1014       (setq nnir-current-query query)
1015       (set-buffer (get-buffer-create nnir-tmp-buffer))
1016       (erase-buffer)
1017       (message "Doing EWS query %s..." qstring)
1018       (call-process nnir-excite-aquery-program
1019                     nil                 ; input from /dev/null
1020                     t                   ; output to current buffer
1021                     nil                 ; don't redisplay
1022                     (nnir-read-server-parm 'nnir-excite-collection server)
1023                     (if (string= (substring qstring 0 1) "(")
1024                         qstring
1025                       (format "(concept %s)" qstring)))
1026       (message "Gathering query output...")
1027
1028       (goto-char (point-min))
1029       (while (re-search-forward
1030               "^[0-9]+\\s-[0-9]+\\s-[0-9]+\\s-\\(\\S-*\\)" nil t)
1031         (setq article (match-string 1))
1032         (unless (string-match
1033                  (concat "^" (regexp-quote prefix)
1034                          "\\(.*\\)/\\([0-9]+\\)") article)
1035           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
1036                            article prefix))
1037         (setq group (substitute ?. ?/ (match-string 1 article)))
1038         (setq group (nnir-group-full-name group server))
1039         (setq article-num (match-string 2 article))
1040         (setq artlist (vconcat artlist (vector (vector group
1041                                                        (string-to-int article-num)
1042                                                        1000)))))
1043       (message "Gathering query output...done")
1044       artlist)))
1045
1046 ;; IMAP interface.  The following function is Copyright (C) 1998 Simon
1047 ;; Josefsson <jas@pdc.kth.se>.
1048 ;; todo:
1049 ;; nnir invokes this two (2) times???!
1050 ;; we should not use nnimap at all but open our own server connection
1051 ;; we should not LIST * but use nnimap-list-pattern from defs
1052 ;; send queries as literals
1053 ;; handle errors
1054
1055 (defun nnir-run-imap (query srv &optional group-option)
1056   (require 'imap)
1057   (require 'nnimap)
1058   (save-excursion
1059     (let ((qstring (cdr (assq 'query query)))
1060           (server (cadr (gnus-server-to-method srv)))
1061           (group (or group-option (gnus-group-group-name)))
1062           (defs (caddr (gnus-server-to-method srv)))
1063           (criteria (or (cdr (assq 'criteria query))
1064                         nnir-imap-search-field))
1065           artlist buf)
1066       (message "Opening server %s" server)
1067       (condition-case ()
1068           (when (nnimap-open-server server defs) ;; xxx
1069             (setq buf nnimap-server-buffer) ;; xxx
1070             (message "Searching %s..." group)
1071             (let ((arts 0)
1072                   (mbx (gnus-group-real-name group)))
1073               (when (imap-mailbox-select mbx nil buf)
1074                 (mapcar
1075                  (lambda (artnum)
1076                    (push (vector group artnum 1) artlist)
1077                    (setq arts (1+ arts)))
1078                  (imap-search (concat criteria " \"" qstring "\"") buf))
1079                 (message "Searching %s... %d matches" mbx arts)))
1080             (message "Searching %s...done" group))
1081         (quit nil))
1082       (reverse artlist))))
1083
1084 ;; Swish++ interface.  The following function is Copyright (C) 2000,
1085 ;; 2001 Christoph Conrad <christoph.conrad@gmx.de>.
1086 ;; -cc- Todo
1087 ;; Search by
1088 ;; - group
1089 ;; Sort by
1090 ;; - rank (default)
1091 ;; - article number
1092 ;; - file size
1093 ;; - group
1094 (defun nnir-run-swish++ (query server &optional group)
1095   "Run given query against swish++.
1096 Returns a vector of (group name, file name) pairs (also vectors,
1097 actually).
1098
1099 Tested with swish++ 4.7 on GNU/Linux and with with swish++ 5.0b2 on
1100 Windows NT 4.0."
1101
1102   (when group
1103     (error "The swish++ backend cannot search specific groups."))
1104
1105   (save-excursion
1106     (let ( (qstring (cdr (assq 'query query)))
1107            (groupspec (cdr (assq 'group query)))
1108            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
1109            (artlist nil)
1110            (score nil) (artno nil) (dirnam nil) (group nil) )
1111
1112       (when (equal "" qstring)
1113         (error "swish++: You didn't enter anything."))
1114
1115       (set-buffer (get-buffer-create nnir-tmp-buffer))
1116       (erase-buffer)
1117
1118       (if groupspec
1119           (message "Doing swish++ query %s on %s..." qstring groupspec)
1120         (message "Doing swish++ query %s..." qstring))
1121
1122       (let* ((cp-list `( ,nnir-swish++-program
1123                          nil            ; input from /dev/null
1124                          t              ; output
1125                          nil            ; don't redisplay
1126                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1127                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1128                          ,qstring       ; the query, in swish++ format
1129                          ))
1130              (exitstatus
1131               (progn
1132                 (message "%s args: %s" nnir-swish++-program
1133                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1134                 (apply 'call-process cp-list))))
1135         (unless (or (null exitstatus)
1136                     (zerop exitstatus))
1137           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1138           ;; swish++ failure reason is in this buffer, show it if
1139           ;; the user wants it.
1140           (when (> gnus-verbose 6)
1141             (display-buffer nnir-tmp-buffer))))
1142
1143       ;; The results are output in the format of:
1144       ;; V 4.7 Linux
1145       ;; rank relative-path-name file-size file-title
1146       ;; V 5.0b2:
1147       ;; rank relative-path-name file-size topic??
1148       ;; where rank is an integer from 1 to 100.
1149       (goto-char (point-min))
1150       (while (re-search-forward
1151               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1152         (setq score (match-string 1)
1153               artno (file-name-nondirectory (match-string 2))
1154               dirnam (file-name-directory (match-string 2)))
1155
1156         ;; don't match directories
1157         (when (string-match "^[0-9]+\\(\\.[a-z0-9]+\\)?$" artno)
1158           ;; nnml-use-compressed-files might be any string, but probably this
1159           ;; is sufficient.  Note that we can't only use the value of
1160           ;; nnml-use-compressed-files because old articles might have been
1161           ;; saved with a different value.
1162           (when (not (null dirnam))
1163
1164             ;; maybe limit results to matching groups.
1165             (when (or (not groupspec)
1166                       (string-match groupspec dirnam))
1167
1168               ;; remove nnir-swish++-remove-prefix from beginning of dirname
1169               (when (string-match (concat "^" prefix)
1170                                   dirnam)
1171                 (setq dirnam (replace-match "" t t dirnam)))
1172
1173               (setq dirnam (substring dirnam 0 -1))
1174               ;; eliminate all ".", "/", "\" from beginning. Always matches.
1175               (string-match "^[./\\]*\\(.*\\)$" dirnam)
1176               ;; "/" -> "."
1177               (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1178               ;; "\\" -> "."
1179               (setq group (substitute ?. ?\\ group))
1180
1181               (push (vector (nnir-group-full-name group server)
1182                             (string-to-int artno)
1183                             (string-to-int score))
1184                     artlist)))))
1185
1186       (message "Massaging swish++ output...done")
1187
1188       ;; Sort by score
1189       (apply 'vector
1190              (sort* artlist
1191                     (function (lambda (x y)
1192                                 (> (nnir-artitem-rsv x)
1193                                    (nnir-artitem-rsv y)))))))))
1194
1195 ;; Swish-E interface.  The following function is Copyright (C) 2000,
1196 ;; 2001 by Christoph Conrad <christoph.conrad@gmx.de>.
1197 (defun nnir-run-swish-e (query server &optional group)
1198   "Run given query against swish-e.
1199 Returns a vector of (group name, file name) pairs (also vectors,
1200 actually).
1201
1202 Tested with swish-e-2.0.1 on Windows NT 4.0."
1203
1204   ;; swish-e crashes with empty parameter to "-w" on commandline...
1205   (when group
1206     (error "The swish-e backend cannot search specific groups."))
1207
1208   (save-excursion
1209     (let ((qstring (cdr (assq 'query query)))
1210           (prefix
1211            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1212                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1213           (artlist nil)
1214           (score nil) (artno nil) (dirnam nil) (group nil) )
1215
1216       (when (equal "" qstring)
1217         (error "swish-e: You didn't enter anything."))
1218
1219       (set-buffer (get-buffer-create nnir-tmp-buffer))
1220       (erase-buffer)
1221
1222       (message "Doing swish-e query %s..." query)
1223       (let* ((index-files
1224               (or (nnir-read-server-parm
1225                    'nnir-swish-e-index-files server)
1226                   (error "Missing parameter `nnir-swish-e-index-files'")))
1227              (additional-switches
1228               (nnir-read-server-parm
1229                'nnir-swish-e-additional-switches server))
1230              (cp-list `(,nnir-swish-e-program
1231                         nil             ; input from /dev/null
1232                         t               ; output
1233                         nil             ; don't redisplay
1234                         "-f" ,@index-files
1235                         ,@additional-switches
1236                         "-w"
1237                         ,qstring        ; the query, in swish-e format
1238                         ))
1239              (exitstatus
1240               (progn
1241                 (message "%s args: %s" nnir-swish-e-program
1242                          (mapconcat 'identity (cddddr cp-list) " "))
1243                 (apply 'call-process cp-list))))
1244         (unless (or (null exitstatus)
1245                     (zerop exitstatus))
1246           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1247           ;; swish-e failure reason is in this buffer, show it if
1248           ;; the user wants it.
1249           (when (> gnus-verbose 6)
1250             (display-buffer nnir-tmp-buffer))))
1251
1252       ;; The results are output in the format of:
1253       ;; rank path-name file-title file-size
1254       (goto-char (point-min))
1255       (while (re-search-forward
1256               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1257         (setq score (match-string 1)
1258               artno (match-string 3)
1259               dirnam (file-name-directory (match-string 2)))
1260
1261         ;; don't match directories
1262         (when (string-match "^[0-9]+$" artno)
1263           (when (not (null dirnam))
1264
1265             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1266             (when (string-match (concat "^" prefix) dirnam)
1267               (setq dirnam (replace-match "" t t dirnam)))
1268
1269             (setq dirnam (substring dirnam 0 -1))
1270             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1271             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1272             ;; "/" -> "."
1273             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1274             ;; Windows "\\" -> "."
1275             (setq group (substitute ?. ?\\ group))
1276
1277             (push (vector (nnir-group-full-name group server)
1278                           (string-to-int artno)
1279                           (string-to-int score))
1280                   artlist))))
1281
1282       (message "Massaging swish-e output...done")
1283
1284       ;; Sort by score
1285       (apply 'vector
1286              (sort* artlist
1287                     (function (lambda (x y)
1288                                 (> (nnir-artitem-rsv x)
1289                                    (nnir-artitem-rsv y)))))))))
1290
1291 ;; HyREX interface
1292 (defun nnir-run-hyrex (query server &optional group)
1293   (save-excursion
1294     (let ((artlist nil)
1295           (groupspec (cdr (assq 'group query)))
1296           (qstring (cdr (assq 'query query)))
1297           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1298           score artno dirnam)
1299       (when (and group groupspec)
1300         (error (concat "It does not make sense to use a group spec"
1301                        " with process-marked groups.")))
1302       (when group
1303         (setq groupspec (gnus-group-real-name group)))
1304       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1305         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1306         (error "Server with groupspec doesn't match group !"))
1307       (set-buffer (get-buffer-create nnir-tmp-buffer))
1308       (erase-buffer)
1309       (if groupspec
1310           (message "Doing hyrex-search query %s on %s..." query groupspec)
1311         (message "Doing hyrex-search query %s..." query))
1312       (let* ((cp-list
1313               `( ,nnir-hyrex-program
1314                  nil                    ; input from /dev/null
1315                  t                      ; output
1316                  nil                    ; don't redisplay
1317                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1318                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1319                  ,qstring          ; the query, in hyrex-search format
1320                  ))
1321              (exitstatus
1322               (progn
1323                 (message "%s args: %s" nnir-hyrex-program
1324                          (mapconcat 'identity (cddddr cp-list) " "))
1325                 (apply 'call-process cp-list))))
1326         (unless (or (null exitstatus)
1327                     (zerop exitstatus))
1328           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1329           ;; nnir-search failure reason is in this buffer, show it if
1330           ;; the user wants it.
1331           (when (> gnus-verbose 6)
1332             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1333       (if groupspec
1334           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1335         (message "Doing hyrex-search query \"%s\"...done" qstring))
1336       (sit-for 0)
1337       ;; nnir-search returns:
1338       ;;   for nnml/nnfolder: "filename mailid weigth"
1339       ;;   for nnimap:        "group mailid weigth"
1340       (goto-char (point-min))
1341       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1342       ;; HyREX couldn't search directly in groups -- so filter out here.
1343       (when groupspec
1344         (keep-lines groupspec))
1345       ;; extract data from result lines
1346       (goto-char (point-min))
1347       (while (re-search-forward
1348               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1349         (setq dirnam (match-string 1)
1350               artno (match-string 2)
1351               score (match-string 3))
1352         (when (string-match prefix dirnam)
1353           (setq dirnam (replace-match "" t t dirnam)))
1354         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1355                       (string-to-int artno)
1356                       (string-to-int score))
1357               artlist))
1358       (message "Massaging hyrex-search output...done.")
1359       (apply 'vector
1360              (sort* artlist
1361                     (function (lambda (x y)
1362                                 (if (string-lessp (nnir-artitem-group x)
1363                                                   (nnir-artitem-group y))
1364                                     t
1365                                   (< (nnir-artitem-number x)
1366                                      (nnir-artitem-number y)))))))
1367       )))
1368
1369 ;; Namazu interface
1370 (defun nnir-run-namazu (query server &optional group)
1371   "Run given query against Namazu.  Returns a vector of (group name, file name)
1372 pairs (also vectors, actually).
1373
1374 Tested with Namazu 2.0.6 on a GNU/Linux system."
1375   (when group
1376     (error "The Namazu backend cannot search specific groups"))
1377   (save-excursion
1378     (let (
1379           (artlist nil)
1380           (qstring (cdr (assq 'query query)))
1381           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1382           (score nil)
1383           (group nil)
1384           (article nil)
1385           (process-environment (copy-sequence process-environment))
1386           )
1387       (setenv "LC_MESSAGES" "C")
1388       (set-buffer (get-buffer-create nnir-tmp-buffer))
1389       (erase-buffer)
1390       (let* ((cp-list
1391               `( ,nnir-namazu-program
1392                  nil                    ; input from /dev/null
1393                  t                      ; output
1394                  nil                    ; don't redisplay
1395                  "-q"                   ; don't be verbose
1396                  "-a"                   ; show all matches
1397                  "-s"                   ; use short format
1398                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1399                  ,qstring               ; the query, in namazu format
1400                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1401                  ))
1402              (exitstatus
1403               (progn
1404                 (message "%s args: %s" nnir-namazu-program
1405                          (mapconcat 'identity (cddddr cp-list) " "))
1406                 (apply 'call-process cp-list))))
1407         (unless (or (null exitstatus)
1408                     (zerop exitstatus))
1409           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1410           ;; Namazu failure reason is in this buffer, show it if
1411           ;; the user wants it.
1412           (when (> gnus-verbose 6)
1413             (display-buffer nnir-tmp-buffer))))
1414
1415       ;; Namazu output looks something like this:
1416       ;; 2. Re: Gnus agent expire broken (score: 55)
1417       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1418
1419       (goto-char (point-min))
1420       (while (re-search-forward
1421               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1422               nil t)
1423         (setq score (match-string 3)
1424               group (file-name-directory (match-string 4))
1425               article (file-name-nondirectory (match-string 4)))
1426
1427         ;; make sure article and group is sane
1428         (when (and (string-match "^[0-9]+$" article)
1429                    (not (null group)))
1430           (when (string-match (concat "^" prefix) group)
1431             (setq group (replace-match "" t t group)))
1432
1433           ;; remove trailing slash from groupname
1434           (setq group (substring group 0 -1))
1435
1436           ;; stuff results into artlist vector
1437           (push (vector (nnir-group-full-name (substitute ?. ?/ group) server)
1438                         (string-to-int article)
1439                         (string-to-int score)) artlist)))
1440
1441       ;; sort artlist by score
1442       (apply 'vector
1443              (sort* artlist
1444                     (function (lambda (x y)
1445                                 (> (nnir-artitem-rsv x)
1446                                    (nnir-artitem-rsv y)))))))))
1447
1448 ;;; Util Code:
1449
1450 (defun nnir-read-parms (query)
1451   "Reads additional search parameters according to `nnir-engines'."
1452   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1453     (cons (cons 'query query)
1454           (mapcar 'nnir-read-parm parmspec))))
1455
1456 (defun nnir-read-parm (parmspec)
1457   "Reads a single search parameter.
1458 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1459   (let ((sym (car parmspec))
1460         (prompt (cdr parmspec)))
1461     (if (listp prompt)
1462         (let* ((result (apply 'completing-read prompt))
1463                (mapping (or (assoc result nnir-imap-search-arguments)
1464                             (assoc nil nnir-imap-search-arguments))))
1465           (cons sym (format (cdr mapping) result)))
1466       (cons sym (read-string prompt)))))
1467
1468 (defun nnir-run-query (query)
1469   "Invoke appropriate search engine function (see `nnir-engines').
1470 If some groups were process-marked, run the query for each of the groups
1471 and concat the results."
1472   (let ((q (car (read-from-string query))))
1473     (if gnus-group-marked
1474         (apply 'vconcat
1475                (mapcar (lambda (x)
1476                          (let ((server (nnir-group-server x))
1477                                search-func)
1478                            (setq search-func (cadr
1479                                               (assoc
1480                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1481                            (if search-func
1482                                (funcall search-func q server x)
1483                              nil)))
1484                        gnus-group-marked)
1485                )
1486       (apply 'vconcat
1487              (mapcar (lambda (x)
1488                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1489                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1490                                  search-func)
1491                              (setq search-func (cadr
1492                                                 (assoc
1493                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1494                              (if search-func
1495                                  (funcall search-func q server nil)
1496                                nil))
1497                          nil))
1498                      gnus-opened-servers)
1499              ))
1500     ))
1501
1502 (defun nnir-read-server-parm (key server)
1503   "Returns the parameter value of for the given server, where server is of
1504 form 'backend:name'."
1505   (let ((method (gnus-server-to-method server)))
1506     (cond ((and method (assq key (cddr method)))
1507            (nth 1 (assq key (cddr method))))
1508           ((and nnir-mail-backend
1509                 (gnus-server-equal method nnir-mail-backend))
1510            (symbol-value key))
1511           (t nil))))
1512 ;;     (if method
1513 ;;       (if (assq key (cddr method))
1514 ;;        (nth 1 (assq key (cddr method)))
1515 ;;      (symbol-value key))
1516 ;;       (symbol-value key))
1517 ;;     ))
1518
1519 (defun nnir-group-full-name (shortname server)
1520   "For the given group name, return a full Gnus group name.
1521 The Gnus backend/server information is added."
1522   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1523
1524 (defun nnir-possibly-change-server (server)
1525   (unless (and server (nnir-server-opened server))
1526     (nnir-open-server server)))
1527
1528
1529 ;; Data type article list.
1530
1531 (defun nnir-artlist-length (artlist)
1532   "Returns number of articles in artlist."
1533   (length artlist))
1534
1535 (defun nnir-artlist-article (artlist n)
1536   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1537   (elt artlist (1- n)))
1538
1539 (defun nnir-artitem-group (artitem)
1540   "Returns the group from the ARTITEM."
1541   (elt artitem 0))
1542
1543 (defun nnir-artlist-artitem-group (artlist n)
1544   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1545   (nnir-artitem-group (nnir-artlist-article artlist n)))
1546
1547 (defun nnir-artitem-number (artitem)
1548   "Returns the number from the ARTITEM."
1549   (elt artitem 1))
1550
1551 (defun nnir-artlist-artitem-number (artlist n)
1552   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1553   (nnir-artitem-number (nnir-artlist-article artlist n)))
1554
1555 (defun nnir-artitem-rsv (artitem)
1556   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1557   (elt artitem 2))
1558
1559 (defun nnir-artlist-artitem-rsv (artlist n)
1560   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1561 \(counting from 1)."
1562   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1563
1564 ;; unused?
1565 (defun nnir-artlist-groups (artlist)
1566   "Returns a list of all groups in the given ARTLIST."
1567   (let ((res nil)
1568         (with-dups nil))
1569     ;; from each artitem, extract group component
1570     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1571     ;; remove duplicates from above
1572     (mapcar (function (lambda (x) (add-to-list 'res x)))
1573             with-dups)
1574     res))
1575
1576
1577 ;; The end.
1578 (provide 'nnir)
1579
1580 ;;; arch-tag: 9b3fecf8-4397-4bbb-bf3c-6ac3cbbc6664