Allow nnir searching for an entire server.
[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          (srv (if (gnus-server-server-name)
496                   "all" "")))
497     (add-to-list 'parms (cons 'unique-id (message-unique-id)) t)
498     (gnus-group-read-ephemeral-group
499      (concat "nnir:" (prin1-to-string parms)) (list 'nnir srv) t
500      (cons (current-buffer) gnus-current-window-configuration)
501      nil)))
502
503 ;; Summary mode commands.
504
505 (defun gnus-summary-nnir-goto-thread ()
506   "Only applies to nnir groups.  Go to group this article came from
507 and show thread that contains this article."
508   (interactive)
509   (unless (eq 'nnir (car (gnus-find-method-for-group gnus-newsgroup-name)))
510     (error "Can't execute this command unless in nnir group"))
511   (let* ((cur (gnus-summary-article-number))
512          (group (nnir-artlist-artitem-group nnir-artlist cur))
513          (backend-number (nnir-artlist-artitem-number nnir-artlist cur))
514          (id (mail-header-id (gnus-summary-article-header)))
515          (refs (split-string
516                 (mail-header-references (gnus-summary-article-header)))))
517     (if (eq (car (gnus-find-method-for-group group)) 'nnimap)
518         (progn
519           (nnimap-possibly-change-group (gnus-group-short-name group) nil)
520           (with-current-buffer (nnimap-buffer)
521             (let* ((cmd
522                     (let ((value
523                            (format
524                             "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
525                             id id)))
526                       (dolist (refid refs value)
527                         (setq value
528                               (format
529                                "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
530                                refid refid value)))))
531                    (result (nnimap-command "UID SEARCH %s" cmd)))
532               (gnus-summary-read-group-1
533                group t t gnus-summary-buffer nil
534                (and (car result)
535                     (delete 0 (mapcar
536                                #'string-to-number
537                                (cdr (assoc "SEARCH" (cdr result))))))))))
538       (gnus-summary-read-group-1 group t t gnus-summary-buffer
539                                  nil (list backend-number))
540       (gnus-summary-limit (list backend-number))
541       (gnus-summary-refer-thread))))
542
543
544 (if (fboundp 'eval-after-load)
545     (eval-after-load "gnus-sum"
546       '(define-key gnus-summary-goto-map
547          "T" 'gnus-summary-nnir-goto-thread))
548   (add-hook 'gnus-summary-mode-hook
549             (function (lambda ()
550                         (define-key gnus-summary-goto-map
551                           "T" 'gnus-summary-nnir-goto-thread)))))
552
553
554
555 ;; Gnus backend interface functions.
556
557 (deffoo nnir-open-server (server &optional definitions)
558   ;; Just set the server variables appropriately.
559   (nnoo-change-server 'nnir server definitions))
560
561 (deffoo nnir-request-group (group &optional server fast info)
562   "GROUP is the query string."
563   (nnir-possibly-change-server server)
564   ;; Check for cache and return that if appropriate.
565   (if (and (equal group nnir-current-query)
566            (equal gnus-group-marked nnir-current-group-marked)
567            (or (null server)
568                (equal server nnir-current-server)))
569       nnir-artlist
570     ;; Cache miss.
571     (setq nnir-artlist (nnir-run-query group server)))
572   (with-current-buffer nntp-server-buffer
573     (setq nnir-current-query group)
574     (when server (setq nnir-current-server server))
575     (setq nnir-current-group-marked gnus-group-marked)
576     (if (zerop (length nnir-artlist))
577         (nnheader-report 'nnir "Search produced empty results.")
578       ;; Remember data for cache.
579       (nnheader-insert "211 %d %d %d %s\n"
580                        (nnir-artlist-length nnir-artlist) ; total #
581                        1              ; first #
582                        (nnir-artlist-length nnir-artlist) ; last #
583                        group))))      ; group name
584
585 (deffoo nnir-retrieve-headers (articles &optional group server fetch-old)
586   (save-excursion
587     (let ((artlist (copy-sequence articles))
588           art artitem artgroup artno artrsv artfullgroup
589           novitem novdata foo server)
590       (while (not (null artlist))
591         (setq art (car artlist))
592         (or (numberp art)
593             (nnheader-report
594              'nnir
595              "nnir-retrieve-headers doesn't grok message ids: %s"
596              art))
597         (setq artitem (nnir-artlist-article nnir-artlist art))
598         (setq artrsv (nnir-artitem-rsv artitem))
599         (setq artfullgroup (nnir-artitem-group artitem))
600         (setq artno (nnir-artitem-number artitem))
601         (setq artgroup (gnus-group-real-name artfullgroup))
602         (setq server (gnus-group-server artfullgroup))
603         ;; retrieve NOV or HEAD data for this article, transform into
604         ;; NOV data and prepend to `novdata'
605         (set-buffer nntp-server-buffer)
606         (nnir-possibly-change-server server)
607         (let ((gnus-override-method
608                (gnus-server-to-method server)))
609           ;; if nnir-get-article-nov-override-function is set, use it
610           (if nnir-get-article-nov-override-function
611               (setq novitem (funcall nnir-get-article-nov-override-function
612                                      artitem))
613             ;; else, set novitem through nnheader-parse-nov/nnheader-parse-head
614             (case (setq foo (gnus-retrieve-headers (list artno)
615                                                    artfullgroup nil))
616               (nov
617                (goto-char (point-min))
618                (setq novitem (nnheader-parse-nov)))
619               (headers
620                (goto-char (point-min))
621                (setq novitem (nnheader-parse-head)))
622               (t (error "Unknown header type %s while requesting article %s of group %s"
623                         foo artno artfullgroup)))))
624         ;; replace article number in original group with article number
625         ;; in nnir group
626         (when novitem
627           (mail-header-set-number novitem art)
628           (mail-header-set-from novitem
629                                 (mail-header-from novitem))
630           (mail-header-set-subject
631            novitem
632            (format "[%d: %s/%d] %s"
633                    artrsv artgroup artno
634                    (mail-header-subject novitem)))
635           (push novitem novdata)
636           (setq artlist (cdr artlist))))
637       (setq novdata (nreverse novdata))
638       (set-buffer nntp-server-buffer) (erase-buffer)
639       (mapc 'nnheader-insert-nov novdata)
640       'nov)))
641
642 (deffoo nnir-request-article (article
643                               &optional group server to-buffer)
644   (if (stringp article)
645       (nnheader-report
646        'nnir
647        "nnir-retrieve-headers doesn't grok message ids: %s"
648        article)
649     (save-excursion
650       (let* ((artitem (nnir-artlist-article nnir-artlist
651                                             article))
652              (artfullgroup (nnir-artitem-group artitem))
653              (artno (nnir-artitem-number artitem))
654              ;; Bug?
655              ;; Why must we bind nntp-server-buffer here?  It won't
656              ;; work if `buf' is used, say.  (Of course, the set-buffer
657              ;; line below must then be updated, too.)
658              (nntp-server-buffer (or to-buffer nntp-server-buffer)))
659         (set-buffer nntp-server-buffer)
660         (erase-buffer)
661         (message "Requesting article %d from group %s"
662                  artno artfullgroup)
663         (gnus-request-article artno artfullgroup nntp-server-buffer)
664         (cons artfullgroup artno)))))
665
666
667 (nnoo-define-skeleton nnir)
668
669
670 (defmacro nnir-add-result (dirnam artno score prefix server artlist)
671   "Ask `nnir-compose-result' to construct a result vector,
672 and if it is non-nil, add it to artlist."
673   `(let ((result (nnir-compose-result ,dirnam ,artno ,score ,prefix ,server)))
674      (when (not (null result))
675        (push result ,artlist))))
676
677 (autoload 'nnmaildir-base-name-to-article-number "nnmaildir")
678
679 ;; Helper function currently used by the Swish++ and Namazu backends;
680 ;; perhaps useful for other backends as well
681 (defun nnir-compose-result (dirnam article score prefix server)
682   "Extract the group from dirnam, and create a result vector
683 ready to be added to the list of search results."
684
685   ;; remove nnir-*-remove-prefix from beginning of dirnam filename
686   (when (string-match (concat "^" prefix) dirnam)
687     (setq dirnam (replace-match "" t t dirnam)))
688
689   (when (file-readable-p (concat prefix dirnam article))
690     ;; remove trailing slash and, for nnmaildir, cur/new/tmp
691     (setq dirnam
692           (substring dirnam 0
693                      (if (string= (gnus-group-server server) "nnmaildir")
694                          -5 -1)))
695
696     ;; Set group to dirnam without any leading dots or slashes,
697     ;; and with all subsequent slashes replaced by dots
698     (let ((group (gnus-replace-in-string
699                  (gnus-replace-in-string dirnam "^[./\\]" "" t)
700                  "[/\\]" "." t)))
701
702     (vector (nnir-group-full-name group server)
703             (if (string= (gnus-group-server server) "nnmaildir")
704                 (nnmaildir-base-name-to-article-number
705                  (substring article 0 (string-match ":" article))
706                  group nil)
707               (string-to-number article))
708             (string-to-number score)))))
709
710 ;;; Search Engine Interfaces:
711
712 ;; freeWAIS-sf interface.
713 (defun nnir-run-waissearch (query server &optional group)
714   "Run given query agains waissearch.  Returns vector of (group name, file name)
715 pairs (also vectors, actually)."
716   ;; (when group
717   ;;   (error "The freeWAIS-sf backend cannot search specific groups"))
718   (save-excursion
719     (let ((qstring (cdr (assq 'query query)))
720           (prefix (nnir-read-server-parm 'nnir-wais-remove-prefix server))
721           artlist score artno dirnam)
722       (set-buffer (get-buffer-create nnir-tmp-buffer))
723       (erase-buffer)
724       (message "Doing WAIS query %s..." query)
725       (call-process nnir-wais-program
726                     nil                 ; input from /dev/null
727                     t                   ; output to current buffer
728                     nil                 ; don't redisplay
729                     "-d" (nnir-read-server-parm 'nnir-wais-database server) ; database to search
730                     qstring)
731       (message "Massaging waissearch output...")
732       ;; remove superfluous lines
733       (keep-lines "Score:")
734       ;; extract data from result lines
735       (goto-char (point-min))
736       (while (re-search-forward
737               "Score: +\\([0-9]+\\).*'\\([0-9]+\\) +\\([^']+\\)/'" nil t)
738         (setq score (match-string 1)
739               artno (match-string 2)
740               dirnam (match-string 3))
741         (unless (string-match prefix dirnam)
742           (nnheader-report 'nnir "Dir name %s doesn't contain prefix %s"
743                            dirnam prefix))
744         (setq group (gnus-replace-in-string
745                      (replace-match "" t t dirnam) "/" "."))
746         (push (vector (nnir-group-full-name group server)
747                       (string-to-number artno)
748                       (string-to-number score))
749               artlist))
750       (message "Massaging waissearch output...done")
751       (apply 'vector
752              (sort artlist
753                    (function (lambda (x y)
754                                (> (nnir-artitem-rsv x)
755                                   (nnir-artitem-rsv y)))))))))
756
757 ;; imap interface
758 (defun nnir-run-imap (query srv &optional groups)
759   "Run a search against an IMAP back-end server.
760 This uses a custom query language parser; see `nnir-imap-make-query' for
761 details on the language and supported extensions"
762   (save-excursion
763     (let ((qstring (cdr (assq 'query query)))
764           (server (cadr (gnus-server-to-method srv)))
765           (defs (caddr (gnus-server-to-method srv)))
766           (criteria (or (cdr (assq 'criteria query))
767                         (cdr (assoc nnir-imap-default-search-key
768                                     nnir-imap-search-arguments))))
769           (gnus-inhibit-demon t)
770           (groups (or groups (nnir-get-active srv)))
771           artlist)
772       (message "Opening server %s" server)
773       (apply
774        'vconcat
775        (mapcar
776         (lambda (x)
777           (let ((group x))
778             (condition-case ()
779                 (when (nnimap-possibly-change-group
780                        (gnus-group-short-name group) server)
781                   (with-current-buffer (nnimap-buffer)
782                     (message "Searching %s..." group)
783                     (let ((arts 0)
784                           (result (nnimap-command "UID SEARCH %s"
785                                                   (if (string= criteria "")
786                                                       qstring
787                                                     (nnir-imap-make-query
788                                                      criteria qstring)))))
789                       (mapc
790                        (lambda (artnum) (push (vector group artnum 1) artlist)
791                          (setq arts (1+ arts)))
792                        (and (car result)
793                             (delete 0 (mapcar #'string-to-number
794                                               (cdr (assoc "SEARCH"
795                                                           (cdr result)))))))
796                       (message "Searching %s... %d matches" group arts)))
797                   (message "Searching %s...done" group))
798               (quit nil))
799             (reverse artlist)))
800         groups)))))
801
802 (defun nnir-imap-make-query (criteria qstring)
803   "Parse the query string and criteria into an appropriate IMAP search
804 expression, returning the string query to make.
805
806 This implements a little language designed to return the expected results
807 to an arbitrary query string to the end user.
808
809 The search is always case-insensitive, as defined by RFC2060, and supports
810 the following features (inspired by the Google search input language):
811
812 Automatic \"and\" queries
813     If you specify multiple words then they will be treated as an \"and\"
814     expression intended to match all components.
815
816 Phrase searches
817     If you wrap your query in double-quotes then it will be treated as a
818     literal string.
819
820 Negative terms
821     If you precede a term with \"-\" then it will negate that.
822
823 \"OR\" queries
824     If you include an upper-case \"OR\" in your search it will cause the
825     term before it and the term after it to be treated as alternatives.
826
827 In future the following will be added to the language:
828  * support for date matches
829  * support for location of text matching within the query
830  * from/to/etc headers
831  * additional search terms
832  * flag based searching
833  * anything else that the RFC supports, basically."
834   ;; Walk through the query and turn it into an IMAP query string.
835   (nnir-imap-query-to-imap criteria (nnir-imap-parse-query qstring)))
836
837
838 (defun nnir-imap-query-to-imap (criteria query)
839   "Turn a s-expression format query into IMAP."
840   (mapconcat
841    ;; Turn the expressions into IMAP text
842    (lambda (item)
843      (nnir-imap-expr-to-imap criteria item))
844    ;; The query, already in s-expr format.
845    query
846    ;; Append a space between each expression
847    " "))
848
849
850 (defun nnir-imap-expr-to-imap (criteria expr)
851   "Convert EXPR into an IMAP search expression on CRITERIA"
852   ;; What sort of expression is this, eh?
853   (cond
854    ;; Simple string term
855    ((stringp expr)
856     (format "%s %S" criteria expr))
857    ;; Trivial term: and
858    ((eq expr 'and) nil)
859    ;; Composite term: or expression
860    ((eq (car-safe expr) 'or)
861     (format "OR %s %s"
862             (nnir-imap-expr-to-imap criteria (second expr))
863             (nnir-imap-expr-to-imap criteria (third expr))))
864    ;; Composite term: just the fax, mam
865    ((eq (car-safe expr) 'not)
866     (format "NOT (%s)" (nnir-imap-query-to-imap criteria (rest expr))))
867    ;; Composite term: just expand it all.
868    ((and (not (null expr)) (listp expr))
869     (format "(%s)" (nnir-imap-query-to-imap criteria expr)))
870    ;; Complex value, give up for now.
871    (t (error "Unhandled input: %S" expr))))
872
873
874 (defun nnir-imap-parse-query (string)
875   "Turn STRING into an s-expression based query based on the IMAP
876 query language as defined in `nnir-imap-make-query'.
877
878 This involves turning individual tokens into higher level terms
879 that the search language can then understand and use."
880   (with-temp-buffer
881     ;; Set up the parsing environment.
882     (insert string)
883     (goto-char (point-min))
884     ;; Now, collect the output terms and return them.
885     (let (out)
886       (while (not (nnir-imap-end-of-input))
887         (push (nnir-imap-next-expr) out))
888       (reverse out))))
889
890
891 (defun nnir-imap-next-expr (&optional count)
892   "Return the next expression from the current buffer."
893   (let ((term (nnir-imap-next-term count))
894         (next (nnir-imap-peek-symbol)))
895     ;; Are we looking at an 'or' expression?
896     (cond
897      ;; Handle 'expr or expr'
898      ((eq next 'or)
899       (list 'or term (nnir-imap-next-expr 2)))
900      ;; Anything else
901      (t term))))
902
903
904 (defun nnir-imap-next-term (&optional count)
905   "Return the next TERM from the current buffer."
906   (let ((term (nnir-imap-next-symbol count)))
907     ;; What sort of term is this?
908     (cond
909      ;; and -- just ignore it
910      ((eq term 'and) 'and)
911      ;; negated term
912      ((eq term 'not) (list 'not (nnir-imap-next-expr)))
913      ;; generic term
914      (t term))))
915
916
917 (defun nnir-imap-peek-symbol ()
918   "Return the next symbol from the current buffer, but don't consume it."
919   (save-excursion
920     (nnir-imap-next-symbol)))
921
922 (defun nnir-imap-next-symbol (&optional count)
923   "Return the next symbol from the current buffer, or nil if we are
924 at the end of the buffer.  If supplied COUNT skips some symbols before
925 returning the one at the supplied position."
926   (when (and (numberp count) (> count 1))
927     (nnir-imap-next-symbol (1- count)))
928   (let ((case-fold-search t))
929     ;; end of input stream?
930     (unless (nnir-imap-end-of-input)
931       ;; No, return the next symbol from the stream.
932       (cond
933        ;; negated expression -- return it and advance one char.
934        ((looking-at "-") (forward-char 1) 'not)
935        ;; quoted string
936        ((looking-at "\"") (nnir-imap-delimited-string "\""))
937        ;; list expression -- we parse the content and return this as a list.
938        ((looking-at "(")
939         (nnir-imap-parse-query (nnir-imap-delimited-string ")")))
940        ;; keyword input -- return a symbol version
941        ((looking-at "\\band\\b") (forward-char 3) 'and)
942        ((looking-at "\\bor\\b")  (forward-char 2) 'or)
943        ((looking-at "\\bnot\\b") (forward-char 3) 'not)
944        ;; Simple, boring keyword
945        (t (let ((start (point))
946                 (end (if (search-forward-regexp "[[:blank:]]" nil t)
947                          (prog1
948                              (match-beginning 0)
949                            ;; unskip if we hit a non-blank terminal character.
950                            (when (string-match "[^[:blank:]]" (match-string 0))
951                              (backward-char 1)))
952                        (goto-char (point-max)))))
953             (buffer-substring start end)))))))
954
955 (defun nnir-imap-delimited-string (delimiter)
956   "Return a delimited string from the current buffer."
957   (let ((start (point)) end)
958     (forward-char 1)                    ; skip the first delimiter.
959     (while (not end)
960       (unless (search-forward delimiter nil t)
961         (error "Unmatched delimited input with %s in query" delimiter))
962       (let ((here (point)))
963         (unless (equal (buffer-substring (- here 2) (- here 1)) "\\")
964           (setq end (point)))))
965     (buffer-substring (1+ start) (1- end))))
966
967 (defun nnir-imap-end-of-input ()
968   "Are we at the end of input?"
969   (skip-chars-forward "[[:blank:]]")
970   (looking-at "$"))
971
972
973 ;; Swish++ interface.
974 ;; -cc- Todo
975 ;; Search by
976 ;; - group
977 ;; Sort by
978 ;; - rank (default)
979 ;; - article number
980 ;; - file size
981 ;; - group
982 (defun nnir-run-swish++ (query server &optional group)
983   "Run QUERY against swish++.
984 Returns a vector of (group name, file name) pairs (also vectors,
985 actually).
986
987 Tested with swish++ 4.7 on GNU/Linux and with swish++ 5.0b2 on
988 Windows NT 4.0."
989
990   ;; (when group
991   ;;   (error "The swish++ backend cannot search specific groups"))
992
993   (save-excursion
994     (let ( (qstring (cdr (assq 'query query)))
995            (groupspec (cdr (assq 'group query)))
996            (prefix (nnir-read-server-parm 'nnir-swish++-remove-prefix server))
997            artlist
998            ;; nnml-use-compressed-files might be any string, but probably this
999            ;; is sufficient.  Note that we can't only use the value of
1000            ;; nnml-use-compressed-files because old articles might have been
1001            ;; saved with a different value.
1002            (article-pattern (if (string= (gnus-group-server server) "nnmaildir")
1003                                 ":[0-9]+"
1004                               "^[0-9]+\\(\\.[a-z0-9]+\\)?$"))
1005            score artno dirnam filenam)
1006
1007       (when (equal "" qstring)
1008         (error "swish++: You didn't enter anything"))
1009
1010       (set-buffer (get-buffer-create nnir-tmp-buffer))
1011       (erase-buffer)
1012
1013       (if groupspec
1014           (message "Doing swish++ query %s on %s..." qstring groupspec)
1015         (message "Doing swish++ query %s..." qstring))
1016
1017       (let* ((cp-list `( ,nnir-swish++-program
1018                          nil            ; input from /dev/null
1019                          t              ; output
1020                          nil            ; don't redisplay
1021                          "--config-file" ,(nnir-read-server-parm 'nnir-swish++-configuration-file server)
1022                          ,@(nnir-read-server-parm 'nnir-swish++-additional-switches server)
1023                          ,qstring       ; the query, in swish++ format
1024                          ))
1025              (exitstatus
1026               (progn
1027                 (message "%s args: %s" nnir-swish++-program
1028                          (mapconcat 'identity (cddddr cp-list) " ")) ;; ???
1029                 (apply 'call-process cp-list))))
1030         (unless (or (null exitstatus)
1031                     (zerop exitstatus))
1032           (nnheader-report 'nnir "Couldn't run swish++: %s" exitstatus)
1033           ;; swish++ failure reason is in this buffer, show it if
1034           ;; the user wants it.
1035           (when (> gnus-verbose 6)
1036             (display-buffer nnir-tmp-buffer))))
1037
1038       ;; The results are output in the format of:
1039       ;; V 4.7 Linux
1040       ;; rank relative-path-name file-size file-title
1041       ;; V 5.0b2:
1042       ;; rank relative-path-name file-size topic??
1043       ;; where rank is an integer from 1 to 100.
1044       (goto-char (point-min))
1045       (while (re-search-forward
1046               "\\(^[0-9]+\\) \\([^ ]+\\) [0-9]+ \\(.*\\)$" nil t)
1047         (setq score (match-string 1)
1048               filenam (match-string 2)
1049               artno (file-name-nondirectory filenam)
1050               dirnam (file-name-directory filenam))
1051
1052         ;; don't match directories
1053         (when (string-match article-pattern artno)
1054           (when (not (null dirnam))
1055
1056             ;; maybe limit results to matching groups.
1057             (when (or (not groupspec)
1058                       (string-match groupspec dirnam))
1059               (nnir-add-result dirnam artno score prefix server artlist)))))
1060
1061       (message "Massaging swish++ output...done")
1062
1063       ;; Sort by score
1064       (apply 'vector
1065              (sort artlist
1066                    (function (lambda (x y)
1067                                (> (nnir-artitem-rsv x)
1068                                   (nnir-artitem-rsv y)))))))))
1069
1070 ;; Swish-E interface.
1071 (defun nnir-run-swish-e (query server &optional group)
1072   "Run given query against swish-e.
1073 Returns a vector of (group name, file name) pairs (also vectors,
1074 actually).
1075
1076 Tested with swish-e-2.0.1 on Windows NT 4.0."
1077
1078   ;; swish-e crashes with empty parameter to "-w" on commandline...
1079   ;; (when group
1080   ;;   (error "The swish-e backend cannot search specific groups"))
1081
1082   (save-excursion
1083     (let ((qstring (cdr (assq 'query query)))
1084           (prefix
1085            (or (nnir-read-server-parm 'nnir-swish-e-remove-prefix server)
1086                (error "Missing parameter `nnir-swish-e-remove-prefix'")))
1087           artlist score artno dirnam group )
1088
1089       (when (equal "" qstring)
1090         (error "swish-e: You didn't enter anything"))
1091
1092       (set-buffer (get-buffer-create nnir-tmp-buffer))
1093       (erase-buffer)
1094
1095       (message "Doing swish-e query %s..." query)
1096       (let* ((index-files
1097               (or (nnir-read-server-parm
1098                    'nnir-swish-e-index-files server)
1099                   (error "Missing parameter `nnir-swish-e-index-files'")))
1100              (additional-switches
1101               (nnir-read-server-parm
1102                'nnir-swish-e-additional-switches server))
1103              (cp-list `(,nnir-swish-e-program
1104                         nil             ; input from /dev/null
1105                         t               ; output
1106                         nil             ; don't redisplay
1107                         "-f" ,@index-files
1108                         ,@additional-switches
1109                         "-w"
1110                         ,qstring        ; the query, in swish-e format
1111                         ))
1112              (exitstatus
1113               (progn
1114                 (message "%s args: %s" nnir-swish-e-program
1115                          (mapconcat 'identity (cddddr cp-list) " "))
1116                 (apply 'call-process cp-list))))
1117         (unless (or (null exitstatus)
1118                     (zerop exitstatus))
1119           (nnheader-report 'nnir "Couldn't run swish-e: %s" exitstatus)
1120           ;; swish-e failure reason is in this buffer, show it if
1121           ;; the user wants it.
1122           (when (> gnus-verbose 6)
1123             (display-buffer nnir-tmp-buffer))))
1124
1125       ;; The results are output in the format of:
1126       ;; rank path-name file-title file-size
1127       (goto-char (point-min))
1128       (while (re-search-forward
1129               "\\(^[0-9]+\\) \\([^ ]+\\) \"\\([^\"]+\\)\" [0-9]+$" nil t)
1130         (setq score (match-string 1)
1131               artno (match-string 3)
1132               dirnam (file-name-directory (match-string 2)))
1133
1134         ;; don't match directories
1135         (when (string-match "^[0-9]+$" artno)
1136           (when (not (null dirnam))
1137
1138             ;; remove nnir-swish-e-remove-prefix from beginning of dirname
1139             (when (string-match (concat "^" prefix) dirnam)
1140               (setq dirnam (replace-match "" t t dirnam)))
1141
1142             (setq dirnam (substring dirnam 0 -1))
1143             ;; eliminate all ".", "/", "\" from beginning. Always matches.
1144             (string-match "^[./\\]*\\(.*\\)$" dirnam)
1145             ;; "/" -> "."
1146             (setq group (gnus-replace-in-string (match-string 1 dirnam) "/" "."))
1147             ;; Windows "\\" -> "."
1148             (setq group (gnus-replace-in-string group "\\\\" "."))
1149
1150             (push (vector (nnir-group-full-name group server)
1151                           (string-to-number artno)
1152                           (string-to-number score))
1153                   artlist))))
1154
1155       (message "Massaging swish-e output...done")
1156
1157       ;; Sort by score
1158       (apply 'vector
1159              (sort artlist
1160                    (function (lambda (x y)
1161                                (> (nnir-artitem-rsv x)
1162                                   (nnir-artitem-rsv y)))))))))
1163
1164 ;; HyREX interface
1165 (defun nnir-run-hyrex (query server &optional group)
1166   (save-excursion
1167     (let ((artlist nil)
1168           (groupspec (cdr (assq 'group query)))
1169           (qstring (cdr (assq 'query query)))
1170           (prefix (nnir-read-server-parm 'nnir-hyrex-remove-prefix server))
1171           score artno dirnam)
1172       (when (and (not groupspec) group)
1173         (setq groupspec
1174               (regexp-opt
1175                (mapcar (lambda (x) (gnus-group-real-name x)) group))))
1176       (set-buffer (get-buffer-create nnir-tmp-buffer))
1177       (erase-buffer)
1178       (message "Doing hyrex-search query %s..." query)
1179       (let* ((cp-list
1180               `( ,nnir-hyrex-program
1181                  nil                    ; input from /dev/null
1182                  t                      ; output
1183                  nil                    ; don't redisplay
1184                  "-i",(nnir-read-server-parm 'nnir-hyrex-index-directory server) ; index directory
1185                  ,@(nnir-read-server-parm 'nnir-hyrex-additional-switches server)
1186                  ,qstring          ; the query, in hyrex-search format
1187                  ))
1188              (exitstatus
1189               (progn
1190                 (message "%s args: %s" nnir-hyrex-program
1191                          (mapconcat 'identity (cddddr cp-list) " "))
1192                 (apply 'call-process cp-list))))
1193         (unless (or (null exitstatus)
1194                     (zerop exitstatus))
1195           (nnheader-report 'nnir "Couldn't run hyrex-search: %s" exitstatus)
1196           ;; nnir-search failure reason is in this buffer, show it if
1197           ;; the user wants it.
1198           (when (> gnus-verbose 6)
1199             (display-buffer nnir-tmp-buffer)))) ;; FIXME: Dont clear buffer !
1200       (message "Doing hyrex-search query \"%s\"...done" qstring)
1201       (sit-for 0)
1202       ;; nnir-search returns:
1203       ;;   for nnml/nnfolder: "filename mailid weigth"
1204       ;;   for nnimap:        "group mailid weigth"
1205       (goto-char (point-min))
1206       (delete-non-matching-lines "^\\S + [0-9]+ [0-9]+$")
1207       ;; HyREX doesn't search directly in groups -- so filter out here.
1208       (when groupspec
1209         (keep-lines groupspec))
1210       ;; extract data from result lines
1211       (goto-char (point-min))
1212       (while (re-search-forward
1213               "\\(\\S +\\) \\([0-9]+\\) \\([0-9]+\\)" nil t)
1214         (setq dirnam (match-string 1)
1215               artno (match-string 2)
1216               score (match-string 3))
1217         (when (string-match prefix dirnam)
1218           (setq dirnam (replace-match "" t t dirnam)))
1219         (push (vector (nnir-group-full-name
1220                        (gnus-replace-in-string dirnam "/" ".") server)
1221                       (string-to-number artno)
1222                       (string-to-number score))
1223               artlist))
1224       (message "Massaging hyrex-search output...done.")
1225       (apply 'vector
1226              (sort artlist
1227                    (function (lambda (x y)
1228                                (if (string-lessp (nnir-artitem-group x)
1229                                                  (nnir-artitem-group y))
1230                                    t
1231                                  (< (nnir-artitem-number x)
1232                                     (nnir-artitem-number y)))))))
1233       )))
1234
1235 ;; Namazu interface
1236 (defun nnir-run-namazu (query server &optional group)
1237   "Run given query against Namazu.  Returns a vector of (group name, file name)
1238 pairs (also vectors, actually).
1239
1240 Tested with Namazu 2.0.6 on a GNU/Linux system."
1241   ;; (when group
1242   ;;   (error "The Namazu backend cannot search specific groups"))
1243   (save-excursion
1244     (let ((article-pattern (if (string= (gnus-group-server server) "nnmaildir")
1245                                ":[0-9]+"
1246                              "^[0-9]+$"))
1247           artlist
1248           (qstring (cdr (assq 'query query)))
1249           (prefix (nnir-read-server-parm 'nnir-namazu-remove-prefix server))
1250           score group article
1251           (process-environment (copy-sequence process-environment)))
1252       (setenv "LC_MESSAGES" "C")
1253       (set-buffer (get-buffer-create nnir-tmp-buffer))
1254       (erase-buffer)
1255       (let* ((cp-list
1256               `( ,nnir-namazu-program
1257                  nil                    ; input from /dev/null
1258                  t                      ; output
1259                  nil                    ; don't redisplay
1260                  "-q"                   ; don't be verbose
1261                  "-a"                   ; show all matches
1262                  "-s"                   ; use short format
1263                  ,@(nnir-read-server-parm 'nnir-namazu-additional-switches server)
1264                  ,qstring               ; the query, in namazu format
1265                  ,(nnir-read-server-parm 'nnir-namazu-index-directory server) ; index directory
1266                  ))
1267              (exitstatus
1268               (progn
1269                 (message "%s args: %s" nnir-namazu-program
1270                          (mapconcat 'identity (cddddr cp-list) " "))
1271                 (apply 'call-process cp-list))))
1272         (unless (or (null exitstatus)
1273                     (zerop exitstatus))
1274           (nnheader-report 'nnir "Couldn't run namazu: %s" exitstatus)
1275           ;; Namazu failure reason is in this buffer, show it if
1276           ;; the user wants it.
1277           (when (> gnus-verbose 6)
1278             (display-buffer nnir-tmp-buffer))))
1279
1280       ;; Namazu output looks something like this:
1281       ;; 2. Re: Gnus agent expire broken (score: 55)
1282       ;; /home/henrik/Mail/mail/sent/1310 (4,138 bytes)
1283
1284       (goto-char (point-min))
1285       (while (re-search-forward
1286               "^\\([0-9]+\\.\\).*\\((score: \\([0-9]+\\)\\))\n\\([^ ]+\\)"
1287               nil t)
1288         (setq score (match-string 3)
1289               group (file-name-directory (match-string 4))
1290               article (file-name-nondirectory (match-string 4)))
1291
1292         ;; make sure article and group is sane
1293         (when (and (string-match article-pattern article)
1294                    (not (null group)))
1295           (nnir-add-result group article score prefix server artlist)))
1296
1297       ;; sort artlist by score
1298       (apply 'vector
1299              (sort artlist
1300                    (function (lambda (x y)
1301                                (> (nnir-artitem-rsv x)
1302                                   (nnir-artitem-rsv y)))))))))
1303
1304 (defun nnir-run-find-grep (query server &optional grouplist)
1305   "Run find and grep to obtain matching articles."
1306   (let* ((method (gnus-server-to-method server))
1307          (sym (intern
1308                (concat (symbol-name (car method)) "-directory")))
1309          (directory (cadr (assoc sym (cddr method))))
1310          (regexp (cdr (assoc 'query query)))
1311          (grep-options (cdr (assoc 'grep-options query)))
1312          artlist)
1313     (unless directory
1314       (error "No directory found in method specification of server %s"
1315              server))
1316     (apply
1317      'vconcat
1318      (mapcar (lambda (x)
1319                (let ((group x))
1320                  (message "Searching %s using find-grep..."
1321                           (or group server))
1322                  (save-window-excursion
1323                    (set-buffer (get-buffer-create nnir-tmp-buffer))
1324                    (erase-buffer)
1325                    (if (> gnus-verbose 6)
1326                        (pop-to-buffer (current-buffer)))
1327                    (cd directory) ; Using relative paths simplifies
1328                                   ; postprocessing.
1329                    (let ((group
1330                           (if (not group)
1331                               "."
1332                             ;; Try accessing the group literally as
1333                             ;; well as interpreting dots as directory
1334                             ;; separators so the engine works with
1335                             ;; plain nnml as well as the Gnus Cache.
1336                             (let ((group (gnus-group-real-name group)))
1337                               ;; Replace cl-func find-if.
1338                               (if (file-directory-p group)
1339                                   group
1340                                 (if (file-directory-p
1341                                      (setq group
1342                                            (gnus-replace-in-string
1343                                             group
1344                                             "\\." "/" t)))
1345                                     group))))))
1346                      (unless group
1347                        (error "Cannot locate directory for group"))
1348                      (save-excursion
1349                        (apply
1350                         'call-process "find" nil t
1351                         "find" group "-type" "f" "-name" "[0-9]*" "-exec"
1352                         "grep"
1353                         `("-l" ,@(and grep-options
1354                                       (split-string grep-options "\\s-" t))
1355                           "-e" ,regexp "{}" "+"))))
1356
1357                    ;; Translate relative paths to group names.
1358                    (while (not (eobp))
1359                      (let* ((path (split-string
1360                                    (buffer-substring
1361                                     (point)
1362                                     (line-end-position)) "/" t))
1363                             (art (string-to-number (car (last path)))))
1364                        (while (string= "." (car path))
1365                          (setq path (cdr path)))
1366                        (let ((group (mapconcat 'identity
1367                                                ;; Replace cl-func:
1368                                                ;; (subseq path 0 -1)
1369                                                (let ((end (1- (length path)))
1370                                                      res)
1371                                                  (while
1372                                                      (>= (setq end (1- end)) 0)
1373                                                    (push (pop path) res))
1374                                                  (nreverse res))
1375                                                ".")))
1376                          (push
1377                           (vector (nnir-group-full-name group server) art 0)
1378                           artlist))
1379                        (forward-line 1)))
1380                    (message "Searching %s using find-grep...done"
1381                             (or group server))
1382                    artlist)))
1383      grouplist))))
1384
1385 ;; gmane interface
1386 (defun nnir-run-gmane (query srv &optional groups)
1387   "Run a search against a gmane back-end server."
1388   (if (string-match-p "gmane" srv)
1389       (let* ((case-fold-search t)
1390              (qstring (cdr (assq 'query query)))
1391              (server (cadr (gnus-server-to-method srv)))
1392              (groupspec (if groups
1393                             (mapconcat
1394                              (function (lambda (x)
1395                                          (format "group:%s"
1396                                                  (gnus-group-short-name x))))
1397                              groups " ") ""))
1398              (authorspec
1399               (if (assq 'author query)
1400                   (format "author:%s" (cdr (assq 'author query))) ""))
1401              (search (format "%s %s %s"
1402                              qstring groupspec authorspec))
1403              artlist)
1404         (with-current-buffer nntp-server-buffer
1405           (erase-buffer)
1406           (mm-url-insert
1407            (concat
1408             "http://search.gmane.org/nov.php"
1409             "?"
1410             (mm-url-encode-www-form-urlencoded
1411              `(("query" . ,search)
1412                ("HITSPERPAGE" . "999")))))
1413           (unless (featurep 'xemacs) (set-buffer-multibyte t))
1414           (mm-decode-coding-region (point-min) (point-max) 'utf-8)
1415           (goto-char (point-min))
1416           (forward-line 1)
1417           (while (not (eobp))
1418             (unless (or (eolp) (looking-at "\x0d"))
1419               (let ((header (nnheader-parse-nov)))
1420                 (let ((xref (mail-header-xref header))
1421                       (xscore (string-to-number (cdr (assoc 'X-Score
1422                                (mail-header-extra header))))))
1423                   (when (string-match " \\([^:]+\\)[:/]\\([0-9]+\\)" xref)
1424                     (push
1425                      (vector
1426                       (gnus-group-prefixed-name (match-string 1 xref) srv)
1427                       (string-to-number (match-string 2 xref)) xscore)
1428                      artlist)))))
1429             (forward-line 1)))
1430         ;; Sort by score
1431         (apply 'vector
1432                (sort artlist
1433                      (function (lambda (x y)
1434                                  (> (nnir-artitem-rsv x)
1435                                     (nnir-artitem-rsv y)))))))
1436     (message "Can't search non-gmane nntp groups")))
1437
1438 ;;; Util Code:
1439
1440 (defun nnir-read-parms (query nnir-search-engine)
1441   "Reads additional search parameters according to `nnir-engines'."
1442   (let ((parmspec (caddr (assoc nnir-search-engine nnir-engines))))
1443     (nconc query
1444            (mapcar 'nnir-read-parm parmspec))))
1445
1446 (defun nnir-read-parm (parmspec)
1447   "Reads a single search parameter.
1448 `parmspec' is a cons cell, the car is a symbol, the cdr is a prompt."
1449   (let ((sym (car parmspec))
1450         (prompt (cdr parmspec)))
1451     (if (listp prompt)
1452         (let* ((result (apply 'gnus-completing-read prompt))
1453                (mapping (or (assoc result nnir-imap-search-arguments)
1454                             (cons nil nnir-imap-search-other))))
1455           (cons sym (format (cdr mapping) result)))
1456       (cons sym (read-string prompt)))))
1457
1458 (defun nnir-run-query (query nserver)
1459   "Invoke appropriate search engine function (see `nnir-engines').
1460   If some groups were process-marked, run the query for each of the groups
1461   and concat the results."
1462   (let ((q (car (read-from-string query)))
1463         (groups (if (string= "all-ephemeral" nserver)
1464                     (with-current-buffer gnus-server-buffer
1465                       (list (list (gnus-server-server-name))))
1466                   (nnir-sort-groups-by-server
1467                    (or gnus-group-marked (list (gnus-group-group-name)))))))
1468     (apply 'vconcat
1469            (mapcar (lambda (x)
1470                      (let* ((server (car x))
1471                             (nnir-search-engine
1472                              (or (nnir-read-server-parm 'nnir-search-engine
1473                                                         server)
1474                                  (cdr (assoc (car
1475                                               (gnus-server-to-method server))
1476                                              nnir-method-default-engines))))
1477                             search-func)
1478                        (setq search-func (cadr
1479                                           (assoc nnir-search-engine
1480                                                  nnir-engines)))
1481                        (if search-func
1482                            (funcall search-func
1483                                     (if nnir-extra-parms
1484                                         (nnir-read-parms q nnir-search-engine)
1485                                       q)
1486                                     server (cdr x))
1487                          nil)))
1488                    groups))))
1489
1490 (defun nnir-read-server-parm (key server)
1491   "Returns the parameter value of key for the given server, where
1492 server is of form 'backend:name'."
1493   (let ((method (gnus-server-to-method server)))
1494     (cond ((and method (assq key (cddr method)))
1495            (nth 1 (assq key (cddr method))))
1496           (t nil))))
1497
1498 (defun nnir-group-full-name (shortname server)
1499   "For the given group name, return a full Gnus group name.
1500 The Gnus backend/server information is added."
1501   (gnus-group-prefixed-name shortname (gnus-server-to-method server)))
1502
1503 (defun nnir-possibly-change-server (server)
1504   (unless (and server (nnir-server-opened server))
1505     (nnir-open-server server)))
1506
1507
1508 ;; Data type article list.
1509
1510 (defun nnir-artlist-length (artlist)
1511   "Returns number of articles in artlist."
1512   (length artlist))
1513
1514 (defun nnir-artlist-article (artlist n)
1515   "Returns from ARTLIST the Nth artitem (counting starting at 1)."
1516   (elt artlist (1- n)))
1517
1518 (defun nnir-artitem-group (artitem)
1519   "Returns the group from the ARTITEM."
1520   (elt artitem 0))
1521
1522 (defun nnir-artlist-artitem-group (artlist n)
1523   "Returns from ARTLIST the group of the Nth artitem (counting from 1)."
1524   (nnir-artitem-group (nnir-artlist-article artlist n)))
1525
1526 (defun nnir-artitem-number (artitem)
1527   "Returns the number from the ARTITEM."
1528   (elt artitem 1))
1529
1530 (defun nnir-artlist-artitem-number (artlist n)
1531   "Returns from ARTLIST the number of the Nth artitem (counting from 1)."
1532   (nnir-artitem-number (nnir-artlist-article artlist n)))
1533
1534 (defun nnir-artitem-rsv (artitem)
1535   "Returns the Retrieval Status Value (RSV, score) from the ARTITEM."
1536   (elt artitem 2))
1537
1538 (defun nnir-artlist-artitem-rsv (artlist n)
1539   "Returns from ARTLIST the Retrieval Status Value of the Nth
1540 artitem (counting from 1)."
1541   (nnir-artitem-rsv (nnir-artlist-article artlist n)))
1542
1543 ;; unused?
1544 (defun nnir-artlist-groups (artlist)
1545   "Returns a list of all groups in the given ARTLIST."
1546   (let ((res nil)
1547         (with-dups nil))
1548     ;; from each artitem, extract group component
1549     (setq with-dups (mapcar 'nnir-artitem-group artlist))
1550     ;; remove duplicates from above
1551     (mapc (function (lambda (x) (add-to-list 'res x)))
1552             with-dups)
1553     res))
1554
1555 (defun nnir-sort-groups-by-server (groups)
1556   "sorts a list of groups into an alist keyed by server"
1557 (if (car groups)
1558   (let (value)
1559     (dolist (var groups value)
1560       (let ((server (gnus-group-server var)))
1561         (if (assoc server value)
1562             (nconc (cdr (assoc server value)) (list var))
1563           (push (cons (gnus-group-server var) (list var)) value))))
1564     value)
1565   nil))
1566
1567 (defun nnir-get-active (srv)
1568   (let ((method (gnus-server-to-method srv))
1569         groups)
1570     (gnus-request-list method)
1571     (with-current-buffer nntp-server-buffer
1572       (let ((cur (current-buffer))
1573             name)
1574         (goto-char (point-min))
1575         (unless (string= gnus-ignored-newsgroups "")
1576           (delete-matching-lines gnus-ignored-newsgroups))
1577         ;; We treat NNTP as a special case to avoid problems with
1578         ;; garbage group names like `"foo' that appear in some badly
1579         ;; managed active files. -jh.
1580         (if (eq (car method) 'nntp)
1581             (while (not (eobp))
1582               (ignore-errors
1583                 (push (cons
1584                        (mm-string-as-unibyte
1585                         (buffer-substring
1586                          (point)
1587                          (progn
1588                            (skip-chars-forward "^ \t")
1589                            (point))))
1590                        (let ((last (read cur)))
1591                          (cons (read cur) last)))
1592                       groups))
1593               (forward-line))
1594           (while (not (eobp))
1595             (ignore-errors
1596               (push (mm-string-as-unibyte
1597                      (let ((p (point)))
1598                        (skip-chars-forward "^ \t\\\\")
1599                        (setq name (buffer-substring (+ p 1) (- (point) 1)))
1600                        (gnus-group-full-name name method)))
1601                     groups))
1602             (forward-line)))))
1603     groups))
1604
1605 ;; The end.
1606 (provide 'nnir)
1607
1608 ;;; nnir.el ends here