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