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