* nnmairix.el: Remove old documentation in the commentary block.
[gnus] / lisp / nnmairix.el
index c8bd1ca..b009903 100644 (file)
@@ -1,31 +1,28 @@
 ;;; nnmairix.el --- Mairix back end for Gnus, the Emacs newsreader
 
-;; Copyright (C) 2007, 2008  Free Software Foundation, Inc.
+;; Copyright (C) 2007, 2008, 2009  Free Software Foundation, Inc.
 
 ;; Author: David Engster <dengste@eml.cc>
 ;; Keywords: mail searching
-;; Version: 0.5
+;; Version: 0.6
 
-;; This file is free software; you can redistribute it and/or modify
+;; This file is part of GNU Emacs.
+
+;; GNU Emacs is free software: you can redistribute it and/or modify
 ;; it under the terms of the GNU General Public License as published by
-;; the Free Software Foundation; either version 2, or (at your option)
-;; any later version.
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
 
-;; This file is distributed in the hope that it will be useful,
+;; GNU Emacs is distributed in the hope that it will be useful,
 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to
-;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-;; Boston, MA 02110-1301, USA.
+;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
 
 ;;; Commentary:
 
-;; THIS IS BETA SOFTWARE! This back end should not mess up or
-;; even delete your mails, but having a backup is always a good idea.
-
 ;; This is a back end for using the mairix search engine with
 ;; Gnus.  Mairix is a tool for searching words in locally stored
 ;; mail.  Mairix is very fast which allows using it efficiently for
 ;;
 ;; Mairix is written by Richard Curnow.  More information can be found at
 ;; http://www.rpcurnow.force9.co.uk/mairix/
