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