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