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