1a9fe4fb229589056dcbd0885335e076a2b8b9cf
[gnus] / lisp / nnmairix.el
1 ;;; nnmairix.el --- Mairix back end for Gnus, the Emacs newsreader
2
3 ;; Copyright (C) 2007, 2008  Free Software Foundation, Inc.
4
5 ;; Author: David Engster <dengste@eml.cc>
6 ;; Keywords: mail searching
7 ;; Version: 0.5
8
9 ;; This file is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; This file is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to
21 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;; THIS IS BETA SOFTWARE! This back end should not mess up or
27 ;; even delete your mails, but having a backup is always a good idea.
28
29 ;; This is a back end for using the mairix search engine with
30 ;; Gnus.  Mairix is a tool for searching words in locally stored
31 ;; mail.  Mairix is very fast which allows using it efficiently for
32 ;; "smart folders", e.g. folders which are associated with search
33 ;; queries.  Of course, you can also use this back end just for
34 ;; calling mairix with some search query.
35 ;;
36 ;; Mairix is written by Richard Curnow.  More information can be found at
37 ;; http://www.rpcurnow.force9.co.uk/mairix/
38 ;;
39 ;; For details about setting up mairix&Gnus&nnmairix.el, look at the
40 ;; emacswiki:
41 ;;
42 ;; http://www.emacswiki.org/cgi-bin/wiki/GnusMairix
43 ;;
44 ;; The newest version of nnmairix.el can be found at
45 ;; 
46 ;; http://www.emacswiki.org/cgi-bin/emacs/nnmairix.el
47
48 ;; For impatient people, here's the setup in a nutshell:
49 ;;
50 ;; This back end requires an installed mairix binary which is
51 ;; configured to index your mail folder.  You don't have to specify a
52 ;; search folder (but it does no harm, either).  Visit the man page of
53 ;; mairix and mairixrc for details.
54 ;;
55 ;; Put nnmairix.el into your search path and "(require 'nnmarix)" into
56 ;; your .gnus.  Then call nnmairix-create-default-group (or 'G b
57 ;; c'). This function will ask for all necessary information to create
58 ;; a mairix server in Gnus with the default search folder.  This
59 ;; default search folder will be used for all temporary searches: call
60 ;; nnmairix-search ('G b s') and enter a mairix query (like
61 ;; f:test@example.com). To create a mairix group for one specific
62 ;; search query, use 'G b g'.  See the emacswiki or the source for more
63 ;; information.
64
65 ;; Commentary on the code: nnmairix sits between Gnus and the "real"
66 ;; back end which handles the mail (currently nnml, nnimap and
67 ;; nnmaildir were tested). I know this is all a bit hacky, but so far
68 ;; it works for me.  This is the first back end I've written for Gnus,
69 ;; so I'd appreciate any comments, suggestions, bug reports (and, of
70 ;; course, patches) for improving nnmairix.
71
72 ;; nnmairix does not use an active file, since I wanted to contain the
73 ;; back end "inside Gnus" as much as possible without the need of an
74 ;; external file.  It stores the query/folder information in the group
75 ;; parameters instead.  This also implies that once you kill a mairix
76 ;; group, it's gone for good.  I don't think that this is really
77 ;; problematic, since I don't see the need in unsubscribing and
78 ;; re-subscribing search groups
79
80 ;; Every mairix server is "responsible" for one mairix installation,
81 ;; i.e. you can have several mairix servers for different mairix
82 ;; configurations.  Not that I think anyone will actually do this, but
83 ;; I thought it would be a "nice to have feature"...
84
85 ;; KNOWN BUGS:
86 ;; * When using Maildir: path and filename of a mail can change due to
87 ;; reading/replying/etc.  This can lead to dangling symlinks in
88 ;; nnmairix groups and it depends on the back end how well it deals
89 ;; with that (some IMAP servers out there may not be amused).  Update the
90 ;; database ('G b u') and the group to fix it.
91 ;; * Mairix does only support us-ascii characters.
92
93 ;; TODO/MISSING FEATURES:
94 ;; * Possibility to propagate flags like seen, replied, ticked
95 ;;   to original message
96 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
97 ;; * Maybe use an active file instead of group parameters?
98 ;; * Use "-a" when updating groups which are not newly created
99  
100 ;;; Changelog:
101 ;;
102 ;; 02/06/2008 - version 0.5
103 ;; 
104 ;;    * New function: nnmairix-goto-original-article. Uses the
105 ;;      registry or the mail file path for determining original group.
106 ;; 
107 ;;    * Deal with empty Xref header
108 ;;
109 ;;    * Changed summary mode keybindings since the old ones were
110 ;;      already taken
111 ;;
112 ;;   (Thanks to Tassilo Horn and Ted Zlatanov for their help)
113 ;;
114 ;; 01/07/2008 - version 0.4
115 ;;
116 ;;    * New/fixed doc strings and code cleanup.
117 ;;
118 ;; 18/11/2007 - version 0.3
119 ;;
120 ;;    * Fixed bugs when dealing with nnml and native servers
121 ;;     
122 ;;    * Make variables customizable
123 ;;
124 ;; 10/10/2007 - version 0.2
125 ;;
126 ;;    * Use nnml-directory/directory server variables for nnml and
127 ;;    nnmaildir backends as path for search folders. This way it
128 ;;    becomes independent of 'base' setting in .mairixirc (but not for
129 ;;    nnimap).
130 ;;
131 ;;    * As a result: Changed nnmairix-backend-to-server so that user
132 ;;    is asked when more than one nnmairix server exists and we do not
133 ;;    know which one is responsible for current backend.
134 ;;
135 ;;    * Rename files when using nnml backends so that there are no
136 ;;    holes in article numbers. This should fix all problems regarding
137 ;;    wrong article counts with nnml.
138 ;;
139 ;;    * More commands for creating queries (using widgets or the
140 ;;    minibuffer).
141 ;;
142 ;;    * Fixed bug in nnmairix-create-search-group-from-message
143 ;;
144 ;;    * Changed copyright to FSF
145 ;;
146 ;;      (Thanks to Georg C. F. Greve and Bastien for suggestions and
147 ;;      ideas!)
148 ;;
149 ;; 10/03/2007 - version 0.1 - first release
150
151
152 ;;; Code:
153
154 (require 'nnoo)
155 (require 'gnus-group)
156 (require 'gnus-sum)
157 (require 'message)
158 (require 'nnml)
159 (require 'widget)
160
161 (nnoo-declare nnmairix)
162
163 ;;; === Keymaps
164
165 ;; Group mode
166 (defun nnmairix-group-mode-hook ()
167   "Nnmairix group mode keymap."
168   (define-key gnus-group-mode-map
169     (kbd "G b") (make-sparse-keymap))
170   (define-key gnus-group-mode-map
171     (kbd "G b g") 'nnmairix-create-search-group)
172   (define-key gnus-group-mode-map
173     (kbd "G b c") 'nnmairix-create-server-and-default-group)
174   (define-key gnus-group-mode-map
175     (kbd "G b q") 'nnmairix-group-change-query-this-group)
176   (define-key gnus-group-mode-map
177     (kbd "G b t") 'nnmairix-group-toggle-threads-this-group)
178   (define-key gnus-group-mode-map
179     (kbd "G b u") 'nnmairix-update-database)
180   (define-key gnus-group-mode-map
181     (kbd "G b s") 'nnmairix-search)
182   (define-key gnus-group-mode-map
183     (kbd "G b i") 'nnmairix-search-interactive)
184   (define-key gnus-group-mode-map
185     (kbd "G b m") 'nnmairix-widget-search))
186
187 ;; Summary mode
188 (defun nnmairix-summary-mode-hook ()
189   "Nnmairix summary mode keymap."
190   (define-key gnus-summary-mode-map
191     (kbd "$ t") 'nnmairix-search-thread-this-article)
192   (define-key gnus-summary-mode-map
193     (kbd "$ f") 'nnmairix-search-from-this-article)
194   (define-key gnus-summary-mode-map
195     (kbd "$ m") 'nnmairix-widget-search-from-this-article)
196   (define-key gnus-summary-mode-map
197     (kbd "$ g") 'nnmairix-create-search-group-from-message)
198   (define-key gnus-summary-mode-map
199     (kbd "$ o") 'nnmairix-goto-original-article))
200
201 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
202 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
203
204
205 ;; Customizable stuff
206
207 (defgroup nnmairix nil
208   "Backend for the Mairix mail search engine."
209   :group 'gnus)
210
211 (defcustom nnmairix-group-prefix "zz_mairix"
212   "Prefix for mairix search groups on back end server.
213 nnmairix will create these groups automatically on the back end
214 server for each nnmairix search group.  The name on the back end
215 server will be this prefix plus a random number.  You can delete
216 unused nnmairix groups on the back end using
217 `nnmairix-purge-old-groups'."
218   :version "23.0"
219   :type 'string
220   :group 'nnmairix)
221
222 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
223   "Buffer used for mairix output."
224   :version "23.0"
225   :type 'string
226   :group 'nnmairix)
227
228 (defcustom nnmairix-customize-query-buffer "*mairix query*"
229   "Name of the buffer for customizing Mairix queries."
230   :version "23.0"
231   :type 'string
232   :group 'nnmairix)
233
234 (defcustom nnmairix-mairix-update-options '("-F" "-Q")
235   "Options when calling mairix for updating the database.
236 The default is '-F' and '-Q' for making updates faster.  You
237 should call mairix without these options from time to
238 time (e.g. via cron job)."
239   :version "23.0"
240   :type '(repeat string)
241   :group 'nnmairix)
242
243 (defcustom nnmairix-mairix-synchronous-update nil
244   "Set this to t if you want Emacs to wait for mairix updating the database."
245   :version "23.0"
246   :type 'boolean
247   :group 'nnmairix)
248
249 (defcustom nnmairix-rename-files-for-nnml t
250   "Rename nnml mail files so that they are consecutively numbered.
251 When using nnml as backend, mairix might produce holes in the
252 article numbers which will produce wrong article counts by
253 Gnus.  This option controls whether nnmairix should rename the
254 files consecutively."
255   :version "23.0"
256   :type 'boolean
257   :group 'nnmairix)
258
259 (defcustom nnmairix-widget-fields-list
260   '(("from" "f" "From") ("to" "t" "To") ("cc" "c" "Cc")
261     ("subject" "s" "Subject")  ("to" "tc" "To or Cc")
262     ("from" "a" "Address") (nil "b" "Body") (nil "n" "Attachment")
263     ("Message-ID" "m" "Message ID") (nil "s" "Size") (nil "d" "Date"))
264   "Fields that should be editable during interactive query customization.
265
266 Header, corresponding mairix command and description for editable
267 fields in interactive query customization.  The header specifies
268 which header contents should be inserted into the editable field
269 when creating a Mairix query based on the current message (can be
270 nil for disabling this)."
271   :version "23.0"
272   :type '(repeat (list
273                   (choice :tag "Field"
274                           (const :tag "none" nil)
275                           (const :tag "From" "from")
276                           (const :tag "To" "to")
277                           (const :tag "Cc" "cc")
278                           (const :tag "Subject" "subject")
279                           (const :tag "Message ID" "Message-ID"))
280                   (string :tag "Command")
281                   (string :tag "Description")))
282   :group 'nnmairix)
283
284 (defcustom nnmairix-widget-select-window-function
285   (lambda () (select-window (get-largest-window)))
286   "Function for selecting the window for customizing the mairix query.
287 The default chooses the largest window in the current frame."
288   :version "23.0"
289   :type 'function
290   :group 'nnmairix)
291
292 ;; ==== Other variables
293
294 (defvar nnmairix-widget-other
295   '(threads flags)
296   "Other editable mairix commands when using customization widgets.
297 Currently there are 'threads and 'flags.")
298
299 (defvar nnmairix-interactive-query-parameters
300   '((?f "from" "f" "From") (?t "to" "t" "To") (?c "to" "tc" "To or Cc")
301     (?a "from" "a" "Address") (?s "subject" "s" "Subject") (?b nil "b" "Body")
302     (?d nil "d" "Date") (?n nil "n" "Attachment"))
303   "Things that should be editable during interactive query generation.
304 Every list element consists of the following entries: Keystroke,
305 message field (if any), mairix command and description.")
306
307 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
308   "Controls on which backends groups should be deleted and re-created.
309 This variable is a list of back ends where the search group should
310 be completely deleted and re-created when the query or thread
311 parameter changes.  I know this is rather \"brute force\" and maybe
312 even dangerous (you have backups, right?), but it should be used at
313 least for nnimap since some IMAP servers are really not amused when
314 mailbox content changes behind their back.  It usually also corrects
315 the problem of \"holes\" in the article numbers which often lead to a
316 wrong count of total articles shown by Gnus.")
317
318 ;;; === Server variables
319
320 (defvoo nnmairix-backend  nil
321   "Backend where mairix stores its searches.")
322
323 (defvoo nnmairix-backend-server nil
324   "Name of the server where mairix stores its searches.")
325
326 (defvoo nnmairix-mairix-command "mairix"
327   "Command to call mairix for this nnmairix server.")
328
329 (defvoo nnmairix-hidden-folders nil
330   "Set this to t if the back end server uses hidden directories for
331 its maildir mail folders (e.g. the Dovecot IMAP server or mutt).")
332
333 (defvoo nnmairix-default-group nil
334   "Default search group. This is the group which is used for all
335 temporary searches, e.g. nnmairix-search.")
336
337 ;;; === Internal variables
338
339 (defvar nnmairix-group-regexp
340   (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
341   "Regexp for mairix groups on back end.")
342
343 (defvar nnmairix-valid-backends '(nnimap nnml nnmaildir)
344   "Back ends (hopefully...) supported by nnmairix.
345 Other backends might or might not work.")
346
347 (defvar nnmairix-last-server nil
348   "Last chosen server.")
349
350 (defvar nnmairix-current-server nil
351   "Current server.")
352
353 ;;; === Gnus backend functions
354   
355 (nnoo-define-basics nnmairix)
356
357 (gnus-declare-backend "nnmairix" 'mail 'address)
358
359 (deffoo nnmairix-open-server (server &optional definitions)
360   ;; just set server variables
361   (setq nnmairix-current-server server)
362   (nnoo-change-server 'nnmairix server definitions))
363
364 (deffoo nnmairix-request-group (group &optional server fast)
365   ;; Call mairix and request group on back end server
366   (when server (nnmairix-open-server server))
367   (let* ((qualgroup (if server
368                         (gnus-group-prefixed-name group (list 'nnmairix server))
369                       group))
370          (query (gnus-group-get-parameter qualgroup 'query t))
371         (folder (gnus-group-get-parameter qualgroup 'folder))
372         (threads (gnus-group-get-parameter qualgroup 'threads))
373         (backendmethod (gnus-server-to-method
374                         (format "%s:%s" (symbol-name nnmairix-backend)
375                                 nnmairix-backend-server)))
376         rval mfolder folderpath)
377     (cond
378      ((not folder)
379       ;; No folder parameter -> error
380       (nnheader-report 'nnmairix "Check folder parameter for group %s" group)
381       nil)
382      ((not query)
383       ;; No query -> return empty group
384       (save-excursion
385         (set-buffer nntp-server-buffer)
386         (erase-buffer)
387         (insert (concat "211 0 1 0 " group))
388         t))
389      (t
390       ;; For maildir++ folders: create a hidden directory (prepend dot)
391       (setq mfolder (if (and nnmairix-hidden-folders
392                              (not (string-match "^\\." folder)))
393                         (concat "." folder)
394                       folder))
395       ;; For nnml and nnmaildir, precede mfolder with directory where mail
396       ;; is actually stored so that it's independent of 'base' setting
397       ;; in .mairixrc.
398       (when (eq nnmairix-backend 'nnml)
399         (setq folderpath (cadr (assoc 'nnml-directory backendmethod)))
400         ;; if nnml-directory is not explicitly set, use global value
401         (when (not folderpath)
402           (setq folderpath nnml-directory)))
403       (when (eq nnmairix-backend 'nnmaildir)
404         (setq folderpath
405               (cadr (assoc 'directory backendmethod))))
406       (when folderpath
407         (setq mfolder
408               (concat
409                (file-name-as-directory
410                 (expand-file-name
411                  folderpath))
412                mfolder)))
413       ;; If (not fast), call Mairix binary
414       (setq rval
415             (if fast 0
416               (nnmairix-call-mairix-binary
417                (split-string nnmairix-mairix-command)
418                mfolder query threads)))
419       ;; Check return value
420       (cond
421        ((zerop rval)                    ; call was succesful
422         (nnmairix-call-backend
423          "open-server" nnmairix-backend-server)
424         ;; If we're dealing with nnml, rename files
425         ;; consecutively and make new active file for this
426         ;; group
427         (when (eq nnmairix-backend 'nnml)
428           (when nnmairix-rename-files-for-nnml
429             (nnmairix-rename-files-consecutively mfolder))
430           (nnml-generate-nov-databases-directory mfolder))
431         (nnmairix-call-backend
432          "request-scan" folder nnmairix-backend-server)
433         (if fast
434             t
435           (nnmairix-request-group-with-article-number-correction folder qualgroup)))
436        ((and (= rval 1)
437              (save-excursion (set-buffer nnmairix-mairix-output-buffer)
438                              (goto-char (point-min))
439                              (looking-at "^Matched 0 messages")))
440         ;; No messages found -> return empty group
441         (nnheader-message 5 "Mairix: No matches found.")
442         (set-buffer nntp-server-buffer)
443         (erase-buffer)
444         (insert (concat "211 0 1 0 " group))
445         t)
446        ;; Everything else is an error
447        (t
448         (nnheader-report
449          'nnmairix "Error running marix. See buffer %s for details"
450          nnmairix-mairix-output-buffer)
451         nil))))))
452
453
454 (deffoo nnmairix-request-create-group (group &optional server args)
455   (let ((qualgroup (if server (gnus-group-prefixed-name group (list 'nnmairix server))
456                      group))
457         (exist t)
458         (count 0)
459         groupname info)
460     (when server (nnmairix-open-server server))
461     (gnus-group-add-parameter qualgroup '(query . nil))
462     (gnus-group-add-parameter qualgroup '(threads . nil))
463     (while exist
464       (setq count (1+ count))
465       (setq groupname (format "%s-%s-%s" nnmairix-group-prefix group
466                               (number-to-string count)))
467       (setq exist (nnmairix-call-backend
468                    "request-group" groupname nnmairix-backend-server)))
469     (nnmairix-call-backend
470      "request-create-group" groupname nnmairix-backend-server)
471     (gnus-group-add-parameter qualgroup '(folder . nil))
472     (gnus-group-set-parameter qualgroup 'folder groupname))
473   t)
474
475
476 (deffoo nnmairix-retrieve-headers (articles group &optional server fetch-old)
477   (when server (nnmairix-open-server server))
478   (let* ((folder (nnmairix-get-backend-folder group server))
479          (corr (nnmairix-get-numcorr group server))
480          (numcorr 0)
481          rval)
482     (when (and corr
483                (not (zerop (cadr corr)))
484                (numberp (car articles)))
485       (setq numcorr (cadr corr))
486       (setq articles
487             (mapcar
488              (lambda (arg) (- arg numcorr))
489              articles)))
490     (setq rval (nnmairix-call-backend
491                 "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
492     (when (eq rval 'nov)
493       (nnmairix-replace-group-and-numbers articles folder group numcorr)
494       rval)))
495
496 (deffoo nnmairix-request-article (article &optional group server to-buffer)
497   (when server (nnmairix-open-server server))
498   (let ((folder (nnmairix-get-backend-folder group server))
499         (corr (nnmairix-get-numcorr group server)))
500     (when (and
501            (numberp article)
502            corr
503            (not (zerop (cadr corr))))
504       (setq article (- article (cadr corr))))
505     (nnmairix-call-backend
506      "request-article" article folder nnmairix-backend-server to-buffer))
507   t)
508
509 (deffoo nnmairix-close-group (group &optional server)
510   ;; Should we do something here?
511   nil)
512
513
514 (deffoo nnmairix-request-list (&optional server)
515   (when server (nnmairix-open-server server))
516   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
517       (let (cpoint cur qualgroup folder)
518         (save-excursion
519           (set-buffer nntp-server-buffer)
520           (goto-char (point-min))
521           (setq cpoint (point))
522           (while (re-search-forward nnmairix-group-regexp (point-max) t)
523             (setq cur (match-string 1)
524                   qualgroup (gnus-group-prefixed-name cur
525                                                       (list 'nnmairix server)))
526             (if (and (gnus-group-entry qualgroup)
527                      (string= (match-string 0)
528                               (gnus-group-get-parameter qualgroup 'folder)))
529                 (progn
530                   (replace-match cur)
531                   (delete-region cpoint (point-at-bol))
532                   (forward-line)
533                   (setq cpoint (point)))
534               (forward-line)))
535           (delete-region cpoint (point-max)))
536         t)
537     nil))
538
539                  
540 (nnoo-define-skeleton nnmairix)
541
542
543 ;;; === Interactive functions
544
545 (defun nnmairix-create-search-group (server group query threads)
546   "Create on SERVER nnmairix search group GROUP with QUERY.
547 If THREADS is t, include whole threads from found messages.  If
548 called interactively, user will be asked for parameters."
549   (interactive
550    (list
551     (gnus-server-to-method (car (nnmairix-get-server)))
552     (read-string "Group name: ")
553     (read-string "Query: ")
554     (y-or-n-p "Include threads? ")))
555   (when (and (stringp query)
556              (string-match "\\s-" query))
557     (setq query (split-string query)))
558   (when (not (listp query))
559     (setq query (list query)))
560   (when (and server group query)
561     (save-excursion
562       (let ((groupname (gnus-group-prefixed-name group server))
563             info)
564         (set-buffer gnus-group-buffer)
565         (gnus-group-make-group group server)
566         (gnus-group-set-parameter groupname 'query  query)
567         (gnus-group-set-parameter groupname 'threads threads)
568         (nnmairix-update-and-clear-marks groupname)))))
569
570 (defun nnmairix-search-interactive ()
571   "Create mairix search interactively with the minibuffer."
572   (interactive)
573   (let ((char-header nnmairix-interactive-query-parameters)
574         header finished query achar)
575     (while (not finished)
576       (while (not achar)
577         (message "Query (%s): " (nnmairix-create-message-line-for-search))
578           (setq achar (read-char))
579           (when (not (assoc achar char-header))
580             (setq achar nil)))
581       (setq header (read-string
582                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
583         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
584         (setq finished (not (y-or-n-p "Add another search query? "))
585               achar nil))
586     (nnmairix-search
587      (mapconcat 'identity query " ")
588      (car (nnmairix-get-server))
589      (y-or-n-p "Include whole threads? "))))
590
591 (defun nnmairix-create-search-group-from-message ()
592   "Interactively create search group with query based on current message."
593   (interactive)
594   (let ((char-header nnmairix-interactive-query-parameters)
595         (server (nnmairix-backend-to-server gnus-current-select-method))
596          query achar header finished group threads cq)
597     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
598               (not (gnus-buffer-live-p gnus-summary-buffer)))
599       (error "No article or summary buffer"))
600     (when (not server)
601       (error "No nnmairix server found for back end %s:%s"
602              (symbol-name (car gnus-current-select-method))
603              (nth 1 gnus-current-select-method)))
604     (while (not finished)
605       (save-excursion
606         (gnus-summary-toggle-header 1)
607         (while (not achar)
608           (message "Query (%s): " (nnmairix-create-message-line-for-search))
609           (setq achar (read-char))
610           (when (not (assoc achar char-header))
611             (setq achar nil)))
612         (set-buffer gnus-article-buffer)
613         (setq header nil)
614         (when (setq cq (nth 1 (assoc achar char-header)))
615           (setq header
616                 (nnmairix-replace-illegal-chars
617                  (gnus-fetch-field (nth 1 (assoc achar char-header))))))
618         (setq header (read-string
619                       (concat "Match " (nth 3 (assoc achar char-header)) " on: ")
620                       header))
621         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
622         (setq finished (not (y-or-n-p "Add another search query? "))
623               achar nil)))
624     (setq threads (y-or-n-p "Include whole threads? "))
625     (setq group (read-string "Group name: "))
626     (set-buffer gnus-summary-buffer)
627     (message "Creating group %s on server %s with query %s." group
628              (gnus-method-to-server server) (mapconcat 'identity query " "))
629     (nnmairix-create-search-group server group query threads)))
630
631 (defun nnmairix-create-server-and-default-group ()
632   "Interactively create new nnmairix server with default search group.
633 All necessary information will be queried from the user."
634   (interactive)
635   (let* ((name (read-string "Name of the mairix server: "))
636         (server (completing-read "Back end server (TAB for completion): "
637                                  (nnmairix-get-valid-servers)))
638         (mairix (read-string "Command to call mairix: " "mairix"))
639         (defaultgroup (read-string "Default search group: "))
640         (backend (symbol-name (car (gnus-server-to-method server))))
641         (servername (nth 1 (gnus-server-to-method server)))
642         (hidden (and (string-match "^nn\\(imap\\|maildir\\)$" backend)
643                      (y-or-n-p
644                       "Does the back end server work with maildir++ (i.e. hidden directories)? ")))
645         create)
646
647     (apply (intern (format "%s-%s" backend "open-server"))
648            (list servername))
649
650     (when (and hidden
651                (string-match "^\\." defaultgroup))
652       (setq defaultgroup (substring defaultgroup 1)))
653     ;; Create default search group
654     (gnus-group-make-group
655      defaultgroup (list 'nnmairix name  (list 'nnmairix-backend (intern backend))
656                         (list 'nnmairix-backend-server servername)
657                         (list 'nnmairix-mairix-command mairix)
658                         (list 'nnmairix-hidden-folders hidden)
659                         (list 'nnmairix-default-group defaultgroup)))))
660
661
662 (defun nnmairix-group-change-query-this-group (&optional query)
663   "Set QUERY for group under cursor."
664   (interactive)
665   (let* ((group (gnus-group-group-name))
666          (method (gnus-find-method-for-group group))
667          (oldquery (gnus-group-get-parameter group 'query t)))
668     (if (eq (car method) 'nnmairix)
669         (progn
670           (when (listp oldquery)
671             (setq oldquery (mapconcat 'identity oldquery " ")))
672           (setq query (or query
673                           (read-string "New query: " oldquery)))
674           (when (stringp query)
675             (setq query (split-string query)))
676           (when query
677             (gnus-group-set-parameter group 'query query)
678             (nnmairix-update-and-clear-marks group)))
679       (error "This is no nnmairix group"))))
680                   
681
682 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
683   "Toggle threads parameter for this group.
684 If THREADS is a positive number, set threads parameter to t.
685 If THREADS is a negative number, set it to nil."
686   (interactive)
687   (let* ((group (gnus-group-group-name))
688          (method (gnus-find-method-for-group group))
689          (getthreads (or threads
690                         (not (gnus-group-get-parameter group 'threads)))))
691     (if (eq (car method) 'nnmairix)
692         (progn
693           (when (numberp getthreads)
694             (setq getthreads (> getthreads 0)))
695           (gnus-group-set-parameter group 'threads getthreads)
696           (if getthreads
697               (message "Threads activated for group %s" group)
698             (message "Threads deacitavted for group %s" group))
699           (nnmairix-update-and-clear-marks group))
700       (error "This is no nnmairix group"))))
701         
702
703 (defun nnmairix-search (query &optional server threads)
704   "Sends QUERY to nnmairix backend SERVER, using default its search group.
705
706 Default search group is automatically entered and results are shown.
707 If THREADS is t, enable threads.
708 If THREADS is a negative number, disable threads.
709 Otherwise, leave threads parameter as it is."
710   (interactive (list (read-string "Query: ")))
711   (when (not server)
712     (setq server (car (nnmairix-get-server))))
713   (if (not server)
714       (error "No opened nnmairix server found")
715     (setq server (gnus-server-to-method server)))
716   (nnmairix-open-server (nth 1 server))
717   (let* ((qualgroup (gnus-group-prefixed-name nnmairix-default-group
718                                               (list 'nnmairix (nth 1 server)))))
719     (set-buffer gnus-group-buffer)
720     (when (stringp query)
721       (setq query (split-string query)))
722     (gnus-group-set-parameter qualgroup 'query query)
723     (if (symbolp threads)
724         (when (eq threads 't)
725           (gnus-group-set-parameter qualgroup 'threads t))
726       (when (< threads 0)
727         (gnus-group-set-parameter qualgroup 'threads nil)))
728     (nnmairix-update-and-clear-marks qualgroup)
729     (when (not (zerop (gnus-group-unread qualgroup)))
730       (gnus-group-read-group nil t qualgroup))))
731
732 (defun nnmairix-search-thread-this-article ()
733   "Search thread for the current article.
734 This is effectively a shortcut for calling `nnmairix-search'
735 with m:msgid of the current article and enabled threads."
736   (interactive)
737   (let* ((server
738           (nnmairix-backend-to-server gnus-current-select-method))
739          mid)
740     (if server
741         (if (gnus-buffer-live-p gnus-article-buffer)
742             (progn
743               (save-excursion
744                 (set-buffer gnus-article-buffer)
745                 (gnus-summary-toggle-header 1)
746                 (setq mid (message-fetch-field "Message-ID")))
747               (while (string-match "[<>]" mid)
748                 (setq mid (replace-match "" t t mid)))
749               (nnmairix-search (concat "m:" mid) server t))
750           (message "No article buffer."))
751       (error "No nnmairix server found for back end %s:%s"
752              (symbol-name (car gnus-current-select-method))
753              (nth 1 gnus-current-select-method)))))
754
755 (defun nnmairix-search-from-this-article ()
756   "Search messages from sender of the current article.
757 This is effectively a shortcut for calling `nnmairix-search' with
758 f:current_from."
759   (interactive)
760   (let* ((server
761           (nnmairix-backend-to-server gnus-current-select-method))
762          from)
763     (if server
764         (if (gnus-buffer-live-p gnus-article-buffer)
765             (progn
766               (save-excursion
767                 (set-buffer gnus-article-buffer)
768                 (gnus-summary-toggle-header 1)
769                 (setq from (cadr (gnus-extract-address-components
770                                   (gnus-fetch-field "From"))))
771                 (nnmairix-search (concat "f:" from) server -1)))
772           (message "No article buffer."))
773       (error "No nnmairix server found for back end %s:%s"
774              (symbol-name (car gnus-current-select-method))
775              (nth 1 gnus-current-select-method)))))
776
777
778 (defun nnmairix-purge-old-groups (&optional dontask server)
779   "Delete mairix search groups which are no longer used.
780
781 You may want to call this from time to time if you are creating
782 and deleting lots of nnmairix groups.  If DONTASK is t, do not ask
783 before deleting a group on the back end.  SERVER specifies nnmairix server."
784   (interactive)
785   (let ((server (or server
786                     (gnus-server-to-method (car (nnmairix-get-server))))))
787     (if (nnmairix-open-server (nth 1 server))
788         (when (nnmairix-call-backend
789                "request-list" nnmairix-backend-server)
790           (let (cur qualgroup folder)
791             (save-excursion
792               (set-buffer nntp-server-buffer)
793               (goto-char (point-min))
794               (while (re-search-forward nnmairix-group-regexp (point-max) t)
795                 (setq cur (match-string 0)
796                       qualgroup (gnus-group-prefixed-name
797                                  (match-string 1) server))
798                 (when (not (and (gnus-group-entry qualgroup)
799                                 (string= cur
800                                          (gnus-group-get-parameter
801                                           qualgroup 'folder))))
802                   (when (or dontask
803                             (y-or-n-p
804                              (concat "Delete group " cur
805                                      " on server " nnmairix-backend-server "? ")))
806                     (nnmairix-call-backend
807                      "request-delete-group" cur t nnmairix-backend-server)))))))
808       (message "Couldn't open server %s" (nth 1 server)))))
809
810
811 (defun nnmairix-update-database (&optional servers)
812   "Call mairix for updating the database for SERVERS.
813
814 If SERVERS is nil, do update for all nnmairix servers.  Mairix
815 will be called asynchronously unless
816 `nnmairix-mairix-synchronous-update' is t.  Mairix will be called
817 with `nnmairix-mairix-update-options'."
818   (interactive)
819   (let ((servers (or servers
820                      (nnmairix-get-nnmairix-servers)))
821         args cur commandsplit)
822     (while servers
823       (setq cur (car (pop servers)))
824       (nnmairix-open-server
825        (nth 1 (gnus-server-to-method cur)))
826       (setq commandsplit (split-string nnmairix-mairix-command))
827       (nnheader-message 7 "Updating mairix database for %s..." cur)
828       (if nnmairix-mairix-synchronous-update
829           (progn
830             (setq args (append (list (car commandsplit) nil
831                                      (get-buffer nnmairix-mairix-output-buffer)
832                                      nil)))
833             (if (> (length commandsplit) 1)
834                 (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
835               (setq args (append args nnmairix-mairix-update-options)))
836             (apply 'call-process args)
837             (nnheader-message 7 "Updating mairix database for %s... done" cur))
838         (progn
839           (setq args (append (list cur (get-buffer nnmairix-mairix-output-buffer)
840                                    (car commandsplit))))
841           (if (> (length commandsplit) 1)
842               (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
843             (setq args (append args nnmairix-mairix-update-options)))
844           (set-process-sentinel (apply 'start-process args)
845                                 'nnmairix-sentinel-mairix-update-finished))))))
846
847 ;; Silence byte-compiler.
848 (eval-when-compile
849   (defvar gnus-registry-install)
850   (autoload 'gnus-registry-fetch-group "gnus-registry"))
851
852 (defun nnmairix-goto-original-article (&optional no-registry)
853   "Jump to the original group and display article.
854 The original group of the article is first determined with the
855 registry (if enabled). If the registry is not enabled or did not
856 find the article or the prefix NO-REGISTRY is non-nil, this
857 function will try to determine the original group form the path
858 of the mail file. The path is obtained through another mairix
859 search in raw mode."
860   (interactive "P")
861   (when (not (eq (car gnus-current-select-method) 'nnmairix))
862     (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
863       (if (eq (car method) 'nnmairix)
864           (nnmairix-open-server (nth 1 method))
865         (error "Not in a nnmairix group"))))
866   (when (not (gnus-buffer-live-p gnus-article-buffer))
867     (error "No article buffer available"))
868   (let ((server (nth 1 gnus-current-select-method))
869         mid rval group allgroups)
870     ;; get message id
871     (save-excursion
872       (set-buffer gnus-article-buffer)
873       (gnus-summary-toggle-header 1)
874       (setq mid (message-fetch-field "Message-ID"))
875       ;; first check the registry (if available)
876       (when (and (boundp 'gnus-registry-install)
877                  gnus-registry-install
878                  (not no-registry))
879         (setq group (gnus-registry-fetch-group mid)))
880       (while (string-match "[<>]" mid)
881         (setq mid (replace-match "" t t mid)))
882       (unless group
883         ;; registry was not available or did not find article
884         ;; so we search again with mairix in raw mode to get filename
885         (nnmairix-open-server server)
886         (setq rval 
887               (nnmairix-call-mairix-binary-raw 
888                (split-string nnmairix-mairix-command) 
889                (list (concat "m:" mid))))
890         (if (zerop rval)
891             ;; determine original group(s) from filename
892             (save-excursion
893               (set-buffer nnmairix-mairix-output-buffer)
894               (goto-char (point-min))
895               (while (looking-at "/")
896                 (push (nnmairix-determine-original-group)
897                       allgroups)
898                 (forward-line 1))
899               (if (> (length allgroups) 1)
900                   (setq group 
901                         (completing-read 
902                          "Message exists in more than one group. Choose: " 
903                          allgroups nil t))
904                 (setq group (car allgroups))))
905           (error "Mairix could not find original article. See buffer %s for details" 
906                  nnmairix-mairix-output-buffer))))
907     (if group
908         ;; show article in summary buffer
909         (nnmairix-show-original-article group mid)
910       (message "Couldn't find original article"))))
911
912 (defun nnmairix-determine-original-group ()
913   "Try to determine to original group from the file path."
914   (let (path filename serverbase group maildirflag allgroups)
915     (re-search-forward "^\\(.*\\)/\\(.*?\\)$")
916     (setq path (expand-file-name (match-string 1)))
917     (setq filename (match-string 2))
918     ;; when we deal with maildir, remove cur/new/tmp from path
919     (setq maildirflag (string-match ".+\\..+\\..+" filename))
920     (when maildirflag
921       (setq path
922             (replace-regexp-in-string 
923              ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
924     ;; we first check nnml and nnmaildir servers
925     (setq 
926      group
927      (catch 'found
928        (dolist (cur gnus-opened-servers)
929          (when (or (and (not maildirflag)
930                         (eq (caar cur) 'nnml))
931                    (and maildirflag
932                         (eq (caar cur) 'nnmaildir)))
933            ;; get base path from server
934            (if maildirflag 
935                (setq serverbase (cadr (assoc 'directory (car cur))))               
936              (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
937              (when (not serverbase)
938                (setq serverbase nnml-directory)))
939            (setq serverbase (file-name-as-directory 
940                              (expand-file-name serverbase)))
941            (when (string-match (concat serverbase "\\(.*\\)") path)
942              ;; looks good - rest of the path should be the group
943              (setq group (match-string 1 path))
944              (when (string-match "/$" group)
945                (setq group (replace-match "" t t group)))
946              (when (not maildirflag)
947                ;; for nnml: convert slashes to dots
948                (while (string-match "/" group)
949                  (setq group (replace-match "." t t group))))
950              (setq group (gnus-group-prefixed-name group (car cur)))
951              ;; check whether this group actually exists
952              (when (gnus-group-entry group)
953                (throw 'found group)))))))
954     (unless group
955       ;; we haven't found it yet --> look for nnimap groups
956       ;; assume last element of the path is the group
957       (string-match "^.*/\\.?\\(.*\\)$" path)
958       (setq group (match-string 1 path))
959       ;; convert dots to slashes (nested group)
960       (while (string-match "\\." group)
961         (setq group (replace-match "/" t t group)))
962       (dolist (cur gnus-opened-servers)
963         (when (eq (caar cur) 'nnimap)
964           (when (gnus-group-entry 
965                  (gnus-group-prefixed-name group (car cur)))
966             (push 
967              (gnus-group-prefixed-name group (car cur))
968              allgroups))))
969       (if (> (length allgroups) 1)
970           (setq group (completing-read 
971                        "Group %s exists on more than one IMAP server. Choose: " 
972                        allgroups nil t))
973         (setq group (car allgroups))))
974     group))
975
976
977 ;;; ==== Helper functions
978
979 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
980   "Request FOLDER on backend for nnmairix QUALGROUP and article number correction."
981   (save-excursion
982     (nnmairix-call-backend
983      "request-group" folder nnmairix-backend-server)
984     (set-buffer nnmairix-mairix-output-buffer)
985     (goto-char (point-min))
986     (re-search-forward "^Matched.*messages")
987     (nnheader-message 7 (match-string 0))
988     (set-buffer nntp-server-buffer)
989     (goto-char (point-min))
990     (let ((status (read (current-buffer)))
991           (total (read (current-buffer)))
992           (low (read (current-buffer)))
993           (high (read (current-buffer)))
994           (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
995       (if (= status 211)
996           (progn
997             ;; Article number correction
998             (if (and corr
999                      (> (+ (car (cddr corr)) high) 0))
1000                 (progn
1001                   (when (car corr) ;Group has changed
1002                     (setq corr
1003                           (list nil
1004                                 (car (cddr corr))
1005                                 (+ (car (cddr corr)) high)))
1006                     (gnus-group-set-parameter
1007                      qualgroup 'numcorr corr))
1008                   (setq low (+ low (cadr corr))
1009                         high (+ high (cadr corr))))
1010               (when (member nnmairix-backend
1011                             nnmairix-delete-and-create-on-change)
1012                 (gnus-group-set-parameter
1013                  qualgroup 'numcorr (list nil 0 high))))
1014             (erase-buffer)
1015             (insert (format "%d %d %d %d %s" status total low high
1016                             (gnus-group-real-name qualgroup)))
1017             t)
1018         (progn
1019           (nnheader-report
1020            'nnmairix "Error calling back end on group %s" folder)
1021           nil)))))
1022
1023 (defun nnmairix-call-mairix-binary (command folder query threads)
1024   "Call mairix binary with COMMAND, using FOLDER and QUERY.
1025 If THREADS is non-nil, enable full threads."
1026   (let ((args (cons (car command) '(nil t nil))))
1027     (save-excursion
1028       (set-buffer
1029        (get-buffer-create nnmairix-mairix-output-buffer))
1030       (erase-buffer)
1031       (when (> (length command) 1)
1032         (setq args (append args (cdr command))))
1033       (when threads
1034         (setq args (append args '("-t"))))
1035       (apply 'call-process
1036              (append args (list "-o" folder) query)))))
1037
1038 (defun nnmairix-call-mairix-binary-raw (command query)
1039   "Call mairix binary with COMMAND and QUERY in raw mode."
1040   (let ((args (cons (car command) '(nil t nil))))
1041     (save-excursion
1042       (set-buffer
1043        (get-buffer-create nnmairix-mairix-output-buffer))
1044       (erase-buffer)
1045       (when (> (length command) 1)
1046         (setq args (append args (cdr command))))
1047       (setq args (append args '("-r")))
1048       (apply 'call-process
1049              (append args query)))))
1050
1051 (defun nnmairix-get-server ()
1052   "If there exists just one nnmairix server, return its value.
1053 Otherwise, ask user for server."
1054   (let ((openedserver (nnmairix-get-nnmairix-servers)))
1055     (when (not openedserver)
1056       (error "No opened nnmairix server found"))
1057     (if (> (length openedserver) 1)
1058         (progn
1059           (while
1060               (equal '("")
1061                   (setq nnmairix-last-server
1062                         (list (completing-read "Server: " openedserver nil 1
1063                                                (or nnmairix-last-server
1064                                                    "nnmairix:"))))))
1065           nnmairix-last-server)
1066       (car openedserver))))
1067
1068 (defun nnmairix-get-nnmairix-servers (&optional all)
1069   "Return available nnmairix servers.
1070 If ALL is t, return also the unopened/failed ones."
1071   (let ((alist gnus-opened-servers)
1072         server openedserver)
1073     (while alist
1074       (setq server (pop alist))
1075       (when (and server
1076                  (or all
1077                      (eq (cadr server) 'ok))
1078                  (eq (caar server) 'nnmairix)
1079                  (not (member (car server) gnus-ephemeral-servers)))
1080         (setq server
1081               (concat (symbol-name (caar server)) ":" (nth 1 (car server))))
1082         (push (list server) openedserver)))
1083     openedserver))
1084
1085
1086 (defun nnmairix-get-valid-servers ()
1087   "Return list of valid backend servers for nnmairix groups."
1088   (let ((alist gnus-opened-servers)
1089         (mairixservers (nnmairix-get-nnmairix-servers t))
1090         server mserver openedserver occ cur)
1091     ;; Get list of all nnmairix backends (i.e. backends which are
1092     ;; already occupied)
1093     (dolist (cur mairixservers)
1094       (push
1095        (concat
1096         (symbol-name
1097          (cadr (assoc 'nnmairix-backend
1098                       (gnus-server-to-method (car cur)))))
1099          ":"
1100          (cadr (assoc 'nnmairix-backend-server
1101                       (gnus-server-to-method (car cur)))))
1102         occ))
1103     (while alist
1104       (setq server (pop alist))
1105       (setq mserver (gnus-method-to-server (car server)))
1106       ;; If this is the native server, convert it to the real server
1107       ;; name to avoid confusion
1108       (when (string= mserver "native")
1109         (setq mserver (format "%s:%s"
1110                               (caar server)
1111                               (nth 1 (car server)))))
1112       (when (and server
1113                  (eq (cadr server) 'ok)
1114                  (member (caar server) nnmairix-valid-backends)
1115                  (not (member (car server) gnus-ephemeral-servers))
1116                  (not (member (gnus-method-to-server (car server)) occ)))
1117         (push
1118          (list mserver)
1119          openedserver)))
1120     openedserver))
1121
1122 (defun nnmairix-call-backend (func &rest args)
1123   "Call a function FUNC on backend with ARGS."
1124   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
1125
1126 (defun nnmairix-get-backend-folder (group &optional server)
1127   "Return back end GROUP from nnmairix group on SERVER."
1128   (let* ((qualgroup (if server
1129                         (gnus-group-prefixed-name group (list 'nnmairix server))
1130                       group))
1131          (folder (gnus-group-get-parameter qualgroup 'folder)))
1132     folder))
1133
1134 (defun nnmairix-get-numcorr (group &optional server)
1135   "Return values for article number correction nnmairix GROUP on SERVER."
1136   (let* ((qualgroup (if server
1137                         (gnus-group-prefixed-name group (list 'nnmairix server))
1138                       group))
1139          (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1140     corr))
1141
1142
1143 (defun nnmairix-rename-files-consecutively (path)
1144   "Rename all nnml mail files in PATH so that they have consecutive numbers.
1145 This should correct problems of wrong article counts when using
1146 nnmairix with nnml backends."
1147   (let* ((files
1148          (sort
1149           (mapcar 'string-to-number
1150                   (directory-files path nil "[0-9]+" t))
1151           '<))
1152          (lastplusone (car files))
1153          (path (file-name-as-directory path)))
1154     (dolist (cur files)
1155       (when (not (= cur lastplusone))
1156         (rename-file (concat path
1157                              (number-to-string cur))
1158                      (concat path
1159                              (number-to-string lastplusone)))
1160         (setq cur lastplusone))
1161       (setq lastplusone (1+ cur)))))
1162
1163 (defun nnmairix-replace-group-and-numbers (articles backendgroup mairixgroup numc)
1164   "Replace folder names in Xref header and correct article numbers.
1165 Do this for all ARTICLES on BACKENDGROUP.  Replace using
1166 MAIRIXGROUP.  NUMC contains values for article number correction."
1167   (let ((buf (get-buffer-create " *nnmairix buffer*"))
1168         (corr (not (zerop numc)))
1169         (name (buffer-name nntp-server-buffer))
1170         header cur xref)
1171     (save-excursion
1172       (set-buffer buf)
1173       (erase-buffer)
1174       (set-buffer nntp-server-buffer)
1175       (goto-char (point-min))
1176       (nnheader-message 7 "nnmairix: Rewriting headers...")
1177       (mapcar
1178        (function
1179         (lambda (article)
1180           (when (or (looking-at (number-to-string article))
1181                     (nnheader-find-nov-line article))
1182             (setq cur (nnheader-parse-nov))
1183             (when corr
1184                   (setq article (+ (mail-header-number cur) numc))
1185                   (mail-header-set-number cur article))
1186             (setq xref (mail-header-xref cur))
1187             (when (and (stringp xref)
1188                        (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
1189               (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
1190               (mail-header-set-xref cur xref))
1191             (set-buffer buf)
1192             (nnheader-insert-nov cur)
1193             (set-buffer nntp-server-buffer)
1194             (when (not (eobp))
1195               (forward-line 1)))))
1196        articles)
1197       (nnheader-message 7 "nnmairix: Rewriting headers... done")
1198       (kill-buffer nntp-server-buffer)
1199       (set-buffer buf)
1200       (rename-buffer name)
1201       (setq nntp-server-buffer buf))))
1202
1203 (defun nnmairix-backend-to-server (server)
1204   "Return nnmairix server most probably responsible for back end SERVER.
1205 User will be asked if this cannot be determined.  Result is saved in
1206 parameter 'indexed-servers of corresponding default search
1207 group."
1208   (let ((allservers (nnmairix-get-nnmairix-servers))
1209         mairixserver found defaultgroup)
1210     (if (> (length allservers) 1)
1211         (progn
1212           ;; If there is more than one nnmairix server, we go through them
1213           (while (and allservers (not found))
1214             (setq mairixserver (gnus-server-to-method (car (pop allservers))))
1215             ;; First we look if SERVER is the backend of current nnmairix server
1216             (setq found (and (eq (cadr (assoc 'nnmairix-backend mairixserver))
1217                                  (car server))
1218                              (string= (cadr (assoc 'nnmairix-backend-server mairixserver))
1219                                       (nth 1 server))))
1220             ;; If that's not the case, we look at 'indexed-servers
1221             ;; variable in default search group
1222             (when (not found)
1223               (setq defaultgroup (cadr (assoc 'nnmairix-default-group mairixserver)))
1224               (setq found (member (gnus-method-to-server server)
1225                                   (gnus-group-get-parameter
1226                                    (gnus-group-prefixed-name defaultgroup
1227                                                              mairixserver)
1228                                    'indexed-servers t)))))
1229           ;; If still not found, we ask user
1230           (when (not found)
1231             (setq mairixserver
1232                   (gnus-server-to-method
1233                    (completing-read
1234                     (format "Cannot determine which nnmairix server indexes %s. Please specify: "
1235                             (gnus-method-to-server server))
1236                     (nnmairix-get-nnmairix-servers) nil nil "nnmairix:")))
1237             ;; Save result in parameter of default search group so that
1238             ;; we don't have to ask again
1239             (setq defaultgroup (gnus-group-prefixed-name
1240                                 (cadr (assoc 'nnmairix-default-group mairixserver)) mairixserver))
1241             (gnus-group-set-parameter
1242              defaultgroup
1243              'indexed-servers
1244              (append (gnus-group-get-parameter defaultgroup 'indexed-servers t)
1245                      (list (gnus-method-to-server server)))))
1246           mairixserver)
1247       ;; If there is just one (or none) nnmairix server:
1248       (gnus-server-to-method (caar allservers)))))
1249
1250 (defun nnmairix-update-and-clear-marks (group &optional method)
1251   "Update group and clear all marks from GROUP using METHOD."
1252   (when method
1253     (setq group (gnus-group-prefixed-name group method)))
1254   (let ((method (or method
1255                     (gnus-find-method-for-group group)))
1256         (folder (gnus-group-get-parameter group 'folder))
1257         (corr (gnus-group-get-parameter group 'numcorr t))
1258         info)
1259     (if (eq (nth 0 method) 'nnmairix)
1260         (save-excursion
1261           (nnmairix-open-server (nth 1 method))
1262           (set-buffer gnus-group-buffer)
1263           (setq info (gnus-get-info group))
1264           ;; Clear active and info
1265           (gnus-set-active group nil)
1266           (gnus-info-clear-data info)
1267           ;; Delete and re-create group if needed
1268           (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1269             (if (string-match nnmairix-group-regexp folder)
1270                 (progn
1271                   (nnmairix-call-backend "open-server"
1272                                          nnmairix-backend-server)
1273                   (nnmairix-call-backend "request-delete-group"
1274                                          folder t nnmairix-backend-server)
1275                   (nnmairix-call-backend "request-create-group"
1276                                          folder nnmairix-backend-server)
1277                   ;; set flag that group has changed for article number correction
1278                   (when corr
1279                     (setcar corr t)
1280                     (gnus-group-set-parameter group 'numcorr corr)))
1281               (error "Nnmairix-update-and-clear-marks - delete/create with\
1282  non-mairix group!! - check folder parameter")))
1283           (when (gnus-group-jump-to-group group)
1284             (gnus-group-get-new-news-this-group)))
1285       (error "Nnmairix-update-and-clear-marks - Called with non-nnmairix group"))))
1286   
1287
1288 (defun nnmairix-sentinel-mairix-update-finished (proc status)
1289   "Sentinel for mairix update process PROC with STATUS."
1290   (if (equal status "finished\n")
1291       (nnheader-message 7 "Updating mairix database for %s... done" proc)
1292     (error "There was an error updating the mairix database for server %s.  \
1293 See %s for details" proc nnmairix-mairix-output-buffer)))
1294
1295 (defun nnmairix-create-message-line-for-search ()
1296   "Create message line for interactive query in minibuffer."
1297   (mapconcat
1298    (function
1299     (lambda (cur)
1300       (format "%c=%s" (car cur) (nth 3 cur))))
1301    nnmairix-interactive-query-parameters ","))
1302
1303 (defun nnmairix-replace-illegal-chars (header)
1304   "Replace illegal characters in HEADER for mairix query."
1305   (when header
1306     (if (> emacs-major-version 20)
1307         (while (string-match "[^-.@/,& [:alnum:]]" header)
1308           (setq header (replace-match "" t t header)))
1309       (while (string-match "[[]{}:<>]" header)
1310         (setq header (replace-match "" t t header))))
1311     (while (string-match "[-& ]" header)
1312       (setq header (replace-match "," t t header)))
1313   header))
1314
1315 (defun nnmairix-show-original-article (group mid)
1316   "Switch to GROUP and display Article with message-id MID."
1317   (when (string-match "Summary" (buffer-name (current-buffer)))
1318     (gnus-summary-exit))
1319   (pop-to-buffer gnus-group-buffer)
1320   (gnus-group-jump-to-group group)
1321   (gnus-summary-read-group group 1 t)   
1322   (gnus-summary-refer-article mid)
1323   (gnus-summary-limit-to-headers (format "message-id: <%s>" mid))
1324   (gnus-summary-select-article)
1325   ;; Force redisplay
1326   (gnus-summary-show-article)
1327   (nnheader-message 5 "Switched to group %s." group))
1328
1329
1330 ;; ==== Widget stuff
1331
1332 (defvar nnmairix-widgets)
1333 (defvar nnmairix-widgets-values nil)
1334
1335 (defun nnmairix-widget-search-from-this-article ()
1336   "Create mairix query based on current article using graphical widgets."
1337   (interactive)
1338   (nnmairix-widget-search
1339    (nnmairix-widget-get-values)))
1340
1341
1342 (defun nnmairix-widget-get-values ()
1343   "Create values for editable fields from current article."
1344   (if (not (gnus-buffer-live-p gnus-article-buffer))
1345       (error "No article buffer available")
1346     (save-excursion
1347       (gnus-summary-toggle-header 1)
1348       (set-buffer gnus-article-buffer)
1349       (mapcar
1350        (function
1351         (lambda (field)
1352           (list (caddr field)
1353                 (if (car field)
1354                     (nnmairix-replace-illegal-chars
1355                      (gnus-fetch-field (car field)))
1356                   nil))))
1357        nnmairix-widget-fields-list))))
1358   
1359
1360 (defun nnmairix-widget-search (&optional mvalues)
1361   "Create mairix query interactively using graphical widgets.
1362 MVALUES may contain values from current article."
1363   (interactive)
1364   ;; Select window for mairix customization
1365   (funcall nnmairix-widget-select-window-function)
1366   ;; generate widgets
1367   (nnmairix-widget-create-query mvalues)
1368   ;; generate Buttons
1369   (widget-create 'push-button
1370                  :notify
1371                  (if mvalues
1372                      (lambda (&rest ignore)
1373                        (nnmairix-widget-send-query nnmairix-widgets
1374                                                    t))
1375                    (lambda (&rest ignore)
1376                      (nnmairix-widget-send-query nnmairix-widgets
1377                                                  nil)))
1378                  "Send Query")
1379   (widget-insert "   ")
1380   (widget-create 'push-button
1381                  :notify
1382                  (if mvalues
1383                      (lambda (&rest ignore)
1384                        (nnmairix-widget-create-group nnmairix-widgets
1385                                                      t))
1386                    (lambda (&rest ignore)
1387                      (nnmairix-widget-create-group nnmairix-widgets
1388                                                    nil)))
1389                  "Create permanent group")
1390   (widget-insert "   ")
1391   (widget-create 'push-button
1392                  :notify (lambda (&rest ignore)
1393                            (kill-buffer nnmairix-customize-query-buffer))
1394                  "Cancel")
1395   (use-local-map widget-keymap)
1396   (widget-setup)
1397   (goto-char (point-min)))
1398
1399 (defun nnmairix-widget-send-query (widgets &optional withvalues)
1400   "Send query from WIDGETS to mairix binary.
1401 If WITHVALUES is t, query is based on current article."
1402   (nnmairix-search
1403    (nnmairix-widget-make-query-from-widgets widgets)
1404    (if withvalues
1405        (gnus-method-to-server
1406         (nnmairix-backend-to-server gnus-current-select-method))
1407      (car (nnmairix-get-server)))
1408    (if (widget-value (cadr (assoc "Threads" widgets)))
1409        t
1410      -1))
1411   (kill-buffer nnmairix-customize-query-buffer))
1412
1413 (defun nnmairix-widget-create-group (widgets &optional withvalues)
1414   "Create nnmairix group based on current widget values WIDGETS.
1415 If WITHVALUES is t, query is based on current article."
1416   (let ((group (read-string "Name of the group: ")))
1417     (when (not (zerop (length group)))
1418       (nnmairix-create-search-group
1419        (if withvalues
1420            (gnus-method-to-server
1421             (nnmairix-backend-to-server gnus-current-select-method))
1422          (car (nnmairix-get-server)))
1423        group
1424        (nnmairix-widget-make-query-from-widgets widgets)
1425        (widget-value (cadr (assoc "Threads" widgets))))))
1426   (kill-buffer nnmairix-customize-query-buffer))
1427
1428
1429 (defun nnmairix-widget-make-query-from-widgets (widgets)
1430   "Create mairix query from widget values WIDGETS."
1431   (let (query temp flag)
1432     ;; first we do the editable fields
1433     (dolist (cur nnmairix-widget-fields-list)
1434       ;; See if checkbox is checked
1435       (when (widget-value
1436              (cadr (assoc (concat "c" (caddr cur)) widgets)))
1437         ;; create query for the field
1438         (push
1439          (concat
1440           (nth 1 cur)
1441           ":"
1442           (nnmairix-replace-illegal-chars
1443            (widget-value
1444            (cadr (assoc (concat "e" (caddr cur)) widgets)))))
1445          query)))
1446     ;; Flags
1447     (when (member 'flags nnmairix-widget-other)
1448       (setq flag
1449             (mapconcat
1450              (function
1451               (lambda (flag)
1452                 (setq temp
1453                       (widget-value (cadr (assoc (car flag) nnmairix-widgets))))
1454                 (if (string= "yes" temp)
1455                     (cadr flag)
1456                   (if (string= "no" temp)
1457                       (concat "-" (cadr flag))))))
1458              '(("seen" "s") ("replied" "r") ("flagged" "f")) ""))
1459       (when (not (zerop (length flag)))
1460         (push (concat "F:" flag) query)))
1461     ;; return query string
1462     (mapconcat 'identity query " ")))
1463
1464
1465 (defun nnmairix-widget-create-query (&optional values)
1466   "Create widgets for creating mairix queries.
1467 Fill in VALUES if based on an article."
1468   (let (allwidgets)
1469     (when (get-buffer nnmairix-customize-query-buffer)
1470       (kill-buffer nnmairix-customize-query-buffer))
1471     (switch-to-buffer nnmairix-customize-query-buffer)
1472     (kill-all-local-variables)
1473     (erase-buffer)
1474     (widget-insert "Specify your query for Mairix (check boxes for activating fields):\n\n")
1475     (widget-insert "(Whitespaces will be converted to ',' (i.e. AND). Use '/' for OR.)\n\n")
1476 ;    (make-local-variable 'nnmairix-widgets)
1477     (setq nnmairix-widgets (nnmairix-widget-build-editable-fields values))
1478     (when (member 'flags nnmairix-widget-other)
1479       (widget-insert "\nFlags:\n      Seen:     ")
1480       (nnmairix-widget-add "seen"
1481                            'menu-choice
1482                            :value "ignore"
1483                            '(item "yes") '(item "no") '(item "ignore"))
1484       (widget-insert "      Replied:  ")
1485       (nnmairix-widget-add "replied"
1486                            'menu-choice
1487                            :value "ignore"
1488                            '(item "yes") '(item "no") '(item "ignore"))
1489       (widget-insert "      Ticked:   ")
1490       (nnmairix-widget-add "flagged"
1491                            'menu-choice
1492                            :value "ignore"
1493                            '(item "yes") '(item "no") '(item "ignore")))
1494     (when (member 'threads nnmairix-widget-other)
1495       (widget-insert "\n")
1496       (nnmairix-widget-add "Threads" 'checkbox nil))
1497       (widget-insert " Show full threads\n\n")))
1498
1499
1500 (defun nnmairix-widget-build-editable-fields (values)
1501   "Build editable field widgets in `nnmairix-widget-fields-list'.
1502 VALUES may contain values for editable fields from current article."
1503   ;; how can this be done less ugly?
1504   (let ((ret))
1505     (mapc
1506      (function
1507       (lambda (field)
1508         (setq field (caddr field))
1509         (setq ret
1510               (nconc
1511                (list
1512                 (list
1513                  (concat "c" field)
1514                  (widget-create 'checkbox
1515                                 :tag field
1516                                 :notify (lambda (widget &rest ignore)
1517                                           (nnmairix-widget-toggle-activate widget))
1518                                 nil)))
1519                (list
1520                 (list
1521                  (concat "e" field)
1522                  (widget-create 'editable-field
1523                                 :size 60
1524                                 :format (concat " " field ":"
1525                                                 (make-string (- 11 (length field)) ?\ )
1526                                                 "%v")
1527                                 :value (or (cadr (assoc field values)) ""))))
1528                ret))
1529         (widget-insert "\n")
1530         ;; Deactivate editable field
1531         (widget-apply (cadr (nth 1 ret)) :deactivate)))
1532      nnmairix-widget-fields-list)
1533     ret))
1534
1535 (defun nnmairix-widget-add (name &rest args)
1536   "Add a widget NAME with optional ARGS."
1537   (push
1538    (list name
1539          (apply 'widget-create args))
1540    nnmairix-widgets))
1541
1542 (defun nnmairix-widget-toggle-activate (widget)
1543   "Toggle activation status of WIDGET dependent on corresponding checkbox value."
1544   (let ((field (widget-get widget :tag)))
1545     (if (widget-value widget)
1546         (widget-apply
1547          (cadr (assoc (concat "e" field) nnmairix-widgets))
1548          :activate)
1549       (widget-apply
1550        (cadr (assoc (concat "e" field) nnmairix-widgets))
1551        :deactivate)))
1552   (widget-setup))
1553
1554 (provide 'nnmairix)
1555
1556 ;; arch-tag: bb187498-b229-4a55-8c07-6d3f80713e94
1557 ;;; nnmairix.el ends here