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