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