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