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