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