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