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