-;;
-;; For details about setting up mairix&Gnus&nnmairix.el, look at the
-;; emacswiki:
-;;
-;; http://www.emacswiki.org/cgi-bin/wiki/GnusMairix
-;;
-;; The newest version of nnmairix.el can be found at
-;; 
-;; http://www.emacswiki.org/cgi-bin/emacs/nnmairix.el
-
-;; For impatient people, here's the setup in a nutshell:
-;;
-;; This back end requires an installed mairix binary which is
-;; configured to index your mail folder.  You don't have to specify a
-;; search folder (but it does no harm, either).  Visit the man page of
-;; mairix and mairixrc for details.
-;;
-;; Put nnmairix.el into your search path and "(require 'nnmarix)" into
-;; your .gnus.  Then call nnmairix-create-default-group (or 'G b
-;; c'). This function will ask for all necessary information to create
-;; a mairix server in Gnus with the default search folder.  This
-;; default search folder will be used for all temporary searches: call
-;; nnmairix-search ('G b s') and enter a mairix query (like
-;; f:test@example.com). To create a mairix group for one specific
-;; search query, use 'G b g'.  See the emacswiki or the source for more
-;; information.
 
 ;; Commentary on the code: nnmairix sits between Gnus and the "real"
 ;; back end which handles the mail (currently nnml, nnimap and
 ;; I thought it would be a "nice to have feature"...
 
 ;; KNOWN BUGS:
-;; * When using Maildir: path and filename of a mail can change due to
-;; reading/replying/etc.  This can lead to dangling symlinks in
-;; nnmairix groups and it depends on the back end how well it deals
-;; with that (some IMAP servers out there may not be amused).  Update the
-;; database ('G b u') and the group to fix it.
 ;; * Mairix does only support us-ascii characters.
 
 ;; TODO/MISSING FEATURES:
-;; * Possibility to propagate flags like seen, replied, ticked
-;;   to original message
 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
 ;; * Maybe use an active file instead of group parameters?
-;; * Use "-a" when updating groups which are not newly created
+;; * Maybe use "-a" when updating groups which are not newly created?
+
 ;;; Changelog:
+;; 05/30/2008 - version 0.6
+;;
+;;    * It is now possible to propagate marks from the nnmairix groups
+;;      to the original messages (and for maildir also vice versa). See
+;;      the docs for details on this feature - it's pretty delicate
+;;      and currently needs a patched mairix binary to work smoothly.
+;;
+;;    * Keep messages in nnmairix groups always read/unread
+;;      (bound to 'G b r').
+;;
+;;    * Recreate back end folder for nnmairix groups in case you
+;;      somehow get wrong article counts (bound to 'G b d').
+;;
+;;    * New group parameter 'allow-fast'. Toggling of parameter bound
+;;      to 'G b a'. The default is nil, meaning that the group will
+;;      always be updated with a mairix search, even when only entered.
+;;
+;;    * More/Better use of the registry (if available). Can now also
+;;      deal with duplicate messages in different groups.
 ;;
 ;; 02/06/2008 - version 0.5
-;; 
+;;
 ;;    * New function: nnmairix-goto-original-article. Uses the
 ;;      registry or the mail file path for determining original group.
-;; 
+;;
 ;;    * Deal with empty Xref header
 ;;
 ;;    * Changed summary mode keybindings since the old ones were
 ;;
 ;;    * New/fixed doc strings and code cleanup.
 ;;
-;; 18/11/2007 - version 0.3
+;; 11/18/2007 - version 0.3
 ;;
 ;;    * Fixed bugs when dealing with nnml and native servers
-;;     
+;;
 ;;    * Make variables customizable
 ;;
 ;; 10/10/2007 - version 0.2
 ;;
 ;;    * Use nnml-directory/directory server variables for nnml and
-;;    nnmaildir backends as path for search folders. This way it
+;;    nnmaildir back ends as path for search folders. This way it
 ;;    becomes independent of 'base' setting in .mairixirc (but not for
 ;;    nnimap).
 ;;
 ;;    * As a result: Changed nnmairix-backend-to-server so that user
 ;;    is asked when more than one nnmairix server exists and we do not
-;;    know which one is responsible for current backend.
+;;    know which one is responsible for current back end.
 ;;
-;;    * Rename files when using nnml backends so that there are no
+;;    * Rename files when using nnml back ends so that there are no
 ;;    holes in article numbers. This should fix all problems regarding
 ;;    wrong article counts with nnml.
 ;;
 
 ;;; Code:
 
+(eval-when-compile (require 'cl))       ;For (pop (cdr ogroup)).
+
 (require 'nnoo)
 (require 'gnus-group)
 (require 'gnus-sum)
 
 ;;; === Keymaps
 
+(eval-when-compile
+  (when (featurep 'xemacs)
+    ;; The `kbd' macro requires that the `read-kbd-macro' macro is available.
+    (require 'edmacro)))
+
 ;; Group mode
 (defun nnmairix-group-mode-hook ()
   "Nnmairix group mode keymap."
   (define-key gnus-group-mode-map
     (kbd "G b i") 'nnmairix-search-interactive)
   (define-key gnus-group-mode-map
-    (kbd "G b m") 'nnmairix-widget-search))
+    (kbd "G b m") 'nnmairix-widget-search)
+  (define-key gnus-group-mode-map
+    (kbd "G b p") 'nnmairix-group-toggle-propmarks-this-group)
+  (define-key gnus-group-mode-map
+    (kbd "G b r") 'nnmairix-group-toggle-readmarks-this-group)
+  (define-key gnus-group-mode-map
+    (kbd "G b d") 'nnmairix-group-delete-recreate-this-group)
+  (define-key gnus-group-mode-map
+    (kbd "G b a") 'nnmairix-group-toggle-allowfast-this-group)
+  (define-key gnus-group-mode-map
+    (kbd "G b o") 'nnmairix-propagate-marks))
 
 ;; Summary mode
 (defun nnmairix-summary-mode-hook ()
   (define-key gnus-summary-mode-map
     (kbd "$ g") 'nnmairix-create-search-group-from-message)
   (define-key gnus-summary-mode-map
-    (kbd "$ o") 'nnmairix-goto-original-article))
+    (kbd "$ o") 'nnmairix-goto-original-article)
+  (define-key gnus-summary-mode-map
+    (kbd "$ u") 'nnmairix-remove-tick-mark-original-article))
 
 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
 
+;; ;;;###autoload
+;; (defun nnmairix-initalize (&optional force)
+;;   (interactive "P")
+;;   (if (not (or (file-readable-p "~/.mairixrc")
+;;            force))
+;;       (message "No file `~/.mairixrc', skipping nnmairix setup")
+;;     (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
+;;     (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)))
 
 ;; Customizable stuff
 
 (defgroup nnmairix nil
-  "Backend for the Mairix mail search engine."
+  "Back end for the Mairix mail search engine."
   :group 'gnus)
 
 (defcustom nnmairix-group-prefix "zz_mairix"
@@ -215,19 +225,19 @@ server for each nnmairix search group.  The name on the back end
 server will be this prefix plus a random number.  You can delete
 unused nnmairix groups on the back end using
 `nnmairix-purge-old-groups'."
-  :version "23.0"
+  :version "23.1"
   :type 'string
   :group 'nnmairix)
 
 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
   "Buffer used for mairix output."
-  :version "23.0"
+  :version "23.1"
   :type 'string
   :group 'nnmairix)
 
 (defcustom nnmairix-customize-query-buffer "*mairix query*"
   "Name of the buffer for customizing Mairix queries."
-  :version "23.0"
+  :version "23.1"
   :type 'string
   :group 'nnmairix)
 
@@ -236,23 +246,30 @@ unused nnmairix groups on the back end using
 The default is '-F' and '-Q' for making updates faster.  You
 should call mairix without these options from time to
 time (e.g. via cron job)."
-  :version "23.0"
+  :version "23.1"
+  :type '(repeat string)
+  :group 'nnmairix)
+
+(defcustom nnmairix-mairix-search-options '("-Q")
+  "Options when calling mairix for searching.
+The default is '-Q' for making searching faster."
+  :version "23.1"
   :type '(repeat string)
   :group 'nnmairix)
 
 (defcustom nnmairix-mairix-synchronous-update nil
   "Set this to t if you want Emacs to wait for mairix updating the database."
-  :version "23.0"
+  :version "23.1"
   :type 'boolean
   :group 'nnmairix)
 
 (defcustom nnmairix-rename-files-for-nnml t
   "Rename nnml mail files so that they are consecutively numbered.
-When using nnml as backend, mairix might produce holes in the
+When using nnml as back end, mairix might produce holes in the
 article numbers which will produce wrong article counts by
 Gnus.  This option controls whether nnmairix should rename the
 files consecutively."
-  :version "23.0"
+  :version "23.1"
   :type 'boolean
   :group 'nnmairix)
 
@@ -268,7 +285,7 @@ fields in interactive query customization.  The header specifies
 which header contents should be inserted into the editable field
 when creating a Mairix query based on the current message (can be
 nil for disabling this)."
-  :version "23.0"
+  :version "23.1"
   :type '(repeat (list
                  (choice :tag "Field"
                          (const :tag "none" nil)
@@ -285,10 +302,52 @@ nil for disabling this)."
   (lambda () (select-window (get-largest-window)))
   "Function for selecting the window for customizing the mairix query.
 The default chooses the largest window in the current frame."
-  :version "23.0"
+  :version "23.1"
   :type 'function
   :group 'nnmairix)
 
+(defcustom nnmairix-propagate-marks-upon-close t
+  "Flag if marks should be propagated upon closing a group.
+The default of this variable is t. If set to 'ask, the
+user will be asked if the flags should be propagated when the
+group is closed.  If set to nil, the user will have to manually
+call 'nnmairix-propagate-marks'."
+  :version "23.1"
+  :type '(choice (const :tag "always" t)
+                (const :tag "ask" 'ask)
+                (const :tag "never" nil))
+  :group 'nnmairix)
+
+(defcustom nnmairix-propagate-marks-to-nnmairix-groups nil
+  "Flag if marks from original articles should be seen in nnmairix groups.
+The default is nil since it will only work if the articles are in
+maildir format and NOT managed by the nnmaildir back end but
+e.g. an IMAP server (which stores the marks in the maildir file
+name).  You may safely set this to t for testing - the worst that
+can happen are wrong marks in nnmairix groups."
+  :version "23.1"
+  :type 'boolean
+  :group 'nnmairix)
+
+(defcustom nnmairix-only-use-registry nil
+  "Use only the registry for determining original group(s).
+If set to t, nnmairix will only use the registry for determining
+the original group(s) of an article (which is also necessary for
+propapagting marks).  If set to nil, it will also try to determine
+the group from an additional mairix search which might be slow
+when propagating lots of marks."
+  :version "23.1"
+  :type 'boolean
+  :group 'nnmairix)
+
+(defcustom nnmairix-allowfast-default nil
+  "Whether fast entering should be the default for nnmairix groups.
+You may set this to t to make entering the group faster, but note that
+this might lead to problems, especially when used with marks propagation."
+  :version "23.1"
+  :type 'boolean
+  :group 'nnmairix)
+
 ;; ==== Other variables
 
 (defvar nnmairix-widget-other
@@ -305,20 +364,18 @@ Every list element consists of the following entries: Keystroke,
 message field (if any), mairix command and description.")
 
 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
-  "Controls on which backends groups should be deleted and re-created.
-This variable is a list of back ends where the search group should
-be completely deleted and re-created when the query or thread
-parameter changes.  I know this is rather \"brute force\" and maybe
-even dangerous (you have backups, right?), but it should be used at
-least for nnimap since some IMAP servers are really not amused when
-mailbox content changes behind their back.  It usually also corrects
-the problem of \"holes\" in the article numbers which often lead to a
+  "Controls on which back ends groups should be deleted and re-created.
+This variable is a list of back ends where the search group
+should be completely deleted and re-created when the query or
+thread parameter changes.  The default is to this for all
+currently supported back ends.  It usually also corrects the
+problem of \"holes\" in the article numbers which often lead to a
 wrong count of total articles shown by Gnus.")
 
 ;;; === Server variables
 
 (defvoo nnmairix-backend  nil
-  "Backend where mairix stores its searches.")
+  "Back end where mairix stores its searches.")
 
 (defvoo nnmairix-backend-server nil
   "Name of the server where mairix stores its searches.")
@@ -336,21 +393,28 @@ temporary searches, e.g. nnmairix-search.")
 
 ;;; === Internal variables
 
-;; Regexp for mairix groups on back end
-(setq nnmairix-group-regexp (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix))
+(defconst nnmairix-group-regexp
+  (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
+  "Regexp for mairix groups on back end.")
 
-;; Back ends (hopefully...) supported by nnmairix.
-;; Other backends might or might not work.
-(setq nnmairix-valid-backends '(nnimap nnml nnmaildir))
+(defconst nnmairix-valid-backends '(nnimap nnml nnmaildir)
+  "Back ends supported by nnmairix.
+Other back ends might or might not work.")
 
-;; Last chosen server
-(setq nnmairix-last-server nil)
+(defvar nnmairix-last-server nil
+  "Last chosen server.")
 
-;; Current server
-(setq nnmairix-current-server nil)
+(defvar nnmairix-current-server nil
+  "Current server.")
+
+(defvar nnmairix-marks-cache nil
+  "Cache for marks which should be set upon closing current group.")
+
+(defvar nnmairix-version-output nil
+  "Version string of mairix binary.")
+
+;;; === Gnus back end functions
 
-;;; === Gnus backend functions
-  
 (nnoo-define-basics nnmairix)
 
 (gnus-declare-backend "nnmairix" 'mail 'address)
@@ -366,13 +430,14 @@ temporary searches, e.g. nnmairix-search.")
   (let* ((qualgroup (if server
                        (gnus-group-prefixed-name group (list 'nnmairix server))
                      group))
+        (folder (gnus-group-get-parameter qualgroup 'folder))
+        (allowfast (gnus-group-get-parameter qualgroup 'allow-fast))
         (query (gnus-group-get-parameter qualgroup 'query t))
-       (folder (gnus-group-get-parameter qualgroup 'folder))
-       (threads (gnus-group-get-parameter qualgroup 'threads))
-       (backendmethod (gnus-server-to-method
-                       (format "%s:%s" (symbol-name nnmairix-backend)
-                               nnmairix-backend-server)))
-       rval mfolder folderpath)
+        (threads (gnus-group-get-parameter qualgroup 'threads))
+        (backendmethod (gnus-server-to-method
+                        (format "%s:%s" (symbol-name nnmairix-backend)
+                                nnmairix-backend-server)))
+        rval mfolder folderpath args)
     (cond
      ((not folder)
       ;; No folder parameter -> error
@@ -410,8 +475,10 @@ temporary searches, e.g. nnmairix-search.")
                 folderpath))
               mfolder)))
       ;; If (not fast), call Mairix binary
+      ;; recreate underlying folder on the back end
       (setq rval
-           (if fast 0
+           (if (and fast allowfast)
+               0
              (nnmairix-call-mairix-binary
               (split-string nnmairix-mairix-command)
               mfolder query threads)))
@@ -426,12 +493,13 @@ temporary searches, e.g. nnmairix-search.")
        (when (eq nnmairix-backend 'nnml)
          (when nnmairix-rename-files-for-nnml
            (nnmairix-rename-files-consecutively mfolder))
-         (nnml-generate-nov-databases-directory mfolder))
+         (nnml-generate-nov-databases-directory mfolder nil t))
        (nnmairix-call-backend
         "request-scan" folder nnmairix-backend-server)
-       (if fast
+       (if (and fast allowfast)
            t
-         (nnmairix-request-group-with-article-number-correction folder qualgroup)))
+         (nnmairix-request-group-with-article-number-correction
+          folder qualgroup)))
        ((and (= rval 1)
             (save-excursion (set-buffer nnmairix-mairix-output-buffer)
                             (goto-char (point-min))
@@ -468,6 +536,8 @@ temporary searches, e.g. nnmairix-search.")
     (nnmairix-call-backend
      "request-create-group" groupname nnmairix-backend-server)
     (gnus-group-add-parameter qualgroup '(folder . nil))
+    (when nnmairix-allowfast-default
+      (gnus-group-add-parameter qualgroup '(allow-fast . t)))
     (gnus-group-set-parameter qualgroup 'folder groupname))
   t)
 
@@ -486,8 +556,13 @@ temporary searches, e.g. nnmairix-search.")
            (mapcar
             (lambda (arg) (- arg numcorr))
             articles)))
-    (setq rval (nnmairix-call-backend
-               "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
+    (setq rval 
+         (if (eq nnmairix-backend 'nnimap)
+             (let ((gnus-nov-is-evil t))
+               (nnmairix-call-backend
+                "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
+           (nnmairix-call-backend
+            "retrieve-headers" articles folder nnmairix-backend-server fetch-old)))
     (when (eq rval 'nov)
       (nnmairix-replace-group-and-numbers articles folder group numcorr)
       rval)))
@@ -505,11 +580,6 @@ temporary searches, e.g. nnmairix-search.")
      "request-article" article folder nnmairix-backend-server to-buffer))
   t)
 
-(deffoo nnmairix-close-group (group &optional server)
-  ;; Should we do something here?
-  nil)
-
-
 (deffoo nnmairix-request-list (&optional server)
   (when server (nnmairix-open-server server))
   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
@@ -535,7 +605,157 @@ temporary searches, e.g. nnmairix-search.")
        t)
     nil))
 
-                
+;; Silence byte-compiler.
+(defvar gnus-registry-install)
+(autoload 'gnus-registry-fetch-group "gnus-registry")
+(autoload 'gnus-registry-fetch-groups "gnus-registry")
+(autoload 'gnus-registry-add-group "gnus-registry")
+
+(deffoo nnmairix-request-set-mark (group actions &optional server)
+  (when server
+    (nnmairix-open-server server))
+  (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
+        (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
+        (propto (gnus-group-get-parameter qualgroup 'propto t))
+        (corr (nnmairix-get-numcorr group server))
+        (folder (nnmairix-get-backend-folder group server)))
+    (save-excursion
+      (dolist (cur actions)
+       (let ((type (nth 1 cur))
+             (cmdmarks (nth 2 cur))
+             (range (gnus-uncompress-range (nth 0 cur)))
+             mid ogroup number method temp)
+         (when (and corr
+                    (not (zerop (cadr corr))))
+           (setq range (mapcar (lambda (arg)
+                                 (- arg (cadr corr)))
+                               range)))
+         (when propmarks
+           (nnheader-message 7 "nnmairix: Setting marks...")
+             (dolist (article range)
+               ;; get article (header) and extract message id
+               ;; we try to determine as many original articles as possible
+               (catch 'problem
+                 (nnmairix-call-backend "open-server" nnmairix-backend-server)
+                 (unless (gnus-request-head
+                          article
+                          (gnus-group-prefixed-name
+                           folder
+                           (list nnmairix-backend nnmairix-backend-server)))
+                   (nnheader-message
+                    3 "Unable to set mark: couldn't fetch article header for article number %d"
+                    article)
+                   (throw 'problem nil))
+                 (set-buffer nntp-server-buffer)
+                 (goto-char (point-min))
+                 (let ((case-fold-search t))
+                   (re-search-forward "^message-id:.*\\(<.+>\\)" nil t))
+                 (setq mid (match-string 1))
+                 (unless mid
+                   (nnheader-message
+                    3 "Unable to set mark: article number %d has no message-id header"
+                    article)
+                   (throw 'problem nil))
+                 ;; get original group. First try registry, then file path
+                 (setq ogroup
+                       (nnmairix-determine-original-group-from-registry mid))
+                 (unless (or ogroup
+                             nnmairix-only-use-registry)
+                   (setq ogroup
+                         (nnmairix-determine-original-group-from-path
+                          mid nnmairix-current-server))
+                   ;; if available and allowed, add this entry to the registry
+                   (when (and (boundp 'gnus-registry-install)
+                              gnus-registry-install)
+                     (dolist (cur ogroup)
+                       (unless (gnus-parameter-registry-ignore cur)
+                         (gnus-registry-add-group mid cur)))))
+                 (unless ogroup
+                   (nnheader-message
+                    3 "Unable to set mark: couldn't find original group for %s" mid)
+                   (throw 'problem nil))
+                 ;; store original groups with mid's. We cannot get
+                 ;; the article number immediately since this would
+                 ;; generate problems with maildir (articles might
+                 ;; get moved from /new to /cur and further marks
+                 ;; could then not be set)
+                 (dolist (cur ogroup)
+                   (setq temp (assoc cur
+                                     nnmairix-marks-cache))
+                   (if temp
+                       (nconc temp (list (list mid type cmdmarks)))
+                     (push (list cur (list mid type cmdmarks))
+                           nnmairix-marks-cache)))))
+             (nnheader-message 7 "nnmairix: Setting marks... done")))))))
+
+(deffoo nnmairix-close-group (group &optional server)
+  (when server
+    (nnmairix-open-server server))
+  (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
+        (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
+        method)
+    (when (and propmarks
+              nnmairix-marks-cache)
+      (when (or (eq nnmairix-propagate-marks-upon-close t)
+               (and (eq nnmairix-propagate-marks-upon-close 'ask)
+                    (y-or-n-p "Propagate marks to original articles? ")))
+      (save-excursion
+       (set-buffer gnus-group-buffer)
+       (nnmairix-propagate-marks)
+       ;; update mairix group
+       (gnus-group-jump-to-group qualgroup)
+       (gnus-group-get-new-news-this-group))))))
+
+(autoload 'nnimap-request-update-info-internal "nnimap")
+
+(deffoo nnmairix-request-update-info (group info &optional server)
+;; propagate info from underlying IMAP folder to nnmairix group
+;; This is currently experimental and must be explicitly activated
+;; with nnmairix-propagate-marks-to-nnmairix-group
+  (when server
+    (nnmairix-open-server server))
+  (let* ((qualgroup (gnus-group-prefixed-name
+                   group
+                   (list 'nnmairix nnmairix-current-server)))
+        (readmarks (gnus-group-get-parameter qualgroup 'readmarks))
+        (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
+        (folder (nnmairix-get-backend-folder group server))
+        (corr (nnmairix-get-numcorr group server))
+        (docorr (and corr (not (zerop (cadr corr)))))
+        (folderinfo `(,group 1 ((1 . 1))))
+        readrange marks)
+      (when (and propmarks
+                nnmairix-propagate-marks-to-nnmairix-groups)
+       ;; these groups are not subscribed, so we have to ask the back end directly
+       (if (eq nnmairix-backend 'nnimap)
+           (nnimap-request-update-info-internal folder folderinfo nnmairix-backend-server)
+         (nnmairix-call-backend "request-update-info" folder folderinfo nnmairix-backend-server))
+       ;; set range of read articles
+       (gnus-info-set-read
+        info
+        (if docorr
+            (nnmairix-map-range
+             `(lambda (x) (+ x ,(cadr corr)))
+             (gnus-info-read folderinfo))
+          (gnus-info-read folderinfo)))
+       ;; set other marks
+       (gnus-info-set-marks
+        info
+        (if docorr
+            (mapcar (lambda (cur)
+                        (cons
+                         (car cur)
+                         (nnmairix-map-range
+                          `(lambda (x) (+ x ,(cadr corr)))
+                          (list (cadr cur)))))
+                    (gnus-info-marks folderinfo))
+          (gnus-info-marks folderinfo))))
+      (when (eq readmarks 'unread)
+       (gnus-info-set-read info nil))
+      (when (eq readmarks 'read)
+       (gnus-info-set-read info (gnus-active qualgroup))))
+  t)
+
 (nnoo-define-skeleton nnmairix)
 
 
@@ -633,7 +853,7 @@ All necessary information will be queried from the user."
   (interactive)
   (let* ((name (read-string "Name of the mairix server: "))
        (server (completing-read "Back end server (TAB for completion): "
-                                (nnmairix-get-valid-servers)))
+                                (nnmairix-get-valid-servers) nil 1))
        (mairix (read-string "Command to call mairix: " "mairix"))
        (defaultgroup (read-string "Default search group: "))
        (backend (symbol-name (car (gnus-server-to-method server))))
@@ -657,7 +877,6 @@ All necessary information will be queried from the user."
                        (list 'nnmairix-hidden-folders hidden)
                        (list 'nnmairix-default-group defaultgroup)))))
 
-
 (defun nnmairix-group-change-query-this-group (&optional query)
   "Set QUERY for group under cursor."
   (interactive)
@@ -676,28 +895,68 @@ All necessary information will be queried from the user."
            (gnus-group-set-parameter group 'query query)
            (nnmairix-update-and-clear-marks group)))
       (error "This is no nnmairix group"))))
-                 
+
 
 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
   "Toggle threads parameter for this group.
 If THREADS is a positive number, set threads parameter to t.
 If THREADS is a negative number, set it to nil."
   (interactive)
-  (let* ((group (gnus-group-group-name))
-        (method (gnus-find-method-for-group group))
-        (getthreads (or threads
-                       (not (gnus-group-get-parameter group 'threads)))))
+  (let ((group (gnus-group-group-name)))
+    (when (nnmairix-group-toggle-parameter
+          group 'threads "Threads" threads)
+      (nnmairix-update-and-clear-marks group))))
+
+(defun nnmairix-group-toggle-propmarks-this-group (&optional propmarks)
+  "Toggle marks propagation for this group.
+If PROPMARKS is a positive number, set parameter to t.
+If PROPMARKS is a negative number, set it to nil."
+  (interactive)
+  (unless (nnmairix-check-mairix-version "maildirpatch")
+    (error "You need a mairix binary with maildir patch to use this feature.  See docs for details"))
+  (let ((group (gnus-group-group-name)))
+    (when (or (not (string= (gnus-group-short-name group)
+                           (cadr (assoc 'nnmairix-default-group
+                                       (gnus-find-method-for-group group)))))
+             (y-or-n-p "You should not activate marks propagation for the default \
+search group.  Are you sure? "))
+      (nnmairix-group-toggle-parameter
+       group 'propmarks "Marks propagation" propmarks))))
+
+(defun nnmairix-group-toggle-allowfast-this-group (&optional allowfast)
+  "Toggle fast entering for this group.
+If ALLOWFAST is a positive number, set parameter to t.
+If ALLOWFAST is a negative number, set it to nil."
+  (interactive)
+  (nnmairix-group-toggle-parameter
+   (gnus-group-group-name) 'allow-fast "Fast entering" allowfast))
+
+
+(defun nnmairix-group-toggle-readmarks-this-group (&optional readmarks)
+  "Toggle read/unread marks for this group.
+If READMARKS is a positive number, articles will always be read.
+If READMARKS is a negative number, articles will always be unread.
+If READMARKS is t or zero, marks will stay unchanged."
+  (interactive)
+  (let*  ((group (gnus-group-group-name))
+         (method (gnus-find-method-for-group group))
+         (readmarks (or readmarks
+                        (gnus-group-get-parameter group 'readmarks))))
     (if (eq (car method) 'nnmairix)
-       (progn
-         (when (numberp getthreads)
-           (setq getthreads (> getthreads 0)))
-         (gnus-group-set-parameter group 'threads getthreads)
-         (if getthreads
-             (message "Threads activated for group %s" group)
-           (message "Threads deacitavted for group %s" group))
-         (nnmairix-update-and-clear-marks group))
+       (cond
+        ((or (and (numberp readmarks) (< readmarks 0))
+             (eq readmarks 'read))
+         (gnus-group-set-parameter group 'readmarks 'unread)
+         (nnheader-message 3 "Articles in %s always unread." group))
+        ((or (and (numberp readmarks) (> readmarks 0))
+             (not readmarks))
+             (gnus-group-set-parameter group 'readmarks 'read)
+             (nnheader-message 3 "Articles in %s always read." group))
+        (t
+         (gnus-group-set-parameter group 'readmarks nil)
+         (nnheader-message 3 "Read marks in %s stay unchanged." group)))
       (error "This is no nnmairix group"))))
-        
+
 
 (defun nnmairix-search (query &optional server threads)
   "Sends QUERY to nnmairix backend SERVER, using default its search group.
@@ -725,7 +984,7 @@ Otherwise, leave threads parameter as it is."
       (when (< threads 0)
        (gnus-group-set-parameter qualgroup 'threads nil)))
     (nnmairix-update-and-clear-marks qualgroup)
-    (when (not (zerop (gnus-group-unread qualgroup)))
+    (unless (equal (gnus-active qualgroup) '(1 . 0))
       (gnus-group-read-group nil t qualgroup))))
 
 (defun nnmairix-search-thread-this-article ()
@@ -843,138 +1102,133 @@ with `nnmairix-mairix-update-options'."
          (set-process-sentinel (apply 'start-process args)
                                'nnmairix-sentinel-mairix-update-finished))))))
 
-(defun nnmairix-goto-original-article (&optional no-registry)
-  "Jump to the original group and display article.
-The original group of the article is first determined with the
-registry (if enabled). If the registry is not enabled or did not
-find the article or the prefix NO-REGISTRY is non-nil, this
-function will try to determine the original group form the path
-of the mail file. The path is obtained through another mairix
-search in raw mode."
-  (interactive "P")
-  (when (not (eq (car gnus-current-select-method) 'nnmairix))
-    (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
-      (if (eq (car method) 'nnmairix)
-         (nnmairix-open-server (nth 1 method))
-       (error "Not in a nnmairix group"))))
-  (when (not (gnus-buffer-live-p gnus-article-buffer))
-    (error "No article buffer available"))
-  (let ((server (nth 1 gnus-current-select-method))
-       mid rval group allgroups)
-    ;; get message id
-    (save-excursion
-      (set-buffer gnus-article-buffer)
-      (gnus-summary-toggle-header 1)
-      (setq mid (message-fetch-field "Message-ID"))
-      ;; first check the registry (if available)
-      (when (and (boundp 'gnus-registry-install)
-                gnus-registry-install
-                (not no-registry))
-       (setq group (gnus-registry-fetch-group mid)))
-      (while (string-match "[<>]" mid)
-       (setq mid (replace-match "" t t mid)))
-      (unless group
-       ;; registry was not available or did not find article
-       ;; so we search again with mairix in raw mode to get filename
-       (nnmairix-open-server server)
-       (setq rval 
-             (nnmairix-call-mairix-binary-raw 
-              (split-string nnmairix-mairix-command) 
-              (list (concat "m:" mid))))
-       (if (zerop rval)
-           ;; determine original group(s) from filename
-           (save-excursion
-             (set-buffer nnmairix-mairix-output-buffer)
-             (goto-char (point-min))
-             (while (looking-at "/")
-               (push (nnmairix-determine-original-group)
-                     allgroups)
-               (forward-line 1))
-             (if (> (length allgroups) 1)
-                 (setq group 
-                       (completing-read 
-                        "Message exists in more than one group. Choose: " 
-                        allgroups nil t))
-               (setq group (car allgroups))))
-         (error "Mairix could not find original article. See buffer %s for details" 
-                nnmairix-mairix-output-buffer))))
-    (if group
-       ;; show article in summary buffer
-       (nnmairix-show-original-article group mid)
-      (message "Couldn't find original article"))))
-
-(defun nnmairix-determine-original-group ()
-  "Try to determine to original group from the file path."
-  (let (path filename serverbase group maildirflag allgroups)
-    (re-search-forward "^\\(.*\\)/\\(.*?\\)$")
-    (setq path (expand-file-name (match-string 1)))
-    (setq filename (match-string 2))
-    ;; when we deal with maildir, remove cur/new/tmp from path
-    (setq maildirflag (string-match ".+\\..+\\..+" filename))
-    (when maildirflag
-      (setq path
-           (replace-regexp-in-string 
-            ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
-    ;; we first check nnml and nnmaildir servers
-    (setq 
-     group
-     (catch 'found
-       (dolist (cur gnus-opened-servers)
-        (when (or (and (not maildirflag)
-                       (eq (caar cur) 'nnml))
-                  (and maildirflag
-                       (eq (caar cur) 'nnmaildir)))
-          ;; get base path from server
-          (if maildirflag 
-              (setq serverbase (cadr (assoc 'directory (car cur))))               
-            (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
-            (when (not serverbase)
-              (setq serverbase nnml-directory)))
-          (setq serverbase (file-name-as-directory 
-                            (expand-file-name serverbase)))
-          (when (string-match (concat serverbase "\\(.*\\)") path)
-            ;; looks good - rest of the path should be the group
-            (setq group (match-string 1 path))
-            (when (string-match "/$" group)
-              (setq group (replace-match "" t t group)))
-            (when (not maildirflag)
-              ;; for nnml: convert slashes to dots
-              (while (string-match "/" group)
-                (setq group (replace-match "." t t group))))
-            (setq group (gnus-group-prefixed-name group (car cur)))
-            ;; check whether this group actually exists
-            (when (gnus-group-entry group)
-              (throw 'found group)))))))
-    (unless group
-      ;; we haven't found it yet --> look for nnimap groups
-      ;; assume last element of the path is the group
-      (string-match "^.*/\\.?\\(.*\\)$" path)
-      (setq group (match-string 1 path))
-      ;; convert dots to slashes (nested group)
-      (while (string-match "\\." group)
-       (setq group (replace-match "/" t t group)))
-      (dolist (cur gnus-opened-servers)
-       (when (eq (caar cur) 'nnimap)
-         (when (gnus-group-entry 
-                (gnus-group-prefixed-name group (car cur)))
-           (push 
-            (gnus-group-prefixed-name group (car cur))
-            allgroups))))
-      (if (> (length allgroups) 1)
-         (setq group (completing-read 
-                      "Group %s exists on more than one IMAP server. Choose: " 
-                      allgroups nil t))
-       (setq group (car allgroups))))
-    group))
-
+(defun nnmairix-group-delete-recreate-this-group ()
+  "Deletes and recreates group on the back end.
+You can use this function on nnmairix groups which continously
+show wrong article counts."
+  (interactive)
+  (let* ((group (gnus-group-group-name))
+        (method (gnus-find-method-for-group group)))
+    (unless (eq (car method) 'nnmairix)
+      (error "This is not a nnmairix group"))
+    (when (y-or-n-p
+          (format "Really recreate group %s on the back end? " group))
+      (nnmairix-delete-recreate-group group)
+      (gnus-group-get-new-news-this-group))))
+
+(defun nnmairix-propagate-marks (&optional server)
+  "Propagate marks from nnmairix group to original articles.
+Unless SERVER is explicitly specified, will use the last opened
+nnmairix server. Only marks from current session will be set."
+  (interactive)
+  (if server
+      (nnmairix-open-server server)
+    (unless (eq (car gnus-current-select-method) 'nnmairix)
+      (if nnmairix-current-server
+         (nnmairix-open-server nnmairix-current-server)
+       (error "No opened nnmairix server"))))
+  (if nnmairix-marks-cache
+      (let (number ogroup number-cache method mid-marks temp)
+       ;; first we get the article numbers
+       (catch 'problem
+         (while (setq ogroup (pop nnmairix-marks-cache))
+           (while (setq mid-marks (pop (cdr ogroup)))
+             (setq number
+                   (cdr
+                    (gnus-request-head (car mid-marks) (car ogroup))))
+             (unless number
+               (nnheader-message
+                3 "Unable to set mark: couldn't determine article number for %s in %s"
+                (car mid-marks) (car ogroup))
+               (throw 'problem nil))
+             (setq temp (assoc (car ogroup) number-cache))
+             (if temp
+                 (catch 'done
+                   (dolist (cur (cdr temp))
+                     (when (equal (cdr cur) (list (nth 1 mid-marks) (nth 2 mid-marks)))
+                       (nconc (car cur) (list number))
+                       (throw 'done nil)))
+                   (nconc temp (list (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))))
+               (push (list (car ogroup) (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))
+                     number-cache)))))
+       ;; now we set the marks
+       (save-excursion
+         (set-buffer gnus-group-buffer)
+         (nnheader-message 5 "nnmairix: Propagating marks...")
+         (dolist (cur number-cache)
+           (setq method (gnus-find-method-for-group (car cur)))
+           (apply (intern (format "%s-%s"
+                                  (symbol-name (car method))
+                                  "request-set-mark"))
+                  (gnus-group-short-name (car cur))
+                  (cdr cur)
+                  (list (nth 1 method)))
+           (gnus-group-jump-to-group (car cur))
+           (gnus-group-get-new-news-this-group)))
+       (nnheader-message 5 "nnmairix: Propagating marks... done"))
+    (nnheader-message 3 "No marks to propagate.")))
+
+(defun nnmairix-update-groups (servername &optional skipdefault updatedb)
+  "Update all search groups on SERVERNAME.
+If SKIPDEFAULT is t, the default search group will not be
+updated.
+If UPDATEDB is t, database for SERVERNAME will be updated first."
+  (interactive (list (completing-read "Update groups on server: "
+                               (nnmairix-get-nnmairix-servers))))
+  (save-excursion
+    (when (string-match ".*:\\(.*\\)" servername)
+      (setq servername (match-string 1 servername)))
+    (if (not (assoc (format "nnmairix:%s" servername)
+                   (nnmairix-get-nnmairix-servers)))
+       (nnheader-message 3 "Server %s not opened" servername)
+      (when updatedb
+       (let ((nnmairix-mairix-synchronous-update t))
+         (nnmairix-update-database
+          (list (list (format "nnmairix:%s" servername))))))
+      (let ((groups (nnmairix-get-groups-from-server servername))
+           default)
+       (when skipdefault
+         (setq default
+               (format "nnmairix+%s:%s"
+                       servername
+                       (cadr
+                        (assoc 'nnmairix-default-group
+                               (gnus-server-to-method
+                                (format "nnmairix:%s" servername)))))))
+       (dolist (cur groups)
+         (unless (and skipdefault
+                      (string= (car cur) default))
+           (gnus-group-jump-to-group (car cur))
+           (gnus-group-mark-group 1)))
+       (gnus-group-get-new-news-this-group)))))
+
+(defun nnmairix-remove-tick-mark-original-article ()
+  "Remove tick mark from original article.
+Marks propagation has to be enabled for this to work."
+  (interactive)
+  (unless (eq (car gnus-current-select-method) 'nnmairix)
+    (error "Not in a nnmairix group"))
+  (save-excursion
+    (let ((mid (mail-header-message-id (gnus-summary-article-header)))
+         groups cur)
+      (when mid
+       (setq groups (nnmairix-determine-original-group-from-registry mid))
+       (unless (or groups
+                   nnmairix-only-use-registry)
+         (setq groups
+               (nnmairix-determine-original-group-from-path mid nnmairix-current-server)))
+       (unless groups
+         (error "Couldn't find original article"))
+       (dolist (cur groups)
+         (push `(,cur (,mid del (tick))) nnmairix-marks-cache))
+       (nnheader-message 5 "Will remove tick mark for %s upon closing." mid)))))
 
 ;;; ==== Helper functions
 
 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
-  "Request FOLDER on backend for nnmairix QUALGROUP and article number correction."
+  "Request FOLDER on back end for nnmairix QUALGROUP and article number correction."
   (save-excursion
-    (nnmairix-call-backend
-     "request-group" folder nnmairix-backend-server fast)
+    (nnmairix-call-backend "request-group" folder nnmairix-backend-server)
     (set-buffer nnmairix-mairix-output-buffer)
     (goto-char (point-min))
     (re-search-forward "^Matched.*messages")
@@ -1006,15 +1260,16 @@ search in raw mode."
                (gnus-group-set-parameter
                 qualgroup 'numcorr (list nil 0 high))))
            (erase-buffer)
-           (insert (format "%d %d %d %d %s" status total low high group))
+           (insert (format "%d %d %d %d %s" status total low high
+                           (gnus-group-real-name qualgroup)))
            t)
        (progn
          (nnheader-report
           'nnmairix "Error calling back end on group %s" folder)
          nil)))))
 
-(defun nnmairix-call-mairix-binary (command folder query threads)
-  "Call mairix binary with COMMAND, using FOLDER and QUERY.
+(defun nnmairix-call-mairix-binary (command folder searchquery threads)
+  "Call mairix binary with COMMAND, using FOLDER and SEARCHQUERY.
 If THREADS is non-nil, enable full threads."
   (let ((args (cons (car command) '(nil t nil))))
     (save-excursion
@@ -1023,10 +1278,15 @@ If THREADS is non-nil, enable full threads."
       (erase-buffer)
       (when (> (length command) 1)
        (setq args (append args (cdr command))))
+      (when nnmairix-mairix-search-options
+       (setq args (append args nnmairix-mairix-search-options)))
+      ;; If we have a patched mairix binary, call it with "-c"
+      (when (nnmairix-check-mairix-version "maildirpatch")
+       (setq args (append args '("-c"))))
       (when threads
        (setq args (append args '("-t"))))
       (apply 'call-process
-            (append args (list "-o" folder) query)))))
+            (append args (list "-o" folder) searchquery)))))
 
 (defun nnmairix-call-mairix-binary-raw (command query)
   "Call mairix binary with COMMAND and QUERY in raw mode."
@@ -1075,9 +1335,8 @@ If ALL is t, return also the unopened/failed ones."
        (push (list server) openedserver)))
     openedserver))
 
-
 (defun nnmairix-get-valid-servers ()
-  "Return list of valid backend servers for nnmairix groups."
+  "Return list of valid back end servers for nnmairix groups."
   (let ((alist gnus-opened-servers)
        (mairixservers (nnmairix-get-nnmairix-servers t))
        server mserver openedserver occ cur)
@@ -1112,6 +1371,16 @@ If ALL is t, return also the unopened/failed ones."
         openedserver)))
     openedserver))
 
+(defun nnmairix-get-groups-from-server (servername)
+  "Return all groups for nnmairix server SERVERNAME."
+  (let ((searchstring (format "nnmairix\\+%s:" servername))
+       groups)
+    (dolist (cur gnus-newsrc-alist)
+      (when (string-match searchstring
+                         (car cur))
+       (push (list (car cur)) groups)))
+    groups))
+
 (defun nnmairix-call-backend (func &rest args)
   "Call a function FUNC on backend with ARGS."
   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
@@ -1167,25 +1436,24 @@ MAIRIXGROUP.  NUMC contains values for article number correction."
       (set-buffer nntp-server-buffer)
       (goto-char (point-min))
       (nnheader-message 7 "nnmairix: Rewriting headers...")
-      (mapcar
-       (function
-       (lambda (article)
-         (when (or (looking-at (number-to-string article))
-                   (nnheader-find-nov-line article))
-           (setq cur (nnheader-parse-nov))
-           (when corr
-                 (setq article (+ (mail-header-number cur) numc))
-                 (mail-header-set-number cur article))
-           (setq xref (mail-header-xref cur))
-           (when (and (stringp xref)
-                      (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
-             (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
-             (mail-header-set-xref cur xref))
-           (set-buffer buf)
-           (nnheader-insert-nov cur)
-           (set-buffer nntp-server-buffer)
-           (when (not (eobp))
-             (forward-line 1)))))
+      (mapc
+       (lambda (article)
+         (when (or (looking-at (number-to-string article))
+                   (nnheader-find-nov-line article))
+           (setq cur (nnheader-parse-nov))
+           (when corr
+             (setq article (+ (mail-header-number cur) numc))
+             (mail-header-set-number cur article))
+           (setq xref (mail-header-xref cur))
+           (when (and (stringp xref)
+                      (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
+             (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
+             (mail-header-set-xref cur xref))
+           (set-buffer buf)
+           (nnheader-insert-nov cur)
+           (set-buffer nntp-server-buffer)
+           (when (not (eobp))
+             (forward-line 1))))
        articles)
       (nnheader-message 7 "nnmairix: Rewriting headers... done")
       (kill-buffer nntp-server-buffer)
@@ -1240,43 +1508,50 @@ group."
       ;; If there is just one (or none) nnmairix server:
       (gnus-server-to-method (caar allservers)))))
 
+
+(defun nnmairix-delete-recreate-group (group)
+  "Delete and recreate folder from GROUP on the back end."
+  (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
+    (let ((folder (gnus-group-get-parameter group 'folder)))
+      (if (string-match nnmairix-group-regexp folder)
+         (progn
+           (nnmairix-call-backend "open-server"
+                                  nnmairix-backend-server)
+           (nnmairix-call-backend "request-delete-group"
+                                  folder t nnmairix-backend-server)
+           (nnmairix-call-backend "request-create-group"
+                                  folder nnmairix-backend-server))
+       (error "`nnmairix-delete-recreate-group' called on \
+non-mairix group.  Check folder parameter")))))
+
 (defun nnmairix-update-and-clear-marks (group &optional method)
   "Update group and clear all marks from GROUP using METHOD."
-  (when method
-    (setq group (gnus-group-prefixed-name group method)))
   (let ((method (or method
                    (gnus-find-method-for-group group)))
-       (folder (gnus-group-get-parameter group 'folder))
        (corr (gnus-group-get-parameter group 'numcorr t))
        info)
+    (unless (or (gnus-group-prefixed-p group)
+               (not method))
+      (setq group (gnus-group-prefixed-name group method)))
     (if (eq (nth 0 method) 'nnmairix)
        (save-excursion
          (nnmairix-open-server (nth 1 method))
          (set-buffer gnus-group-buffer)
+         ;; (gnus-group-set-parameter group 'propmarks nil)
          (setq info (gnus-get-info group))
          ;; Clear active and info
          (gnus-set-active group nil)
          (gnus-info-clear-data info)
          ;; Delete and re-create group if needed
+         (nnmairix-delete-recreate-group group)
+         ;; set flag that group has changed for article number correction
          (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
-           (if (string-match nnmairix-group-regexp folder)
-               (progn
-                 (nnmairix-call-backend "open-server"
-                                        nnmairix-backend-server)
-                 (nnmairix-call-backend "request-delete-group"
-                                        folder t nnmairix-backend-server)
-                 (nnmairix-call-backend "request-create-group"
-                                        folder nnmairix-backend-server)
-                 ;; set flag that group has changed for article number correction
-                 (when corr
-                   (setcar corr t)
-                   (gnus-group-set-parameter group 'numcorr corr)))
-             (error "Nnmairix-update-and-clear-marks - delete/create with\
- non-mairix group!! - check folder parameter")))
-         (when (gnus-group-jump-to-group group)
-           (gnus-group-get-new-news-this-group)))
-      (error "Nnmairix-update-and-clear-marks - Called with non-nnmairix group"))))
-  
+           (when corr
+             (setcar corr t)
+             (gnus-group-set-parameter group 'numcorr corr)))
+         (gnus-group-jump-to-group group)
+         (gnus-group-get-new-news-this-group))
+      (error "`nnmairix-update-and-clear-marks' called with non-nnmairix group"))))
 
 (defun nnmairix-sentinel-mairix-update-finished (proc status)
   "Sentinel for mairix update process PROC with STATUS."
@@ -1305,20 +1580,245 @@ See %s for details" proc nnmairix-mairix-output-buffer)))
       (setq header (replace-match "," t t header)))
   header))
 
+(defun nnmairix-group-toggle-parameter (group parameter description &optional par)
+  "Toggle on GROUP a certain PARAMETER.
+DESCRIPTION will be shown to the user with the activation
+status.  If PAR is a positive number, the group parameter will be
+set to t and to nil otherwise."
+  (let* ((method (gnus-find-method-for-group group))
+        (par (or par
+                 (not (gnus-group-get-parameter group parameter)))))
+    (if (eq (car method) 'nnmairix)
+       (progn
+         (when (numberp par)
+           (setq par (> par 0)))
+         (gnus-group-set-parameter group parameter par)
+         (if par
+             (message "%s activated for group %s" description group)
+           (message "%s deactivated for group %s" description group))
+         t)
+      (error "This is no nnmairix group")
+      nil)))
+
+;; Search for original article helper functions
+
+(defun nnmairix-goto-original-article (&optional no-registry)
+  "Jump to the original group and display article.
+The original group of the article is first determined with the
+registry (if enabled).  If the registry is not enabled or did not
+find the article or the prefix NO-REGISTRY is non-nil, this
+function will try to determine the original group form the path
+of the mail file.  The path is obtained through another mairix
+search in raw mode."
+  (interactive "P")
+  (when (not (eq (car gnus-current-select-method) 'nnmairix))
+    (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
+      (if (eq (car method) 'nnmairix)
+         (nnmairix-open-server (nth 1 method))
+       (error "Not in a nnmairix group"))))
+  (when (not (gnus-buffer-live-p gnus-article-buffer))
+    (error "No article buffer available"))
+  (let ((server (nth 1 gnus-current-select-method))
+       mid rval group allgroups)
+    ;; get message id
+    (save-excursion
+      (set-buffer gnus-article-buffer)
+      (gnus-summary-toggle-header 1)
+      (setq mid (message-fetch-field "Message-ID"))
+      ;; first check the registry (if available)
+      (unless no-registry
+       (setq allgroups (nnmairix-determine-original-group-from-registry mid)))
+      (unless (or allgroups
+                 nnmairix-only-use-registry)
+       ;; registry was not available or did not find article
+       ;; so we search again with mairix in raw mode to get filename
+       (setq allgroups
+             (nnmairix-determine-original-group-from-path mid server))
+       ;; if available and allowed, add this entry to the registry
+       (when (and (not no-registry)
+                  (boundp 'gnus-registry-install)
+                  gnus-registry-install)
+         (dolist (cur allgroups)
+           (unless (gnus-parameter-registry-ignore cur)
+             (gnus-registry-add-group mid cur)))))
+      (if (> (length allgroups) 1)
+         (setq group
+               (completing-read
+                "Message exists in more than one group. Choose: "
+                allgroups nil t))
+       (setq group (car allgroups))))
+    (if group
+       ;; show article in summary buffer
+       (nnmairix-show-original-article group mid)
+      (nnheader-message 3 "Couldn't find original article"))))
+
+(defun nnmairix-determine-original-group-from-registry (mid)
+  "Try to determinale original group for message-id MID from the registry."
+  (when (and (boundp 'gnus-registry-install)
+            gnus-registry-install)
+    (unless (string-match "^<" mid)
+      (set mid (concat "<" mid)))
+    (unless (string-match ">$" mid)
+      (set mid (concat mid ">")))
+    (gnus-registry-fetch-groups mid)))
+
+(defun nnmairix-determine-original-group-from-path (mid server)
+  "Determine original group(s) for message-id MID from the file path.
+The file path is obtained through a mairix search for the id on
+SERVER."
+  (nnmairix-open-server server)
+  (while (string-match "[<>]" mid)
+    (setq mid (replace-match "" t t mid)))
+  ;; mairix somehow does not like '$' in message-id
+  (when (string-match "\\$" mid)
+    (setq mid (concat mid "=")))
+  (while (string-match "\\$" mid)
+    (setq mid (replace-match "=," t t mid)))
+  (let (allgroups)
+    (if (zerop (nnmairix-call-mairix-binary-raw
+               (split-string nnmairix-mairix-command)
+               (list (concat "m:" mid))))
+       (save-excursion
+         (set-buffer nnmairix-mairix-output-buffer)
+         (goto-char (point-min))
+         (while (re-search-forward "^/.*$" nil t)
+           (push (nnmairix-get-group-from-file-path (match-string 0))
+                 allgroups)
+           (forward-line 1)))
+      (error "Mairix could not find original article.  See buffer %s for details"
+            nnmairix-mairix-output-buffer))
+    allgroups))
+
+(defun nnmairix-get-group-from-file-path (file)
+  "Get group by parsing the message location FILE."
+  (let (path filename serverbase group maildirflag allgroups)
+    (string-match "^\\(.*\\)/\\(.*?\\)$" file)
+    (setq path (expand-file-name (match-string 1 file)))
+    (setq filename (match-string 2 file))
+    ;; when we deal with maildir, remove cur/new/tmp from path
+    (setq maildirflag (string-match ".+\\..+\\..+" filename))
+    (when maildirflag
+      (setq path
+           (replace-regexp-in-string
+            ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
+    ;; we first check nnml and nnmaildir servers
+    (setq
+     group
+     (catch 'found
+       (dolist (cur gnus-opened-servers)
+        (when (or (and (not maildirflag)
+                       (eq (caar cur) 'nnml))
+                  (and maildirflag
+                       (eq (caar cur) 'nnmaildir)))
+          ;; get base path from server
+          (if maildirflag
+              (setq serverbase (cadr (assoc 'directory (car cur))))
+            (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
+            (unless serverbase
+              (setq serverbase nnml-directory)))
+          (setq serverbase (file-name-as-directory
+                            (expand-file-name serverbase)))
+          (when (string-match (concat serverbase "\\(.*\\)") path)
+            ;; looks good - rest of the path should be the group
+            (setq group (match-string 1 path))
+            (when (string-match "/$" group)
+              (setq group (replace-match "" t t group)))
+            (unless maildirflag
+              ;; for nnml: convert slashes to dots
+              (while (string-match "/" group)
+                (setq group (replace-match "." t t group))))
+            (setq group (gnus-group-prefixed-name group (car cur)))
+            ;; check whether this group actually exists
+            (when (gnus-group-entry group)
+              (throw 'found group)))))))
+    (unless group
+      ;; we haven't found it yet --> look for nnimap groups. Assume
+      ;; last element of the path is the group. This might fail since
+      ;; IMAP servers may present groups to the client in arbitrary
+      ;; ways...
+      (string-match "^.*/\\.?\\(.*\\)$" path)
+      (setq group (match-string 1 path))
+      ;; convert dots to slashes (nested group)
+      (while (string-match "\\." group)
+       (setq group (replace-match "/" t t group)))
+      (dolist (cur gnus-opened-servers)
+       (when (eq (caar cur) 'nnimap)
+         (when (gnus-group-entry
+                (gnus-group-prefixed-name group (car cur)))
+           (push
+            (gnus-group-prefixed-name group (car cur))
+            allgroups))))
+      (if (> (length allgroups) 1)
+         (setq group (completing-read
+                      "Group %s exists on more than one IMAP server. Choose: "
+                      allgroups nil t))
+       (setq group (car allgroups))))
+    group))
+
 (defun nnmairix-show-original-article (group mid)
   "Switch to GROUP and display Article with message-id MID."
+  (unless (string-match "^<" mid)
+    (set mid (concat "<" mid)))
+  (unless (string-match ">$" mid)
+    (set mid (concat mid ">")))
   (when (string-match "Summary" (buffer-name (current-buffer)))
     (gnus-summary-exit))
   (pop-to-buffer gnus-group-buffer)
   (gnus-group-jump-to-group group)
-  (gnus-summary-read-group group 1 t)  
+  (gnus-summary-read-group group 1 t)
   (gnus-summary-refer-article mid)
-  (gnus-summary-limit-to-headers (format "message-id: <%s>" mid))
+  (gnus-summary-limit-to-headers (format "message-id: %s" mid))
   (gnus-summary-select-article)
   ;; Force redisplay
   (gnus-summary-show-article)
   (nnheader-message 5 "Switched to group %s." group))
 
+(defun nnmairix-map-range (func range)
+  "Map function FUNC on all members of RANGE."
+  (cond
+   ((numberp range)
+    (funcall func range))
+   (t
+    (mapcar (lambda (cur)
+             (cond
+              ((listp cur)
+               (cons
+                (funcall func (car cur))
+                (funcall func (cdr cur))))
+              ((numberp cur)
+               (funcall func cur))))
+           range))))
+
+(defun nnmairix-check-mairix-version (version &optional server)
+  "Check mairix VERSION on SERVER.
+If VERSION is a number: specifies the minimum version.
+If VERSION is a string: must be contained in mairix version output."
+  (unless server
+    (setq server nnmairix-current-server))
+  (let ((versionstring (cadr (assoc server nnmairix-version-output))))
+    (unless versionstring
+      ;; call "mairix -V" to get the version string
+      (with-temp-buffer
+       (setq versionstring
+             (let* ((commandsplit (split-string nnmairix-mairix-command))
+                    (args (append (list (car commandsplit))
+                                 `(nil t nil) (cdr commandsplit) '("-V"))))
+             (apply 'call-process args)
+             (goto-char (point-min))
+             (re-search-forward "mairix.*")
+             (match-string 0))))
+      ;; save version string for current session
+      (setq nnmairix-version-output
+           (append nnmairix-version-output
+                   (list (list server versionstring)))))
+    (cond
+     ((stringp version)
+      (string-match version versionstring))
+     ((numberp version)
+      (<= version (string-to-number
+                  (progn
+                    (string-match "mairix \\([0-9\\.]+\\)" versionstring)
+                    (match-string 1 versionstring))))))))
 
 ;; ==== Widget stuff
 
@@ -1331,7 +1831,6 @@ See %s for details" proc nnmairix-mairix-output-buffer)))
   (nnmairix-widget-search
    (nnmairix-widget-get-values)))
 
-
 (defun nnmairix-widget-get-values ()
   "Create values for editable fields from current article."
   (if (not (gnus-buffer-live-p gnus-article-buffer))
@@ -1342,13 +1841,13 @@ See %s for details" proc nnmairix-mairix-output-buffer)))
       (mapcar
        (function
        (lambda (field)
-         (list (caddr field)
+         (list (car (cddr field))
                (if (car field)
                    (nnmairix-replace-illegal-chars
                     (gnus-fetch-field (car field)))
                  nil))))
        nnmairix-widget-fields-list))))
-  
+
 
 (defun nnmairix-widget-search (&optional mvalues)
   "Create mairix query interactively using graphical widgets.
@@ -1426,7 +1925,7 @@ If WITHVALUES is t, query is based on current article."
     (dolist (cur nnmairix-widget-fields-list)
       ;; See if checkbox is checked
       (when (widget-value
-            (cadr (assoc (concat "c" (caddr cur)) widgets)))
+            (cadr (assoc (concat "c" (car (cddr cur))) widgets)))
        ;; create query for the field
        (push
         (concat
@@ -1434,7 +1933,7 @@ If WITHVALUES is t, query is based on current article."
          ":"
          (nnmairix-replace-illegal-chars
           (widget-value
-          (cadr (assoc (concat "e" (caddr cur)) widgets)))))
+          (cadr (assoc (concat "e" (car (cddr cur))) widgets)))))
         query)))
     ;; Flags
     (when (member 'flags nnmairix-widget-other)
@@ -1489,7 +1988,6 @@ Fill in VALUES if based on an article."
       (nnmairix-widget-add "Threads" 'checkbox nil))
       (widget-insert " Show full threads\n\n")))
 
-
 (defun nnmairix-widget-build-editable-fields (values)
   "Build editable field widgets in `nnmairix-widget-fields-list'.
 VALUES may contain values for editable fields from current article."
@@ -1498,7 +1996,7 @@ VALUES may contain values for editable fields from current article."
     (mapc
      (function
       (lambda (field)
-       (setq field (caddr field))
+       (setq field (car (cddr field)))
        (setq ret
              (nconc
               (list
@@ -1533,7 +2031,7 @@ VALUES may contain values for editable fields from current article."
    nnmairix-widgets))
 
 (defun nnmairix-widget-toggle-activate (widget)
-  "Toggle activation status of WIDGET dependent on corresponding checkbox value."
+  "Toggle activation status of WIDGET depending on corresponding checkbox value."
   (let ((field (widget-get widget :tag)))
     (if (widget-value widget)
        (widget-apply