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