(nnir-run-swish++): Compressed files might not have .gz
[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 foreign 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          (setq gname (match-string 1 gname))
713        nil)
714      (if (string-match "^\\([^+]+\\)\\+\\(.+\\)$" gname)
715          (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
716        (concat gname ":"))))
717
718 ;; Summary mode commands.
719
720 (defun gnus-summary-nnir-goto-thread ()
721   "Only applies to nnir groups.  Go to group this article came from
722 and show thread that contains this article."
723   (interactive)
724   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
725     (error "Can't execute this command unless in nnir group."))
726   (let* ((cur (gnus-summary-article-number))
727          (group (nnir-artlist-artitem-group nnir-artlist cur))
728          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
729          server backend-group)
730     (setq server (nnir-group-server group))
731     (setq backend-group (gnus-group-real-name group))
732     (gnus-group-read-ephemeral-group
733      backend-group
734      (gnus-server-to-method server)
735      t                                  ; activate
736      (cons (current-buffer)
737            'summary)                    ; window config
738      nil
739      (list backend-number))
740     (gnus-summary-limit (list backend-number))
741     (gnus-summary-refer-thread)))
742
743 (if (fboundp 'eval-after-load)
744     (eval-after-load "gnus-sum"
745       '(define-key gnus-summary-goto-map
746          "T" 'gnus-summary-nnir-goto-thread))
747   (add-hook 'gnus-summary-mode-hook
748             (function (lambda ()
749                         (define-key gnus-summary-goto-map
750                           "T" 'gnus-summary-nnir-goto-thread)))))
751
752
753
754 ;; Gnus backend interface functions.
755
756 (deffoo nnir-open-server (server &optional definitions)
757   ;; Just set the server variables appropriately.
758   (nnoo-change-server 'nnir server definitions))
759
760 (deffoo nnir-request-group (group &optional server fast)
761   "GROUP is the query string."
762   (nnir-possibly-change-server server)
763   ;; Check for cache and return that if appropriate.
764   (if (and (equal group nnir-current-query)
765            (equal gnus-group-marked nnir-current-group-marked)
766            (or (null server)
767                (equal server nnir-current-server)))
768       nnir-artlist
769     ;; Cache miss.
770     (setq nnir-artlist (nnir-run-query group)))
771   (save-excursion
772     (set-buffer nntp-server-buffer)
773     (if (zerop (length nnir-artlist))
774         (progn
775           (setq nnir-current-query nil
776                 nnir-current-server nil
777                 nnir-current-group-marked nil
778                 nnir-artlist nil)
779           (nnheader-report 'nnir "Search produced empty results."))
780       ;; Remember data for cache.
781       (setq nnir-current-query group)
782       (when server (setq nnir-current-server server))
783       (setq nnir-current-group-marked gnus-group-marked)
784       (nnheader-insert "211 %d %d %d %s\n"
785                        (nnir-artlist-length nnir-artlist) ; total #
786                        1              ; first #
787                        (nnir-artlist-length nnir-artlist) ; last #
788                        group))))     ; group name
789
790 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
791   (save-excursion
792     (let ((artlist (copy-sequence articles))
793           (art nil)
794           (artitem nil)
795           (artgroup nil) (artno nil)
796           (artrsv nil)
797           (artfullgroup nil)
798           (novitem nil)
799           (novdata nil)
800           (foo nil)
801           server)
802       (while (not (null artlist))
803         (setq art (car artlist))
804         (setq artitem (nnir-artlist-article nnir-artlist art))
805         (setq artrsv (nnir-artitem-rsv artitem))
806         (setq artfullgroup (nnir-artitem-group artitem))
807         (setq artno (nnir-artitem-number artitem))
808         (setq artgroup (gnus-group-real-name artfullgroup))
809         (setq server (nnir-group-server artfullgroup))
810         ;; retrieve NOV or HEAD data for this article, transform into
811         ;; NOV data and prepend to `novdata'
812         (set-buffer nntp-server-buffer)
813         (nnir-possibly-change-server server)
814         (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
815           (nov
816            (goto-char (point-min))
817            (setq novitem (nnheader-parse-nov))
818            (unless novitem
819              (pop-to-buffer nntp-server-buffer)
820              (error
821               "nnheader-parse-nov returned nil for article %s in group %s"
822               artno artfullgroup)))
823           (headers
824            (goto-char (point-min))
825            (setq novitem (nnheader-parse-head))
826            (unless novitem
827              (pop-to-buffer nntp-server-buffer)
828              (error
829               "nnheader-parse-head returned nil for article %s in group %s"
830               artno artfullgroup)))
831           (t (nnheader-report 'nnir "Don't support header type %s." foo)))
832        ;; replace article number in original group with article number
833         ;; in nnir group
834         (mail-header-set-number novitem art)
835         (mail-header-set-from novitem
836                               (mail-header-from novitem))
837         (mail-header-set-subject
838          novitem
839          (format "[%d: %s/%d] %s"
840                  artrsv artgroup artno
841                  (mail-header-subject novitem)))
842         ;;-(mail-header-set-extra novitem nil)
843         (push novitem novdata)
844         (setq artlist (cdr artlist)))
845       (setq novdata (nreverse novdata))
846       (set-buffer nntp-server-buffer) (erase-buffer)
847       (mapcar 'nnheader-insert-nov novdata)
848       'nov)))
849
850 (deffoo nnir-request-article (article
851                               &optional group server to-buffer)
852   (save-excursion
853     (let* ((artitem (nnir-artlist-article nnir-artlist
854                                           article))
855            (artfullgroup (nnir-artitem-group artitem))
856            (artno (nnir-artitem-number artitem))
857            ;; Bug?
858            ;; Why must we bind nntp-server-buffer here?  It won't
859            ;; work if `buf' is used, say.  (Of course, the set-buffer
860            ;; line below must then be updated, too.)
861            (nntp-server-buffer (or to-buffer nntp-server-buffer)))
862       (set-buffer nntp-server-buffer)
863       (erase-buffer)
864       (message "Requesting article %d from group %s"
865                artno artfullgroup)
866       (gnus-request-article artno artfullgroup nntp-server-buffer)
867       (cons artfullgroup artno))))
868
869
870 (nnoo-define-skeleton nnir)
871
872 ;;; Search Engine Interfaces:
873
874 ;; Glimpse interface.
875 (defun nnir-run-glimpse (query server &optional group)
876   "Run given query against glimpse.  Returns a vector of (group name, file name)
877 pairs (also vectors, actually)."
878   (save-excursion
879     (let ((artlist nil)
880           (groupspec (cdr (assq 'group query)))
881           (qstring (cdr (assq 'query query)))
882           (prefix (nnir-read-server-parm 'nnir-glimpse-remove-prefix server))
883           artno dirnam)
884       (when (and group groupspec)
885         (error (concat "It does not make sense to use a group spec"
886                        " with process-marked groups.")))
887       (when group
888         (setq groupspec (gnus-group-real-name group)))
889       (set-buffer (get-buffer-create nnir-tmp-buffer))
890       (erase-buffer)
891       (if groupspec
892           (message "Doing glimpse query %s on %s..." query groupspec)
893         (message "Doing glimpse query %s..." query))
894       (let* ((cp-list
895               `( ,nnir-glimpse-program
896                  nil                    ; input from /dev/null
897                  t                      ; output
898                  nil                    ; don't redisplay
899                  "-H" ,(nnir-read-server-parm 'nnir-glimpse-home server) ; search home dir
900                  "-W"                   ; match pattern in file
901                  "-l" "-y"              ; misc options
902                  ,@(nnir-read-server-parm 'nnir-glimpse-additional-switches server)
903                  "-F" ,prefix           ; restrict output to mail
904                  ,qstring               ; the query, in glimpse format
905                  ))
906              (exitstatus
907               (progn
908                 (message "%s args: %s" nnir-glimpse-program
909                          (mapconcat 'identity (cddddr cp-list) " "))
910                 (apply 'call-process cp-list))))
911         (unless (or (null exitstatus)
912                     (zerop exitstatus))
913           (nnheader-report 'nnir "Couldn't run glimpse: %s" exitstatus)
914           ;; Glimpse failure reason is in this buffer, show it if
915           ;; the user wants it.
916           (when (> gnus-verbose 6)
917             (display-buffer nnir-tmp-buffer))))
918       (when groupspec
919         (keep-lines groupspec))
920       (if groupspec
921           (message "Doing glimpse query %s on %s...done" query groupspec)
922         (message "Doing glimpse query %s...done" query))
923       (sit-for 0)
924       ;; remove superfluous stuff from glimpse output
925       (goto-char (point-min))
926       (delete-non-matching-lines "/[0-9]+$")
927       ;;(delete-matching-lines "\\.overview~?$")
928       (goto-char (point-min))
929       (while (re-search-forward (concat "^" prefix "\\(.+\\)" "/\\([0-9]\\)+$") nil t)
930         ;; replace / with . in group names
931         (setq dirnam (substitute ?. ?/ (match-string 1))
932               artno  (match-string 2))
933         (push (vector (nnir-group-full-name dirnam server)
934                       (string-to-int artno)) artlist))
935
936       (sort* artlist
937              (function (lambda (x y)
938                          (if (string-lessp (nnir-artitem-group x)
939                                            (nnir-artitem-group y))
940                              t
941                            (< (nnir-artitem-number x)
942                               (nnir-artitem-number y))))))
943       )))
944
945 ;; freeWAIS-sf interface.
946 (defun nnir-run-waissearch (query server &optional group)
947   "Run given query agains waissearch.  Returns vector of (group name, file name)
948 pairs (also vectors, actually)."
949   (when group
950     (error "The freeWAIS-sf backend cannot search specific groups."))
951   (save-excursion
952     (let ((qstring (cdr (assq 'query query)))
953           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
954           (artlist nil)
955           (score nil) (artno nil) (dirnam nil) (group nil))
956       (set-buffer (get-buffer-create nnir-tmp-buffer))
957       (erase-buffer)
958       (message "Doing WAIS query %s..." query)
959       (call-process nnir-wais-program
960                     nil                 ; input from /dev/null
961                     t                   ; output to current buffer
962                     nil                 ; don't redisplay
963                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
964                     qstring)
965       (message "Massaging waissearch output...")
966       ;; remove superfluous lines
967       (keep-lines "Score:")
968       ;; extract data from result lines
969       (goto-char (point-min))
970       (while (re-search-forward
971               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
972         (setq score (match-string 1)
973               artno (match-string 2)
974               dirnam (match-string 3))
975         (unless (string-match prefix dirnam)
976           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
977                            dirnam prefix))
978         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
979         (push (vector (nnir-group-full-name group server)
980                       (string-to-int artno)
981                       (string-to-int score))
982               artlist))
983       (message "Massaging waissearch output...done")
984       (apply 'vector
985              (sort* artlist
986                     (function (lambda (x y)
987                                 (> (nnir-artitem-rsv x)
988                                    (nnir-artitem-rsv y)))))))))
989
990 ;; EWS (Excite for Web Servers) interface
991 (defun nnir-run-excite-search (query server &optional group)
992   "Run a given query against EWS.  Returns vector of (group name, file name)
993 pairs (also vectors, actually)."
994   (when group
995     (error "Searching specific groups not implemented for EWS."))
996   (save-excursion
997     (let ((qstring (cdr (assq 'query query)))
998           (prefix (nnir-read-server-parm 'nnir-excite-remove-prefix server))
999           artlist group article-num article)
1000       (setq nnir-current-query query)
1001       (set-buffer (get-buffer-create nnir-tmp-buffer))
1002       (erase-buffer)
1003       (message "Doing EWS query %s..." qstring)
1004       (call-process nnir-excite-aquery-program
1005                     nil                 ; input from /dev/null
1006                     t                   ; output to current buffer
1007                     nil                 ; don't redisplay
1008                     (nnir-read-server-parm 'nnir-excite-collection server)
1009                     (if (string= (substring qstring 0 1) "(")
1010                         qstring
1011                       (format "(concept %s)" qstring)))
1012       (message "Gathering query output...")
1013
1014       (goto-char (point-min))
1015       (while (re-search-forward
1016               "^[0-9]+\\s-[0-9]+\\s-[0-9]+\\s-\\(\\S-*\\)" nil t)
1017         (setq article (match-string 1))
1018         (unless (string-match
1019                  (concat "^" (regexp-quote prefix)
1020                          "\\(.*\\)/\\([0-9]+\\)") article)
1021           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
1022                            article prefix))
1023         (setq group (substitute ?. ?/ (match-string 1 article)))
1024         (setq group (nnir-group-full-name group server))
1025         (setq article-num (match-string 2 article))
1026         (setq artlist (vconcat artlist (vector (vector group
1027                                                        (string-to-int article-num)
1028                                                        1000)))))
1029       (message "Gathering query output...done")
1030       artlist)))
1031
1032 ;; IMAP interface.  The following function is Copyright (C) 1998 Simon
1033 ;; Josefsson <jas@pdc.kth.se>.
1034 ;; todo:
1035 ;; nnir invokes this two (2) times???!
1036 ;; we should not use nnimap at all but open our own server connection
1037 ;; we should not LIST * but use nnimap-list-pattern from defs
1038 ;; send queries as literals
1039 ;; handle errors
1040
1041 (defun nnir-run-imap (query srv &optional group-option)
1042   (require 'imap)
1043   (require 'nnimap)
1044   (save-excursion
1045     (let ((qstring (cdr (assq 'query query)))
1046           (server (cadr (gnus-server-to-method srv)))
1047           (group (or group-option (gnus-group-group-name)))
1048           (defs (caddr (gnus-server-to-method srv)))
1049           (criteria (or (cdr (assq 'criteria query))
1050                         nnir-imap-search-field))
1051           artlist buf)
1052       (message "Opening server %s" server)
1053       (condition-case ()
1054           (when (nnimap-open-server server defs) ;; xxx
1055             (setq buf nnimap-server-buffer) ;; xxx
1056             (message "Searching %s..." group)
1057             (let ((arts 0)
1058                   (mbx (gnus-group-real-name group)))
1059               (when (imap-mailbox-select mbx nil buf)
1060                 (mapcar
1061                  (lambda (artnum)
1062                    (push (vector group artnum 1) artlist)
1063                    (setq arts (1+ arts)))
1064                  (imap-search (concat criteria " \"" qstring "\"") buf))
1065                 (message "Searching %s... %d matches" mbx arts)))
1066             (message "Searching %s...done" group))
1067         (quit nil))
1068       (reverse artlist))))
1069
1070 ;; Swish++ interface.  The following function is Copyright (C) 2000,
1071 ;; 2001 Christoph Conrad <christoph.conrad@gmx.de>.
1072 ;; -cc- Todo
1073 ;; Search by
1074 ;; - group
1075 ;; Sort by
1076 ;; - rank (default)
1077 ;; - article number
1078 ;; - file size
1079 ;; - group
1080 (defun nnir-run-swish++ (query server &optional group)
1081   "Run given query against swish++.
1082 Returns a vector of (group name, file name) pairs (also vectors,
1083 actually).
1084
1085 Tested with swish++ 4.7 on GNU/Linux and with with swish++ 5.0b2 on
1086 Windows NT 4.0."
1087
1088   (when group
1089     (error "The swish++ backend cannot search specific groups."))
1090
1091   (save-excursion
1092     (let ( (qstring (cdr (assq 'query query)))
1093            (groupspec (cdr (assq 'group query)))
1094            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
1095            (artlist nil)
1096            (score nil) (artno nil) (dirnam nil) (group nil) )
1097
1098       (when (equal "" qstring)
1099         (error "swish++: You didn't enter anything."))
1100
1101       (set-buffer (get-buffer-create nnir-tmp-buffer))
1102       (erase-buffer)
1103
1104       (if groupspec
1105           (message "Doing swish++ query %s on %s..." qstring groupspec)
1106         (message "Doing swish++ query %s..." qstring))
1107
1108       (let* ((cp-list `( ,nnir-swish++-program
1109                          nil            ; input from /dev/null
1110                          t              ; output
1111                          nil            ; don't redisplay
1112                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1113                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1114                          ,qstring       ; the query, in swish++ format
1115                          ))
1116              (exitstatus
1117               (progn
1118                 (message "%s args: %s" nnir-swish++-program
1119                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1120                 (apply 'call-process cp-list))))
1121         (unless (or (null exitstatus)
1122                     (zerop exitstatus))
1123           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1124           ;; swish++ failure reason is in this buffer, show it if
1125           ;; the user wants it.
1126           (when (> gnus-verbose 6)
1127             (display-buffer nnir-tmp-buffer))))
1128
1129       ;; The results are output in the format of:
1130       ;; V 4.7 Linux
1131       ;; rank relative-path-name file-size file-title
1132       ;; V 5.0b2:
1133       ;; rank relative-path-name file-size topic??
1134       ;; where rank is an integer from 1 to 100.
1135       (goto-char (point-min))
1136       (while (re-search-forward
1137               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1138         (setq score (match-string 1)
1139               artno (file-name-nondirectory (match-string 2))
1140               dirnam (file-name-directory (match-string 2)))
1141
1142         ;; don't match directories
1143         (when (string-match "^[0-9]+\\(\\.[a-z0-9]+\\)?$" artno)
1144           ;; nnml-use-compressed-files might be any string, but probably this
1145           ;; is sufficient.  Note that we can't only use the value of
1146           ;; nnml-use-compressed-files because old articles might have been
1147           ;; saved with a different value.
1148           (when (not (null dirnam))
1149
1150             ;; maybe limit results to matching groups.
1151             (when (or (not groupspec)
1152                       (string-match groupspec dirnam))
1153
1154               ;; remove nnir-swish++-remove-prefix from beginning of dirname
1155               (when (string-match (concat "^" prefix)
1156                                   dirnam)
1157                 (setq dirnam (replace-match "" t t dirnam)))
1158
1159               (setq dirnam (substring dirnam 0 -1))
1160               ;; eliminate all ".", "/", "\" from beginning. Always matches.
1161               (string-match "^[./\\]*\\(.*\\)$" dirnam)
1162               ;; "/" -> "."
1163               (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1164               ;; "\\" -> "."
1165               (setq group (substitute ?. ?\\ group))
1166
1167               (push (vector (nnir-group-full-name group server)
1168                             (string-to-int artno)
1169                             (string-to-int score))
1170                     artlist)))))
1171
1172       (message "Massaging swish++ output...done")
1173
1174       ;; Sort by score
1175       (apply 'vector
1176              (sort* artlist
1177                     (function (lambda (x y)
1178                                 (> (nnir-artitem-rsv x)
1179                                    (nnir-artitem-rsv y)))))))))
1180
1181 ;; Swish-E interface.  The following function is Copyright (C) 2000,
1182 ;; 2001 by Christoph Conrad <christoph.conrad@gmx.de>.
1183 (defun nnir-run-swish-e (query server &optional group)
1184   "Run given query against swish-e.
1185 Returns a vector of (group name, file name) pairs (also vectors,
1186 actually).
1187
1188 Tested with swish-e-2.0.1 on Windows NT 4.0."
1189
1190   ;; swish-e crashes with empty parameter to "-w" on commandline...
1191   (when group
1192     (error "The swish-e backend cannot search specific groups."))
1193
1194   (save-excursion
1195     (let ((qstring (cdr (assq 'query query)))
1196           (prefix
1197            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1198                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1199           (artlist nil)
1200           (score nil) (artno nil) (dirnam nil) (group nil) )
1201
1202       (when (equal "" qstring)
1203         (error "swish-e: You didn't enter anything."))
1204
1205       (set-buffer (get-buffer-create nnir-tmp-buffer))
1206       (erase-buffer)
1207
1208       (message "Doing swish-e query %s..." query)
1209       (let* ((index-files
1210               (or (nnir-read-server-parm
1211                    'nnir-swish-e-index-files server)
1212                   (error "Missing parameter `nnir-swish-e-index-files'")))
1213              (additional-switches
1214               (nnir-read-server-parm
1215                'nnir-swish-e-additional-switches server))
1216              (cp-list `(,nnir-swish-e-program
1217                         nil             ; input from /dev/null
1218                         t               ; output
1219                         nil             ; don't redisplay
1220                         "-f" ,@index-files
1221                         ,@additional-switches
1222                         "-w"
1223                         ,qstring        ; the query, in swish-e format
1224                         ))
1225              (exitstatus
1226               (progn
1227                 (message "%s args: %s" nnir-swish-e-program
1228                          (mapconcat 'identity (cddddr cp-list) " "))
1229                 (apply 'call-process cp-list))))
1230         (unless (or (null exitstatus)
1231                     (zerop exitstatus))
1232           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1233           ;; swish-e failure reason is in this buffer, show it if
1234           ;; the user wants it.
1235           (when (> gnus-verbose 6)
1236             (display-buffer nnir-tmp-buffer))))
1237
1238       ;; The results are output in the format of:
1239       ;; rank path-name file-title file-size
1240       (goto-char (point-min))
1241       (while (re-search-forward
1242               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1243         (setq score (match-string 1)
1244               artno (match-string 3)
1245               dirnam (file-name-directory (match-string 2)))
1246
1247         ;; don't match directories
1248         (when (string-match "^[0-9]+$" artno)
1249           (when (not (null dirnam))
1250
1251             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1252             (when (string-match (concat "^" prefix) dirnam)
1253               (setq dirnam (replace-match "" t t dirnam)))
1254
1255             (setq dirnam (substring dirnam 0 -1))
1256             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1257             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1258             ;; "/" -> "."
1259             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1260             ;; Windows "\\" -> "."
1261             (setq group (substitute ?. ?\\ group))
1262
1263             (push (vector (nnir-group-full-name group server)
1264                           (string-to-int artno)
1265                           (string-to-int score))
1266                   artlist))))
1267
1268       (message "Massaging swish-e output...done")
1269
1270       ;; Sort by score
1271       (apply 'vector
1272              (sort* artlist
1273                     (function (lambda (x y)
1274                                 (> (nnir-artitem-rsv x)
1275                                    (nnir-artitem-rsv y)))))))))
1276
1277 ;; HyREX interface
1278 (defun nnir-run-hyrex (query server &optional group)
1279   (save-excursion
1280     (let ((artlist nil)
1281           (groupspec (cdr (assq 'group query)))
1282           (qstring (cdr (assq 'query query)))
1283           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1284           score artno dirnam)
1285       (when (and group groupspec)
1286         (error (concat "It does not make sense to use a group spec"
1287                        " with process-marked groups.")))
1288       (when group
1289         (setq groupspec (gnus-group-real-name group)))
1290       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1291         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1292         (error "Server with groupspec doesn't match group !"))
1293       (set-buffer (get-buffer-create nnir-tmp-buffer))
1294       (erase-buffer)
1295       (if groupspec
1296           (message "Doing hyrex-search query %s on %s..." query groupspec)
1297         (message "Doing hyrex-search query %s..." query))
1298       (let* ((cp-list
1299               `( ,nnir-hyrex-program
1300                  nil                    ; input from /dev/null
1301                  t                      ; output
1302                  nil                    ; don't redisplay
1303                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1304                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1305                  ,qstring          ; the query, in hyrex-search format
1306                  ))
1307              (exitstatus
1308               (progn
1309                 (message "%s args: %s" nnir-hyrex-program
1310                          (mapconcat 'identity (cddddr cp-list) " "))
1311                 (apply 'call-process cp-list))))
1312         (unless (or (null exitstatus)
1313                     (zerop exitstatus))
1314           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1315           ;; nnir-search failure reason is in this buffer, show it if
1316           ;; the user wants it.
1317           (when (> gnus-verbose 6)
1318             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1319       (if groupspec
1320           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1321         (message "Doing hyrex-search query \"%s\"...done" qstring))
1322       (sit-for 0)
1323       ;; nnir-search returns:
1324       ;;   for nnml/nnfolder: "filename mailid weigth"
1325       ;;   for nnimap:        "group mailid weigth"
1326       (goto-char (point-min))
1327       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1328       ;; HyREX couldn't search directly in groups -- so filter out here.
1329       (when groupspec
1330         (keep-lines groupspec))
1331       ;; extract data from result lines
1332       (goto-char (point-min))
1333       (while (re-search-forward
1334               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1335         (setq dirnam (match-string 1)
1336               artno (match-string 2)
1337               score (match-string 3))
1338         (when (string-match prefix dirnam)
1339           (setq dirnam (replace-match "" t t dirnam)))
1340         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1341                       (string-to-int artno)
1342                       (string-to-int score))
1343               artlist))
1344       (message "Massaging hyrex-search output...done.")
1345       (apply 'vector
1346              (sort* artlist
1347                     (function (lambda (x y)
1348                                 (if (string-lessp (nnir-artitem-group x)
1349                                                   (nnir-artitem-group y))
1350                                     t
1351                                   (< (nnir-artitem-number x)
1352                                      (nnir-artitem-number y)))))))
1353       )))
1354
1355 ;; Namazu interface
1356 (defun nnir-run-namazu (query server &optional group)
1357   "Run given query against Namazu.  Returns a vector of (group name, file name)
1358 pairs (also vectors, actually).
1359
1360 Tested with Namazu 2.0.6 on a GNU/Linux system."
1361   (when group
1362     (error "The Namazu backend cannot search specific groups"))
1363   (save-excursion
1364     (let (
1365           (artlist nil)
1366           (qstring (cdr (assq 'query query)))
1367           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1368           (score nil)
1369           (group nil)
1370           (article nil)
1371           (process-environment (copy-sequence process-environment))
1372           )
1373       (setenv "LC_MESSAGES" "C")
1374       (set-buffer (get-buffer-create nnir-tmp-buffer))
1375       (erase-buffer)
1376       (let* ((cp-list
1377               `( ,nnir-namazu-program
1378                  nil                    ; input from /dev/null
1379                  t                      ; output
1380                  nil                    ; don't redisplay
1381                  "-q"                   ; don't be verbose
1382                  "-a"                   ; show all matches
1383                  "-s"                   ; use short format
1384                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1385                  ,qstring               ; the query, in namazu format
1386                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1387                  ))
1388              (exitstatus
1389               (progn
1390                 (message "%s args: %s" nnir-namazu-program
1391                          (mapconcat 'identity (cddddr cp-list) " "))
1392                 (apply 'call-process cp-list))))
1393         (unless (or (null exitstatus)
1394                     (zerop exitstatus))
1395           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1396           ;; Namazu failure reason is in this buffer, show it if
1397           ;; the user wants it.
1398           (when (> gnus-verbose 6)
1399             (display-buffer nnir-tmp-buffer))))
1400
1401       ;; Namazu output looks something like this:
1402       ;; 2. Re: Gnus agent expire broken (score: 55)
1403       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1404
1405       (goto-char (point-min))
1406       (while (re-search-forward
1407               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1408               nil t)
1409         (setq score (match-string 3)
1410               group (file-name-directory (match-string 4))
1411               article (file-name-nondirectory (match-string 4)))
1412
1413         ;; make sure article and group is sane
1414         (when (and (string-match "^[0-9]+$" article)
1415                    (not (null group)))
1416           (when (string-match (concat "^" prefix) group)
1417             (setq group (replace-match "" t t group)))
1418
1419           ;; remove trailing slash from groupname
1420           (setq group (substring group 0 -1))
1421
1422           ;; stuff results into artlist vector
1423           (push (vector (nnir-group-full-name (substitute ?. ?/ group) server)
1424                         (string-to-int article)
1425                         (string-to-int score)) artlist)))
1426
1427       ;; sort artlist by score
1428       (apply 'vector
1429              (sort* artlist
1430                     (function (lambda (x y)
1431                                 (> (nnir-artitem-rsv x)
1432                                    (nnir-artitem-rsv y)))))))))
1433
1434 ;;; Util Code:
1435
1436 (defun nnir-read-parms (query)
1437   "Reads additional search parameters according to `nnir-engines'."
1438   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1439     (cons (cons 'query query)
1440           (mapcar 'nnir-read-parm parmspec))))
1441
1442 (defun nnir-read-parm (parmspec)
1443   "Reads a single search parameter.
1444 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1445   (let ((sym (car parmspec))
1446         (prompt (cdr parmspec)))
1447     (if (listp prompt)
1448         (let* ((result (apply 'completing-read prompt))
1449                (mapping (or (assoc result nnir-imap-search-arguments)
1450                             (assoc nil nnir-imap-search-arguments))))
1451           (cons sym (format (cdr mapping) result)))
1452       (cons sym (read-string prompt)))))
1453
1454 (defun nnir-run-query (query)
1455   "Invoke appropriate search engine function (see `nnir-engines').
1456 If some groups were process-marked, run the query for each of the groups
1457 and concat the results."
1458   (let ((q (car (read-from-string query))))
1459     (if gnus-group-marked
1460         (apply 'vconcat
1461                (mapcar (lambda (x)
1462                          (let ((server (nnir-group-server x))
1463                                search-func)
1464                            (setq search-func (cadr
1465                                               (assoc
1466                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1467                            (if search-func
1468                                (funcall search-func q server x)
1469                              nil)))
1470                        gnus-group-marked)
1471                )
1472       (apply 'vconcat
1473              (mapcar (lambda (x)
1474                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1475                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1476                                  search-func)
1477                              (setq search-func (cadr
1478                                                 (assoc
1479                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1480                              (if search-func
1481                                  (funcall search-func q server nil)
1482                                nil))
1483                          nil))
1484                      gnus-opened-servers)
1485              ))
1486     ))
1487
1488 (defun nnir-read-server-parm (key server)
1489   "Returns the parameter value of for the given server, where server is of
1490 form 'backend:name'."
1491   (let ((method (gnus-server-to-method server)))
1492     (cond ((and method (assq key (cddr method)))
1493            (nth 1 (assq key (cddr method))))
1494           ((and nnir-mail-backend
1495                 (gnus-server-equal method nnir-mail-backend))
1496            (symbol-value key))
1497           ((null nnir-mail-backend)
1498            (symbol-value key))
1499           (t nil))))
1500 ;;     (if method
1501 ;;       (if (assq key (cddr method))
1502 ;;        (nth 1 (assq key (cddr method)))
1503 ;;      (symbol-value key))
1504 ;;       (symbol-value key))
1505 ;;     ))
1506
1507 (defun nnir-group-full-name (shortname server)
1508   "For the given group name, return a full Gnus group name.
1509 The Gnus backend/server information is added."
1510   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1511
1512 (defun nnir-possibly-change-server (server)
1513   (unless (and server (nnir-server-opened server))
1514     (nnir-open-server server)))
1515
1516
1517 ;; Data type article list.
1518
1519 (defun nnir-artlist-length (artlist)
1520   "Returns number of articles in artlist."
1521   (length artlist))
1522
1523 (defun nnir-artlist-article (artlist n)
1524   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1525   (elt artlist (1- n)))
1526
1527 (defun nnir-artitem-group (artitem)
1528   "Returns the group from the ARTITEM."
1529   (elt artitem 0))
1530
1531 (defun nnir-artlist-artitem-group (artlist n)
1532   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1533   (nnir-artitem-group (nnir-artlist-article artlist n)))
1534
1535 (defun nnir-artitem-number (artitem)
1536   "Returns the number from the ARTITEM."
1537   (elt artitem 1))
1538
1539 (defun nnir-artlist-artitem-number (artlist n)
1540   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1541   (nnir-artitem-number (nnir-artlist-article artlist n)))
1542
1543 (defun nnir-artitem-rsv (artitem)
1544   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1545   (elt artitem 2))
1546
1547 (defun nnir-artlist-artitem-rsv (artlist n)
1548   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1549 \(counting from 1)."
1550   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1551
1552 ;; unused?
1553 (defun nnir-artlist-groups (artlist)
1554   "Returns a list of all groups in the given ARTLIST."
1555   (let ((res nil)
1556         (with-dups nil))
1557     ;; from each artitem, extract group component
1558     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1559     ;; remove duplicates from above
1560     (mapcar (function (lambda (x) (add-to-list 'res x)))
1561             with-dups)
1562     res))
1563
1564
1565 ;; The end.
1566 (provide 'nnir)
1567
1568 ;;; arch-tag: 9b3fecf8-4397-4bbb-bf3c-6ac3cbbc6664