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