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