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