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