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