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