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