1751dfc08f966f0c9031a8a419131e661dd460b5
[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 'cl)
342 (require 'nnoo)
343 (require 'gnus-group)
344 (require 'gnus-sum)
345 (require 'message)
346 (eval-and-compile
347   (require 'gnus-util))
348 (eval-when-compile
349   (require 'nnimap))
350
351 (autoload 'nnmaildir-base-name-to-article-number "nnmaildir")
352
353 (nnoo-declare nnir)
354 (nnoo-define-basics nnir)
355
356 (gnus-declare-backend "nnir" 'mail)
357
358 (defvar nnir-imap-search-field "TEXT"
359   "The IMAP search item when doing an nnir search")
360
361 (defvar nnir-imap-search-arguments
362   '(("Whole message" . "TEXT")
363     ("Subject" . "SUBJECT")
364     ("To" . "TO")
365     ("From" . "FROM")
366     (nil . "HEADER \"%s\""))
367   "Mapping from user readable strings to IMAP search items for use in nnir")
368
369 (defvar nnir-imap-search-argument-history ()
370   "The history for querying search options in nnir")
371
372 ;;; Developer Extension Variable:
373
374 (defvar nnir-engines
375   `((wais    nnir-run-waissearch
376              ())
377     (imap    nnir-run-imap
378              ((criteria 
379                "Search in: "                      ; Prompt
380                ,nnir-imap-search-arguments        ; alist for completing
381                nil                                ; no filtering
382                nil                                ; allow any user input
383                nil                                ; initial value
384                nnir-imap-search-argument-history  ; the history to use
385                ,nnir-imap-search-field            ; default
386                )))
387     (swish++ nnir-run-swish++
388              ((group . "Group spec: ")))
389     (swish-e nnir-run-swish-e
390              ((group . "Group spec: ")))
391     (namazu  nnir-run-namazu
392              ())
393     (hyrex   nnir-run-hyrex
394              ((group . "Group spec: ")))
395   (find-grep nnir-run-find-grep
396              ((grep-options . "Grep options: "))))
397   "Alist of supported search engines.
398 Each element in the alist is a three-element list (ENGINE FUNCTION ARGS).
399 ENGINE is a symbol designating the searching engine.  FUNCTION is also
400 a symbol, giving the function that does the search.  The third element
401 ARGS is a list of cons pairs (PARAM . PROMPT).  When issuing a query,
402 the FUNCTION will issue a query for each of the PARAMs, using PROMPT.
403
404 The value of `nnir-search-engine' must be one of the ENGINE symbols.
405 For example, use the following line for searching using freeWAIS-sf:
406     (setq nnir-search-engine 'wais)
407 Use the following line if you read your mail via IMAP and your IMAP
408 server supports searching:
409     (setq nnir-search-engine 'imap)
410 Note that you have to set additional variables for most backends.  For
411 example, the `wais' backend needs the variables `nnir-wais-program',
412 `nnir-wais-database' and `nnir-wais-remove-prefix'.
413
414 Add an entry here when adding a new search engine.")
415
416 ;;; User Customizable Variables:
417
418 (defgroup nnir nil
419   "Search nnmh and nnml groups in Gnus with swish-e, freeWAIS-sf, or EWS."
420   :group 'gnus)
421
422 ;; Mail backend.
423
424 ;; TODO:
425 ;; If `nil', use server parameters to find out which server to search. CCC
426 ;;
427 (defcustom nnir-mail-backend '(nnml "")
428   "*Specifies which backend should be searched.
429 More precisely, this is used to determine from which backend to fetch the
430 messages found.
431
432 This must be equal to an existing server, so maybe it is best to use
433 something like the following:
434     (setq nnir-mail-backend (nth 0 gnus-secondary-select-methods))
435 The above line works fine if the mail backend you want to search is
436 the first element of gnus-secondary-select-methods (`nth' starts counting
437 at zero)."
438   :type '(sexp)
439   :group 'nnir)
440
441 ;; Search engine to use.
442
443 (defcustom nnir-search-engine 'wais
444   "*The search engine to use.  Must be a symbol.
445 See `nnir-engines' for a list of supported engines, and for example
446 settings of `nnir-search-engine'."
447   :type '(sexp)
448   :group 'nnir)
449
450 ;; freeWAIS-sf.
451
452 (defcustom nnir-wais-program "waissearch"
453   "*Name of waissearch executable."
454   :type '(string)
455   :group 'nnir)
456
457 (defcustom nnir-wais-database (expand-file-name "~/.wais/mail")
458   "*Name of Wais database containing the mail.
459
460 Note that this should be a file name without extension.  For example,
461 if you have a file /home/john/.wais/mail.fmt, use this:
462     (setq nnir-wais-database \"/home/john/.wais/mail\")
463 The string given here is passed to `waissearch -d' as-is."
464   :type '(file)
465   :group 'nnir)
466
467 (defcustom nnir-wais-remove-prefix (concat (getenv "HOME") "/Mail/")
468   "*The prefix to remove from each directory name returned by waissearch
469 in order to get a group name (albeit with / instead of .).  This is a
470 regular expression.
471
472 For example, suppose that Wais returns file names such as
473 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
474 setting:  (setq nnir-wais-remove-prefix \"/home/john/Mail/\")
475 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
476 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
477 arrive at the correct group name, \"mail.misc\"."
478   :type '(regexp)
479   :group 'nnir)
480
481 (defcustom nnir-swish++-configuration-file
482   (expand-file-name "~/Mail/swish++.conf")
483   "*Configuration file for swish++."
484   :type '(file)
485   :group 'nnir)
486
487 (defcustom nnir-swish++-program "search"
488   "*Name of swish++ search executable."
489   :type '(string)
490   :group 'nnir)
491
492 (defcustom nnir-swish++-additional-switches '()
493   "*A list of strings, to be given as additional arguments to swish++.
494
495 Note that this should be a list.  Ie, do NOT use the following:
496     (setq nnir-swish++-additional-switches \"-i -w\") ; wrong
497 Instead, use this:
498     (setq nnir-swish++-additional-switches '(\"-i\" \"-w\"))"
499   :type '(repeat (string))
500   :group 'nnir)
501
502 (defcustom nnir-swish++-remove-prefix (concat (getenv "HOME") "/Mail/")
503   "*The prefix to remove from each file name returned by swish++
504 in order to get a group name (albeit with / instead of .).  This is a
505 regular expression.
506
507 This variable is very similar to `nnir-wais-remove-prefix', except
508 that it is for swish++, not Wais."
509   :type '(regexp)
510   :group 'nnir)
511
512 ;; Swish-E.
513 ;; URL: http://sunsite.berkeley.edu/SWISH-E/
514 ;; New version: http://www.boe.es/swish-e
515 ;; Variables `nnir-swish-e-index-file', `nnir-swish-e-program' and
516 ;; `nnir-swish-e-additional-switches'
517
518 (make-obsolete-variable 'nnir-swish-e-index-file
519                         'nnir-swish-e-index-files)
520 (defcustom nnir-swish-e-index-file
521   (expand-file-name "~/Mail/index.swish-e")
522   "*Index file for swish-e.
523 This could be a server parameter.
524 It is never consulted once `nnir-swish-e-index-files', which should be
525 used instead, has been customized."
526   :type '(file)
527   :group 'nnir)
528
529 (defcustom nnir-swish-e-index-files
530   (list nnir-swish-e-index-file)
531   "*List of index files for swish-e.
532 This could be a server parameter."
533   :type '(repeat (file))
534   :group 'nnir)
535
536 (defcustom nnir-swish-e-program "swish-e"
537   "*Name of swish-e search executable.
538 This cannot be a server parameter."
539   :type '(string)
540   :group 'nnir)
541
542 (defcustom nnir-swish-e-additional-switches '()
543   "*A list of strings, to be given as additional arguments to swish-e.
544
545 Note that this should be a list.  Ie, do NOT use the following:
546     (setq nnir-swish-e-additional-switches \"-i -w\") ; wrong
547 Instead, use this:
548     (setq nnir-swish-e-additional-switches '(\"-i\" \"-w\"))
549
550 This could be a server parameter."
551   :type '(repeat (string))
552   :group 'nnir)
553
554 (defcustom nnir-swish-e-remove-prefix (concat (getenv "HOME") "/Mail/")
555   "*The prefix to remove from each file name returned by swish-e
556 in order to get a group name (albeit with / instead of .).  This is a
557 regular expression.
558
559 This variable is very similar to `nnir-wais-remove-prefix', except
560 that it is for swish-e, not Wais.
561
562 This could be a server parameter."
563   :type '(regexp)
564   :group 'nnir)
565
566 ;; HyREX engine, see <URL:http://ls6-www.cs.uni-dortmund.de/>
567
568 (defcustom nnir-hyrex-program "nnir-search"
569   "*Name of the nnir-search executable."
570   :type '(string)
571   :group 'nnir)
572
573 (defcustom nnir-hyrex-additional-switches '()
574   "*A list of strings, to be given as additional arguments for nnir-search.
575 Note that this should be a list. Ie, do NOT use the following:
576     (setq nnir-hyrex-additional-switches \"-ddl ddl.xml -c nnir\") ; wrong !
577 Instead, use this:
578     (setq nnir-hyrex-additional-switches '(\"-ddl\" \"ddl.xml\" \"-c\" \"nnir\"))"
579   :type '(repeat (string))
580   :group 'nnir)
581
582 (defcustom nnir-hyrex-index-directory (getenv "HOME")
583   "*Index directory for HyREX."
584   :type '(directory)
585   :group 'nnir)
586
587 (defcustom nnir-hyrex-remove-prefix (concat (getenv "HOME") "/Mail/")
588   "*The prefix to remove from each file name returned by HyREX
589 in order to get a group name (albeit with / instead of .).
590
591 For example, suppose that HyREX returns file names such as
592 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
593 setting:  (setq nnir-hyrex-remove-prefix \"/home/john/Mail/\")
594 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
595 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
596 arrive at the correct group name, \"mail.misc\"."
597   :type '(directory)
598   :group 'nnir)
599
600 ;; Namazu engine, see <URL:http://ww.namazu.org/>
601
602 (defcustom nnir-namazu-program "namazu"
603   "*Name of Namazu search executable."
604   :type '(string)
605   :group 'nnir)
606
607 (defcustom nnir-namazu-index-directory (expand-file-name "~/Mail/namazu/")
608   "*Index directory for Namazu."
609   :type '(directory)
610   :group 'nnir)
611
612 (defcustom nnir-namazu-additional-switches '()
613   "*A list of strings, to be given as additional arguments to namazu.
614 The switches `-q', `-a', and `-s' are always used, very few other switches
615 make any sense in this context.
616
617 Note that this should be a list.  Ie, do NOT use the following:
618     (setq nnir-namazu-additional-switches \"-i -w\") ; wrong
619 Instead, use this:
620     (setq nnir-namazu-additional-switches '(\"-i\" \"-w\"))"
621   :type '(repeat (string))
622   :group 'nnir)
623
624 (defcustom nnir-namazu-remove-prefix (concat (getenv "HOME") "/Mail/")
625   "*The prefix to remove from each file name returned by Namazu
626 in order to get a group name (albeit with / instead of .).
627
628 This variable is very similar to `nnir-wais-remove-prefix', except
629 that it is for Namazu, not Wais."
630   :type '(directory)
631   :group 'nnir)
632
633 ;;; Internal Variables:
634
635 (defvar nnir-current-query nil
636   "Internal: stores current query (= group name).")
637
638 (defvar nnir-current-server nil
639   "Internal: stores current server (does it ever change?).")
640
641 (defvar nnir-current-group-marked nil
642   "Internal: stores current list of process-marked groups.")
643
644 (defvar nnir-artlist nil
645   "Internal: stores search result.")
646
647 (defvar nnir-tmp-buffer " *nnir*"
648   "Internal: temporary buffer.")
649
650 ;;; Code:
651
652 ;; Gnus glue.
653
654 (defun gnus-group-make-nnir-group (extra-parms query)
655   "Create an nnir group.  Asks for query."
656   (interactive "P\nsQuery: ")
657   (setq nnir-current-query nil
658         nnir-current-server nil
659         nnir-current-group-marked nil
660         nnir-artlist nil)
661   (let ((parms nil))
662     (if extra-parms
663         (setq parms (nnir-read-parms query))
664       (setq parms (list (cons 'query query))))
665     (add-to-list 'parms (cons 'unique-id (message-unique-id)) t)
666     (gnus-group-read-ephemeral-group
667      (concat "nnir:" (prin1-to-string parms)) '(nnir "") t
668      (cons (current-buffer)
669            gnus-current-window-configuration)
670      nil)))
671
672 (defun nnir-group-mode-hook ()
673   (define-key gnus-group-mode-map (kbd "G G")
674     'gnus-group-make-nnir-group))
675 (add-hook 'gnus-group-mode-hook 'nnir-group-mode-hook)
676
677 ;; Why is this needed? Is this for compatibility with old/new gnusae? Using
678 ;; gnus-group-server instead works for me.  -- Justus Piater
679 (defmacro nnir-group-server (group)
680   "Return the server for a newsgroup GROUP.
681 The returned format is as `gnus-server-to-method' needs it.  See
682 `gnus-group-real-prefix' and `gnus-group-real-name'."
683   `(let ((gname ,group))
684      (if (string-match "^\\([^:]+\\):" gname)
685          (progn
686            (setq gname (match-string 1 gname))
687            (if (string-match "^\\([^+]+\\)\\+\\(.+\\)$" gname)
688                (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
689              (concat gname ":")))
690        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
691
692 ;; Summary mode commands.
693
694 (defun gnus-summary-nnir-goto-thread ()
695   "Only applies to nnir groups.  Go to group this article came from
696 and show thread that contains this article."
697   (interactive)
698   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
699     (error "Can't execute this command unless in nnir group."))
700   (let* ((cur (gnus-summary-article-number))
701          (group (nnir-artlist-artitem-group nnir-artlist cur))
702          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
703          server backend-group)
704     (setq server (nnir-group-server group))
705     (setq backend-group (gnus-group-real-name group))
706     (gnus-group-read-ephemeral-group
707      backend-group
708      (gnus-server-to-method server)
709      t                                  ; activate
710      (cons (current-buffer)
711            'summary)                    ; window config
712      nil
713      (list backend-number))
714     (gnus-summary-limit (list backend-number))
715     (gnus-summary-refer-thread)))
716
717 (if (fboundp 'eval-after-load)
718     (eval-after-load "gnus-sum"
719       '(define-key gnus-summary-goto-map
720          "T" 'gnus-summary-nnir-goto-thread))
721   (add-hook 'gnus-summary-mode-hook
722             (function (lambda ()
723                         (define-key gnus-summary-goto-map
724                           "T" 'gnus-summary-nnir-goto-thread)))))
725
726
727
728 ;; Gnus backend interface functions.
729
730 (deffoo nnir-open-server (server &optional definitions)
731   ;; Just set the server variables appropriately.
732   (nnoo-change-server 'nnir server definitions))
733
734 (deffoo nnir-request-group (group &optional server fast)
735   "GROUP is the query string."
736   (nnir-possibly-change-server server)
737   ;; Check for cache and return that if appropriate.
738   (if (and (equal group nnir-current-query)
739            (equal gnus-group-marked nnir-current-group-marked)
740            (or (null server)
741                (equal server nnir-current-server)))
742       nnir-artlist
743     ;; Cache miss.
744     (setq nnir-artlist (nnir-run-query group)))
745   (save-excursion
746     (set-buffer nntp-server-buffer)
747     (if (zerop (length nnir-artlist))
748         (progn
749           (setq nnir-current-query nil
750                 nnir-current-server nil
751                 nnir-current-group-marked nil
752                 nnir-artlist nil)
753           (nnheader-report 'nnir "Search produced empty results."))
754       ;; Remember data for cache.
755       (setq nnir-current-query group)
756       (when server (setq nnir-current-server server))
757       (setq nnir-current-group-marked gnus-group-marked)
758       (nnheader-insert "211 %d %d %d %s\n"
759                        (nnir-artlist-length nnir-artlist) ; total #
760                        1              ; first #
761                        (nnir-artlist-length nnir-artlist) ; last #
762                        group))))     ; group name
763
764 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
765   (save-excursion
766     (let ((artlist (copy-sequence articles))
767           (art nil)
768           (artitem nil)
769           (artgroup nil) (artno nil)
770           (artrsv nil)
771           (artfullgroup nil)
772           (novitem nil)
773           (novdata nil)
774           (foo nil)
775           server)
776       (while (not (null artlist))
777         (setq art (car artlist))
778         (or (numberp art)
779             (nnheader-report
780              'nnir
781              "nnir-retrieve-headers doesn't grok message ids: %s"
782              art))
783         (setq artitem (nnir-artlist-article nnir-artlist art))
784         (setq artrsv (nnir-artitem-rsv artitem))
785         (setq artfullgroup (nnir-artitem-group artitem))
786         (setq artno (nnir-artitem-number artitem))
787         (setq artgroup (gnus-group-real-name artfullgroup))
788         (setq server (nnir-group-server artfullgroup))
789         ;; retrieve NOV or HEAD data for this article, transform into
790         ;; NOV data and prepend to `novdata'
791         (set-buffer nntp-server-buffer)
792         (nnir-possibly-change-server server)
793         (let ((gnus-override-method
794                (gnus-server-to-method server)))
795           (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
796             (nov
797              (goto-char (point-min))
798              (setq novitem (nnheader-parse-nov))
799              (unless novitem
800                (pop-to-buffer nntp-server-buffer)
801                (error
802                 "nnheader-parse-nov returned nil for article %s in group %s"
803                 artno artfullgroup)))
804             (headers
805              (goto-char (point-min))
806              (setq novitem (nnheader-parse-head))
807              (unless novitem
808                (pop-to-buffer nntp-server-buffer)
809                (error
810                 "nnheader-parse-head returned nil for article %s in group %s"
811                 artno artfullgroup)))
812             (t (error "Unknown header type %s while requesting article %s of group %s"
813                       foo artno artfullgroup))))
814         ;; replace article number in original group with article number
815         ;; in nnir group
816         (mail-header-set-number novitem art)
817         (mail-header-set-from novitem
818                               (mail-header-from novitem))
819         (mail-header-set-subject
820          novitem
821          (format "[%d: %s/%d] %s"
822                  artrsv artgroup artno
823                  (mail-header-subject novitem)))
824         ;;-(mail-header-set-extra novitem nil)
825         (push novitem novdata)
826         (setq artlist (cdr artlist)))
827       (setq novdata (nreverse novdata))
828       (set-buffer nntp-server-buffer) (erase-buffer)
829       (mapcar 'nnheader-insert-nov novdata)
830       'nov)))
831
832 (deffoo nnir-request-article (article
833                               &optional group server to-buffer)
834   (if (stringp article)
835       (nnheader-report
836        'nnir
837        "nnir-retrieve-headers doesn't grok message ids: %s"
838        article)
839     (save-excursion
840       (let* ((artitem (nnir-artlist-article nnir-artlist
841                                             article))
842              (artfullgroup (nnir-artitem-group artitem))
843              (artno (nnir-artitem-number artitem))
844              ;; Bug?
845              ;; Why must we bind nntp-server-buffer here?  It won't
846              ;; work if `buf' is used, say.  (Of course, the set-buffer
847              ;; line below must then be updated, too.)
848              (nntp-server-buffer (or to-buffer nntp-server-buffer)))
849         (set-buffer nntp-server-buffer)
850         (erase-buffer)
851         (message "Requesting article %d from group %s"
852                  artno artfullgroup)
853         (gnus-request-article artno artfullgroup nntp-server-buffer)
854         (cons artfullgroup artno)))))
855
856
857 (nnoo-define-skeleton nnir)
858
859
860 (defmacro nnir-add-result (dirnam artno score prefix server artlist)
861   "Ask `nnir-compose-result' to construct a result vector, 
862 and if it is non-nil, add it to artlist."
863   `(let ((result (nnir-compose-result dirnam artno score prefix server)))
864      (when (not (null result))
865        (push result artlist))))
866
867
868 ;; Helper function currently used by the Swish++ and Namazu backends;
869 ;; perhaps useful for other backends as well
870 (defun nnir-compose-result (dirnam article score prefix server)
871   "Extract the group from dirnam, and create a result vector
872 ready to be added to the list of search results."
873
874   ;; remove nnir-*-remove-prefix from beginning of dirnam filename
875   (when (string-match (concat "^" prefix) dirnam)
876     (setq dirnam (replace-match "" t t dirnam)))
877
878   (when (file-readable-p (concat prefix dirnam article))
879     ;; remove trailing slash and, for nnmaildir, cur/new/tmp
880     (setq dirnam
881           (substring dirnam 0 (if (string= server "nnmaildir:") -5 -1)))
882
883     ;; eliminate all ".", "/", "\" from beginning. Always matches.
884     (string-match "^[./\\]*\\(.*\\)$" dirnam)
885     (setq group (substitute ?. ?/ (match-string 1 dirnam))) ;; "/" -> "."
886     (setq group (substitute ?. ?\\ group)) ;; "\\" -> "."
887
888     (vector (nnir-group-full-name group server)
889             (if (string= server "nnmaildir:")
890                 (nnmaildir-base-name-to-article-number
891                  (substring article 0 (string-match ":" article))
892                  group nil)
893               (string-to-number article))
894             (string-to-number score))))
895
896 ;;; Search Engine Interfaces:
897
898 ;; freeWAIS-sf interface.
899 (defun nnir-run-waissearch (query server &optional group)
900   "Run given query agains waissearch.  Returns vector of (group name, file name)
901 pairs (also vectors, actually)."
902   (when group
903     (error "The freeWAIS-sf backend cannot search specific groups."))
904   (save-excursion
905     (let ((qstring (cdr (assq 'query query)))
906           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
907           (artlist nil)
908           (score nil) (artno nil) (dirnam nil) (group nil))
909       (set-buffer (get-buffer-create nnir-tmp-buffer))
910       (erase-buffer)
911       (message "Doing WAIS query %s..." query)
912       (call-process nnir-wais-program
913                     nil                 ; input from /dev/null
914                     t                   ; output to current buffer
915                     nil                 ; don't redisplay
916                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
917                     qstring)
918       (message "Massaging waissearch output...")
919       ;; remove superfluous lines
920       (keep-lines "Score:")
921       ;; extract data from result lines
922       (goto-char (point-min))
923       (while (re-search-forward
924               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
925         (setq score (match-string 1)
926               artno (match-string 2)
927               dirnam (match-string 3))
928         (unless (string-match prefix dirnam)
929           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
930                            dirnam prefix))
931         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
932         (push (vector (nnir-group-full-name group server)
933                       (string-to-number artno)
934                       (string-to-number score))
935               artlist))
936       (message "Massaging waissearch output...done")
937       (apply 'vector
938              (sort* artlist
939                     (function (lambda (x y)
940                                 (> (nnir-artitem-rsv x)
941                                    (nnir-artitem-rsv y)))))))))
942
943 ;; IMAP interface.
944 ;; todo:
945 ;; nnir invokes this two (2) times???!
946 ;; we should not use nnimap at all but open our own server connection
947 ;; we should not LIST * but use nnimap-list-pattern from defs
948 ;; send queries as literals
949 ;; handle errors
950
951 (defun nnir-run-imap (query srv &optional group-option)
952   "Run a search against an IMAP back-end server.
953 This uses a custom query language parser; see `nnir-imap-make-query' for
954 details on the language and supported extensions"
955   (require 'imap)
956   (require 'nnimap)
957   (save-excursion
958     (let ((qstring (cdr (assq 'query query)))
959           (server (cadr (gnus-server-to-method srv)))
960           (group (or group-option (gnus-group-group-name)))
961           (defs (caddr (gnus-server-to-method srv)))
962           (criteria (or (cdr (assq 'criteria query))
963                         nnir-imap-search-field))
964           artlist buf)
965       (message "Opening server %s" server)
966       (condition-case ()
967           (when (nnimap-open-server server defs) ;; xxx
968             (setq buf nnimap-server-buffer) ;; xxx
969             (message "Searching %s..." group)
970             (let ((arts 0)
971                   (mbx (gnus-group-real-name group)))
972               (when (imap-mailbox-select mbx nil buf)
973                 (mapcar
974                  (lambda (artnum)
975                    (push (vector group artnum 1) artlist)
976                    (setq arts (1+ arts)))
977                  (imap-search (nnir-imap-make-query criteria qstring) buf))
978                 (message "Searching %s... %d matches" mbx arts)))
979             (message "Searching %s...done" group))
980         (quit nil))
981       (reverse artlist))))
982
983 (defun nnir-imap-make-query (criteria qstring)
984   "Parse the query string and criteria into an appropriate IMAP search
985 expression, returning the string query to make.
986
987 This implements a little language designed to return the expected results
988 to an arbitrary query string to the end user.
989
990 The search is always case-insensitive, as defined by RFC2060, and supports
991 the following features (inspired by the Google search input language): 
992
993 Automatic \"and\" queries
994     If you specify multiple words then they will be treated as an \"and\"
995     expression intended to match all components.
996
997 Phrase searches
998     If you wrap your query in double-quotes then it will be treated as a
999     literal string.
1000
1001 Negative terms
1002     If you precede a term with \"-\" then it will negate that.
1003
1004 \"OR\" queries
1005     If you include an upper-case \"OR\" in your search it will cause the
1006     term before it and the term after it to be treated as alternatives.
1007
1008 In future the following will be added to the language:
1009  * support for date matches
1010  * support for location of text matching within the query
1011  * from/to/etc headers
1012  * additional search terms
1013  * flag based searching
1014  * anything else that the RFC supports, basically."
1015   ;; Walk through the query and turn it into an IMAP query string.
1016   (nnir-imap-query-to-imap criteria (nnir-imap-parse-query qstring)))
1017
1018
1019 (defun nnir-imap-query-to-imap (criteria query)
1020   "Turn a s-expression format query into IMAP."
1021   (mapconcat
1022    ;; Turn the expressions into IMAP text
1023    (lambda (item)
1024      (nnir-imap-expr-to-imap criteria item))
1025    ;; The query, already in s-expr format.
1026    query
1027    ;; Append a space between each expression
1028    " "))
1029
1030
1031 (defun nnir-imap-expr-to-imap (criteria expr)
1032   "Convert EXPR into an IMAP search expression on CRITERIA"
1033   ;; What sort of expression is this, eh?
1034   (cond
1035    ;; Simple string term
1036    ((stringp expr)
1037     (format "%s \"%s\"" criteria (imap-quote-specials expr)))
1038    ;; Trivial term: and
1039    ((eq expr 'and) nil)
1040    ;; Composite term: or expression
1041    ((eq (car-safe expr) 'or)
1042     (format "OR %s %s"
1043             (nnir-imap-expr-to-imap criteria (second expr))
1044             (nnir-imap-expr-to-imap criteria (third expr))))
1045    ;; Composite term: just the fax, mam
1046    ((eq (car-safe expr) 'not)
1047     (format "NOT (%s)" (nnir-imap-query-to-imap criteria (rest expr))))
1048    ;; Composite term: just expand it all.
1049    ((and (not (null expr)) (listp expr))
1050     (format "(%s)" (nnir-imap-query-to-imap criteria expr)))
1051    ;; Complex value, give up for now.
1052    (t (error "Unhandled input: %S" expr))))
1053
1054
1055 (defun nnir-imap-parse-query (string)
1056   "Turn STRING into an s-expression based query based on the IMAP
1057 query language as defined in `nnir-imap-make-query'.
1058
1059 This involves turning individual tokens into higher level terms
1060 that the search language can then understand and use."
1061   (with-temp-buffer
1062     ;; Set up the parsing environment.
1063     (insert string)
1064     (goto-char (point-min))
1065     ;; Now, collect the output terms and return them.
1066     (let (out)
1067       (while (not (nnir-imap-end-of-input))
1068         (push (nnir-imap-next-expr) out))
1069       (reverse out))))
1070
1071
1072 (defun nnir-imap-next-expr (&optional count)
1073   "Return the next expression from the current buffer."
1074   (let ((term (nnir-imap-next-term count))
1075         (next (nnir-imap-peek-symbol)))
1076     ;; Are we looking at an 'or' expression?
1077     (cond
1078      ;; Handle 'expr or expr'
1079      ((eq next 'or)
1080       (list 'or term (nnir-imap-next-expr 2)))
1081      ;; Anything else
1082      (t term))))
1083
1084
1085 (defun nnir-imap-next-term (&optional count)
1086   "Return the next TERM from the current buffer."
1087   (let ((term (nnir-imap-next-symbol count)))
1088     ;; What sort of term is this?
1089     (cond
1090      ;; and -- just ignore it
1091      ((eq term 'and) 'and)
1092      ;; negated term
1093      ((eq term 'not) (list 'not (nnir-imap-next-expr)))
1094      ;; generic term
1095      (t term))))
1096
1097
1098 (defun nnir-imap-peek-symbol ()
1099   "Return the next symbol from the current buffer, but don't consume it."
1100   (save-excursion
1101     (nnir-imap-next-symbol)))
1102
1103 (defun nnir-imap-next-symbol (&optional count)
1104   "Return the next symbol from the current buffer, or nil if we are
1105 at the end of the buffer.  If supplied COUNT skips some symbols before
1106 returning the one at the supplied position."
1107   (when (and (numberp count) (> count 1))
1108     (nnir-imap-next-symbol (1- count)))
1109   (let ((case-fold-search t))
1110     ;; end of input stream?
1111     (unless (nnir-imap-end-of-input)
1112       ;; No, return the next symbol from the stream.
1113       (cond
1114        ;; negated expression -- return it and advance one char.
1115        ((looking-at "-") (forward-char 1) 'not)
1116        ;; quoted string
1117        ((looking-at "\"") (nnir-imap-delimited-string "\""))
1118        ;; list expression -- we parse the content and return this as a list.
1119        ((looking-at "(")
1120         (nnir-imap-parse-query (nnir-imap-delimited-string ")")))
1121        ;; keyword input -- return a symbol version
1122        ((looking-at "\\band\\b") (forward-char 3) 'and)
1123        ((looking-at "\\bor\\b")  (forward-char 2) 'or)
1124        ((looking-at "\\bnot\\b") (forward-char 3) 'not)
1125        ;; Simple, boring keyword
1126        (t (let ((start (point))
1127                 (end (if (search-forward-regexp "[[:blank:]]" nil t)
1128                          (prog1
1129                              (match-beginning 0)
1130                            ;; unskip if we hit a non-blank terminal character.
1131                            (when (string-match "[^[:blank:]]" (match-string 0))
1132                              (backward-char 1)))
1133                        (goto-char (point-max)))))
1134             (buffer-substring start end)))))))
1135
1136 (defun nnir-imap-delimited-string (delimiter)
1137   "Return a delimited string from the current buffer."
1138   (let ((start (point)) end)
1139     (forward-char 1)                    ; skip the first delimiter.
1140     (while (not end)
1141       (unless (search-forward delimiter nil t)
1142         (error "Unmatched delimited input with %s in query" delimiter))
1143       (let ((here (point)))
1144         (unless (equal (buffer-substring (- here 2) (- here 1)) "\\")
1145           (setq end (point)))))
1146     (buffer-substring (1+ start) (1- end))))
1147
1148 (defun nnir-imap-end-of-input ()
1149   "Are we at the end of input?"
1150   (skip-chars-forward "[[:blank:]]")
1151   (looking-at "$"))
1152   
1153
1154 ;; Swish++ interface.
1155 ;; -cc- Todo
1156 ;; Search by
1157 ;; - group
1158 ;; Sort by
1159 ;; - rank (default)
1160 ;; - article number
1161 ;; - file size
1162 ;; - group
1163 (defun nnir-run-swish++ (query server &optional group)
1164   "Run QUERY against swish++.
1165 Returns a vector of (group name, file name) pairs (also vectors,
1166 actually).
1167
1168 Tested with swish++ 4.7 on GNU/Linux and with swish++ 5.0b2 on
1169 Windows NT 4.0."
1170
1171   (when group
1172     (error "The swish++ backend cannot search specific groups."))
1173
1174   (save-excursion
1175     (let ( (qstring (cdr (assq 'query query)))
1176            (groupspec (cdr (assq 'group query)))
1177            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
1178            (artlist nil)
1179            ;; nnml-use-compressed-files might be any string, but probably this
1180            ;; is sufficient.  Note that we can't only use the value of
1181            ;; nnml-use-compressed-files because old articles might have been
1182            ;; saved with a different value.
1183            (article-pattern (if (string= server "nnmaildir:")
1184                                 ":[0-9]+"
1185                               "^[0-9]+\\(\\.[a-z0-9]+\\)?$"))
1186            (score nil) (artno nil) (dirnam nil) (group nil) )
1187
1188       (when (equal "" qstring)
1189         (error "swish++: You didn't enter anything."))
1190
1191       (set-buffer (get-buffer-create nnir-tmp-buffer))
1192       (erase-buffer)
1193
1194       (if groupspec
1195           (message "Doing swish++ query %s on %s..." qstring groupspec)
1196         (message "Doing swish++ query %s..." qstring))
1197
1198       (let* ((cp-list `( ,nnir-swish++-program
1199                          nil            ; input from /dev/null
1200                          t              ; output
1201                          nil            ; don't redisplay
1202                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1203                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1204                          ,qstring       ; the query, in swish++ format
1205                          ))
1206              (exitstatus
1207               (progn
1208                 (message "%s args: %s" nnir-swish++-program
1209                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1210                 (apply 'call-process cp-list))))
1211         (unless (or (null exitstatus)
1212                     (zerop exitstatus))
1213           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1214           ;; swish++ failure reason is in this buffer, show it if
1215           ;; the user wants it.
1216           (when (> gnus-verbose 6)
1217             (display-buffer nnir-tmp-buffer))))
1218
1219       ;; The results are output in the format of:
1220       ;; V 4.7 Linux
1221       ;; rank relative-path-name file-size file-title
1222       ;; V 5.0b2:
1223       ;; rank relative-path-name file-size topic??
1224       ;; where rank is an integer from 1 to 100.
1225       (goto-char (point-min))
1226       (while (re-search-forward
1227               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1228         (setq score (match-string 1)
1229               filenam (match-string 2)
1230               artno (file-name-nondirectory filenam)
1231               dirnam (file-name-directory filenam))
1232
1233         ;; don't match directories
1234         (when (string-match article-pattern artno)
1235           (when (not (null dirnam))
1236
1237             ;; maybe limit results to matching groups.
1238             (when (or (not groupspec)
1239                       (string-match groupspec dirnam))
1240               (nnir-add-result dirnam artno score prefix server artlist)))))
1241
1242       (message "Massaging swish++ output...done")
1243
1244       ;; Sort by score
1245       (apply 'vector
1246              (sort* artlist
1247                     (function (lambda (x y)
1248                                 (> (nnir-artitem-rsv x)
1249                                    (nnir-artitem-rsv y)))))))))
1250
1251 ;; Swish-E interface.
1252 (defun nnir-run-swish-e (query server &optional group)
1253   "Run given query against swish-e.
1254 Returns a vector of (group name, file name) pairs (also vectors,
1255 actually).
1256
1257 Tested with swish-e-2.0.1 on Windows NT 4.0."
1258
1259   ;; swish-e crashes with empty parameter to "-w" on commandline...
1260   (when group
1261     (error "The swish-e backend cannot search specific groups."))
1262
1263   (save-excursion
1264     (let ((qstring (cdr (assq 'query query)))
1265           (prefix
1266            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1267                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1268           (artlist nil)
1269           (score nil) (artno nil) (dirnam nil) (group nil) )
1270
1271       (when (equal "" qstring)
1272         (error "swish-e: You didn't enter anything."))
1273
1274       (set-buffer (get-buffer-create nnir-tmp-buffer))
1275       (erase-buffer)
1276
1277       (message "Doing swish-e query %s..." query)
1278       (let* ((index-files
1279               (or (nnir-read-server-parm
1280                    'nnir-swish-e-index-files server)
1281                   (error "Missing parameter `nnir-swish-e-index-files'")))
1282              (additional-switches
1283               (nnir-read-server-parm
1284                'nnir-swish-e-additional-switches server))
1285              (cp-list `(,nnir-swish-e-program
1286                         nil             ; input from /dev/null
1287                         t               ; output
1288                         nil             ; don't redisplay
1289                         "-f" ,@index-files
1290                         ,@additional-switches
1291                         "-w"
1292                         ,qstring        ; the query, in swish-e format
1293                         ))
1294              (exitstatus
1295               (progn
1296                 (message "%s args: %s" nnir-swish-e-program
1297                          (mapconcat 'identity (cddddr cp-list) " "))
1298                 (apply 'call-process cp-list))))
1299         (unless (or (null exitstatus)
1300                     (zerop exitstatus))
1301           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1302           ;; swish-e failure reason is in this buffer, show it if
1303           ;; the user wants it.
1304           (when (> gnus-verbose 6)
1305             (display-buffer nnir-tmp-buffer))))
1306
1307       ;; The results are output in the format of:
1308       ;; rank path-name file-title file-size
1309       (goto-char (point-min))
1310       (while (re-search-forward
1311               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1312         (setq score (match-string 1)
1313               artno (match-string 3)
1314               dirnam (file-name-directory (match-string 2)))
1315
1316         ;; don't match directories
1317         (when (string-match "^[0-9]+$" artno)
1318           (when (not (null dirnam))
1319
1320             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1321             (when (string-match (concat "^" prefix) dirnam)
1322               (setq dirnam (replace-match "" t t dirnam)))
1323
1324             (setq dirnam (substring dirnam 0 -1))
1325             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1326             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1327             ;; "/" -> "."
1328             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1329             ;; Windows "\\" -> "."
1330             (setq group (substitute ?. ?\\ group))
1331
1332             (push (vector (nnir-group-full-name group server)
1333                           (string-to-number artno)
1334                           (string-to-number score))
1335                   artlist))))
1336
1337       (message "Massaging swish-e output...done")
1338
1339       ;; Sort by score
1340       (apply 'vector
1341              (sort* artlist
1342                     (function (lambda (x y)
1343                                 (> (nnir-artitem-rsv x)
1344                                    (nnir-artitem-rsv y)))))))))
1345
1346 ;; HyREX interface
1347 (defun nnir-run-hyrex (query server &optional group)
1348   (save-excursion
1349     (let ((artlist nil)
1350           (groupspec (cdr (assq 'group query)))
1351           (qstring (cdr (assq 'query query)))
1352           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1353           score artno dirnam)
1354       (when (and group groupspec)
1355         (error (concat "It does not make sense to use a group spec"
1356                        " with process-marked groups.")))
1357       (when group
1358         (setq groupspec (gnus-group-real-name group)))
1359       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1360         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1361         (error "Server with groupspec doesn't match group !"))
1362       (set-buffer (get-buffer-create nnir-tmp-buffer))
1363       (erase-buffer)
1364       (if groupspec
1365           (message "Doing hyrex-search query %s on %s..." query groupspec)
1366         (message "Doing hyrex-search query %s..." query))
1367       (let* ((cp-list
1368               `( ,nnir-hyrex-program
1369                  nil                    ; input from /dev/null
1370                  t                      ; output
1371                  nil                    ; don't redisplay
1372                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1373                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1374                  ,qstring          ; the query, in hyrex-search format
1375                  ))
1376              (exitstatus
1377               (progn
1378                 (message "%s args: %s" nnir-hyrex-program
1379                          (mapconcat 'identity (cddddr cp-list) " "))
1380                 (apply 'call-process cp-list))))
1381         (unless (or (null exitstatus)
1382                     (zerop exitstatus))
1383           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1384           ;; nnir-search failure reason is in this buffer, show it if
1385           ;; the user wants it.
1386           (when (> gnus-verbose 6)
1387             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1388       (if groupspec
1389           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1390         (message "Doing hyrex-search query \"%s\"...done" qstring))
1391       (sit-for 0)
1392       ;; nnir-search returns:
1393       ;;   for nnml/nnfolder: "filename mailid weigth"
1394       ;;   for nnimap:        "group mailid weigth"
1395       (goto-char (point-min))
1396       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1397       ;; HyREX couldn't search directly in groups -- so filter out here.
1398       (when groupspec
1399         (keep-lines groupspec))
1400       ;; extract data from result lines
1401       (goto-char (point-min))
1402       (while (re-search-forward
1403               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1404         (setq dirnam (match-string 1)
1405               artno (match-string 2)
1406               score (match-string 3))
1407         (when (string-match prefix dirnam)
1408           (setq dirnam (replace-match "" t t dirnam)))
1409         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1410                       (string-to-number artno)
1411                       (string-to-number score))
1412               artlist))
1413       (message "Massaging hyrex-search output...done.")
1414       (apply 'vector
1415              (sort* artlist
1416                     (function (lambda (x y)
1417                                 (if (string-lessp (nnir-artitem-group x)
1418                                                   (nnir-artitem-group y))
1419                                     t
1420                                   (< (nnir-artitem-number x)
1421                                      (nnir-artitem-number y)))))))
1422       )))
1423
1424 ;; Namazu interface
1425 (defun nnir-run-namazu (query server &optional group)
1426   "Run given query against Namazu.  Returns a vector of (group name, file name)
1427 pairs (also vectors, actually).
1428
1429 Tested with Namazu 2.0.6 on a GNU/Linux system."
1430   (when group
1431     (error "The Namazu backend cannot search specific groups"))
1432   (save-excursion
1433     (let (
1434           (article-pattern (if (string= server "nnmaildir:")
1435                                ":[0-9]+"
1436                              "^[0-9]+$"))
1437           (artlist nil)
1438           (qstring (cdr (assq 'query query)))
1439           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1440           (score nil)
1441           (group nil)
1442           (article nil)
1443           (process-environment (copy-sequence process-environment))
1444           )
1445       (setenv "LC_MESSAGES" "C")
1446       (set-buffer (get-buffer-create nnir-tmp-buffer))
1447       (erase-buffer)
1448       (let* ((cp-list
1449               `( ,nnir-namazu-program
1450                  nil                    ; input from /dev/null
1451                  t                      ; output
1452                  nil                    ; don't redisplay
1453                  "-q"                   ; don't be verbose
1454                  "-a"                   ; show all matches
1455                  "-s"                   ; use short format
1456                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1457                  ,qstring               ; the query, in namazu format
1458                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1459                  ))
1460              (exitstatus
1461               (progn
1462                 (message "%s args: %s" nnir-namazu-program
1463                          (mapconcat 'identity (cddddr cp-list) " "))
1464                 (apply 'call-process cp-list))))
1465         (unless (or (null exitstatus)
1466                     (zerop exitstatus))
1467           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1468           ;; Namazu failure reason is in this buffer, show it if
1469           ;; the user wants it.
1470           (when (> gnus-verbose 6)
1471             (display-buffer nnir-tmp-buffer))))
1472
1473       ;; Namazu output looks something like this:
1474       ;; 2. Re: Gnus agent expire broken (score: 55)
1475       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1476
1477       (goto-char (point-min))
1478       (while (re-search-forward
1479               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1480               nil t)
1481         (setq score (match-string 3)
1482               group (file-name-directory (match-string 4))
1483               article (file-name-nondirectory (match-string 4)))
1484
1485         ;; make sure article and group is sane
1486         (when (and (string-match article-pattern article)
1487                    (not (null group)))
1488           (nnir-add-result group article score prefix server artlist)))
1489
1490       ;; sort artlist by score
1491       (apply 'vector
1492              (sort* artlist
1493                     (function (lambda (x y)
1494                                 (> (nnir-artitem-rsv x)
1495                                    (nnir-artitem-rsv y)))))))))
1496
1497 (defun nnir-run-find-grep (query server &optional group)
1498   "Run find and grep to obtain matching articles."
1499   (let* ((method (gnus-server-to-method server))
1500          (sym (intern
1501                (concat (symbol-name (car method)) "-directory")))
1502          (directory (cadr (assoc sym (cddr method))))
1503          (regexp (cdr (assoc 'query query)))
1504          (grep-options (cdr (assoc 'grep-options query)))
1505          artlist)
1506     (unless directory
1507       (error "No directory found in method specification of server %s"
1508              server))
1509     (message "Searching %s using find-grep..." (or group server))
1510     (save-window-excursion
1511       (set-buffer (get-buffer-create nnir-tmp-buffer))
1512       (erase-buffer)
1513       (if (> gnus-verbose 6)
1514           (pop-to-buffer (current-buffer)))
1515       (cd directory) ; Using relative paths simplifies postprocessing.
1516       (let ((group
1517              (if (not group)
1518                  "."
1519                ;; Try accessing the group literally as well as
1520                ;; interpreting dots as directory separators so the
1521                ;; engine works with plain nnml as well as the Gnus
1522                ;; Cache.
1523                (find-if 'file-directory-p
1524                 (let ((group (gnus-group-real-name group)))
1525                   (list group (gnus-replace-in-string group "\\." "/" t)))))))
1526         (unless group
1527           (error "Cannot locate directory for group"))
1528         (save-excursion
1529           (apply
1530            'call-process "find" nil t
1531            "find" group "-type" "f" "-name" "[0-9]*" "-exec"
1532            "grep"
1533            `("-l" ,@(and grep-options (split-string grep-options "\\s-" t))
1534              "-e" ,regexp "{}" "+"))))
1535
1536       ;; Translate relative paths to group names.
1537       (while (not (eobp))
1538         (let* ((path (split-string
1539                       (buffer-substring (point) (line-end-position)) "/" t))
1540                (art (string-to-number (car (last path)))))
1541           (while (string= "." (car path))
1542             (setq path (cdr path)))
1543           (let ((group (mapconcat 'identity (subseq path 0 -1) ".")))
1544             (push (vector (nnir-group-full-name group server) art 0)
1545                   artlist))
1546           (forward-line 1)))
1547       (message "Searching %s using find-grep...done" (or group server))
1548       artlist)))
1549
1550 ;;; Util Code:
1551
1552 (defun nnir-read-parms (query)
1553   "Reads additional search parameters according to `nnir-engines'."
1554   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1555     (cons (cons 'query query)
1556           (mapcar 'nnir-read-parm parmspec))))
1557
1558 (defun nnir-read-parm (parmspec)
1559   "Reads a single search parameter.
1560 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1561   (let ((sym (car parmspec))
1562         (prompt (cdr parmspec)))
1563     (if (listp prompt)
1564         (let* ((result (apply 'completing-read prompt))
1565                (mapping (or (assoc result nnir-imap-search-arguments)
1566                             (assoc nil nnir-imap-search-arguments))))
1567           (cons sym (format (cdr mapping) result)))
1568       (cons sym (read-string prompt)))))
1569
1570 (defun nnir-run-query (query)
1571   "Invoke appropriate search engine function (see `nnir-engines').
1572 If some groups were process-marked, run the query for each of the groups
1573 and concat the results."
1574   (let ((q (car (read-from-string query))))
1575     (if gnus-group-marked
1576         (apply 'vconcat
1577                (mapcar (lambda (x)
1578                          (let ((server (nnir-group-server x))
1579                                search-func)
1580                            (setq search-func (cadr
1581                                               (assoc
1582                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1583                            (if search-func
1584                                (funcall search-func q server x)
1585                              nil)))
1586                        gnus-group-marked)
1587                )
1588       (apply 'vconcat
1589              (mapcar (lambda (x)
1590                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1591                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1592                                  search-func)
1593                              (setq search-func (cadr
1594                                                 (assoc
1595                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1596                              (if search-func
1597                                  (funcall search-func q server nil)
1598                                nil))
1599                          nil))
1600                      gnus-opened-servers)
1601              ))
1602     ))
1603
1604 (defun nnir-read-server-parm (key server)
1605   "Returns the parameter value of for the given server, where server is of
1606 form 'backend:name'."
1607   (let ((method (gnus-server-to-method server)))
1608     (cond ((and method (assq key (cddr method)))
1609            (nth 1 (assq key (cddr method))))
1610           ((and nnir-mail-backend
1611                 (gnus-server-equal method nnir-mail-backend))
1612            (symbol-value key))
1613           (t nil))))
1614 ;;     (if method
1615 ;;       (if (assq key (cddr method))
1616 ;;        (nth 1 (assq key (cddr method)))
1617 ;;      (symbol-value key))
1618 ;;       (symbol-value key))
1619 ;;     ))
1620
1621 (defun nnir-group-full-name (shortname server)
1622   "For the given group name, return a full Gnus group name.
1623 The Gnus backend/server information is added."
1624   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1625
1626 (defun nnir-possibly-change-server (server)
1627   (unless (and server (nnir-server-opened server))
1628     (nnir-open-server server)))
1629
1630
1631 ;; Data type article list.
1632
1633 (defun nnir-artlist-length (artlist)
1634   "Returns number of articles in artlist."
1635   (length artlist))
1636
1637 (defun nnir-artlist-article (artlist n)
1638   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1639   (elt artlist (1- n)))
1640
1641 (defun nnir-artitem-group (artitem)
1642   "Returns the group from the ARTITEM."
1643   (elt artitem 0))
1644
1645 (defun nnir-artlist-artitem-group (artlist n)
1646   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1647   (nnir-artitem-group (nnir-artlist-article artlist n)))
1648
1649 (defun nnir-artitem-number (artitem)
1650   "Returns the number from the ARTITEM."
1651   (elt artitem 1))
1652
1653 (defun nnir-artlist-artitem-number (artlist n)
1654   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1655   (nnir-artitem-number (nnir-artlist-article artlist n)))
1656
1657 (defun nnir-artitem-rsv (artitem)
1658   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1659   (elt artitem 2))
1660
1661 (defun nnir-artlist-artitem-rsv (artlist n)
1662   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1663 \(counting from 1)."
1664   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1665
1666 ;; unused?
1667 (defun nnir-artlist-groups (artlist)
1668   "Returns a list of all groups in the given ARTLIST."
1669   (let ((res nil)
1670         (with-dups nil))
1671     ;; from each artitem, extract group component
1672     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1673     ;; remove duplicates from above
1674     (mapcar (function (lambda (x) (add-to-list 'res x)))
1675             with-dups)
1676     res))
1677
1678
1679 ;; The end.
1680 (provide 'nnir)
1681
1682 ;;; arch-tag: 9b3fecf8-4397-4bbb-bf3c-6ac3cbbc6664