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