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