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