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