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