0c5f236a2f02ddb231dda566dd0122bac5c2caf6
[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., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, 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 (defconst nnir-version "$Id: nnir.el,v 1.2 2003/09/30 21:30:34 kaig Exp $"
302   "Version of NNIR.")
303
304 (require 'cl)
305 (require 'nnoo)
306 (require 'gnus-group)
307 (require 'gnus-sum)
308 (eval-and-compile
309   (require 'gnus-util))
310 (eval-when-compile
311   (require 'nnimap)
312   (autoload 'read-kbd-macro "edmacro" nil t))
313
314 (nnoo-declare nnir)
315 (nnoo-define-basics nnir)
316
317 (gnus-declare-backend "nnir" 'mail)
318
319 (defvar nnir-imap-search-field "TEXT"
320   "The IMAP search item when doing an nnir search")
321
322 (defvar nnir-imap-search-arguments
323   '(("Whole message" . "TEXT")
324     ("Subject" . "SUBJECT")
325     ("To" . "TO")
326     ("From" . "FROM")
327     (nil . "HEADER \"%s\""))
328   "Mapping from user readable strings to IMAP search items for use in nnir")
329
330 (defvar nnir-imap-search-argument-history ()
331   "The history for querying search options in nnir")
332
333 ;;; Developer Extension Variable:
334
335 (defvar nnir-engines
336   `((glimpse nnir-run-glimpse
337              ((group . "Group spec: ")))
338     (wais    nnir-run-waissearch
339              ())
340     (excite  nnir-run-excite-search
341              ())
342     (imap    nnir-run-imap
343              ((criteria 
344                "Search in: "                      ; Prompt
345                ,nnir-imap-search-arguments        ; alist for completing
346                nil                                ; no filtering
347                nil                                ; allow any user input
348                nil                                ; initial value
349                nnir-imap-search-argument-history  ; the history to use
350                ,nnir-imap-search-field            ; default
351                )))
352     (swish++ nnir-run-swish++
353              ((group . "Group spec: ")))
354     (swish-e nnir-run-swish-e
355              ((group . "Group spec: ")))
356     (namazu  nnir-run-namazu
357              ())
358     (hyrex   nnir-run-hyrex
359              ((group . "Group spec: "))))
360   "Alist of supported search engines.
361 Each element in the alist is a three-element list (ENGINE FUNCTION ARGS).
362 ENGINE is a symbol designating the searching engine.  FUNCTION is also
363 a symbol, giving the function that does the search.  The third element
364 ARGS is a list of cons pairs (PARAM . PROMPT).  When issuing a query,
365 the FUNCTION will issue a query for each of the PARAMs, using PROMPT.
366
367 The value of `nnir-search-engine' must be one of the ENGINE symbols.
368 For example, use the following line for searching using freeWAIS-sf:
369     (setq nnir-search-engine 'wais)
370 Use the following line if you read your mail via IMAP and your IMAP
371 server supports searching:
372     (setq nnir-search-engine 'imap)
373 Note that you have to set additional variables for most backends.  For
374 example, the `wais' backend needs the variables `nnir-wais-program',
375 `nnir-wais-database' and `nnir-wais-remove-prefix'.
376
377 Add an entry here when adding a new search engine.")
378
379 ;;; User Customizable Variables:
380
381 (defgroup nnir nil
382   "Search nnmh and nnml groups in Gnus with Glimpse, freeWAIS-sf, or EWS.")
383
384 ;; Mail backend.
385
386 ;; TODO:
387 ;; If `nil', use server parameters to find out which server to search. CCC
388 ;;
389 (defcustom nnir-mail-backend '(nnml "")
390   "*Specifies which backend should be searched.
391 More precisely, this is used to determine from which backend to fetch the
392 messages found.
393
394 This must be equal to an existing server, so maybe it is best to use
395 something like the following:
396     (setq nnir-mail-backend (nth 0 gnus-secondary-select-methods))
397 The above line works fine if the mail backend you want to search is
398 the first element of gnus-secondary-select-methods (`nth' starts counting
399 at zero)."
400   :type '(sexp)
401   :group 'nnir)
402
403 ;; Search engine to use.
404
405 (defcustom nnir-search-engine 'wais
406   "*The search engine to use.  Must be a symbol.
407 See `nnir-engines' for a list of supported engines, and for example
408 settings of `nnir-search-engine'."
409   :type '(sexp)
410   :group 'nnir)
411
412 ;; Glimpse engine.
413
414 (defcustom nnir-glimpse-program "glimpse"
415   "*Name of Glimpse executable."
416   :type '(string)
417   :group 'nnir)
418
419 (defcustom nnir-glimpse-home (getenv "HOME")
420   "*Value of `-H' glimpse option.
421 `~' and environment variables must be expanded, see the functions
422 `expand-file-name' and `substitute-in-file-name'."
423   :type '(directory)
424   :group 'nnir)
425
426 (defcustom nnir-glimpse-remove-prefix (concat (getenv "HOME") "/Mail/")
427   "*The prefix to remove from each file name returned by Glimpse
428 in order to get a group name (albeit with / instead of .).  This is a
429 regular expression.
430
431 For example, suppose that Glimpse returns file names such as
432 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
433 setting:  (setq nnir-glimpse-remove-prefix \"/home/john/Mail/\")
434 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
435 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
436 arrive at the correct group name, \"mail.misc\"."
437   :type '(regexp)
438   :group 'nnir)
439
440 (defcustom nnir-glimpse-additional-switches '("-i")
441   "*A list of strings, to be given as additional arguments to glimpse.
442 The switches `-H', `-W', `-l' and `-y' are always used -- calling
443 glimpse without them does not make sense in our situation.
444 Suggested elements to put here are `-i' and `-w'.
445
446 Note that this should be a list.  Ie, do NOT use the following:
447     (setq nnir-glimpse-additional-switches \"-i -w\") ; wrong!
448 Instead, use this:
449     (setq nnir-glimpse-additional-switches '(\"-i\" \"-w\"))"
450   :type '(repeat (string))
451   :group 'nnir)
452
453 ;; freeWAIS-sf.
454
455 (defcustom nnir-wais-program "waissearch"
456   "*Name of waissearch executable."
457   :type '(string)
458   :group 'nnir)
459
460 (defcustom nnir-wais-database (expand-file-name "~/.wais/mail")
461   "*Name of Wais database containing the mail.
462
463 Note that this should be a file name without extension.  For example,
464 if you have a file /home/john/.wais/mail.fmt, use this:
465     (setq nnir-wais-database \"/home/john/.wais/mail\")
466 The string given here is passed to `waissearch -d' as-is."
467   :type '(file)
468   :group 'nnir)
469
470 (defcustom nnir-wais-remove-prefix (concat (getenv "HOME") "/Mail/")
471   "*The prefix to remove from each directory name returned by waissearch
472 in order to get a group name (albeit with / instead of .).  This is a
473 regular expression.
474
475 This variable is similar to `nnir-glimpse-remove-prefix', only for Wais,
476 not Glimpse."
477   :type '(regexp)
478   :group 'nnir)
479
480 ;; EWS (Excite for Web Servers) engine.
481
482 (defcustom nnir-excite-aquery-program "aquery.pl"
483   "*Name of the EWS query program.  Should be `aquery.pl' or a path to same."
484   :type '(string)
485   :group 'nnir)
486
487 (defcustom nnir-excite-collection "Mail"
488   "*Name of the EWS collection to search."
489   :type '(string)
490   :group 'nnir)
491
492 (defcustom nnir-excite-remove-prefix (concat (getenv "HOME") "/Mail/")
493   "*The prefix to remove from each file name returned by EWS
494 in order to get a group name (albeit with / instead of .).  This is a
495 regular expression.
496
497 This variable is very similar to `nnir-glimpse-remove-prefix', except
498 that it is for EWS, not Glimpse."
499   :type '(regexp)
500   :group 'nnir)
501
502 ;; Swish++.  Next three variables Copyright (C) 2000, 2001 Christoph
503 ;; Conrad <christoph.conrad@gmx.de>.
504 ;; Swish++ home page: http://homepage.mac.com/pauljlucas/software/swish/
505
506 (defcustom nnir-swish++-configuration-file
507   (expand-file-name "~/Mail/swish++.conf")
508   "*Configuration file for swish++."
509   :type '(file)
510   :group 'nnir)
511
512 (defcustom nnir-swish++-program "search"
513   "*Name of swish++ search executable."
514   :type '(string)
515   :group 'nnir)
516
517 (defcustom nnir-swish++-additional-switches '()
518   "*A list of strings, to be given as additional arguments to swish++.
519
520 Note that this should be a list.  Ie, do NOT use the following:
521     (setq nnir-swish++-additional-switches \"-i -w\") ; wrong
522 Instead, use this:
523     (setq nnir-swish++-additional-switches '(\"-i\" \"-w\"))"
524   :type '(repeat (string))
525   :group 'nnir)
526
527 (defcustom nnir-swish++-remove-prefix (concat (getenv "HOME") "/Mail/")
528   "*The prefix to remove from each file name returned by swish++
529 in order to get a group name (albeit with / instead of .).  This is a
530 regular expression.
531
532 This variable is very similar to `nnir-glimpse-remove-prefix', except
533 that it is for swish++, not Glimpse."
534   :type '(regexp)
535   :group 'nnir)
536
537 ;; Swish-E.  Next three variables Copyright (C) 2000 Christoph Conrad
538 ;; <christoph.conrad@gmx.de>.
539 ;; URL: http://sunsite.berkeley.edu/SWISH-E/
540 ;; New version: http://www.boe.es/swish-e
541
542 (defcustom nnir-swish-e-index-file
543   (expand-file-name "~/Mail/index.swish-e")
544   "*Index file for swish-e.
545 This could be a server parameter."
546   :type '(file)
547   :group 'nnir)
548
549 (defcustom nnir-swish-e-program "swish-e"
550   "*Name of swish-e search executable.
551 This cannot be a server parameter."
552   :type '(string)
553   :group 'nnir)
554
555 (defcustom nnir-swish-e-additional-switches '()
556   "*A list of strings, to be given as additional arguments to swish-e.
557
558 Note that this should be a list.  Ie, do NOT use the following:
559     (setq nnir-swish-e-additional-switches \"-i -w\") ; wrong
560 Instead, use this:
561     (setq nnir-swish-e-additional-switches '(\"-i\" \"-w\"))
562
563 This could be a server parameter."
564   :type '(repeat (string))
565   :group 'nnir)
566
567 (defcustom nnir-swish-e-remove-prefix (concat (getenv "HOME") "/Mail/")
568   "*The prefix to remove from each file name returned by swish-e
569 in order to get a group name (albeit with / instead of .).  This is a
570 regular expression.
571
572 This variable is very similar to `nnir-glimpse-remove-prefix', except
573 that it is for swish-e, not Glimpse.
574
575 This could be a server parameter."
576   :type '(regexp)
577   :group 'nnir)
578
579 ;; HyREX engine, see <URL:http://ls6-www.cs.uni-dortmund.de/>
580
581 (defcustom nnir-hyrex-program "nnir-search"
582   "*Name of the nnir-search executable."
583   :type '(string)
584   :group 'nnir)
585
586 (defcustom nnir-hyrex-additional-switches '()
587   "*A list of strings, to be given as additional arguments for nnir-search.
588 Note that this should be a list. Ie, do NOT use the following:
589     (setq nnir-hyrex-additional-switches \"-ddl ddl.xml -c nnir\") ; wrong !
590 Instead, use this:
591     (setq nnir-hyrex-additional-switches '(\"-ddl\" \"ddl.xml\" \"-c\" \"nnir\"))"
592   :type '(repeat (string))
593   :group 'nnir)
594
595 (defcustom nnir-hyrex-index-directory (getenv "HOME")
596   "*Index directory for HyREX."
597   :type '(directory)
598   :group 'nnir)
599
600 (defcustom nnir-hyrex-remove-prefix (concat (getenv "HOME") "/Mail/")
601   "*The prefix to remove from each file name returned by HyREX
602 in order to get a group name (albeit with / instead of .).
603
604 For example, suppose that HyREX returns file names such as
605 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
606 setting:  (setq nnir-hyrex-remove-prefix \"/home/john/Mail/\")
607 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
608 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
609 arrive at the correct group name, \"mail.misc\"."
610   :type '(directory)
611   :group 'nnir)
612
613 ;; Namazu engine, see <URL:http://ww.namazu.org/>
614
615 (defcustom nnir-namazu-program "namazu"
616   "*Name of Namazu search executable."
617   :type '(string)
618   :group 'nnir)
619
620 (defcustom nnir-namazu-index-directory (expand-file-name "~/Mail/namazu/")
621   "*Index directory for Namazu."
622   :type '(directory)
623   :group 'nnir)
624
625 (defcustom nnir-namazu-additional-switches '()
626   "*A list of strings, to be given as additional arguments to namazu.
627 The switches `-q', `-a', and `-s' are always used, very few other switches
628 make any sense in this context.
629
630 Note that this should be a list.  Ie, do NOT use the following:
631     (setq nnir-namazu-additional-switches \"-i -w\") ; wrong
632 Instead, use this:
633     (setq nnir-namazu-additional-switches '(\"-i\" \"-w\"))"
634   :type '(repeat (string))
635   :group 'nnir)
636
637 (defcustom nnir-namazu-remove-prefix (concat (getenv "HOME") "/Mail/")
638   "*The prefix to remove from each file name returned by Namazu
639 in order to get a group name (albeit with / instead of .).
640
641 This variable is very similar to `nnir-glimpse-remove-prefix', except
642 that it is for Namazu, not Glimpse."
643   :type '(directory)
644   :group 'nnir)
645
646 ;;; Internal Variables:
647
648 (defvar nnir-current-query nil
649   "Internal: stores current query (= group name).")
650
651 (defvar nnir-current-server nil
652   "Internal: stores current server (does it ever change?).")
653
654 (defvar nnir-current-group-marked nil
655   "Internal: stores current list of process-marked groups.")
656
657 (defvar nnir-artlist nil
658   "Internal: stores search result.")
659
660 (defvar nnir-tmp-buffer " *nnir*"
661   "Internal: temporary buffer.")
662
663 ;;; Code:
664
665 ;; Gnus glue.
666
667 (defun gnus-group-make-nnir-group (extra-parms query)
668   "Create an nnir group.  Asks for query."
669   (interactive "P\nsQuery: ")
670   (setq nnir-current-query nil
671         nnir-current-server nil
672         nnir-current-group-marked nil
673         nnir-artlist nil)
674   (let ((parms nil))
675     (if extra-parms
676         (setq parms (nnir-read-parms query))
677       (setq parms (list (cons 'query query))))
678     (gnus-group-read-ephemeral-group
679      (concat "nnir:" (prin1-to-string parms)) '(nnir "") t
680      (cons (current-buffer)
681            gnus-current-window-configuration)
682      nil)))
683
684 ;; Emacs 19 compatibility?
685 (or (fboundp 'kbd) (defalias 'kbd 'read-kbd-macro))
686
687 (defun nnir-group-mode-hook ()
688   (define-key gnus-group-mode-map
689     (if (fboundp 'read-kbd-macro)
690         (kbd "G G")
691       "GG")                             ; XEmacs 19 compat
692     'gnus-group-make-nnir-group))
693 (add-hook 'gnus-group-mode-hook 'nnir-group-mode-hook)
694
695
696
697 ;; Summary mode commands.
698
699 (defun gnus-summary-nnir-goto-thread ()
700   "Only applies to nnir groups.  Go to group this article came from
701 and show thread that contains this article."
702   (interactive)
703   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
704     (error "Can't execute this command unless in nnir group."))
705   (let* ((cur (gnus-summary-article-number))
706          (group (nnir-artlist-artitem-group nnir-artlist cur))
707          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
708          server backend-group)
709     (setq server (nnir-group-server group))
710     (setq backend-group (gnus-group-real-name group))
711     (gnus-group-read-ephemeral-group
712      backend-group
713      (gnus-server-to-method server)
714      t                                  ; activate
715      (cons (current-buffer)
716            'summary)                    ; window config
717      nil
718      (list backend-number))
719     (gnus-summary-limit (list backend-number))
720     (gnus-summary-refer-thread)))
721
722 (if (fboundp 'eval-after-load)
723     (eval-after-load "gnus-sum"
724       '(define-key gnus-summary-goto-map
725          "T" 'gnus-summary-nnir-goto-thread))
726   (add-hook 'gnus-summary-mode-hook
727             (function (lambda ()
728                         (define-key gnus-summary-goto-map
729                           "T" 'gnus-summary-nnir-goto-thread)))))
730
731
732
733 ;; Gnus backend interface functions.
734
735 (deffoo nnir-open-server (server &optional definitions)
736   ;; Just set the server variables appropriately.
737   (nnoo-change-server 'nnir server definitions))
738
739 (deffoo nnir-request-group (group &optional server fast)
740   "GROUP is the query string."
741   (nnir-possibly-change-server server)
742   ;; Check for cache and return that if appropriate.
743   (if (and (equal group nnir-current-query)
744            (equal gnus-group-marked nnir-current-group-marked)
745            (or (null server)
746                (equal server nnir-current-server)))
747       nnir-artlist
748     ;; Cache miss.
749     (setq nnir-artlist (nnir-run-query group)))
750   (save-excursion
751     (set-buffer nntp-server-buffer)
752     (if (zerop (length nnir-artlist))
753         (progn
754           (setq nnir-current-query nil
755                 nnir-current-server nil
756                 nnir-current-group-marked nil
757                 nnir-artlist nil)
758           (nnheader-report 'nnir "Search produced empty results."))
759       ;; Remember data for cache.
760       (setq nnir-current-query group)
761       (when server (setq nnir-current-server server))
762       (setq nnir-current-group-marked gnus-group-marked)
763       (nnheader-insert "211 %d %d %d %s\n"
764                        (nnir-artlist-length nnir-artlist) ; total #
765                        1              ; first #
766                        (nnir-artlist-length nnir-artlist) ; last #
767                        group))))     ; group name
768
769 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
770   (save-excursion
771     (let ((artlist (copy-sequence articles))
772           (idx 1)
773           (art nil)
774           (artitem nil)
775           (artgroup nil) (artno nil)
776           (artrsv nil)
777           (artfullgroup nil)
778           (novitem nil)
779           (novdata nil)
780           (foo nil)
781           server)
782       (while (not (null artlist))
783         (setq art (car artlist))
784         (or (numberp art)
785             (nnheader-report
786              'nnir
787              "nnir-retrieve-headers doesn't grok message ids: %s"
788              art))
789         (setq artitem (nnir-artlist-article nnir-artlist art))
790         (setq artrsv (nnir-artitem-rsv artitem))
791         (setq artfullgroup (nnir-artitem-group artitem))
792         (setq artno (nnir-artitem-number artitem))
793         (setq artgroup (gnus-group-real-name artfullgroup))
794         (setq server (nnir-group-server artfullgroup))
795         ;; retrieve NOV or HEAD data for this article, transform into
796         ;; NOV data and prepend to `novdata'
797         (set-buffer nntp-server-buffer)
798         (nnir-possibly-change-server server)
799         (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
800           (nov
801            (goto-char (point-min))
802            (setq novitem (nnheader-parse-nov))
803            (unless novitem
804              (pop-to-buffer nntp-server-buffer)
805              (error
806               "nnheader-parse-nov returned nil for article %s in group %s"
807               artno artfullgroup)))
808           (headers
809            (goto-char (point-min))
810            (setq novitem (nnheader-parse-head))
811            (unless novitem
812              (pop-to-buffer nntp-server-buffer)
813              (error
814               "nnheader-parse-head returned nil for article %s in group %s"
815               artno artfullgroup)))
816           (t (nnheader-report 'nnir "Don't support header type %s." foo)))
817        ;; replace article number in original group with article number
818         ;; in nnir group
819         (mail-header-set-number novitem idx)
820         (mail-header-set-from novitem
821                               (mail-header-from novitem))
822         (mail-header-set-subject
823          novitem
824          (format "[%d: %s/%d] %s"
825                  artrsv artgroup artno
826                  (mail-header-subject novitem)))
827         ;;-(mail-header-set-extra novitem nil)
828         (push novitem novdata)
829         (setq artlist (cdr artlist))
830         (setq idx (1+ idx)))
831       (setq novdata (nreverse novdata))
832       (set-buffer nntp-server-buffer) (erase-buffer)
833       (mapcar 'nnheader-insert-nov novdata)
834       'nov)))
835
836 (deffoo nnir-request-article (article
837                               &optional group server to-buffer)
838   (save-excursion
839     (let* ((artitem (nnir-artlist-article nnir-artlist
840                                           article))
841            (artfullgroup (nnir-artitem-group artitem))
842            (artno (nnir-artitem-number artitem))
843            ;; Bug?
844            ;; Why must we bind nntp-server-buffer here?  It won't
845            ;; work if `buf' is used, say.  (Of course, the set-buffer
846            ;; line below must then be updated, too.)
847            (nntp-server-buffer (or to-buffer nntp-server-buffer)))
848       (set-buffer nntp-server-buffer)
849       (erase-buffer)
850       (message "Requesting article %d from group %s"
851                artno artfullgroup)
852       (gnus-request-article artno artfullgroup nntp-server-buffer)
853       (cons artfullgroup artno))))
854
855
856 (nnoo-define-skeleton nnir)
857
858 ;;; Search Engine Interfaces:
859
860 ;; Glimpse interface.
861 (defun nnir-run-glimpse (query server &optional group)
862   "Run given query against glimpse.  Returns a vector of (group name, file name)
863 pairs (also vectors, actually)."
864   (save-excursion
865     (let ((artlist nil)
866           (groupspec (cdr (assq 'group query)))
867           (qstring (cdr (assq 'query query)))
868           (prefix (nnir-read-server-parm 'nnir-glimps-remove-prefix server))
869           artno dirnam)
870       (when (and group groupspec)
871         (error (concat "It does not make sense to use a group spec"
872                        " with process-marked groups.")))
873       (when group
874         (setq groupspec (gnus-group-real-name group)))
875       (set-buffer (get-buffer-create nnir-tmp-buffer))
876       (erase-buffer)
877       (if groupspec
878           (message "Doing glimpse query %s on %s..." query groupspec)
879         (message "Doing glimpse query %s..." query))
880       (let* ((cp-list
881               `( ,nnir-glimpse-program
882                  nil                    ; input from /dev/null
883                  t                      ; output
884                  nil                    ; don't redisplay
885                  "-H" ,(nnir-read-server-parm 'nnir-glimpse-home server) ; search home dir
886                  "-W"                   ; match pattern in file
887                  "-l" "-y"              ; misc options
888                  ,@(nnir-read-server-parm 'nnir-glimpse-additional-switches server)
889                  "-F" ,prefix           ; restrict output to mail
890                  ,qstring               ; the query, in glimpse format
891                  ))
892              (exitstatus
893               (progn
894                 (message "%s args: %s" nnir-glimpse-program
895                          (mapconcat 'identity (cddddr cp-list) " "))
896                 (apply 'call-process cp-list))))
897         (unless (or (null exitstatus)
898                     (zerop exitstatus))
899           (nnheader-report 'nnir "Couldn't run glimpse: %s" exitstatus)
900           ;; Glimpse failure reason is in this buffer, show it if
901           ;; the user wants it.
902           (when (> gnus-verbose 6)
903             (display-buffer nnir-tmp-buffer))))
904       (when groupspec
905         (keep-lines groupspec))
906       (if groupspec
907           (message "Doing glimpse query %s on %s...done" query groupspec)
908         (message "Doing glimpse query %s...done" query))
909       (sit-for 0)
910       ;; remove superfluous stuff from glimpse output
911       (goto-char (point-min))
912       (delete-non-matching-lines "/[0-9]+$")
913       ;;(delete-matching-lines "\\.overview~?$")
914       (goto-char (point-min))
915       (while (re-search-forward (concat "^" prefix "\\(.+\\)" "/\\([0-9]\\)+$") nil t)
916         ;; replace / with . in group names
917         (setq dirnam (substitute ?. ?/ (match-string 1))
918               artno  (match-string 2))
919         (push (vector (nnir-group-full-name dirnam server)
920                       (string-to-int artno)) artlist))
921
922       (sort* artlist
923              (function (lambda (x y)
924                          (if (string-lessp (nnir-artitem-group x)
925                                            (nnir-artitem-group y))
926                              t
927                            (< (nnir-artitem-number x)
928                               (nnir-artitem-number y))))))
929       )))
930
931 ;; freeWAIS-sf interface.
932 (defun nnir-run-waissearch (query server &optional group)
933   "Run given query agains waissearch.  Returns vector of (group name, file name)
934 pairs (also vectors, actually)."
935   (when group
936     (error "The freeWAIS-sf backend cannot search specific groups."))
937   (save-excursion
938     (let ((qstring (cdr (assq 'query query)))
939           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
940           (artlist nil)
941           (score nil) (artno nil) (dirnam nil) (group nil))
942       (set-buffer (get-buffer-create nnir-tmp-buffer))
943       (erase-buffer)
944       (message "Doing WAIS query %s..." query)
945       (call-process nnir-wais-program
946                     nil                 ; input from /dev/null
947                     t                   ; output to current buffer
948                     nil                 ; don't redisplay
949                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
950                     qstring)
951       (message "Massaging waissearch output...")
952       ;; remove superfluous lines
953       (keep-lines "Score:")
954       ;; extract data from result lines
955       (goto-char (point-min))
956       (while (re-search-forward
957               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
958         (setq score (match-string 1)
959               artno (match-string 2)
960               dirnam (match-string 3))
961         (unless (string-match prefix dirnam)
962           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
963                            dirnam prefix))
964         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
965         (push (vector (nnir-group-full-name group server)
966                       (string-to-int artno)
967                       (string-to-int score))
968               artlist))
969       (message "Massaging waissearch output...done")
970       (apply 'vector
971              (sort* artlist
972                     (function (lambda (x y)
973                                 (> (nnir-artitem-rsv x)
974                                    (nnir-artitem-rsv y)))))))))
975
976 ;; EWS (Excite for Web Servers) interface
977 (defun nnir-run-excite-search (query server &optional group)
978   "Run a given query against EWS.  Returns vector of (group name, file name)
979 pairs (also vectors, actually)."
980   (when group
981     (error "Searching specific groups not implemented for EWS."))
982   (save-excursion
983     (let ((qstring (cdr (assq 'query query)))
984           (prefix (nnir-read-server-parm 'nnir-excite-remove-prefix server))
985           artlist group article-num article)
986       (setq nnir-current-query query)
987       (set-buffer (get-buffer-create nnir-tmp-buffer))
988       (erase-buffer)
989       (message "Doing EWS query %s..." qstring)
990       (call-process nnir-excite-aquery-program
991                     nil                 ; input from /dev/null
992                     t                   ; output to current buffer
993                     nil                 ; don't redisplay
994                     (nnir-read-server-parm 'nnir-excite-collection server)
995                     (if (string= (substring qstring 0 1) "(")
996                         qstring
997                       (format "(concept %s)" qstring)))
998       (message "Gathering query output...")
999
1000       (goto-char (point-min))
1001       (while (re-search-forward
1002               "^[0-9]+\\s-[0-9]+\\s-[0-9]+\\s-\\(\\S-*\\)" nil t)
1003         (setq article (match-string 1))
1004         (unless (string-match
1005                  (concat "^" (regexp-quote prefix)
1006                          "\\(.*\\)/\\([0-9]+\\)") article)
1007           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
1008                            article prefix))
1009         (setq group (substitute ?. ?/ (match-string 1 article)))
1010         (setq group (nnir-group-full-name group server))
1011         (setq article-num (match-string 2 article))
1012         (setq artlist (vconcat artlist (vector (vector group
1013                                                        (string-to-int article-num)
1014                                                        1000)))))
1015       (message "Gathering query output...done")
1016       artlist)))
1017
1018 ;; IMAP interface.  The following function is Copyright (C) 1998 Simon
1019 ;; Josefsson <jas@pdc.kth.se>.
1020 ;; todo:
1021 ;; nnir invokes this two (2) times???!
1022 ;; we should not use nnimap at all but open our own server connection
1023 ;; we should not LIST * but use nnimap-list-pattern from defs
1024 ;; send queries as literals
1025 ;; handle errors
1026
1027 (defun nnir-run-imap (query srv &optional group-option)
1028   (require 'imap)
1029   (require 'nnimap)
1030   (save-excursion
1031     (let ((qstring (cdr (assq 'query query)))
1032           (server (cadr (gnus-server-to-method srv)))
1033           (group (or group-option (gnus-group-group-name)))
1034           (defs (caddr (gnus-server-to-method srv)))
1035           (criteria (or (cdr (assq 'criteria query))
1036                         nnir-imap-search-field))
1037           artlist buf)
1038       (message "Opening server %s" server)
1039       (condition-case ()
1040           (when (nnimap-open-server server defs) ;; xxx
1041             (setq buf nnimap-server-buffer) ;; xxx
1042             (message "Searching %s..." group)
1043             (let ((arts 0)
1044                   (mbx (gnus-group-real-name group)))
1045               (when (imap-mailbox-select mbx nil buf)
1046                 (mapcar
1047                  (lambda (artnum)
1048                    (push (vector group artnum 1) artlist)
1049                    (setq arts (1+ arts)))
1050                  (imap-search (concat criteria " \"" qstring "\"") buf))
1051                 (message "Searching %s... %d matches" mbx arts)))
1052             (message "Searching %s...done" group))
1053         (quit nil))
1054       (reverse artlist))))
1055
1056 ;; Swish++ interface.  The following function is Copyright (C) 2000,
1057 ;; 2001 Christoph Conrad <christoph.conrad@gmx.de>.
1058 ;; -cc- Todo
1059 ;; Search by
1060 ;; - group
1061 ;; Sort by
1062 ;; - rank (default)
1063 ;; - article number
1064 ;; - file size
1065 ;; - group
1066 (defun nnir-run-swish++ (query server &optional group)
1067   "Run given query against swish++.
1068 Returns a vector of (group name, file name) pairs (also vectors,
1069 actually).
1070
1071 Tested with swish++ 4.7 on GNU/Linux and with with swish++ 5.0b2 on
1072 Windows NT 4.0."
1073
1074   (when group
1075     (error "The swish++ backend cannot search specific groups."))
1076
1077   (save-excursion
1078     (let ( (qstring (cdr (assq 'query query)))
1079            (groupspec (cdr (assq 'group query)))
1080            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
1081            (artlist nil)
1082            (score nil) (artno nil) (dirnam nil) (group nil) )
1083
1084       (when (equal "" qstring)
1085         (error "swish++: You didn't enter anything."))
1086
1087       (set-buffer (get-buffer-create nnir-tmp-buffer))
1088       (erase-buffer)
1089
1090       (if groupspec
1091           (message "Doing swish++ query %s on %s..." qstring groupspec)
1092         (message "Doing swish++ query %s..." qstring))
1093
1094       (let* ((cp-list `( ,nnir-swish++-program
1095                          nil            ; input from /dev/null
1096                          t              ; output
1097                          nil            ; don't redisplay
1098                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1099                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1100                          ,qstring       ; the query, in swish++ format
1101                          ))
1102              (exitstatus
1103               (progn
1104                 (message "%s args: %s" nnir-swish++-program
1105                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1106                 (apply 'call-process cp-list))))
1107         (unless (or (null exitstatus)
1108                     (zerop exitstatus))
1109           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1110           ;; swish++ failure reason is in this buffer, show it if
1111           ;; the user wants it.
1112           (when (> gnus-verbose 6)
1113             (display-buffer nnir-tmp-buffer))))
1114
1115       ;; The results are output in the format of:
1116       ;; V 4.7 Linux
1117       ;; rank relative-path-name file-size file-title
1118       ;; V 5.0b2:
1119       ;; rank relative-path-name file-size topic??
1120       ;; where rank is an integer from 1 to 100.
1121       (goto-char (point-min))
1122       (while (re-search-forward
1123               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1124         (setq score (match-string 1)
1125               artno (file-name-nondirectory (match-string 2))
1126               dirnam (file-name-directory (match-string 2)))
1127
1128         ;; don't match directories
1129         (when (string-match "^[0-9]+$" artno)
1130           (when (not (null dirnam))
1131
1132             ;; maybe limit results to matching groups.
1133             (when (or (not groupspec)
1134                       (string-match groupspec dirnam))
1135
1136               ;; remove nnir-swish++-remove-prefix from beginning of dirname
1137               (when (string-match (concat "^" prefix)
1138                                   dirnam)
1139                 (setq dirnam (replace-match "" t t dirnam)))
1140
1141               (setq dirnam (substring dirnam 0 -1))
1142               ;; eliminate all ".", "/", "\" from beginning. Always matches.
1143               (string-match "^[./\\]*\\(.*\\)$" dirnam)
1144               ;; "/" -> "."
1145               (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1146               ;; "\\" -> "."
1147               (setq group (substitute ?. ?\\ group))
1148
1149               (push (vector (nnir-group-full-name group server)
1150                             (string-to-int artno)
1151                             (string-to-int score))
1152                     artlist)))))
1153
1154       (message "Massaging swish++ output...done")
1155
1156       ;; Sort by score
1157       (apply 'vector
1158              (sort* artlist
1159                     (function (lambda (x y)
1160                                 (> (nnir-artitem-rsv x)
1161                                    (nnir-artitem-rsv y)))))))))
1162
1163 ;; Swish-E interface.  The following function is Copyright (C) 2000,
1164 ;; 2001 by Christoph Conrad <christoph.conrad@gmx.de>.
1165 (defun nnir-run-swish-e (query server &optional group)
1166   "Run given query against swish-e.
1167 Returns a vector of (group name, file name) pairs (also vectors,
1168 actually).
1169
1170 Tested with swish-e-2.0.1 on Windows NT 4.0."
1171
1172   ;; swish-e crashes with empty parameter to "-w" on commandline...
1173   (when group
1174     (error "The swish-e backend cannot search specific groups."))
1175
1176   (save-excursion
1177     (let ((qstring (cdr (assq 'query query)))
1178           (prefix
1179            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1180                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1181           (artlist nil)
1182           (score nil) (artno nil) (dirnam nil) (group nil) )
1183
1184       (when (equal "" qstring)
1185         (error "swish-e: You didn't enter anything."))
1186
1187       (set-buffer (get-buffer-create nnir-tmp-buffer))
1188       (erase-buffer)
1189
1190       (message "Doing swish-e query %s..." query)
1191       (let* ((index-file
1192               (or (nnir-read-server-parm
1193                    'nnir-swish-e-index-file server)
1194                   (error "Missing parameter `nnir-swish-e-index-file'")))
1195              (additional-switches
1196               (nnir-read-server-parm
1197                'nnir-swish++-additional-switches server))
1198              (cp-list `(,nnir-swish-e-program
1199                         nil             ; input from /dev/null
1200                         t               ; output
1201                         nil             ; don't redisplay
1202                         "-f" ,index-file
1203                         ,@additional-switches
1204                         "-w"
1205                         ,qstring        ; the query, in swish-e format
1206                         ))
1207              (exitstatus
1208               (progn
1209                 (message "%s args: %s" nnir-swish-e-program
1210                          (mapconcat 'identity (cddddr cp-list) " "))
1211                 (apply 'call-process cp-list))))
1212         (unless (or (null exitstatus)
1213                     (zerop exitstatus))
1214           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1215           ;; swish-e failure reason is in this buffer, show it if
1216           ;; the user wants it.
1217           (when (> gnus-verbose 6)
1218             (display-buffer nnir-tmp-buffer))))
1219
1220       ;; The results are output in the format of:
1221       ;; rank path-name file-title file-size
1222       (goto-char (point-min))
1223       (while (re-search-forward
1224               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1225         (setq score (match-string 1)
1226               artno (match-string 3)
1227               dirnam (file-name-directory (match-string 2)))
1228
1229         ;; don't match directories
1230         (when (string-match "^[0-9]+$" artno)
1231           (when (not (null dirnam))
1232
1233             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1234             (when (string-match (concat "^" prefix) dirnam)
1235               (setq dirnam (replace-match "" t t dirnam)))
1236
1237             (setq dirnam (substring dirnam 0 -1))
1238             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1239             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1240             ;; "/" -> "."
1241             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1242             ;; Windows "\\" -> "."
1243             (setq group (substitute ?. ?\\ group))
1244
1245             (push (vector (nnir-group-full-name group server)
1246                           (string-to-int artno)
1247                           (string-to-int score))
1248                   artlist))))
1249
1250       (message "Massaging swish-e output...done")
1251
1252       ;; Sort by score
1253       (apply 'vector
1254              (sort* artlist
1255                     (function (lambda (x y)
1256                                 (> (nnir-artitem-rsv x)
1257                                    (nnir-artitem-rsv y)))))))))
1258
1259 ;; HyREX interface
1260 (defun nnir-run-hyrex (query server &optional group)
1261   (save-excursion
1262     (let ((artlist nil)
1263           (groupspec (cdr (assq 'group query)))
1264           (qstring (cdr (assq 'query query)))
1265           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1266           score artno dirnam)
1267       (when (and group groupspec)
1268         (error (concat "It does not make sense to use a group spec"
1269                        " with process-marked groups.")))
1270       (when group
1271         (setq groupspec (gnus-group-real-name group)))
1272       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1273         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1274         (error "Server with groupspec doesn't match group !"))
1275       (set-buffer (get-buffer-create nnir-tmp-buffer))
1276       (erase-buffer)
1277       (if groupspec
1278           (message "Doing hyrex-search query %s on %s..." query groupspec)
1279         (message "Doing hyrex-search query %s..." query))
1280       (let* ((cp-list
1281               `( ,nnir-hyrex-program
1282                  nil                    ; input from /dev/null
1283                  t                      ; output
1284                  nil                    ; don't redisplay
1285                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1286                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1287                  ,qstring          ; the query, in hyrex-search format
1288                  ))
1289              (exitstatus
1290               (progn
1291                 (message "%s args: %s" nnir-hyrex-program
1292                          (mapconcat 'identity (cddddr cp-list) " "))
1293                 (apply 'call-process cp-list))))
1294         (unless (or (null exitstatus)
1295                     (zerop exitstatus))
1296           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1297           ;; nnir-search failure reason is in this buffer, show it if
1298           ;; the user wants it.
1299           (when (> gnus-verbose 6)
1300             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1301       (if groupspec
1302           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1303         (message "Doing hyrex-search query \"%s\"...done" qstring))
1304       (sit-for 0)
1305       ;; nnir-search returns:
1306       ;;   for nnml/nnfolder: "filename mailid weigth"
1307       ;;   for nnimap:        "group mailid weigth"
1308       (goto-char (point-min))
1309       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1310       ;; HyREX couldn't search directly in groups -- so filter out here.
1311       (when groupspec
1312         (keep-lines groupspec))
1313       ;; extract data from result lines
1314       (goto-char (point-min))
1315       (while (re-search-forward
1316               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1317         (setq dirnam (match-string 1)
1318               artno (match-string 2)
1319               score (match-string 3))
1320         (when (string-match prefix dirnam)
1321           (setq dirnam (replace-match "" t t dirnam)))
1322         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1323                       (string-to-int artno)
1324                       (string-to-int score))
1325               artlist))
1326       (message "Massaging hyrex-search output...done.")
1327       (apply 'vector
1328              (sort* artlist
1329                     (function (lambda (x y)
1330                                 (if (string-lessp (nnir-artitem-group x)
1331                                                   (nnir-artitem-group y))
1332                                     t
1333                                   (< (nnir-artitem-number x)
1334                                      (nnir-artitem-number y)))))))
1335       )))
1336
1337 ;; Namazu interface
1338 (defun nnir-run-namazu (query server &optional group)
1339   "Run given query against Namazu.  Returns a vector of (group name, file name)
1340 pairs (also vectors, actually).
1341
1342 Tested with Namazu 2.0.6 on a GNU/Linux system."
1343   (when group
1344     (error "The Namazu backend cannot search specific groups"))
1345   (save-excursion
1346     (let (
1347           (artlist nil)
1348           (qstring (cdr (assq 'query query)))
1349           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1350           (score nil)
1351           (group nil)
1352           (article nil)
1353           (process-environment (copy-sequence process-environment))
1354           )
1355       (setenv "LC_MESSAGES" "C")
1356       (set-buffer (get-buffer-create nnir-tmp-buffer))
1357       (erase-buffer)
1358       (let* ((cp-list
1359               `( ,nnir-namazu-program
1360                  nil                    ; input from /dev/null
1361                  t                      ; output
1362                  nil                    ; don't redisplay
1363                  "-q"                   ; don't be verbose
1364                  "-a"                   ; show all matches
1365                  "-s"                   ; use short format
1366                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1367                  ,qstring               ; the query, in namazu format
1368                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1369                  ))
1370              (exitstatus
1371               (progn
1372                 (message "%s args: %s" nnir-namazu-program
1373                          (mapconcat 'identity (cddddr cp-list) " "))
1374                 (apply 'call-process cp-list))))
1375         (unless (or (null exitstatus)
1376                     (zerop exitstatus))
1377           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1378           ;; Namazu failure reason is in this buffer, show it if
1379           ;; the user wants it.
1380           (when (> gnus-verbose 6)
1381             (display-buffer nnir-tmp-buffer))))
1382
1383       ;; Namazu output looks something like this:
1384       ;; 2. Re: Gnus agent expire broken (score: 55)
1385       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1386
1387       (goto-char (point-min))
1388       (while (re-search-forward
1389               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1390               nil t)
1391         (setq score (match-string 3)
1392               group (file-name-directory (match-string 4))
1393               article (file-name-nondirectory (match-string 4)))
1394
1395         ;; make sure article and group is sane
1396         (when (and (string-match "^[0-9]+$" article)
1397                    (not (null group)))
1398           (when (string-match (concat "^" prefix) group)
1399             (setq group (replace-match "" t t group)))
1400
1401           ;; remove trailing slash from groupname
1402           (setq group (substring group 0 -1))
1403
1404           ;; stuff results into artlist vector
1405           (push (vector (nnir-group-full-name (substitute ?. ?/ group) server)
1406                         (string-to-int article)
1407                         (string-to-int score)) artlist)))
1408
1409       ;; sort artlist by score
1410       (apply 'vector
1411              (sort* artlist
1412                     (function (lambda (x y)
1413                                 (> (nnir-artitem-rsv x)
1414                                    (nnir-artitem-rsv y)))))))))
1415
1416 ;;; Util Code:
1417
1418 (defun nnir-read-parms (query)
1419   "Reads additional search parameters according to `nnir-engines'."
1420   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1421     (cons (cons 'query query)
1422           (mapcar 'nnir-read-parm parmspec))))
1423
1424 (defun nnir-read-parm (parmspec)
1425   "Reads a single search parameter.
1426 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1427   (let ((sym (car parmspec))
1428         (prompt (cdr parmspec)))
1429     (if (listp prompt)
1430         (let* ((result (apply 'completing-read prompt))
1431                (mapping (or (assoc result nnir-imap-search-arguments)
1432                             (assoc nil nnir-imap-search-arguments))))
1433           (cons sym (format (cdr mapping) result)))
1434       (cons sym (read-string prompt)))))
1435
1436 (defun nnir-run-query (query)
1437   "Invoke appropriate search engine function (see `nnir-engines').
1438 If some groups were process-marked, run the query for each of the groups
1439 and concat the results."
1440   (let ((q (car (read-from-string query))))
1441     (if gnus-group-marked
1442         (apply 'vconcat
1443                (mapcar (lambda (x)
1444                          (let ((server (nnir-group-server x))
1445                                search-func)
1446                            (setq search-func (cadr
1447                                               (assoc
1448                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1449                            (if search-func
1450                                (funcall search-func q server x)
1451                              nil)))
1452                        gnus-group-marked)
1453                )
1454       (apply 'vconcat
1455              (mapcar (lambda (x)
1456                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1457                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1458                                  search-func)
1459                              (setq search-func (cadr
1460                                                 (assoc
1461                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1462                              (if search-func
1463                                  (funcall search-func q server nil)
1464                                nil))
1465                          nil))
1466                      gnus-opened-servers)
1467              ))
1468     ))
1469
1470 (defun nnir-read-server-parm (key server)
1471   "Returns the parameter value of for the given server, where server is of
1472 form 'backend:name'."
1473   (let ((method (gnus-server-to-method server)))
1474     (cond ((and method (assq key (cddr method)))
1475            (nth 1 (assq key (cddr method))))
1476           ((and nnir-mail-backend
1477                 (gnus-method-equal method nnir-mail-backend))
1478            (symbol-value key))
1479           ((null nnir-mail-backend)
1480            (symbol-value key))
1481           (t nil))))
1482 ;;     (if method
1483 ;;       (if (assq key (cddr method))
1484 ;;        (nth 1 (assq key (cddr method)))
1485 ;;      (symbol-value key))
1486 ;;       (symbol-value key))
1487 ;;     ))
1488
1489 (defmacro nnir-group-server (group)
1490   "Returns the server for a foreign newsgroup in the format as gnus-server-to-method needs it. Compare to gnus-group-real-prefix and gnus-group-real-name."
1491   `(let ((gname ,group))
1492     (if (string-match "^\\([^:]+\\):" gname)
1493         (setq gname (match-string 1 gname))
1494       nil)
1495     (if (string-match "^\\([^+]+\\)\\+\\(.+\\)$" gname)
1496         (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
1497       (concat gname ":"))
1498     ))
1499
1500 (defun nnir-group-full-name (shortname server)
1501   "For the given group name, return a full Gnus group name.
1502 The Gnus backend/server information is added."
1503   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1504
1505 (defun nnir-possibly-change-server (server)
1506   (unless (and server (nnir-server-opened server))
1507     (nnir-open-server server)))
1508
1509
1510 ;; Data type article list.
1511
1512 (defun nnir-artlist-length (artlist)
1513   "Returns number of articles in artlist."
1514   (length artlist))
1515
1516 (defun nnir-artlist-article (artlist n)
1517   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1518   (elt artlist (1- n)))
1519
1520 (defun nnir-artitem-group (artitem)
1521   "Returns the group from the ARTITEM."
1522   (elt artitem 0))
1523
1524 (defun nnir-artlist-artitem-group (artlist n)
1525   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1526   (nnir-artitem-group (nnir-artlist-article artlist n)))
1527
1528 (defun nnir-artitem-number (artitem)
1529   "Returns the number from the ARTITEM."
1530   (elt artitem 1))
1531
1532 (defun nnir-artlist-artitem-number (artlist n)
1533   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1534   (nnir-artitem-number (nnir-artlist-article artlist n)))
1535
1536 (defun nnir-artitem-rsv (artitem)
1537   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1538   (elt artitem 2))
1539
1540 (defun nnir-artlist-artitem-rsv (artlist n)
1541   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1542 (counting from 1)."
1543   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1544
1545 ;; unused?
1546 (defun nnir-artlist-groups (artlist)
1547   "Returns a list of all groups in the given ARTLIST."
1548   (let ((res nil)
1549         (with-dups nil))
1550     ;; from each artitem, extract group component
1551     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1552     ;; remove duplicates from above
1553     (mapcar (function (lambda (x) (add-to-list 'res x)))
1554             with-dups)
1555     res))
1556
1557
1558 ;; The end.
1559 (provide 'nnir)