Add assignment status.
[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 ;; nnmaildir support for Swish++ and Namazu backends by:
12 ;;   Justus Piater <Justus <at> Piater.name>
13
14 ;; FIXME: This file should be move to ../lisp/ after all copyright assignments
15 ;; are on file.  As of 2008-04-13, we don't have an assignment/disclaimer from
16 ;; Torsten Hilbrich, but he's willing to sign.  I've sent hmm the form.
17 ;; -- rsteib
18
19 ;; TODO: Documentation in the Gnus manual
20
21 ;; From: Reiner Steib
22 ;; Subject: Re: Including nnir.el
23 ;; Newsgroups: gmane.emacs.gnus.general
24 ;; Message-ID: <v9d5dnp6aq.fsf@marauder.physik.uni-ulm.de>
25 ;; Date: 2006-06-05 22:49:01 GMT
26 ;;
27 ;; On Sun, Jun 04 2006, Sascha Wilde wrote:
28 ;;
29 ;; > The one thing most hackers like to forget: Documentation.  By now the
30 ;; > documentation is only in the comments at the head of the source, I
31 ;; > would use it as basis to cook up some minimal texinfo docs.
32 ;; >
33 ;; > Where in the existing gnus manual would this fit best?
34
35 ;; Maybe (info "(gnus)Combined Groups") for a general description.
36 ;; `gnus-group-make-nnir-group' might be described in (info
37 ;; "(gnus)Foreign Groups") as well.
38
39 ;; Keywords: news mail searching ir
40
41 ;; This file is part of GNU Emacs.
42
43 ;; This is free software; you can redistribute it and/or modify
44 ;; it under the terms of the GNU General Public License as published by
45 ;; the Free Software Foundation; either version 3, or (at your option)
46 ;; any later version.
47
48 ;; GNU Emacs is distributed in the hope that it will be useful,
49 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
50 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
51 ;; GNU General Public License for more details.
52
53 ;; You should have received a copy of the GNU General Public License
54 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
55 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
56 ;; Boston, MA 02110-1301, USA.
57
58 ;;; Commentary:
59
60 ;; The most recent version of this can always be fetched from the Gnus
61 ;; CVS repository.  See http://www.gnus.org/ for more information.
62
63 ;; This code is still in the development stage but I'd like other
64 ;; people to have a look at it.  Please do not hesitate to contact me
65 ;; with your ideas.
66
67 ;; What does it do?  Well, it allows you to index your mail using some
68 ;; search engine (freeWAIS-sf, swish-e and others -- see later),
69 ;; then type `G G' in the Group buffer and issue a query to the search
70 ;; engine.  You will then get a buffer which shows all articles
71 ;; matching the query, sorted by Retrieval Status Value (score).
72
73 ;; When looking at the retrieval result (in the Summary buffer) you
74 ;; can type `G T' (aka M-x gnus-summary-nnir-goto-thread RET) on an
75 ;; article.  You will be teleported into the group this article came
76 ;; from, showing the thread this article is part of.  (See below for
77 ;; restrictions.)
78
79 ;; The Lisp installation is simple: just put this file on your
80 ;; load-path, byte-compile it, and load it from ~/.gnus or something.
81 ;; This will install a new command `G G' in your Group buffer for
82 ;; searching your mail.  Note that you also need to configure a number
83 ;; of variables, as described below.
84
85 ;; Restrictions:
86 ;;
87 ;; * If you don't use HyREX as your search engine, this expects that
88 ;;   you use nnml or another one-file-per-message backend, because the
89 ;;   others doesn't support nnfolder.
90 ;; * It can only search the mail backend's which are supported by one
91 ;;   search engine, because of different query languages.
92 ;; * There are restrictions to the Wais setup.
93 ;; * There are restrictions to the imap setup.
94 ;; * gnus-summary-nnir-goto-thread: Fetches whole group first, before
95 ;;   limiting to the right articles.  This is much too slow, of
96 ;;   course.  May issue a query for number of articles to fetch; you
97 ;;   must accept the default of all articles at this point or things
98 ;;   may break.
99
100 ;; The Lisp setup involves setting a few variables and setting up the
101 ;; search engine. You can define the variables in the server definition
102 ;; like this :
103 ;;   (setq gnus-secondary-select-methods '(
104 ;;       (nnimap "" (nnimap-address "localhost")
105 ;;                  (nnir-search-engine hyrex)
106 ;;                  (nnir-hyrex-additional-switches ("-d" "ddl-nnimap.xml"))
107 ;;       )))
108 ;; Or you can define the global ones. The variables set in the mailer-
109 ;; definition will be used first.
110 ;; The variable to set is `nnir-search-engine'.  Choose one of the engines
111 ;; listed in `nnir-engines'.  (Actually `nnir-engines' is an alist,
112 ;; type `C-h v nnir-engines RET' for more information; this includes
113 ;; examples for setting `nnir-search-engine', too.)
114 ;;
115 ;; The variable nnir-mail-backend isn't used anymore.
116 ;;
117
118 ;; You must also set up a search engine.  I'll tell you about the two
119 ;; search engines currently supported:
120
121 ;; 1. freeWAIS-sf
122 ;;
123 ;; As always with freeWAIS-sf, you need a so-called `format file'.  I
124 ;; use the following file:
125 ;;
126 ;; ,-----
127 ;; | # Kai's format file for freeWAIS-sf for indexing mails.
128 ;; | # Each mail is in a file, much like the MH format.
129 ;; |
130 ;; | # Document separator should never match -- each file is a document.
131 ;; | record-sep: /^@this regex should never match@$/
132 ;; |
133 ;; | # Searchable fields specification.
134 ;; |
135 ;; | region: /^[sS]ubject:/ /^[sS]ubject: */
136 ;; |         subject "Subject header" stemming TEXT BOTH
137 ;; | end: /^[^ \t]/
138 ;; |
139 ;; | region: /^([tT][oO]|[cC][cC]):/ /^([tT][oO]|[cC][cC]): */
140 ;; |         to "To and Cc headers" SOUNDEX BOTH
141 ;; | end: /^[^ \t]/
142 ;; |
143 ;; | region: /^[fF][rR][oO][mM]:/ /^[fF][rR][oO][mM]: */
144 ;; |         from "From header" SOUNDEX BOTH
145 ;; | end: /^[^ \t]/
146 ;; |
147 ;; | region: /^$/
148 ;; |         stemming TEXT GLOBAL
149 ;; | end: /^@this regex should never match@$/
150 ;; `-----
151 ;;
152 ;; 1998-07-22: waisindex would dump core on me for large articles with
153 ;; the above settings.  I used /^$/ as the end regex for the global
154 ;; field.  That seemed to work okay.
155
156 ;; There is a Perl module called `WAIS.pm' which is available from
157 ;; CPAN as well as ls6-ftp.cs.uni-dortmund.de:/pub/wais/Perl.  This
158 ;; module comes with a nifty tool called `makedb', which I use for
159 ;; indexing.  Here's my `makedb.conf':
160 ;;
161 ;; ,-----
162 ;; | # Config file for makedb
163 ;; |
164 ;; | # Global options
165 ;; | waisindex = /usr/local/bin/waisindex
166 ;; | wais_opt  = -stem -t fields
167 ;; | # `-stem' option necessary when `stemming' is specified for the
168 ;; | # global field in the *.fmt file
169 ;; |
170 ;; | # Own variables
171 ;; | homedir = /home/kai
172 ;; |
173 ;; | # The mail database.
174 ;; | database        = mail
175 ;; | files           = `find $homedir/Mail -name \*[0-9] -print`
176 ;; | dbdir           = $homedir/.wais
177 ;; | limit           = 100
178 ;; `-----
179 ;;
180 ;; The Lisp setup involves the `nnir-wais-*' variables.  The most
181 ;; difficult to understand variable is probably
182 ;; `nnir-wais-remove-prefix'.  Here's what it does: the output of
183 ;; `waissearch' basically contains the file name and the (full)
184 ;; directory name.  As Gnus works with group names rather than
185 ;; directory names, the directory name is transformed into a group
186 ;; name as follows: first, a prefix is removed from the (full)
187 ;; directory name, then all `/' are replaced with `.'.  The variable
188 ;; `nnir-wais-remove-prefix' should contain a regex matching exactly
189 ;; this prefix.  It defaults to `$HOME/Mail/' (note the trailing
190 ;; slash).
191
192 ;; 2. Namazu
193 ;;
194 ;; The Namazu backend requires you to have one directory containing all
195 ;; index files, this is controlled by the `nnir-namazu-index-directory'
196 ;; variable.  To function the `nnir-namazu-remove-prefix' variable must
197 ;; also be correct, see the documentation for `nnir-wais-remove-prefix'
198 ;; above.
199 ;;
200 ;; It is particularly important not to pass any any switches to namazu
201 ;; that will change the output format.  Good switches to use include
202 ;; `--sort', `--ascending', `--early' and `--late'.  Refer to the Namazu
203 ;; documentation for further information on valid switches.
204 ;;
205 ;; To index my mail with the `mknmz' program I use the following
206 ;; configuration file:
207 ;;
208 ;; ,----
209 ;; | package conf;  # Don't remove this line!
210 ;; |
211 ;; | # Paths which will not be indexed. Don't use `^' or `$' anchors.
212 ;; | $EXCLUDE_PATH = "spam|sent";
213 ;; |
214 ;; | # Header fields which should be searchable. case-insensitive
215 ;; | $REMAIN_HEADER = "from|date|message-id|subject";
216 ;; |
217 ;; | # Searchable fields. case-insensitive
218 ;; | $SEARCH_FIELD = "from|date|message-id|subject";
219 ;; |
220 ;; | # The max length of a word.
221 ;; | $WORD_LENG_MAX = 128;
222 ;; |
223 ;; | # The max length of a field.
224 ;; | $MAX_FIELD_LENGTH = 256;
225 ;; `----
226 ;;
227 ;; My mail is stored in the directories ~/Mail/mail/, ~/Mail/lists/ and
228 ;; ~/Mail/archive/, so to index them I go to the directory set in
229 ;; `nnir-namazu-index-directory' and issue the following command.
230 ;;
231 ;;      mknmz --mailnews ~/Mail/archive/ ~/Mail/mail/ ~/Mail/lists/
232 ;;
233 ;; For maximum searching efficiency I have a cron job set to run this
234 ;; command every four hours.
235
236 ;; 3. HyREX
237 ;;
238 ;; The HyREX backend requires you to have one directory from where all
239 ;; your relative paths are to, if you use them. This directory must be
240 ;; set in the `nnir-hyrex-index-directory' variable, which defaults to
241 ;; your home directory. You must also pass the base, class and
242 ;; directory options or simply your dll to the `nnir-hyrex-programm' by
243 ;; setting the `nnir-hyrex-additional-switches' variable accordently.
244 ;; To function the `nnir-hyrex-remove-prefix' variable must also be
245 ;; correct, see the documentation for `nnir-wais-remove-prefix' above.
246
247 ;; 4. find-grep
248 ;;
249 ;; The find-grep engine simply runs find(1) to locate eligible
250 ;; articles and searches them with grep(1).  This, of course, is much
251 ;; slower than using a proper search engine but OTOH doesn't require
252 ;; maintenance of an index and is still faster than using any built-in
253 ;; means for searching.  The method specification of the server to
254 ;; search must include a directory for this engine to work (E.g.,
255 ;; `nnml-directory').  The tools must be POSIX compliant.  GNU Find
256 ;; prior to version 4.2.12 (4.2.26 on Linux due to incorrect ARG_MAX
257 ;; handling) does not work.
258 ;; ,----
259 ;; |    ;; find-grep configuration for searching the Gnus Cache
260 ;; |
261 ;; |    (nnml "cache"
262 ;; |          (nnml-get-new-mail nil)
263 ;; |          (nnir-search-engine find-grep)
264 ;; |          (nnml-directory "~/News/cache/")
265 ;; |          (nnml-active-file "~/News/cache/active"))
266 ;; `----
267
268 ;; Developer information:
269
270 ;; I have tried to make the code expandable.  Basically, it is divided
271 ;; into two layers.  The upper layer is somewhat like the `nnvirtual'
272 ;; or `nnkiboze' backends: given a specification of what articles to
273 ;; show from another backend, it creates a group containing exactly
274 ;; those articles.  The lower layer issues a query to a search engine
275 ;; and produces such a specification of what articles to show from the
276 ;; other backend.
277
278 ;; The interface between the two layers consists of the single
279 ;; function `nnir-run-query', which just selects the appropriate
280 ;; function for the search engine one is using.  The input to
281 ;; `nnir-run-query' is a string, representing the query as input by
282 ;; the user.  The output of `nnir-run-query' is supposed to be a
283 ;; vector, each element of which should in turn be a three-element
284 ;; vector.  The first element should be full group name of the article,
285 ;; the second element should be the article number, and the third
286 ;; element should be the Retrieval Status Value (RSV) as returned from
287 ;; the search engine.  An RSV is the score assigned to the document by
288 ;; the search engine.  For Boolean search engines, the
289 ;; RSV is always 1000 (or 1 or 100, or whatever you like).
290
291 ;; The sorting order of the articles in the summary buffer created by
292 ;; nnir is based on the order of the articles in the above mentioned
293 ;; vector, so that's where you can do the sorting you'd like.  Maybe
294 ;; it would be nice to have a way of displaying the search result
295 ;; sorted differently?
296
297 ;; So what do you need to do when you want to add another search
298 ;; engine?  You write a function that executes the query.  Temporary
299 ;; data from the search engine can be put in `nnir-tmp-buffer'.  This
300 ;; function should return the list of articles as a vector, as
301 ;; described above.  Then, you need to register this backend in
302 ;; `nnir-engines'.  Then, users can choose the backend by setting
303 ;; `nnir-search-engine'.
304
305 ;; Todo, or future ideas:
306
307 ;; * It should be possible to restrict search to certain groups.
308 ;;
309 ;; * There is currently no error checking.
310 ;;
311 ;; * The summary buffer display is currently really ugly, with all the
312 ;;   added information in the subjects.  How could I make this
313 ;;   prettier?
314 ;;
315 ;; * A function which can be called from an nnir summary buffer which
316 ;;   teleports you into the group the current article came from and
317 ;;   shows you the whole thread this article is part of.
318 ;;   Implementation suggestions?
319 ;;   (1998-07-24: There is now a preliminary implementation, but
320 ;;   it is much too slow and quite fragile.)
321 ;;
322 ;; * Support other mail backends.  In particular, probably quite a few
323 ;;   people use nnfolder.  How would one go about searching nnfolders
324 ;;   and producing the right data needed?  The group name and the RSV
325 ;;   are simple, but what about the article number?
326 ;;   - The article number is encoded in the `X-Gnus-Article-Number'
327 ;;     header of each mail.
328 ;;   - The HyREX engine supports nnfolder.
329 ;;
330 ;; * Support compressed mail files.  Probably, just stripping off the
331 ;;   `.gz' or `.Z' file name extension is sufficient.
332 ;;
333 ;; * At least for imap, the query is performed twice.
334 ;;
335
336 ;; Have you got other ideas?
337
338 ;;; Setup Code:
339
340 (require 'cl)
341 (require 'nnoo)
342 (require 'gnus-group)
343 (require 'gnus-sum)
344 (require 'message)
345 (eval-and-compile
346   (require 'gnus-util))
347 (eval-when-compile
348   (require 'nnimap)
349   (autoload 'read-kbd-macro "edmacro" nil t))
350
351 (nnoo-declare nnir)
352 (nnoo-define-basics nnir)
353
354 (gnus-declare-backend "nnir" 'mail)
355
356 (defvar nnir-imap-search-field "TEXT"
357   "The IMAP search item when doing an nnir search")
358
359 (defvar nnir-imap-search-arguments
360   '(("Whole message" . "TEXT")
361     ("Subject" . "SUBJECT")
362     ("To" . "TO")
363     ("From" . "FROM")
364     (nil . "HEADER \"%s\""))
365   "Mapping from user readable strings to IMAP search items for use in nnir")
366
367 (defvar nnir-imap-search-argument-history ()
368   "The history for querying search options in nnir")
369
370 ;;; Developer Extension Variable:
371
372 (defvar nnir-engines
373   `((wais    nnir-run-waissearch
374              ())
375     (imap    nnir-run-imap
376              ((criteria 
377                "Search in: "                      ; Prompt
378                ,nnir-imap-search-arguments        ; alist for completing
379                nil                                ; no filtering
380                nil                                ; allow any user input
381                nil                                ; initial value
382                nnir-imap-search-argument-history  ; the history to use
383                ,nnir-imap-search-field            ; default
384                )))
385     (swish++ nnir-run-swish++
386              ((group . "Group spec: ")))
387     (swish-e nnir-run-swish-e
388              ((group . "Group spec: ")))
389     (namazu  nnir-run-namazu
390              ())
391     (hyrex   nnir-run-hyrex
392              ((group . "Group spec: ")))
393   (find-grep nnir-run-find-grep
394              ((grep-options . "Grep options: "))))
395   "Alist of supported search engines.
396 Each element in the alist is a three-element list (ENGINE FUNCTION ARGS).
397 ENGINE is a symbol designating the searching engine.  FUNCTION is also
398 a symbol, giving the function that does the search.  The third element
399 ARGS is a list of cons pairs (PARAM . PROMPT).  When issuing a query,
400 the FUNCTION will issue a query for each of the PARAMs, using PROMPT.
401
402 The value of `nnir-search-engine' must be one of the ENGINE symbols.
403 For example, use the following line for searching using freeWAIS-sf:
404     (setq nnir-search-engine 'wais)
405 Use the following line if you read your mail via IMAP and your IMAP
406 server supports searching:
407     (setq nnir-search-engine 'imap)
408 Note that you have to set additional variables for most backends.  For
409 example, the `wais' backend needs the variables `nnir-wais-program',
410 `nnir-wais-database' and `nnir-wais-remove-prefix'.
411
412 Add an entry here when adding a new search engine.")
413
414 ;;; User Customizable Variables:
415
416 (defgroup nnir nil
417   "Search nnmh and nnml groups in Gnus with swish-e, freeWAIS-sf, or EWS."
418   :group 'gnus)
419
420 ;; Mail backend.
421
422 ;; TODO:
423 ;; If `nil', use server parameters to find out which server to search. CCC
424 ;;
425 (defcustom nnir-mail-backend '(nnml "")
426   "*Specifies which backend should be searched.
427 More precisely, this is used to determine from which backend to fetch the
428 messages found.
429
430 This must be equal to an existing server, so maybe it is best to use
431 something like the following:
432     (setq nnir-mail-backend (nth 0 gnus-secondary-select-methods))
433 The above line works fine if the mail backend you want to search is
434 the first element of gnus-secondary-select-methods (`nth' starts counting
435 at zero)."
436   :type '(sexp)
437   :group 'nnir)
438
439 ;; Search engine to use.
440
441 (defcustom nnir-search-engine 'wais
442   "*The search engine to use.  Must be a symbol.
443 See `nnir-engines' for a list of supported engines, and for example
444 settings of `nnir-search-engine'."
445   :type '(sexp)
446   :group 'nnir)
447
448 ;; freeWAIS-sf.
449
450 (defcustom nnir-wais-program "waissearch"
451   "*Name of waissearch executable."
452   :type '(string)
453   :group 'nnir)
454
455 (defcustom nnir-wais-database (expand-file-name "~/.wais/mail")
456   "*Name of Wais database containing the mail.
457
458 Note that this should be a file name without extension.  For example,
459 if you have a file /home/john/.wais/mail.fmt, use this:
460     (setq nnir-wais-database \"/home/john/.wais/mail\")
461 The string given here is passed to `waissearch -d' as-is."
462   :type '(file)
463   :group 'nnir)
464
465 (defcustom nnir-wais-remove-prefix (concat (getenv "HOME") "/Mail/")
466   "*The prefix to remove from each directory name returned by waissearch
467 in order to get a group name (albeit with / instead of .).  This is a
468 regular expression.
469
470 For example, suppose that Wais returns file names such as
471 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
472 setting:  (setq nnir-wais-remove-prefix \"/home/john/Mail/\")
473 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
474 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
475 arrive at the correct group name, \"mail.misc\"."
476   :type '(regexp)
477   :group 'nnir)
478
479 (defcustom nnir-swish++-configuration-file
480   (expand-file-name "~/Mail/swish++.conf")
481   "*Configuration file for swish++."
482   :type '(file)
483   :group 'nnir)
484
485 (defcustom nnir-swish++-program "search"
486   "*Name of swish++ search executable."
487   :type '(string)
488   :group 'nnir)
489
490 (defcustom nnir-swish++-additional-switches '()
491   "*A list of strings, to be given as additional arguments to swish++.
492
493 Note that this should be a list.  Ie, do NOT use the following:
494     (setq nnir-swish++-additional-switches \"-i -w\") ; wrong
495 Instead, use this:
496     (setq nnir-swish++-additional-switches '(\"-i\" \"-w\"))"
497   :type '(repeat (string))
498   :group 'nnir)
499
500 (defcustom nnir-swish++-remove-prefix (concat (getenv "HOME") "/Mail/")
501   "*The prefix to remove from each file name returned by swish++
502 in order to get a group name (albeit with / instead of .).  This is a
503 regular expression.
504
505 This variable is very similar to `nnir-wais-remove-prefix', except
506 that it is for swish++, not Wais."
507   :type '(regexp)
508   :group 'nnir)
509
510 ;; Swish-E.
511 ;; URL: http://sunsite.berkeley.edu/SWISH-E/
512 ;; New version: http://www.boe.es/swish-e
513 ;; Variables `nnir-swish-e-index-file', `nnir-swish-e-program' and
514 ;; `nnir-swish-e-additional-switches'
515
516 (make-obsolete-variable 'nnir-swish-e-index-file
517                         'nnir-swish-e-index-files)
518 (defcustom nnir-swish-e-index-file
519   (expand-file-name "~/Mail/index.swish-e")
520   "*Index file for swish-e.
521 This could be a server parameter.
522 It is never consulted once `nnir-swish-e-index-files', which should be
523 used instead, has been customized."
524   :type '(file)
525   :group 'nnir)
526
527 (defcustom nnir-swish-e-index-files
528   (list nnir-swish-e-index-file)
529   "*List of index files for swish-e.
530 This could be a server parameter."
531   :type '(repeat (file))
532   :group 'nnir)
533
534 (defcustom nnir-swish-e-program "swish-e"
535   "*Name of swish-e search executable.
536 This cannot be a server parameter."
537   :type '(string)
538   :group 'nnir)
539
540 (defcustom nnir-swish-e-additional-switches '()
541   "*A list of strings, to be given as additional arguments to swish-e.
542
543 Note that this should be a list.  Ie, do NOT use the following:
544     (setq nnir-swish-e-additional-switches \"-i -w\") ; wrong
545 Instead, use this:
546     (setq nnir-swish-e-additional-switches '(\"-i\" \"-w\"))
547
548 This could be a server parameter."
549   :type '(repeat (string))
550   :group 'nnir)
551
552 (defcustom nnir-swish-e-remove-prefix (concat (getenv "HOME") "/Mail/")
553   "*The prefix to remove from each file name returned by swish-e
554 in order to get a group name (albeit with / instead of .).  This is a
555 regular expression.
556
557 This variable is very similar to `nnir-wais-remove-prefix', except
558 that it is for swish-e, not Wais.
559
560 This could be a server parameter."
561   :type '(regexp)
562   :group 'nnir)
563
564 ;; HyREX engine, see <URL:http://ls6-www.cs.uni-dortmund.de/>
565
566 (defcustom nnir-hyrex-program "nnir-search"
567   "*Name of the nnir-search executable."
568   :type '(string)
569   :group 'nnir)
570
571 (defcustom nnir-hyrex-additional-switches '()
572   "*A list of strings, to be given as additional arguments for nnir-search.
573 Note that this should be a list. Ie, do NOT use the following:
574     (setq nnir-hyrex-additional-switches \"-ddl ddl.xml -c nnir\") ; wrong !
575 Instead, use this:
576     (setq nnir-hyrex-additional-switches '(\"-ddl\" \"ddl.xml\" \"-c\" \"nnir\"))"
577   :type '(repeat (string))
578   :group 'nnir)
579
580 (defcustom nnir-hyrex-index-directory (getenv "HOME")
581   "*Index directory for HyREX."
582   :type '(directory)
583   :group 'nnir)
584
585 (defcustom nnir-hyrex-remove-prefix (concat (getenv "HOME") "/Mail/")
586   "*The prefix to remove from each file name returned by HyREX
587 in order to get a group name (albeit with / instead of .).
588
589 For example, suppose that HyREX returns file names such as
590 \"/home/john/Mail/mail/misc/42\".  For this example, use the following
591 setting:  (setq nnir-hyrex-remove-prefix \"/home/john/Mail/\")
592 Note the trailing slash.  Removing this prefix gives \"mail/misc/42\".
593 `nnir' knows to remove the \"/42\" and to replace \"/\" with \".\" to
594 arrive at the correct group name, \"mail.misc\"."
595   :type '(directory)
596   :group 'nnir)
597
598 ;; Namazu engine, see <URL:http://ww.namazu.org/>
599
600 (defcustom nnir-namazu-program "namazu"
601   "*Name of Namazu search executable."
602   :type '(string)
603   :group 'nnir)
604
605 (defcustom nnir-namazu-index-directory (expand-file-name "~/Mail/namazu/")
606   "*Index directory for Namazu."
607   :type '(directory)
608   :group 'nnir)
609
610 (defcustom nnir-namazu-additional-switches '()
611   "*A list of strings, to be given as additional arguments to namazu.
612 The switches `-q', `-a', and `-s' are always used, very few other switches
613 make any sense in this context.
614
615 Note that this should be a list.  Ie, do NOT use the following:
616     (setq nnir-namazu-additional-switches \"-i -w\") ; wrong
617 Instead, use this:
618     (setq nnir-namazu-additional-switches '(\"-i\" \"-w\"))"
619   :type '(repeat (string))
620   :group 'nnir)
621
622 (defcustom nnir-namazu-remove-prefix (concat (getenv "HOME") "/Mail/")
623   "*The prefix to remove from each file name returned by Namazu
624 in order to get a group name (albeit with / instead of .).
625
626 This variable is very similar to `nnir-wais-remove-prefix', except
627 that it is for Namazu, not Wais."
628   :type '(directory)
629   :group 'nnir)
630
631 ;;; Internal Variables:
632
633 (defvar nnir-current-query nil
634   "Internal: stores current query (= group name).")
635
636 (defvar nnir-current-server nil
637   "Internal: stores current server (does it ever change?).")
638
639 (defvar nnir-current-group-marked nil
640   "Internal: stores current list of process-marked groups.")
641
642 (defvar nnir-artlist nil
643   "Internal: stores search result.")
644
645 (defvar nnir-tmp-buffer " *nnir*"
646   "Internal: temporary buffer.")
647
648 ;;; Code:
649
650 ;; Gnus glue.
651
652 (defun gnus-group-make-nnir-group (extra-parms query)
653   "Create an nnir group.  Asks for query."
654   (interactive "P\nsQuery: ")
655   (setq nnir-current-query nil
656         nnir-current-server nil
657         nnir-current-group-marked nil
658         nnir-artlist nil)
659   (let ((parms nil))
660     (if extra-parms
661         (setq parms (nnir-read-parms query))
662       (setq parms (list (cons 'query query))))
663     (add-to-list 'parms (cons 'unique-id (message-unique-id)) t)
664     (gnus-group-read-ephemeral-group
665      (concat "nnir:" (prin1-to-string parms)) '(nnir "") t
666      (cons (current-buffer)
667            gnus-current-window-configuration)
668      nil)))
669
670 ;; Emacs 19 compatibility?
671 (or (fboundp 'kbd) (defalias 'kbd 'read-kbd-macro))
672
673 (defun nnir-group-mode-hook ()
674   (define-key gnus-group-mode-map (kbd "G G")
675     'gnus-group-make-nnir-group))
676 (add-hook 'gnus-group-mode-hook 'nnir-group-mode-hook)
677
678 ;; Why is this needed? Is this for compatibility with old/new gnusae? Using
679 ;; gnus-group-server instead works for me.  -- Justus Piater
680 (defmacro nnir-group-server (group)
681   "Return the server for a newsgroup GROUP.
682 The returned format is as `gnus-server-to-method' needs it.  See
683 `gnus-group-real-prefix' and `gnus-group-real-name'."
684   `(let ((gname ,group))
685      (if (string-match "^\\([^:]+\\):" gname)
686          (progn
687            (setq gname (match-string 1 gname))
688            (if (string-match "^\\([^+]+\\)\\+\\(.+\\)$" gname)
689                (format "%s:%s" (match-string 1 gname) (match-string 2 gname))
690              (concat gname ":")))
691        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
692
693 ;; Summary mode commands.
694
695 (defun gnus-summary-nnir-goto-thread ()
696   "Only applies to nnir groups.  Go to group this article came from
697 and show thread that contains this article."
698   (interactive)
699   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
700     (error "Can't execute this command unless in nnir group."))
701   (let* ((cur (gnus-summary-article-number))
702          (group (nnir-artlist-artitem-group nnir-artlist cur))
703          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
704          server backend-group)
705     (setq server (nnir-group-server group))
706     (setq backend-group (gnus-group-real-name group))
707     (gnus-group-read-ephemeral-group
708      backend-group
709      (gnus-server-to-method server)
710      t                                  ; activate
711      (cons (current-buffer)
712            'summary)                    ; window config
713      nil
714      (list backend-number))
715     (gnus-summary-limit (list backend-number))
716     (gnus-summary-refer-thread)))
717
718 (if (fboundp 'eval-after-load)
719     (eval-after-load "gnus-sum"
720       '(define-key gnus-summary-goto-map
721          "T" 'gnus-summary-nnir-goto-thread))
722   (add-hook 'gnus-summary-mode-hook
723             (function (lambda ()
724                         (define-key gnus-summary-goto-map
725                           "T" 'gnus-summary-nnir-goto-thread)))))
726
727
728
729 ;; Gnus backend interface functions.
730
731 (deffoo nnir-open-server (server &optional definitions)
732   ;; Just set the server variables appropriately.
733   (nnoo-change-server 'nnir server definitions))
734
735 (deffoo nnir-request-group (group &optional server fast)
736   "GROUP is the query string."
737   (nnir-possibly-change-server server)
738   ;; Check for cache and return that if appropriate.
739   (if (and (equal group nnir-current-query)
740            (equal gnus-group-marked nnir-current-group-marked)
741            (or (null server)
742                (equal server nnir-current-server)))
743       nnir-artlist
744     ;; Cache miss.
745     (setq nnir-artlist (nnir-run-query group)))
746   (save-excursion
747     (set-buffer nntp-server-buffer)
748     (if (zerop (length nnir-artlist))
749         (progn
750           (setq nnir-current-query nil
751                 nnir-current-server nil
752                 nnir-current-group-marked nil
753                 nnir-artlist nil)
754           (nnheader-report 'nnir "Search produced empty results."))
755       ;; Remember data for cache.
756       (setq nnir-current-query group)
757       (when server (setq nnir-current-server server))
758       (setq nnir-current-group-marked gnus-group-marked)
759       (nnheader-insert "211 %d %d %d %s\n"
760                        (nnir-artlist-length nnir-artlist) ; total #
761                        1              ; first #
762                        (nnir-artlist-length nnir-artlist) ; last #
763                        group))))     ; group name
764
765 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
766   (save-excursion
767     (let ((artlist (copy-sequence articles))
768           (art nil)
769           (artitem nil)
770           (artgroup nil) (artno nil)
771           (artrsv nil)
772           (artfullgroup nil)
773           (novitem nil)
774           (novdata nil)
775           (foo nil)
776           server)
777       (while (not (null artlist))
778         (setq art (car artlist))
779         (or (numberp art)
780             (nnheader-report
781              'nnir
782              "nnir-retrieve-headers doesn't grok message ids: %s"
783              art))
784         (setq artitem (nnir-artlist-article nnir-artlist art))
785         (setq artrsv (nnir-artitem-rsv artitem))
786         (setq artfullgroup (nnir-artitem-group artitem))
787         (setq artno (nnir-artitem-number artitem))
788         (setq artgroup (gnus-group-real-name artfullgroup))
789         (setq server (nnir-group-server artfullgroup))
790         ;; retrieve NOV or HEAD data for this article, transform into
791         ;; NOV data and prepend to `novdata'
792         (set-buffer nntp-server-buffer)
793         (nnir-possibly-change-server server)
794         (let ((gnus-override-method
795                (gnus-server-to-method server)))
796           (case (setq foo (gnus-retrieve-headers (list artno) artfullgroup nil))
797             (nov
798              (goto-char (point-min))
799              (setq novitem (nnheader-parse-nov))
800              (unless novitem
801                (pop-to-buffer nntp-server-buffer)
802                (error
803                 "nnheader-parse-nov returned nil for article %s in group %s"
804                 artno artfullgroup)))
805             (headers
806              (goto-char (point-min))
807              (setq novitem (nnheader-parse-head))
808              (unless novitem
809                (pop-to-buffer nntp-server-buffer)
810                (error
811                 "nnheader-parse-head returned nil for article %s in group %s"
812                 artno artfullgroup)))
813             (t (error "Unknown header type %s while requesting article %s of group %s"
814                       foo artno artfullgroup))))
815         ;; replace article number in original group with article number
816         ;; in nnir group
817         (mail-header-set-number novitem art)
818         (mail-header-set-from novitem
819                               (mail-header-from novitem))
820         (mail-header-set-subject
821          novitem
822          (format "[%d: %s/%d] %s"
823                  artrsv artgroup artno
824                  (mail-header-subject novitem)))
825         ;;-(mail-header-set-extra novitem nil)
826         (push novitem novdata)
827         (setq artlist (cdr artlist)))
828       (setq novdata (nreverse novdata))
829       (set-buffer nntp-server-buffer) (erase-buffer)
830       (mapcar 'nnheader-insert-nov novdata)
831       'nov)))
832
833 (deffoo nnir-request-article (article
834                               &optional group server to-buffer)
835   (if (stringp article)
836       (nnheader-report
837        'nnir
838        "nnir-retrieve-headers doesn't grok message ids: %s"
839        article)
840     (save-excursion
841       (let* ((artitem (nnir-artlist-article nnir-artlist
842                                             article))
843              (artfullgroup (nnir-artitem-group artitem))
844              (artno (nnir-artitem-number artitem))
845              ;; Bug?
846              ;; Why must we bind nntp-server-buffer here?  It won't
847              ;; work if `buf' is used, say.  (Of course, the set-buffer
848              ;; line below must then be updated, too.)
849              (nntp-server-buffer (or to-buffer nntp-server-buffer)))
850         (set-buffer nntp-server-buffer)
851         (erase-buffer)
852         (message "Requesting article %d from group %s"
853                  artno artfullgroup)
854         (gnus-request-article artno artfullgroup nntp-server-buffer)
855         (cons artfullgroup artno)))))
856
857
858 (nnoo-define-skeleton nnir)
859
860
861 ;; Helper function currently used by the Swish++ and Namazu backends;
862 ;; perhaps useful for other backends as well
863 (defun nnir-compose-result (dirnam article score prefix server)
864   "Extract the group from dirnam, and create a result vector
865 ready to be added to the list of search results."
866
867   ;; remove nnir-*-remove-prefix from beginning of dirnam filename
868   (when (string-match (concat "^" prefix) dirnam)
869     (setq dirnam (replace-match "" t t dirnam)))
870
871   ;; remove trailing slash and, for nnmaildir, cur/new/tmp
872   (setq dirnam (substring dirnam 0 (if (string= server "nnmaildir:") -5 -1)))
873
874   ;; eliminate all ".", "/", "\" from beginning. Always matches.
875   (string-match "^[./\\]*\\(.*\\)$" dirnam)
876   (setq group (substitute ?. ?/ (match-string 1 dirnam))) ;; "/" -> "."
877   (setq group (substitute ?. ?\\ group)) ;; "\\" -> "."
878
879   (vector (nnir-group-full-name group server)
880           (if (string= server "nnmaildir:")
881               (nnmaildir-base-name-to-article-number
882                (substring article 0 (string-match ":" article))
883                group nil)
884             (string-to-int article))
885           (string-to-int score)))
886
887
888 ;;; Search Engine Interfaces:
889
890 ;; freeWAIS-sf interface.
891 (defun nnir-run-waissearch (query server &optional group)
892   "Run given query agains waissearch.  Returns vector of (group name, file name)
893 pairs (also vectors, actually)."
894   (when group
895     (error "The freeWAIS-sf backend cannot search specific groups."))
896   (save-excursion
897     (let ((qstring (cdr (assq 'query query)))
898           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
899           (artlist nil)
900           (score nil) (artno nil) (dirnam nil) (group nil))
901       (set-buffer (get-buffer-create nnir-tmp-buffer))
902       (erase-buffer)
903       (message "Doing WAIS query %s..." query)
904       (call-process nnir-wais-program
905                     nil                 ; input from /dev/null
906                     t                   ; output to current buffer
907                     nil                 ; don't redisplay
908                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
909                     qstring)
910       (message "Massaging waissearch output...")
911       ;; remove superfluous lines
912       (keep-lines "Score:")
913       ;; extract data from result lines
914       (goto-char (point-min))
915       (while (re-search-forward
916               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
917         (setq score (match-string 1)
918               artno (match-string 2)
919               dirnam (match-string 3))
920         (unless (string-match prefix dirnam)
921           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
922                            dirnam prefix))
923         (setq group (substitute ?. ?/ (replace-match "" t t dirnam)))
924         (push (vector (nnir-group-full-name group server)
925                       (string-to-int artno)
926                       (string-to-int score))
927               artlist))
928       (message "Massaging waissearch output...done")
929       (apply 'vector
930              (sort* artlist
931                     (function (lambda (x y)
932                                 (> (nnir-artitem-rsv x)
933                                    (nnir-artitem-rsv y)))))))))
934
935 ;; IMAP interface.
936 ;; todo:
937 ;; nnir invokes this two (2) times???!
938 ;; we should not use nnimap at all but open our own server connection
939 ;; we should not LIST * but use nnimap-list-pattern from defs
940 ;; send queries as literals
941 ;; handle errors
942
943 (defun nnir-run-imap (query srv &optional group-option)
944   (require 'imap)
945   (require 'nnimap)
946   (save-excursion
947     (let ((qstring (cdr (assq 'query query)))
948           (server (cadr (gnus-server-to-method srv)))
949           (group (or group-option (gnus-group-group-name)))
950           (defs (caddr (gnus-server-to-method srv)))
951           (criteria (or (cdr (assq 'criteria query))
952                         nnir-imap-search-field))
953           artlist buf)
954       (message "Opening server %s" server)
955       (condition-case ()
956           (when (nnimap-open-server server defs) ;; xxx
957             (setq buf nnimap-server-buffer) ;; xxx
958             (message "Searching %s..." group)
959             (let ((arts 0)
960                   (mbx (gnus-group-real-name group)))
961               (when (imap-mailbox-select mbx nil buf)
962                 (mapcar
963                  (lambda (artnum)
964                    (push (vector group artnum 1) artlist)
965                    (setq arts (1+ arts)))
966                  (imap-search (concat criteria " \"" qstring "\"") buf))
967                 (message "Searching %s... %d matches" mbx arts)))
968             (message "Searching %s...done" group))
969         (quit nil))
970       (reverse artlist))))
971
972 ;; Swish++ interface.
973 ;; -cc- Todo
974 ;; Search by
975 ;; - group
976 ;; Sort by
977 ;; - rank (default)
978 ;; - article number
979 ;; - file size
980 ;; - group
981 (defun nnir-run-swish++ (query server &optional group)
982   "Run given query against swish++.
983 Returns a vector of (group name, file name) pairs (also vectors,
984 actually).
985
986 Tested with swish++ 4.7 on GNU/Linux and with with swish++ 5.0b2 on
987 Windows NT 4.0."
988
989   (when group
990     (error "The swish++ backend cannot search specific groups."))
991
992   (save-excursion
993     (let ( (qstring (cdr (assq 'query query)))
994            (groupspec (cdr (assq 'group query)))
995            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
996            (artlist nil)
997            (article-pattern (if (string= server "nnmaildir:")
998                                 ":[0-9]+"
999                               "^[0-9]+\\(\\.[a-z0-9]+\\)?$"))
1000            (score nil) (artno nil) (dirnam nil) (group nil) )
1001
1002       (when (equal "" qstring)
1003         (error "swish++: You didn't enter anything."))
1004
1005       (set-buffer (get-buffer-create nnir-tmp-buffer))
1006       (erase-buffer)
1007
1008       (if groupspec
1009           (message "Doing swish++ query %s on %s..." qstring groupspec)
1010         (message "Doing swish++ query %s..." qstring))
1011
1012       (let* ((cp-list `( ,nnir-swish++-program
1013                          nil            ; input from /dev/null
1014                          t              ; output
1015                          nil            ; don't redisplay
1016                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1017                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1018                          ,qstring       ; the query, in swish++ format
1019                          ))
1020              (exitstatus
1021               (progn
1022                 (message "%s args: %s" nnir-swish++-program
1023                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1024                 (apply 'call-process cp-list))))
1025         (unless (or (null exitstatus)
1026                     (zerop exitstatus))
1027           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1028           ;; swish++ failure reason is in this buffer, show it if
1029           ;; the user wants it.
1030           (when (> gnus-verbose 6)
1031             (display-buffer nnir-tmp-buffer))))
1032
1033       ;; The results are output in the format of:
1034       ;; V 4.7 Linux
1035       ;; rank relative-path-name file-size file-title
1036       ;; V 5.0b2:
1037       ;; rank relative-path-name file-size topic??
1038       ;; where rank is an integer from 1 to 100.
1039       (goto-char (point-min))
1040       (while (re-search-forward
1041               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1042         (setq score (match-string 1)
1043               filenam (match-string 2)
1044               artno (file-name-nondirectory filenam)
1045               dirnam (file-name-directory filenam))
1046
1047         ;; don't match directories or inexistent/unreadable files
1048         (when (and (string-match article-pattern artno)
1049                    (file-readable-p filenam))
1050           ;; nnml-use-compressed-files might be any string, but probably this
1051           ;; is sufficient.  Note that we can't only use the value of
1052           ;; nnml-use-compressed-files because old articles might have been
1053           ;; saved with a different value.
1054           (when (not (null dirnam))
1055
1056             ;; maybe limit results to matching groups.
1057             (when (or (not groupspec)
1058                       (string-match groupspec dirnam))
1059               (push (nnir-compose-result dirnam artno score prefix server)
1060                     artlist)))))
1061
1062       (message "Massaging swish++ output...done")
1063
1064       ;; Sort by score
1065       (apply 'vector
1066              (sort* artlist
1067                     (function (lambda (x y)
1068                                 (> (nnir-artitem-rsv x)
1069                                    (nnir-artitem-rsv y)))))))))
1070
1071 ;; Swish-E interface.
1072 (defun nnir-run-swish-e (query server &optional group)
1073   "Run given query against swish-e.
1074 Returns a vector of (group name, file name) pairs (also vectors,
1075 actually).
1076
1077 Tested with swish-e-2.0.1 on Windows NT 4.0."
1078
1079   ;; swish-e crashes with empty parameter to "-w" on commandline...
1080   (when group
1081     (error "The swish-e backend cannot search specific groups."))
1082
1083   (save-excursion
1084     (let ((qstring (cdr (assq 'query query)))
1085           (prefix
1086            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1087                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1088           (artlist nil)
1089           (score nil) (artno nil) (dirnam nil) (group nil) )
1090
1091       (when (equal "" qstring)
1092         (error "swish-e: You didn't enter anything."))
1093
1094       (set-buffer (get-buffer-create nnir-tmp-buffer))
1095       (erase-buffer)
1096
1097       (message "Doing swish-e query %s..." query)
1098       (let* ((index-files
1099               (or (nnir-read-server-parm
1100                    'nnir-swish-e-index-files server)
1101                   (error "Missing parameter `nnir-swish-e-index-files'")))
1102              (additional-switches
1103               (nnir-read-server-parm
1104                'nnir-swish-e-additional-switches server))
1105              (cp-list `(,nnir-swish-e-program
1106                         nil             ; input from /dev/null
1107                         t               ; output
1108                         nil             ; don't redisplay
1109                         "-f" ,@index-files
1110                         ,@additional-switches
1111                         "-w"
1112                         ,qstring        ; the query, in swish-e format
1113                         ))
1114              (exitstatus
1115               (progn
1116                 (message "%s args: %s" nnir-swish-e-program
1117                          (mapconcat 'identity (cddddr cp-list) " "))
1118                 (apply 'call-process cp-list))))
1119         (unless (or (null exitstatus)
1120                     (zerop exitstatus))
1121           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1122           ;; swish-e failure reason is in this buffer, show it if
1123           ;; the user wants it.
1124           (when (> gnus-verbose 6)
1125             (display-buffer nnir-tmp-buffer))))
1126
1127       ;; The results are output in the format of:
1128       ;; rank path-name file-title file-size
1129       (goto-char (point-min))
1130       (while (re-search-forward
1131               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1132         (setq score (match-string 1)
1133               artno (match-string 3)
1134               dirnam (file-name-directory (match-string 2)))
1135
1136         ;; don't match directories
1137         (when (string-match "^[0-9]+$" artno)
1138           (when (not (null dirnam))
1139
1140             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1141             (when (string-match (concat "^" prefix) dirnam)
1142               (setq dirnam (replace-match "" t t dirnam)))
1143
1144             (setq dirnam (substring dirnam 0 -1))
1145             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1146             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1147             ;; "/" -> "."
1148             (setq group (substitute ?. ?/ (match-string 1 dirnam)))
1149             ;; Windows "\\" -> "."
1150             (setq group (substitute ?. ?\\ group))
1151
1152             (push (vector (nnir-group-full-name group server)
1153                           (string-to-int artno)
1154                           (string-to-int score))
1155                   artlist))))
1156
1157       (message "Massaging swish-e output...done")
1158
1159       ;; Sort by score
1160       (apply 'vector
1161              (sort* artlist
1162                     (function (lambda (x y)
1163                                 (> (nnir-artitem-rsv x)
1164                                    (nnir-artitem-rsv y)))))))))
1165
1166 ;; HyREX interface
1167 (defun nnir-run-hyrex (query server &optional group)
1168   (save-excursion
1169     (let ((artlist nil)
1170           (groupspec (cdr (assq 'group query)))
1171           (qstring (cdr (assq 'query query)))
1172           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1173           score artno dirnam)
1174       (when (and group groupspec)
1175         (error (concat "It does not make sense to use a group spec"
1176                        " with process-marked groups.")))
1177       (when group
1178         (setq groupspec (gnus-group-real-name group)))
1179       (when (and group (not (equal group (nnir-group-full-name groupspec server))))
1180         (message "%s vs. %s" group (nnir-group-full-name groupspec server))
1181         (error "Server with groupspec doesn't match group !"))
1182       (set-buffer (get-buffer-create nnir-tmp-buffer))
1183       (erase-buffer)
1184       (if groupspec
1185           (message "Doing hyrex-search query %s on %s..." query groupspec)
1186         (message "Doing hyrex-search query %s..." query))
1187       (let* ((cp-list
1188               `( ,nnir-hyrex-program
1189                  nil                    ; input from /dev/null
1190                  t                      ; output
1191                  nil                    ; don't redisplay
1192                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1193                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1194                  ,qstring          ; the query, in hyrex-search format
1195                  ))
1196              (exitstatus
1197               (progn
1198                 (message "%s args: %s" nnir-hyrex-program
1199                          (mapconcat 'identity (cddddr cp-list) " "))
1200                 (apply 'call-process cp-list))))
1201         (unless (or (null exitstatus)
1202                     (zerop exitstatus))
1203           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1204           ;; nnir-search failure reason is in this buffer, show it if
1205           ;; the user wants it.
1206           (when (> gnus-verbose 6)
1207             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1208       (if groupspec
1209           (message "Doing hyrex-search query \"%s\" on %s...done" qstring groupspec)
1210         (message "Doing hyrex-search query \"%s\"...done" qstring))
1211       (sit-for 0)
1212       ;; nnir-search returns:
1213       ;;   for nnml/nnfolder: "filename mailid weigth"
1214       ;;   for nnimap:        "group mailid weigth"
1215       (goto-char (point-min))
1216       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1217       ;; HyREX couldn't search directly in groups -- so filter out here.
1218       (when groupspec
1219         (keep-lines groupspec))
1220       ;; extract data from result lines
1221       (goto-char (point-min))
1222       (while (re-search-forward
1223               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1224         (setq dirnam (match-string 1)
1225               artno (match-string 2)
1226               score (match-string 3))
1227         (when (string-match prefix dirnam)
1228           (setq dirnam (replace-match "" t t dirnam)))
1229         (push (vector (nnir-group-full-name (substitute ?. ?/ dirnam) server)
1230                       (string-to-int artno)
1231                       (string-to-int score))
1232               artlist))
1233       (message "Massaging hyrex-search output...done.")
1234       (apply 'vector
1235              (sort* artlist
1236                     (function (lambda (x y)
1237                                 (if (string-lessp (nnir-artitem-group x)
1238                                                   (nnir-artitem-group y))
1239                                     t
1240                                   (< (nnir-artitem-number x)
1241                                      (nnir-artitem-number y)))))))
1242       )))
1243
1244 ;; Namazu interface
1245 (defun nnir-run-namazu (query server &optional group)
1246   "Run given query against Namazu.  Returns a vector of (group name, file name)
1247 pairs (also vectors, actually).
1248
1249 Tested with Namazu 2.0.6 on a GNU/Linux system."
1250   (when group
1251     (error "The Namazu backend cannot search specific groups"))
1252   (save-excursion
1253     (let (
1254           (article-pattern (if (string= server "nnmaildir:")
1255                                ":[0-9]+"
1256                              "^[0-9]+$"))
1257           (artlist nil)
1258           (qstring (cdr (assq 'query query)))
1259           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1260           (score nil)
1261           (group nil)
1262           (article nil)
1263           (process-environment (copy-sequence process-environment))
1264           )
1265       (setenv "LC_MESSAGES" "C")
1266       (set-buffer (get-buffer-create nnir-tmp-buffer))
1267       (erase-buffer)
1268       (let* ((cp-list
1269               `( ,nnir-namazu-program
1270                  nil                    ; input from /dev/null
1271                  t                      ; output
1272                  nil                    ; don't redisplay
1273                  "-q"                   ; don't be verbose
1274                  "-a"                   ; show all matches
1275                  "-s"                   ; use short format
1276                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1277                  ,qstring               ; the query, in namazu format
1278                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1279                  ))
1280              (exitstatus
1281               (progn
1282                 (message "%s args: %s" nnir-namazu-program
1283                          (mapconcat 'identity (cddddr cp-list) " "))
1284                 (apply 'call-process cp-list))))
1285         (unless (or (null exitstatus)
1286                     (zerop exitstatus))
1287           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1288           ;; Namazu failure reason is in this buffer, show it if
1289           ;; the user wants it.
1290           (when (> gnus-verbose 6)
1291             (display-buffer nnir-tmp-buffer))))
1292
1293       ;; Namazu output looks something like this:
1294       ;; 2. Re: Gnus agent expire broken (score: 55)
1295       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1296
1297       (goto-char (point-min))
1298       (while (re-search-forward
1299               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1300               nil t)
1301         (setq score (match-string 3)
1302               group (file-name-directory (match-string 4))
1303               article (file-name-nondirectory (match-string 4)))
1304
1305         ;; make sure article and group is sane
1306         (when (and (string-match article-pattern article)
1307                    (not (null group)))
1308           (push (nnir-compose-result group article score prefix server)
1309                 artlist)))
1310
1311       ;; sort artlist by score
1312       (apply 'vector
1313              (sort* artlist
1314                     (function (lambda (x y)
1315                                 (> (nnir-artitem-rsv x)
1316                                    (nnir-artitem-rsv y)))))))))
1317
1318 (defun nnir-run-find-grep (query server &optional group)
1319   "Run find and grep to obtain matching articles."
1320   (let* ((method (gnus-server-to-method server))
1321          (sym (intern
1322                (concat (symbol-name (car method)) "-directory")))
1323          (directory (cadr (assoc sym (cddr method))))
1324          (regexp (cdr (assoc 'query query)))
1325          (grep-options (cdr (assoc 'grep-options query)))
1326          artlist)
1327     (unless directory
1328       (error "No directory found in method specification of server %s"
1329              server))
1330     (message "Searching %s using find-grep..." (or group server))
1331     (save-window-excursion
1332       (set-buffer (get-buffer-create nnir-tmp-buffer))
1333       (erase-buffer)
1334       (if (> gnus-verbose 6)
1335           (pop-to-buffer (current-buffer)))
1336       (cd directory) ; Using relative paths simplifies postprocessing.
1337       (let ((group
1338              (if (not group)
1339                  "."
1340                ;; Try accessing the group literally as well as
1341                ;; interpreting dots as directory separators so the
1342                ;; engine works with plain nnml as well as the Gnus
1343                ;; Cache.
1344                (find-if 'file-directory-p
1345                 (let ((group (gnus-group-real-name group)))
1346                   (list group (gnus-replace-in-string group "\\." "/" t)))))))
1347         (unless group
1348           (error "Cannot locate directory for group"))
1349         (save-excursion
1350           (apply
1351            'call-process "find" nil t
1352            "find" group "-type" "f" "-name" "[0-9]*" "-exec"
1353            "grep"
1354            `("-l" ,@(and grep-options (split-string grep-options "\\s-" t))
1355              "-e" ,regexp "{}" "+"))))
1356
1357       ;; Translate relative paths to group names.
1358       (while (not (eobp))
1359         (let* ((path (split-string
1360                       (buffer-substring (point) (line-end-position)) "/" t))
1361                (art (string-to-number (car (last path)))))
1362           (while (string= "." (car path))
1363             (setq path (cdr path)))
1364           (let ((group (mapconcat 'identity (subseq path 0 -1) ".")))
1365             (push (vector (nnir-group-full-name group server) art 0)
1366                   artlist))
1367           (forward-line 1)))
1368       (message "Searching %s using find-grep...done" (or group server))
1369       artlist)))
1370
1371 ;;; Util Code:
1372
1373 (defun nnir-read-parms (query)
1374   "Reads additional search parameters according to `nnir-engines'."
1375   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1376     (cons (cons 'query query)
1377           (mapcar 'nnir-read-parm parmspec))))
1378
1379 (defun nnir-read-parm (parmspec)
1380   "Reads a single search parameter.
1381 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1382   (let ((sym (car parmspec))
1383         (prompt (cdr parmspec)))
1384     (if (listp prompt)
1385         (let* ((result (apply 'completing-read prompt))
1386                (mapping (or (assoc result nnir-imap-search-arguments)
1387                             (assoc nil nnir-imap-search-arguments))))
1388           (cons sym (format (cdr mapping) result)))
1389       (cons sym (read-string prompt)))))
1390
1391 (defun nnir-run-query (query)
1392   "Invoke appropriate search engine function (see `nnir-engines').
1393 If some groups were process-marked, run the query for each of the groups
1394 and concat the results."
1395   (let ((q (car (read-from-string query))))
1396     (if gnus-group-marked
1397         (apply 'vconcat
1398                (mapcar (lambda (x)
1399                          (let ((server (nnir-group-server x))
1400                                search-func)
1401                            (setq search-func (cadr
1402                                               (assoc
1403                                                (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1404                            (if search-func
1405                                (funcall search-func q server x)
1406                              nil)))
1407                        gnus-group-marked)
1408                )
1409       (apply 'vconcat
1410              (mapcar (lambda (x)
1411                        (if (and (equal (cadr x) 'ok) (not (equal (cadar x) "-ephemeral")))
1412                            (let ((server (format "%s:%s" (caar x) (cadar x)))
1413                                  search-func)
1414                              (setq search-func (cadr
1415                                                 (assoc
1416                                                  (nnir-read-server-parm 'nnir-search-engine server) nnir-engines)))
1417                              (if search-func
1418                                  (funcall search-func q server nil)
1419                                nil))
1420                          nil))
1421                      gnus-opened-servers)
1422              ))
1423     ))
1424
1425 (defun nnir-read-server-parm (key server)
1426   "Returns the parameter value of for the given server, where server is of
1427 form 'backend:name'."
1428   (let ((method (gnus-server-to-method server)))
1429     (cond ((and method (assq key (cddr method)))
1430            (nth 1 (assq key (cddr method))))
1431           ((and nnir-mail-backend
1432                 (gnus-server-equal method nnir-mail-backend))
1433            (symbol-value key))
1434           (t nil))))
1435 ;;     (if method
1436 ;;       (if (assq key (cddr method))
1437 ;;        (nth 1 (assq key (cddr method)))
1438 ;;      (symbol-value key))
1439 ;;       (symbol-value key))
1440 ;;     ))
1441
1442 (defun nnir-group-full-name (shortname server)
1443   "For the given group name, return a full Gnus group name.
1444 The Gnus backend/server information is added."
1445   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1446
1447 (defun nnir-possibly-change-server (server)
1448   (unless (and server (nnir-server-opened server))
1449     (nnir-open-server server)))
1450
1451
1452 ;; Data type article list.
1453
1454 (defun nnir-artlist-length (artlist)
1455   "Returns number of articles in artlist."
1456   (length artlist))
1457
1458 (defun nnir-artlist-article (artlist n)
1459   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1460   (elt artlist (1- n)))
1461
1462 (defun nnir-artitem-group (artitem)
1463   "Returns the group from the ARTITEM."
1464   (elt artitem 0))
1465
1466 (defun nnir-artlist-artitem-group (artlist n)
1467   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1468   (nnir-artitem-group (nnir-artlist-article artlist n)))
1469
1470 (defun nnir-artitem-number (artitem)
1471   "Returns the number from the ARTITEM."
1472   (elt artitem 1))
1473
1474 (defun nnir-artlist-artitem-number (artlist n)
1475   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1476   (nnir-artitem-number (nnir-artlist-article artlist n)))
1477
1478 (defun nnir-artitem-rsv (artitem)
1479   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1480   (elt artitem 2))
1481
1482 (defun nnir-artlist-artitem-rsv (artlist n)
1483   "Returns from ARTLIST the Retrieval Status Value of the Nth artitem
1484 \(counting from 1)."
1485   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1486
1487 ;; unused?
1488 (defun nnir-artlist-groups (artlist)
1489   "Returns a list of all groups in the given ARTLIST."
1490   (let ((res nil)
1491         (with-dups nil))
1492     ;; from each artitem, extract group component
1493     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1494     ;; remove duplicates from above
1495     (mapcar (function (lambda (x) (add-to-list 'res x)))
1496             with-dups)
1497     res))
1498
1499
1500 ;; The end.
1501 (provide 'nnir)
1502
1503 ;;; arch-tag: 9b3fecf8-4397-4bbb-bf3c-6ac3cbbc6664