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