Fix 2004-03-15 tiny change entry.
[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 hmm 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 group)
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 (autoload 'imap-mailbox-select "imap")
943 (autoload 'imap-search "imap")
944 (autoload 'imap-quote-specials "imap")
945
946 (defun nnir-run-imap (query srv &optional group-option)
947   "Run a search against an IMAP back-end server.
948 This uses a custom query language parser; see `nnir-imap-make-query' for
949 details on the language and supported extensions"
950   (save-excursion
951     (let ((qstring (cdr (assq 'query query)))
952           (server (cadr (gnus-server-to-method srv)))
953           (group (or group-option (gnus-group-group-name)))
954           (defs (caddr (gnus-server-to-method srv)))
955           (criteria (or (cdr (assq 'criteria query))
956                         nnir-imap-search-field))
957           artlist buf)
958       (message "Opening server %s" server)
959       (condition-case ()
960           (when (nnimap-open-server server defs) ;; xxx
961             (setq buf nnimap-server-buffer) ;; xxx
962             (message "Searching %s..." group)
963             (let ((arts 0)
964                   (mbx (gnus-group-real-name group)))
965               (when (imap-mailbox-select mbx nil buf)
966                 (mapc
967                  (lambda (artnum)
968                    (push (vector group artnum 1) artlist)
969                    (setq arts (1+ arts)))
970                  (imap-search (nnir-imap-make-query criteria qstring) buf))
971                 (message "Searching %s... %d matches" mbx arts)))
972             (message "Searching %s...done" group))
973         (quit nil))
974       (reverse artlist))))
975
976 (defun nnir-imap-make-query (criteria qstring)
977   "Parse the query string and criteria into an appropriate IMAP search
978 expression, returning the string query to make.
979
980 This implements a little language designed to return the expected results
981 to an arbitrary query string to the end user.
982
983 The search is always case-insensitive, as defined by RFC2060, and supports
984 the following features (inspired by the Google search input language): 
985
986 Automatic \"and\" queries
987     If you specify multiple words then they will be treated as an \"and\"
988     expression intended to match all components.
989
990 Phrase searches
991     If you wrap your query in double-quotes then it will be treated as a
992     literal string.
993
994 Negative terms
995     If you precede a term with \"-\" then it will negate that.
996
997 \"OR\" queries
998     If you include an upper-case \"OR\" in your search it will cause the
999     term before it and the term after it to be treated as alternatives.
1000
1001 In future the following will be added to the language:
1002  * support for date matches
1003  * support for location of text matching within the query
1004  * from/to/etc headers
1005  * additional search terms
1006  * flag based searching
1007  * anything else that the RFC supports, basically."
1008   ;; Walk through the query and turn it into an IMAP query string.
1009   (nnir-imap-query-to-imap criteria (nnir-imap-parse-query qstring)))
1010
1011
1012 (defun nnir-imap-query-to-imap (criteria query)
1013   "Turn a s-expression format query into IMAP."
1014   (mapconcat
1015    ;; Turn the expressions into IMAP text
1016    (lambda (item)
1017      (nnir-imap-expr-to-imap criteria item))
1018    ;; The query, already in s-expr format.
1019    query
1020    ;; Append a space between each expression
1021    " "))
1022
1023
1024 (defun nnir-imap-expr-to-imap (criteria expr)
1025   "Convert EXPR into an IMAP search expression on CRITERIA"
1026   ;; What sort of expression is this, eh?
1027   (cond
1028    ;; Simple string term
1029    ((stringp expr)
1030     (format "%s \"%s\"" criteria (imap-quote-specials expr)))
1031    ;; Trivial term: and
1032    ((eq expr 'and) nil)
1033    ;; Composite term: or expression
1034    ((eq (car-safe expr) 'or)
1035     (format "OR %s %s"
1036             (nnir-imap-expr-to-imap criteria (second expr))
1037             (nnir-imap-expr-to-imap criteria (third expr))))
1038    ;; Composite term: just the fax, mam
1039    ((eq (car-safe expr) 'not)
1040     (format "NOT (%s)" (nnir-imap-query-to-imap criteria (rest expr))))
1041    ;; Composite term: just expand it all.
1042    ((and (not (null expr)) (listp expr))
1043     (format "(%s)" (nnir-imap-query-to-imap criteria expr)))
1044    ;; Complex value, give up for now.
1045    (t (error "Unhandled input: %S" expr))))
1046
1047
1048 (defun nnir-imap-parse-query (string)
1049   "Turn STRING into an s-expression based query based on the IMAP
1050 query language as defined in `nnir-imap-make-query'.
1051
1052 This involves turning individual tokens into higher level terms
1053 that the search language can then understand and use."
1054   (with-temp-buffer
1055     ;; Set up the parsing environment.
1056     (insert string)
1057     (goto-char (point-min))
1058     ;; Now, collect the output terms and return them.
1059     (let (out)
1060       (while (not (nnir-imap-end-of-input))
1061         (push (nnir-imap-next-expr) out))
1062       (reverse out))))
1063
1064
1065 (defun nnir-imap-next-expr (&optional count)
1066   "Return the next expression from the current buffer."
1067   (let ((term (nnir-imap-next-term count))
1068         (next (nnir-imap-peek-symbol)))
1069     ;; Are we looking at an 'or' expression?
1070     (cond
1071      ;; Handle 'expr or expr'
1072      ((eq next 'or)
1073       (list 'or term (nnir-imap-next-expr 2)))
1074      ;; Anything else
1075      (t term))))
1076
1077
1078 (defun nnir-imap-next-term (&optional count)
1079   "Return the next TERM from the current buffer."
1080   (let ((term (nnir-imap-next-symbol count)))
1081     ;; What sort of term is this?
1082     (cond
1083      ;; and -- just ignore it
1084      ((eq term 'and) 'and)
1085      ;; negated term
1086      ((eq term 'not) (list 'not (nnir-imap-next-expr)))
1087      ;; generic term
1088      (t term))))
1089
1090
1091 (defun nnir-imap-peek-symbol ()
1092   "Return the next symbol from the current buffer, but don't consume it."
1093   (save-excursion
1094     (nnir-imap-next-symbol)))
1095
1096 (defun nnir-imap-next-symbol (&optional count)
1097   "Return the next symbol from the current buffer, or nil if we are
1098 at the end of the buffer.  If supplied COUNT skips some symbols before
1099 returning the one at the supplied position."
1100   (when (and (numberp count) (> count 1))
1101     (nnir-imap-next-symbol (1- count)))
1102   (let ((case-fold-search t))
1103     ;; end of input stream?
1104     (unless (nnir-imap-end-of-input)
1105       ;; No, return the next symbol from the stream.
1106       (cond
1107        ;; negated expression -- return it and advance one char.
1108        ((looking-at "-") (forward-char 1) 'not)
1109        ;; quoted string
1110        ((looking-at "\"") (nnir-imap-delimited-string "\""))
1111        ;; list expression -- we parse the content and return this as a list.
1112        ((looking-at "(")
1113         (nnir-imap-parse-query (nnir-imap-delimited-string ")")))
1114        ;; keyword input -- return a symbol version
1115        ((looking-at "\\band\\b") (forward-char 3) 'and)
1116        ((looking-at "\\bor\\b")  (forward-char 2) 'or)
1117        ((looking-at "\\bnot\\b") (forward-char 3) 'not)
1118        ;; Simple, boring keyword
1119        (t (let ((start (point))
1120                 (end (if (search-forward-regexp "[[:blank:]]" nil t)
1121                          (prog1
1122                              (match-beginning 0)
1123                            ;; unskip if we hit a non-blank terminal character.
1124                            (when (string-match "[^[:blank:]]" (match-string 0))
1125                              (backward-char 1)))
1126                        (goto-char (point-max)))))
1127             (buffer-substring start end)))))))
1128
1129 (defun nnir-imap-delimited-string (delimiter)
1130   "Return a delimited string from the current buffer."
1131   (let ((start (point)) end)
1132     (forward-char 1)                    ; skip the first delimiter.
1133     (while (not end)
1134       (unless (search-forward delimiter nil t)
1135         (error "Unmatched delimited input with %s in query" delimiter))
1136       (let ((here (point)))
1137         (unless (equal (buffer-substring (- here 2) (- here 1)) "\\")
1138           (setq end (point)))))
1139     (buffer-substring (1+ start) (1- end))))
1140
1141 (defun nnir-imap-end-of-input ()
1142   "Are we at the end of input?"
1143   (skip-chars-forward "[[:blank:]]")
1144   (looking-at "$"))
1145   
1146
1147 ;; Swish++ interface.
1148 ;; -cc- Todo
1149 ;; Search by
1150 ;; - group
1151 ;; Sort by
1152 ;; - rank (default)
1153 ;; - article number
1154 ;; - file size
1155 ;; - group
1156 (defun nnir-run-swish++ (query server &optional group)
1157   "Run QUERY against swish++.
1158 Returns a vector of (group name, file name) pairs (also vectors,
1159 actually).
1160
1161 Tested with swish++ 4.7 on GNU/Linux and with swish++ 5.0b2 on
1162 Windows NT 4.0."
1163
1164   (when group
1165     (error "The swish++ backend cannot search specific groups."))
1166
1167   (save-excursion
1168     (let ( (qstring (cdr (assq 'query query)))
1169            (groupspec (cdr (assq 'group query)))
1170            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
1171            artlist
1172            ;; nnml-use-compressed-files might be any string, but probably this
1173            ;; is sufficient.  Note that we can't only use the value of
1174            ;; nnml-use-compressed-files because old articles might have been
1175            ;; saved with a different value.
1176            (article-pattern (if (string= server "nnmaildir:")
1177                                 ":[0-9]+"
1178                               "^[0-9]+\\(\\.[a-z0-9]+\\)?$"))
1179            score artno dirnam group filenam )
1180
1181       (when (equal "" qstring)
1182         (error "swish++: You didn't enter anything."))
1183
1184       (set-buffer (get-buffer-create nnir-tmp-buffer))
1185       (erase-buffer)
1186
1187       (if groupspec
1188           (message "Doing swish++ query %s on %s..." qstring groupspec)
1189         (message "Doing swish++ query %s..." qstring))
1190
1191       (let* ((cp-list `( ,nnir-swish++-program
1192                          nil            ; input from /dev/null
1193                          t              ; output
1194                          nil            ; don't redisplay
1195                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1196                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1197                          ,qstring       ; the query, in swish++ format
1198                          ))
1199              (exitstatus
1200               (progn
1201                 (message "%s args: %s" nnir-swish++-program
1202                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1203                 (apply 'call-process cp-list))))
1204         (unless (or (null exitstatus)
1205                     (zerop exitstatus))
1206           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1207           ;; swish++ failure reason is in this buffer, show it if
1208           ;; the user wants it.
1209           (when (> gnus-verbose 6)
1210             (display-buffer nnir-tmp-buffer))))
1211
1212       ;; The results are output in the format of:
1213       ;; V 4.7 Linux
1214       ;; rank relative-path-name file-size file-title
1215       ;; V 5.0b2:
1216       ;; rank relative-path-name file-size topic??
1217       ;; where rank is an integer from 1 to 100.
1218       (goto-char (point-min))
1219       (while (re-search-forward
1220               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1221         (setq score (match-string 1)
1222               filenam (match-string 2)
1223               artno (file-name-nondirectory filenam)
1224               dirnam (file-name-directory filenam))
1225
1226         ;; don't match directories
1227         (when (string-match article-pattern artno)
1228           (when (not (null dirnam))
1229
1230             ;; maybe limit results to matching groups.
1231             (when (or (not groupspec)
1232                       (string-match groupspec dirnam))
1233               (nnir-add-result dirnam artno score prefix server artlist)))))
1234
1235       (message "Massaging swish++ output...done")
1236
1237       ;; Sort by score
1238       (apply 'vector
1239              (sort* artlist
1240                     (function (lambda (x y)
1241                                 (> (nnir-artitem-rsv x)
1242                                    (nnir-artitem-rsv y)))))))))
1243
1244 ;; Swish-E interface.
1245 (defun nnir-run-swish-e (query server &optional group)
1246   "Run given query against swish-e.
1247 Returns a vector of (group name, file name) pairs (also vectors,
1248 actually).
1249
1250 Tested with swish-e-2.0.1 on Windows NT 4.0."
1251
1252   ;; swish-e crashes with empty parameter to "-w" on commandline...
1253   (when group
1254     (error "The swish-e backend cannot search specific groups."))
1255
1256   (save-excursion
1257     (let ((qstring (cdr (assq 'query query)))
1258           (prefix
1259            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1260                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1261           artlist score artno dirnam group )
1262
1263       (when (equal "" qstring)
1264         (error "swish-e: You didn't enter anything."))
1265
1266       (set-buffer (get-buffer-create nnir-tmp-buffer))
1267       (erase-buffer)
1268
1269       (message "Doing swish-e query %s..." query)
1270       (let* ((index-files
1271               (or (nnir-read-server-parm
1272                    'nnir-swish-e-index-files server)
1273                   (error "Missing parameter `nnir-swish-e-index-files'")))
1274              (additional-switches
1275               (nnir-read-server-parm
1276                'nnir-swish-e-additional-switches server))
1277              (cp-list `(,nnir-swish-e-program
1278                         nil             ; input from /dev/null
1279                         t               ; output
1280                         nil             ; don't redisplay
1281                         "-f" ,@index-files
1282                         ,@additional-switches
1283                         "-w"
1284                         ,qstring        ; the query, in swish-e format
1285                         ))
1286              (exitstatus
1287               (progn
1288                 (message "%s args: %s" nnir-swish-e-program
1289                          (mapconcat 'identity (cddddr cp-list) " "))
1290                 (apply 'call-process cp-list))))
1291         (unless (or (null exitstatus)
1292                     (zerop exitstatus))
1293           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1294           ;; swish-e failure reason is in this buffer, show it if
1295           ;; the user wants it.
1296           (when (> gnus-verbose 6)
1297             (display-buffer nnir-tmp-buffer))))
1298
1299       ;; The results are output in the format of:
1300       ;; rank path-name file-title file-size
1301       (goto-char (point-min))
1302       (while (re-search-forward
1303               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1304         (setq score (match-string 1)
1305               artno (match-string 3)
1306               dirnam (file-name-directory (match-string 2)))
1307
1308         ;; don't match directories
1309         (when (string-match "^[0-9]+$" artno)
1310           (when (not (null dirnam))
1311
1312             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1313             (when (string-match (concat "^" prefix) dirnam)
1314               (setq dirnam (replace-match "" t t dirnam)))
1315
1316             (setq dirnam (substring dirnam 0 -1))
1317             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1318             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1319             ;; "/" -> "."
1320             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1321             ;; Windows "\\" -> "."
1322             (setq group (substitute ?. ?\\ group))
1323
1324             (push (vector (nnir-group-full-name group server)
1325                           (string-to-number artno)
1326                           (string-to-number score))
1327                   artlist))))
1328
1329       (message "Massaging swish-e output...done")
1330
1331       ;; Sort by score
1332       (apply 'vector
1333              (sort* artlist
1334                     (function (lambda (x y)
1335                                 (> (nnir-artitem-rsv x)
1336                                    (nnir-artitem-rsv y)))))))))
1337
1338 ;; HyREX interface
1339 (defun nnir-run-hyrex (query server &optional group)
1340   (save-excursion
1341     (let ((artlist nil)
1342           (groupspec (cdr (assq 'group query)))
1343           (qstring (cdr (assq 'query query)))
1344           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1345           score artno dirnam)
1346       (when (and group groupspec)
1347         (error (concat "It does not make sense to use a group spec"
1348                        " with process-marked groups.")))
1349       (when group
1350         (setq groupspec (gnus-group-real-name group)))
1351       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1352         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1353         (error "Server with groupspec doesn't match group !"))
1354       (set-buffer (get-buffer-create nnir-tmp-buffer))
1355       (erase-buffer)
1356       (if groupspec
1357           (message "Doing hyrex-search query %s on %s..." query groupspec)
1358         (message "Doing hyrex-search query %s..." query))
1359       (let* ((cp-list
1360               `( ,nnir-hyrex-program
1361                  nil                    ; input from /dev/null
1362                  t                      ; output
1363                  nil                    ; don't redisplay
1364                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1365                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1366                  ,qstring          ; the query, in hyrex-search format
1367                  ))
1368              (exitstatus
1369               (progn
1370                 (message "%s args: %s" nnir-hyrex-program
1371                          (mapconcat 'identity (cddddr cp-list) " "))
1372                 (apply 'call-process cp-list))))
1373         (unless (or (null exitstatus)
1374                     (zerop exitstatus))
1375           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1376           ;; nnir-search failure reason is in this buffer, show it if
1377           ;; the user wants it.
1378           (when (> gnus-verbose 6)
1379             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1380       (if groupspec
1381           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1382         (message "Doing hyrex-search query \"%s\"...done" qstring))
1383       (sit-for 0)
1384       ;; nnir-search returns:
1385       ;;   for nnml/nnfolder: "filename mailid weigth"
1386       ;;   for nnimap:        "group mailid weigth"
1387       (goto-char (point-min))
1388       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1389       ;; HyREX couldn't search directly in groups -- so filter out here.
1390       (when groupspec
1391         (keep-lines groupspec))
1392       ;; extract data from result lines
1393       (goto-char (point-min))
1394       (while (re-search-forward
1395               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1396         (setq dirnam (match-string 1)
1397               artno (match-string 2)
1398               score (match-string 3))
1399         (when (string-match prefix dirnam)
1400           (setq dirnam (replace-match "" t t dirnam)))
1401         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1402                       (string-to-number artno)
1403                       (string-to-number score))
1404               artlist))
1405       (message "Massaging hyrex-search output...done.")
1406       (apply 'vector
1407              (sort* artlist
1408                     (function (lambda (x y)
1409                                 (if (string-lessp (nnir-artitem-group x)
1410                                                   (nnir-artitem-group y))
1411                                     t
1412                                   (< (nnir-artitem-number x)
1413                                      (nnir-artitem-number y)))))))
1414       )))
1415
1416 ;; Namazu interface
1417 (defun nnir-run-namazu (query server &optional group)
1418   "Run given query against Namazu.  Returns a vector of (group name, file name)
1419 pairs (also vectors, actually).
1420
1421 Tested with Namazu 2.0.6 on a GNU/Linux system."
1422   (when group
1423     (error "The Namazu backend cannot search specific groups"))
1424   (save-excursion
1425     (let ((article-pattern (if (string= server "nnmaildir:")
1426                                ":[0-9]+"
1427                              "^[0-9]+$"))
1428           artlist
1429           (qstring (cdr (assq 'query query)))
1430           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1431           score group article
1432           (process-environment (copy-sequence process-environment)))
1433       (setenv "LC_MESSAGES" "C")
1434       (set-buffer (get-buffer-create nnir-tmp-buffer))
1435       (erase-buffer)
1436       (let* ((cp-list
1437               `( ,nnir-namazu-program
1438                  nil                    ; input from /dev/null
1439                  t                      ; output
1440                  nil                    ; don't redisplay
1441                  "-q"                   ; don't be verbose
1442                  "-a"                   ; show all matches
1443                  "-s"                   ; use short format
1444                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1445                  ,qstring               ; the query, in namazu format
1446                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1447                  ))
1448              (exitstatus
1449               (progn
1450                 (message "%s args: %s" nnir-namazu-program
1451                          (mapconcat 'identity (cddddr cp-list) " "))
1452                 (apply 'call-process cp-list))))
1453         (unless (or (null exitstatus)
1454                     (zerop exitstatus))
1455           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1456           ;; Namazu failure reason is in this buffer, show it if
1457           ;; the user wants it.
1458           (when (> gnus-verbose 6)
1459             (display-buffer nnir-tmp-buffer))))
1460
1461       ;; Namazu output looks something like this:
1462       ;; 2. Re: Gnus agent expire broken (score: 55)
1463       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1464
1465       (goto-char (point-min))
1466       (while (re-search-forward
1467               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1468               nil t)
1469         (setq score (match-string 3)
1470               group (file-name-directory (match-string 4))
1471               article (file-name-nondirectory (match-string 4)))
1472
1473         ;; make sure article and group is sane
1474         (when (and (string-match article-pattern article)
1475                    (not (null group)))
1476           (nnir-add-result group article score prefix server artlist)))
1477
1478       ;; sort artlist by score
1479       (apply 'vector
1480              (sort* artlist
1481                     (function (lambda (x y)
1482                                 (> (nnir-artitem-rsv x)
1483                                    (nnir-artitem-rsv y)))))))))
1484
1485 (defun nnir-run-find-grep (query server &optional group)
1486   "Run find and grep to obtain matching articles."
1487   (let* ((method (gnus-server-to-method server))
1488          (sym (intern
1489                (concat (symbol-name (car method)) "-directory")))
1490          (directory (cadr (assoc sym (cddr method))))
1491          (regexp (cdr (assoc 'query query)))
1492          (grep-options (cdr (assoc 'grep-options query)))
1493          artlist)
1494     (unless directory
1495       (error "No directory found in method specification of server %s"
1496              server))
1497     (message "Searching %s using find-grep..." (or group server))
1498     (save-window-excursion
1499       (set-buffer (get-buffer-create nnir-tmp-buffer))
1500       (erase-buffer)
1501       (if (> gnus-verbose 6)
1502           (pop-to-buffer (current-buffer)))
1503       (cd directory) ; Using relative paths simplifies postprocessing.
1504       (let ((group
1505              (if (not group)
1506                  "."
1507                ;; Try accessing the group literally as well as
1508                ;; interpreting dots as directory separators so the
1509                ;; engine works with plain nnml as well as the Gnus
1510                ;; Cache.
1511                (find-if 'file-directory-p
1512                 (let ((group (gnus-group-real-name group)))
1513                   (list group (gnus-replace-in-string group "\\." "/" t)))))))
1514         (unless group
1515           (error "Cannot locate directory for group"))
1516         (save-excursion
1517           (apply
1518            'call-process "find" nil t
1519            "find" group "-type" "f" "-name" "[0-9]*" "-exec"
1520            "grep"
1521            `("-l" ,@(and grep-options (split-string grep-options "\\s-" t))
1522              "-e" ,regexp "{}" "+"))))
1523
1524       ;; Translate relative paths to group names.
1525       (while (not (eobp))
1526         (let* ((path (split-string
1527                       (buffer-substring (point) (line-end-position)) "/" t))
1528                (art (string-to-number (car (last path)))))
1529           (while (string= "." (car path))
1530             (setq path (cdr path)))
1531           (let ((group (mapconcat 'identity (subseq path 0 -1) ".")))
1532             (push (vector (nnir-group-full-name group server) art 0)
1533                   artlist))
1534           (forward-line 1)))
1535       (message "Searching %s using find-grep...done" (or group server))
1536       artlist)))
1537
1538 ;;; Util Code:
1539
1540 (defun nnir-read-parms (query)
1541   "Reads additional search parameters according to `nnir-engines'."
1542   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1543     (cons (cons 'query query)
1544           (mapcar 'nnir-read-parm parmspec))))
1545
1546 (defun nnir-read-parm (parmspec)
1547   "Reads a single search parameter.
1548 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1549   (let ((sym (car parmspec))
1550         (prompt (cdr parmspec)))
1551     (if (listp prompt)
1552         (let* ((result (apply 'completing-read prompt))
1553                (mapping (or (assoc result nnir-imap-search-arguments)
1554                             (assoc nil nnir-imap-search-arguments))))
1555           (cons sym (format (cdr mapping) result)))
1556       (cons sym (read-string prompt)))))
1557
1558 (defun nnir-run-query (query)
1559   "Invoke appropriate search engine function (see `nnir-engines').
1560 If some groups were process-marked, run the query for each of the groups
1561 and concat the results."
1562   (let ((q (car (read-from-string query))))
1563     (if gnus-group-marked
1564         (apply 'vconcat
1565                (mapcar (lambda (x)
1566                          (let ((server (nnir-group-server x))
1567                                search-func)
1568                            (setq search-func (cadr
1569                                               (assoc
1570                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1571                            (if search-func
1572                                (funcall search-func q server x)
1573                              nil)))
1574                        gnus-group-marked)
1575                )
1576       (apply 'vconcat
1577              (mapcar (lambda (x)
1578                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1579                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1580                                  search-func)
1581                              (setq search-func (cadr
1582                                                 (assoc
1583                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1584                              (if search-func
1585                                  (funcall search-func q server nil)
1586                                nil))
1587                          nil))
1588                      gnus-opened-servers)
1589              ))
1590     ))
1591
1592 (defun nnir-read-server-parm (key server)
1593   "Returns the parameter value of for the given server, where server is of
1594 form 'backend:name'."
1595   (let ((method (gnus-server-to-method server)))
1596     (cond ((and method (assq key (cddr method)))
1597            (nth 1 (assq key (cddr method))))
1598           ((and nnir-mail-backend
1599                 (gnus-server-equal method nnir-mail-backend))
1600            (symbol-value key))
1601           (t nil))))
1602 ;;     (if method
1603 ;;       (if (assq key (cddr method))
1604 ;;        (nth 1 (assq key (cddr method)))
1605 ;;      (symbol-value key))
1606 ;;       (symbol-value key))
1607 ;;     ))
1608
1609 (defun nnir-group-full-name (shortname server)
1610   "For the given group name, return a full Gnus group name.
1611 The Gnus backend/server information is added."
1612   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1613
1614 (defun nnir-possibly-change-server (server)
1615   (unless (and server (nnir-server-opened server))
1616     (nnir-open-server server)))
1617
1618
1619 ;; Data type article list.
1620
1621 (defun nnir-artlist-length (artlist)
1622   "Returns number of articles in artlist."
1623   (length artlist))
1624
1625 (defun nnir-artlist-article (artlist n)
1626   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1627   (elt artlist (1- n)))
1628
1629 (defun nnir-artitem-group (artitem)
1630   "Returns the group from the ARTITEM."
1631   (elt artitem 0))
1632
1633 (defun nnir-artlist-artitem-group (artlist n)
1634   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1635   (nnir-artitem-group (nnir-artlist-article artlist n)))
1636
1637 (defun nnir-artitem-number (artitem)
1638   "Returns the number from the ARTITEM."
1639   (elt artitem 1))
1640
1641 (defun nnir-artlist-artitem-number (artlist n)
1642   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1643   (nnir-artitem-number (nnir-artlist-article artlist n)))
1644
1645 (defun nnir-artitem-rsv (artitem)
1646   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1647   (elt artitem 2))
1648
1649 (defun nnir-artlist-artitem-rsv (artlist n)
1650   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1651 \(counting from 1)."
1652   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1653
1654 ;; unused?
1655 (defun nnir-artlist-groups (artlist)
1656   "Returns a list of all groups in the given ARTLIST."
1657   (let ((res nil)
1658         (with-dups nil))
1659     ;; from each artitem, extract group component
1660     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1661     ;; remove duplicates from above
1662     (mapc (function (lambda (x) (add-to-list 'res x)))
1663             with-dups)
1664     res))
1665
1666
1667 ;; The end.
1668 (provide 'nnir)
1669
1670 ;;; arch-tag: 9b3fecf8-4397-4bbb-bf3c-6ac3cbbc6664