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