(gnus-group-completing-read): Remove all newlines from group names. They mess up...
[gnus] / lisp / nnmairix.el
1 ;;; nnmairix.el --- Mairix back end for Gnus, the Emacs newsreader
2
3 ;; Copyright (C) 2007, 2008, 2009, 2010  Free Software Foundation, Inc.
4
5 ;; Author: David Engster <dengste@eml.cc>
6 ;; Keywords: mail searching
7 ;; Version: 0.6
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This is a back end for using the mairix search engine with
27 ;; Gnus.  Mairix is a tool for searching words in locally stored
28 ;; mail.  Mairix is very fast which allows using it efficiently for
29 ;; "smart folders", e.g. folders which are associated with search
30 ;; queries.  Of course, you can also use this back end just for
31 ;; calling mairix with some search query.
32 ;;
33 ;; Mairix is written by Richard Curnow.  More information can be found at
34 ;; http://www.rpcurnow.force9.co.uk/mairix/
35
36 ;; Commentary on the code: nnmairix sits between Gnus and the "real"
37 ;; back end which handles the mail (currently nnml, nnimap and
38 ;; nnmaildir were tested). I know this is all a bit hacky, but so far
39 ;; it works for me.  This is the first back end I've written for Gnus,
40 ;; so I'd appreciate any comments, suggestions, bug reports (and, of
41 ;; course, patches) for improving nnmairix.
42
43 ;; nnmairix does not use an active file, since I wanted to contain the
44 ;; back end "inside Gnus" as much as possible without the need of an
45 ;; external file.  It stores the query/folder information in the group
46 ;; parameters instead.  This also implies that once you kill a mairix
47 ;; group, it's gone for good.  I don't think that this is really
48 ;; problematic, since I don't see the need in unsubscribing and
49 ;; re-subscribing search groups
50
51 ;; Every mairix server is "responsible" for one mairix installation,
52 ;; i.e. you can have several mairix servers for different mairix
53 ;; configurations.  Not that I think anyone will actually do this, but
54 ;; I thought it would be a "nice to have feature"...
55
56 ;; KNOWN BUGS:
57 ;; * Mairix does only support us-ascii characters.
58
59 ;; TODO/MISSING FEATURES:
60 ;; * Support of more back ends (nnmh, nnfolder, nnmbox...)?
61 ;; * Maybe use an active file instead of group parameters?
62 ;; * Maybe use "-a" when updating groups which are not newly created?
63
64 ;;; Changelog:
65 ;; 05/30/2008 - version 0.6
66 ;;
67 ;;    * It is now possible to propagate marks from the nnmairix groups
68 ;;      to the original messages (and for maildir also vice versa). See
69 ;;      the docs for details on this feature - it's pretty delicate
70 ;;      and currently needs a patched mairix binary to work smoothly.
71 ;;
72 ;;    * Keep messages in nnmairix groups always read/unread
73 ;;      (bound to 'G b r').
74 ;;
75 ;;    * Recreate back end folder for nnmairix groups in case you
76 ;;      somehow get wrong article counts (bound to 'G b d').
77 ;;
78 ;;    * New group parameter 'allow-fast'. Toggling of parameter bound
79 ;;      to 'G b a'. The default is nil, meaning that the group will
80 ;;      always be updated with a mairix search, even when only entered.
81 ;;
82 ;;    * More/Better use of the registry (if available). Can now also
83 ;;      deal with duplicate messages in different groups.
84 ;;
85 ;; 02/06/2008 - version 0.5
86 ;;
87 ;;    * New function: nnmairix-goto-original-article. Uses the
88 ;;      registry or the mail file path for determining original group.
89 ;;
90 ;;    * Deal with empty Xref header
91 ;;
92 ;;    * Changed summary mode keybindings since the old ones were
93 ;;      already taken
94 ;;
95 ;;   (Thanks to Tassilo Horn and Ted Zlatanov for their help)
96 ;;
97 ;; 01/07/2008 - version 0.4
98 ;;
99 ;;    * New/fixed doc strings and code cleanup.
100 ;;
101 ;; 11/18/2007 - version 0.3
102 ;;
103 ;;    * Fixed bugs when dealing with nnml and native servers
104 ;;
105 ;;    * Make variables customizable
106 ;;
107 ;; 10/10/2007 - version 0.2
108 ;;
109 ;;    * Use nnml-directory/directory server variables for nnml and
110 ;;    nnmaildir back ends as path for search folders. This way it
111 ;;    becomes independent of 'base' setting in .mairixirc (but not for
112 ;;    nnimap).
113 ;;
114 ;;    * As a result: Changed nnmairix-backend-to-server so that user
115 ;;    is asked when more than one nnmairix server exists and we do not
116 ;;    know which one is responsible for current back end.
117 ;;
118 ;;    * Rename files when using nnml back ends so that there are no
119 ;;    holes in article numbers. This should fix all problems regarding
120 ;;    wrong article counts with nnml.
121 ;;
122 ;;    * More commands for creating queries (using widgets or the
123 ;;    minibuffer).
124 ;;
125 ;;    * Fixed bug in nnmairix-create-search-group-from-message
126 ;;
127 ;;    * Changed copyright to FSF
128 ;;
129 ;;      (Thanks to Georg C. F. Greve and Bastien for suggestions and
130 ;;      ideas!)
131 ;;
132 ;; 10/03/2007 - version 0.1 - first release
133
134
135 ;;; Code:
136
137 (eval-when-compile (require 'cl))       ;For (pop (cdr ogroup)).
138
139 (require 'nnoo)
140 (require 'gnus-group)
141 (require 'gnus-sum)
142 (require 'message)
143 (require 'nnml)
144 (require 'widget)
145
146 (nnoo-declare nnmairix)
147
148 ;;; === Keymaps
149
150 (eval-when-compile
151   (when (featurep 'xemacs)
152     ;; The `kbd' macro requires that the `read-kbd-macro' macro is available.
153     (require 'edmacro)))
154
155 ;; Group mode
156 (defun nnmairix-group-mode-hook ()
157   "Nnmairix group mode keymap."
158   (define-key gnus-group-mode-map
159     (kbd "G b") (make-sparse-keymap))
160   (define-key gnus-group-mode-map
161     (kbd "G b g") 'nnmairix-create-search-group)
162   (define-key gnus-group-mode-map
163     (kbd "G b c") 'nnmairix-create-server-and-default-group)
164   (define-key gnus-group-mode-map
165     (kbd "G b q") 'nnmairix-group-change-query-this-group)
166   (define-key gnus-group-mode-map
167     (kbd "G b t") 'nnmairix-group-toggle-threads-this-group)
168   (define-key gnus-group-mode-map
169     (kbd "G b u") 'nnmairix-update-database)
170   (define-key gnus-group-mode-map
171     (kbd "G b s") 'nnmairix-search)
172   (define-key gnus-group-mode-map
173     (kbd "G b i") 'nnmairix-search-interactive)
174   (define-key gnus-group-mode-map
175     (kbd "G b m") 'nnmairix-widget-search)
176   (define-key gnus-group-mode-map
177     (kbd "G b p") 'nnmairix-group-toggle-propmarks-this-group)
178   (define-key gnus-group-mode-map
179     (kbd "G b r") 'nnmairix-group-toggle-readmarks-this-group)
180   (define-key gnus-group-mode-map
181     (kbd "G b d") 'nnmairix-group-delete-recreate-this-group)
182   (define-key gnus-group-mode-map
183     (kbd "G b a") 'nnmairix-group-toggle-allowfast-this-group)
184   (define-key gnus-group-mode-map
185     (kbd "G b o") 'nnmairix-propagate-marks))
186
187 ;; Summary mode
188 (defun nnmairix-summary-mode-hook ()
189   "Nnmairix summary mode keymap."
190   (define-key gnus-summary-mode-map
191     (kbd "G G t") 'nnmairix-search-thread-this-article)
192   (define-key gnus-summary-mode-map
193     (kbd "G G f") 'nnmairix-search-from-this-article)
194   (define-key gnus-summary-mode-map
195     (kbd "G G m") 'nnmairix-widget-search-from-this-article)
196   (define-key gnus-summary-mode-map
197     (kbd "G G g") 'nnmairix-create-search-group-from-message)
198   (define-key gnus-summary-mode-map
199     (kbd "G G o") 'nnmairix-goto-original-article)
200   (define-key gnus-summary-mode-map
201     (kbd "G G u") 'nnmairix-remove-tick-mark-original-article))
202
203 (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
204 (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)
205
206 ;; ;;;###autoload
207 ;; (defun nnmairix-initalize (&optional force)
208 ;;   (interactive "P")
209 ;;   (if (not (or (file-readable-p "~/.mairixrc")
210 ;;             force))
211 ;;       (message "No file `~/.mairixrc', skipping nnmairix setup")
212 ;;     (add-hook 'gnus-group-mode-hook 'nnmairix-group-mode-hook)
213 ;;     (add-hook 'gnus-summary-mode-hook 'nnmairix-summary-mode-hook)))
214
215 ;; Customizable stuff
216
217 (defgroup nnmairix nil
218   "Back end for the Mairix mail search engine."
219   :group 'gnus)
220
221 (defcustom nnmairix-group-prefix "zz_mairix"
222   "Prefix for mairix search groups on back end server.
223 nnmairix will create these groups automatically on the back end
224 server for each nnmairix search group.  The name on the back end
225 server will be this prefix plus a random number.  You can delete
226 unused nnmairix groups on the back end using
227 `nnmairix-purge-old-groups'."
228   :version "23.1"
229   :type 'string
230   :group 'nnmairix)
231
232 (defcustom nnmairix-mairix-output-buffer "*mairix output*"
233   "Buffer used for mairix output."
234   :version "23.1"
235   :type 'string
236   :group 'nnmairix)
237
238 (defcustom nnmairix-customize-query-buffer "*mairix query*"
239   "Name of the buffer for customizing Mairix queries."
240   :version "23.1"
241   :type 'string
242   :group 'nnmairix)
243
244 (defcustom nnmairix-mairix-update-options '("-F" "-Q")
245   "Options when calling mairix for updating the database.
246 The default is '-F' and '-Q' for making updates faster.  You
247 should call mairix without these options from time to
248 time (e.g. via cron job)."
249   :version "23.1"
250   :type '(repeat string)
251   :group 'nnmairix)
252
253 (defcustom nnmairix-mairix-search-options '("-Q")
254   "Options when calling mairix for searching.
255 The default is '-Q' for making searching faster."
256   :version "23.1"
257   :type '(repeat string)
258   :group 'nnmairix)
259
260 (defcustom nnmairix-mairix-synchronous-update nil
261   "Set this to t if you want Emacs to wait for mairix updating the database."
262   :version "23.1"
263   :type 'boolean
264   :group 'nnmairix)
265
266 (defcustom nnmairix-rename-files-for-nnml t
267   "Rename nnml mail files so that they are consecutively numbered.
268 When using nnml as back end, mairix might produce holes in the
269 article numbers which will produce wrong article counts by
270 Gnus.  This option controls whether nnmairix should rename the
271 files consecutively."
272   :version "23.1"
273   :type 'boolean
274   :group 'nnmairix)
275
276 (defcustom nnmairix-widget-fields-list
277   '(("from" "f" "From") ("to" "t" "To") ("cc" "c" "Cc")
278     ("subject" "s" "Subject")  ("to" "tc" "To or Cc")
279     ("from" "a" "Address") (nil "b" "Body") (nil "n" "Attachment")
280     ("Message-ID" "m" "Message ID") (nil "s" "Size") (nil "d" "Date"))
281   "Fields that should be editable during interactive query customization.
282
283 Header, corresponding mairix command and description for editable
284 fields in interactive query customization.  The header specifies
285 which header contents should be inserted into the editable field
286 when creating a Mairix query based on the current message (can be
287 nil for disabling this)."
288   :version "23.1"
289   :type '(repeat (list
290                   (choice :tag "Field"
291                           (const :tag "none" nil)
292                           (const :tag "From" "from")
293                           (const :tag "To" "to")
294                           (const :tag "Cc" "cc")
295                           (const :tag "Subject" "subject")
296                           (const :tag "Message ID" "Message-ID"))
297                   (string :tag "Command")
298                   (string :tag "Description")))
299   :group 'nnmairix)
300
301 (defcustom nnmairix-widget-select-window-function
302   (lambda () (select-window (get-largest-window)))
303   "Function for selecting the window for customizing the mairix query.
304 The default chooses the largest window in the current frame."
305   :version "23.1"
306   :type 'function
307   :group 'nnmairix)
308
309 (defcustom nnmairix-propagate-marks-upon-close t
310   "Flag if marks should be propagated upon closing a group.
311 The default of this variable is t. If set to 'ask, the
312 user will be asked if the flags should be propagated when the
313 group is closed.  If set to nil, the user will have to manually
314 call 'nnmairix-propagate-marks'."
315   :version "23.1"
316   :type '(choice (const :tag "always" t)
317                  (const :tag "ask" 'ask)
318                  (const :tag "never" nil))
319   :group 'nnmairix)
320
321 (defcustom nnmairix-propagate-marks-to-nnmairix-groups nil
322   "Flag if marks from original articles should be seen in nnmairix groups.
323 The default is nil since it will only work if the articles are in
324 maildir format and NOT managed by the nnmaildir back end but
325 e.g. an IMAP server (which stores the marks in the maildir file
326 name).  You may safely set this to t for testing - the worst that
327 can happen are wrong marks in nnmairix groups."
328   :version "23.1"
329   :type 'boolean
330   :group 'nnmairix)
331
332 (defcustom nnmairix-only-use-registry nil
333   "Use only the registry for determining original group(s).
334 If set to t, nnmairix will only use the registry for determining
335 the original group(s) of an article (which is also necessary for
336 propapagting marks).  If set to nil, it will also try to determine
337 the group from an additional mairix search which might be slow
338 when propagating lots of marks."
339   :version "23.1"
340   :type 'boolean
341   :group 'nnmairix)
342
343 (defcustom nnmairix-allowfast-default nil
344   "Whether fast entering should be the default for nnmairix groups.
345 You may set this to t to make entering the group faster, but note that
346 this might lead to problems, especially when used with marks propagation."
347   :version "23.1"
348   :type 'boolean
349   :group 'nnmairix)
350
351 ;; ==== Other variables
352
353 (defvar nnmairix-widget-other
354   '(threads flags)
355   "Other editable mairix commands when using customization widgets.
356 Currently there are 'threads and 'flags.")
357
358 (defvar nnmairix-interactive-query-parameters
359   '((?f "from" "f" "From") (?t "to" "t" "To") (?c "to" "tc" "To or Cc")
360     (?a "from" "a" "Address") (?s "subject" "s" "Subject") (?b nil "b" "Body")
361     (?d nil "d" "Date") (?n nil "n" "Attachment"))
362   "Things that should be editable during interactive query generation.
363 Every list element consists of the following entries: Keystroke,
364 message field (if any), mairix command and description.")
365
366 (defvar nnmairix-delete-and-create-on-change '(nnimap nnmaildir nnml)
367   "Controls on which back ends groups should be deleted and re-created.
368 This variable is a list of back ends where the search group
369 should be completely deleted and re-created when the query or
370 thread parameter changes.  The default is to this for all
371 currently supported back ends.  It usually also corrects the
372 problem of \"holes\" in the article numbers which often lead to a
373 wrong count of total articles shown by Gnus.")
374
375 ;;; === Server variables
376
377 (defvoo nnmairix-backend  nil
378   "Back end where mairix stores its searches.")
379
380 (defvoo nnmairix-backend-server nil
381   "Name of the server where mairix stores its searches.")
382
383 (defvoo nnmairix-mairix-command "mairix"
384   "Command to call mairix for this nnmairix server.")
385
386 (defvoo nnmairix-hidden-folders nil
387   "Set this to t if the back end server uses hidden directories for
388 its maildir mail folders (e.g. the Dovecot IMAP server or mutt).")
389
390 (defvoo nnmairix-default-group nil
391   "Default search group. This is the group which is used for all
392 temporary searches, e.g. nnmairix-search.")
393
394 ;;; === Internal variables
395
396 (defconst nnmairix-group-regexp
397   (format "%s-\\(.*\\)-[0-9]+" nnmairix-group-prefix)
398   "Regexp for mairix groups on back end.")
399
400 (defconst nnmairix-valid-backends '(nnimap nnml nnmaildir)
401   "Back ends supported by nnmairix.
402 Other back ends might or might not work.")
403
404 (defvar nnmairix-last-server nil
405   "Last chosen server.")
406
407 (defvar nnmairix-current-server nil
408   "Current server.")
409
410 (defvar nnmairix-marks-cache nil
411   "Cache for marks which should be set upon closing current group.")
412
413 (defvar nnmairix-version-output nil
414   "Version string of mairix binary.")
415
416 ;;; === Gnus back end functions
417
418 (nnoo-define-basics nnmairix)
419
420 (gnus-declare-backend "nnmairix" 'mail 'address)
421
422 (deffoo nnmairix-open-server (server &optional definitions)
423   ;; just set server variables
424   (setq nnmairix-current-server server)
425   (nnoo-change-server 'nnmairix server definitions))
426
427 (deffoo nnmairix-request-group (group &optional server fast info)
428   ;; Call mairix and request group on back end server
429   (when server (nnmairix-open-server server))
430   (let* ((qualgroup (if server
431                         (gnus-group-prefixed-name group (list 'nnmairix server))
432                       group))
433          (folder (gnus-group-get-parameter qualgroup 'folder))
434          (allowfast (gnus-group-get-parameter qualgroup 'allow-fast))
435          (query (gnus-group-get-parameter qualgroup 'query t))
436          (threads (gnus-group-get-parameter qualgroup 'threads))
437          (backendmethod (gnus-server-to-method
438                          (format "%s:%s" (symbol-name nnmairix-backend)
439                                  nnmairix-backend-server)))
440          rval mfolder folderpath args)
441     (cond
442      ((not folder)
443       ;; No folder parameter -> error
444       (nnheader-report 'nnmairix "Check folder parameter for group %s" group)
445       nil)
446      ((not query)
447       ;; No query -> return empty group
448       (with-current-buffer nntp-server-buffer
449         (erase-buffer)
450         (insert (concat "211 0 1 0 " group))
451         t))
452      (t
453       ;; For maildir++ folders: create a hidden directory (prepend dot)
454       (setq mfolder (if (and nnmairix-hidden-folders
455                              (not (string-match "^\\." folder)))
456                         (concat "." folder)
457                       folder))
458       ;; For nnml and nnmaildir, precede mfolder with directory where mail
459       ;; is actually stored so that it's independent of 'base' setting
460       ;; in .mairixrc.
461       (when (eq nnmairix-backend 'nnml)
462         (setq folderpath (cadr (assoc 'nnml-directory backendmethod)))
463         ;; if nnml-directory is not explicitly set, use global value
464         (when (not folderpath)
465           (setq folderpath nnml-directory)))
466       (when (eq nnmairix-backend 'nnmaildir)
467         (setq folderpath
468               (cadr (assoc 'directory backendmethod))))
469       (when folderpath
470         (setq mfolder
471               (concat
472                (file-name-as-directory
473                 (expand-file-name
474                  folderpath))
475                mfolder)))
476       ;; If (not fast), call Mairix binary
477       ;; recreate underlying folder on the back end
478       (setq rval
479             (if (and fast allowfast)
480                 0
481               (nnmairix-call-mairix-binary
482                (split-string nnmairix-mairix-command)
483                mfolder query threads)))
484       ;; Check return value
485       (cond
486        ((zerop rval)                    ; call was succesful
487         (nnmairix-call-backend
488          "open-server" nnmairix-backend-server)
489         ;; If we're dealing with nnml, rename files
490         ;; consecutively and make new active file for this
491         ;; group
492         (when (eq nnmairix-backend 'nnml)
493           (when nnmairix-rename-files-for-nnml
494             (nnmairix-rename-files-consecutively mfolder))
495           (nnml-generate-nov-databases-directory mfolder nil t))
496         (nnmairix-call-backend
497          "request-scan" folder nnmairix-backend-server)
498         (if (and fast allowfast)
499             t
500           (nnmairix-request-group-with-article-number-correction
501            folder qualgroup)))
502        ((and (= rval 1)
503              (with-current-buffer nnmairix-mairix-output-buffer
504                (goto-char (point-min))
505                (looking-at "^Matched 0 messages")))
506         ;; No messages found -> return empty group
507         (nnheader-message 5 "Mairix: No matches found.")
508         (set-buffer nntp-server-buffer)
509         (erase-buffer)
510         (insert (concat "211 0 1 0 " group))
511         t)
512        ;; Everything else is an error
513        (t
514         (nnheader-report
515          'nnmairix "Error running marix. See buffer %s for details"
516          nnmairix-mairix-output-buffer)
517         nil))))))
518
519
520 (deffoo nnmairix-request-create-group (group &optional server args)
521   (let ((qualgroup (if server (gnus-group-prefixed-name group (list 'nnmairix server))
522                      group))
523         (exist t)
524         (count 0)
525         groupname info)
526     (when server (nnmairix-open-server server))
527     (gnus-group-add-parameter qualgroup '(query . nil))
528     (gnus-group-add-parameter qualgroup '(threads . nil))
529     (while exist
530       (setq count (1+ count))
531       (setq groupname (format "%s-%s-%s" nnmairix-group-prefix group
532                               (number-to-string count)))
533       (setq exist (nnmairix-call-backend
534                    "request-group" groupname nnmairix-backend-server)))
535     (nnmairix-call-backend
536      "request-create-group" groupname nnmairix-backend-server)
537     (gnus-group-add-parameter qualgroup '(folder . nil))
538     (when nnmairix-allowfast-default
539       (gnus-group-add-parameter qualgroup '(allow-fast . t)))
540     (gnus-group-set-parameter qualgroup 'folder groupname))
541   t)
542
543
544 (deffoo nnmairix-retrieve-headers (articles group &optional server fetch-old)
545   (when server (nnmairix-open-server server))
546   (let* ((folder (nnmairix-get-backend-folder group server))
547          (corr (nnmairix-get-numcorr group server))
548          (numcorr 0)
549          rval)
550     (when (and corr
551                (not (zerop (cadr corr)))
552                (numberp (car articles)))
553       (setq numcorr (cadr corr))
554       (setq articles
555             (mapcar
556              (lambda (arg) (- arg numcorr))
557              articles)))
558     (setq rval
559           (if (eq nnmairix-backend 'nnimap)
560               (let ((gnus-nov-is-evil t))
561                 (nnmairix-call-backend
562                  "retrieve-headers" articles folder nnmairix-backend-server fetch-old))
563             (nnmairix-call-backend
564              "retrieve-headers" articles folder nnmairix-backend-server fetch-old)))
565     (nnmairix-replace-group-and-numbers articles folder group numcorr rval)
566     rval))
567
568 (deffoo nnmairix-request-article (article &optional group server to-buffer)
569   (when server (nnmairix-open-server server))
570   (let ((folder (nnmairix-get-backend-folder group server))
571         (corr (nnmairix-get-numcorr group server)))
572     (when (and
573            (numberp article)
574            corr
575            (not (zerop (cadr corr))))
576       (setq article (- article (cadr corr))))
577     (nnmairix-call-backend
578      "request-article" article folder nnmairix-backend-server to-buffer))
579   t)
580
581 (deffoo nnmairix-request-list (&optional server)
582   (when server (nnmairix-open-server server))
583   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
584       (let (cpoint cur qualgroup folder)
585         (with-current-buffer nntp-server-buffer
586           (goto-char (point-min))
587           (setq cpoint (point))
588           (while (re-search-forward nnmairix-group-regexp (point-max) t)
589             (setq cur (match-string 1)
590                   qualgroup (gnus-group-prefixed-name cur
591                                                       (list 'nnmairix server)))
592             (if (and (gnus-group-entry qualgroup)
593                      (string= (match-string 0)
594                               (gnus-group-get-parameter qualgroup 'folder)))
595                 (progn
596                   (replace-match cur)
597                   (delete-region cpoint (point-at-bol))
598                   (forward-line)
599                   (setq cpoint (point)))
600               (forward-line)))
601           (delete-region cpoint (point-max)))
602         t)
603     nil))
604
605 ;; Silence byte-compiler.
606 (defvar gnus-registry-install)
607 (autoload 'gnus-registry-fetch-group "gnus-registry")
608 (autoload 'gnus-registry-fetch-groups "gnus-registry")
609 (autoload 'gnus-registry-add-group "gnus-registry")
610
611 (deffoo nnmairix-request-set-mark (group actions &optional server)
612   (when server
613     (nnmairix-open-server server))
614   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
615          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
616          (propto (gnus-group-get-parameter qualgroup 'propto t))
617          (corr (nnmairix-get-numcorr group server))
618          (folder (nnmairix-get-backend-folder group server)))
619     (save-excursion
620       (dolist (cur actions)
621         (let ((type (nth 1 cur))
622               (cmdmarks (nth 2 cur))
623               (range (gnus-uncompress-range (nth 0 cur)))
624               mid ogroup number method temp)
625           (when (and corr
626                      (not (zerop (cadr corr))))
627             (setq range (mapcar (lambda (arg)
628                                   (- arg (cadr corr)))
629                                 range)))
630           (when propmarks
631             (nnheader-message 7 "nnmairix: Setting marks...")
632               (dolist (article range)
633                 ;; get article (header) and extract message id
634                 ;; we try to determine as many original articles as possible
635                 (catch 'problem
636                   (nnmairix-call-backend "open-server" nnmairix-backend-server)
637                   (unless (gnus-request-head
638                            article
639                            (gnus-group-prefixed-name
640                             folder
641                             (list nnmairix-backend nnmairix-backend-server)))
642                     (nnheader-message
643                      3 "Unable to set mark: couldn't fetch article header for article number %d"
644                      article)
645                     (throw 'problem nil))
646                   (set-buffer nntp-server-buffer)
647                   (goto-char (point-min))
648                   (let ((case-fold-search t))
649                     (re-search-forward "^message-id:.*\\(<.+>\\)" nil t))
650                   (setq mid (match-string 1))
651                   (unless mid
652                     (nnheader-message
653                      3 "Unable to set mark: article number %d has no message-id header"
654                      article)
655                     (throw 'problem nil))
656                   ;; get original group. First try registry, then file path
657                   (setq ogroup
658                         (nnmairix-determine-original-group-from-registry mid))
659                   (unless (or ogroup
660                               nnmairix-only-use-registry)
661                     (setq ogroup
662                           (nnmairix-determine-original-group-from-path
663                            mid nnmairix-current-server))
664                     ;; if available and allowed, add this entry to the registry
665                     (when (and (boundp 'gnus-registry-install)
666                                gnus-registry-install)
667                       (dolist (cur ogroup)
668                         (unless (gnus-parameter-registry-ignore cur)
669                           (gnus-registry-add-group mid cur)))))
670                   (unless ogroup
671                     (nnheader-message
672                      3 "Unable to set mark: couldn't find original group for %s" mid)
673                     (throw 'problem nil))
674                   ;; store original groups with mid's. We cannot get
675                   ;; the article number immediately since this would
676                   ;; generate problems with maildir (articles might
677                   ;; get moved from /new to /cur and further marks
678                   ;; could then not be set)
679                   (dolist (cur ogroup)
680                     (setq temp (assoc cur
681                                       nnmairix-marks-cache))
682                     (if temp
683                         (nconc temp (list (list mid type cmdmarks)))
684                       (push (list cur (list mid type cmdmarks))
685                             nnmairix-marks-cache)))))
686               (nnheader-message 7 "nnmairix: Setting marks... done")))))))
687
688 (deffoo nnmairix-close-group (group &optional server)
689   (when server
690     (nnmairix-open-server server))
691   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
692          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
693          method)
694     (when (and propmarks
695                nnmairix-marks-cache)
696       (when (or (eq nnmairix-propagate-marks-upon-close t)
697                 (and (eq nnmairix-propagate-marks-upon-close 'ask)
698                      (y-or-n-p "Propagate marks to original articles? ")))
699       (with-current-buffer gnus-group-buffer
700         (nnmairix-propagate-marks)
701         ;; update mairix group
702         (gnus-group-jump-to-group qualgroup)
703         (gnus-group-get-new-news-this-group))))))
704
705 (autoload 'nnimap-request-update-info-internal "nnimap")
706
707 (deffoo nnmairix-request-marks (group info &optional server)
708 ;; propagate info from underlying IMAP folder to nnmairix group
709 ;; This is currently experimental and must be explicitly activated
710 ;; with nnmairix-propagate-marks-to-nnmairix-group
711   (when server
712     (nnmairix-open-server server))
713   (let* ((qualgroup (gnus-group-prefixed-name
714                     group
715                     (list 'nnmairix nnmairix-current-server)))
716          (readmarks (gnus-group-get-parameter qualgroup 'readmarks))
717          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
718          (folder (nnmairix-get-backend-folder group server))
719          (corr (nnmairix-get-numcorr group server))
720          (docorr (and corr (not (zerop (cadr corr)))))
721          (folderinfo `(,group 1 ((1 . 1))))
722          readrange marks)
723       (when (and propmarks
724                  nnmairix-propagate-marks-to-nnmairix-groups)
725         ;; these groups are not subscribed, so we have to ask the back end directly
726         (if (eq nnmairix-backend 'nnimap)
727             (nnimap-request-update-info-internal folder folderinfo nnmairix-backend-server)
728           (nnmairix-call-backend "request-update-info" folder folderinfo nnmairix-backend-server))
729         ;; set range of read articles
730         (gnus-info-set-read
731          info
732          (if docorr
733              (nnmairix-map-range
734               `(lambda (x) (+ x ,(cadr corr)))
735               (gnus-info-read folderinfo))
736            (gnus-info-read folderinfo)))
737         ;; set other marks
738         (gnus-info-set-marks
739          info
740          (if docorr
741              (mapcar (lambda (cur)
742                          (cons
743                           (car cur)
744                           (nnmairix-map-range
745                            `(lambda (x) (+ x ,(cadr corr)))
746                            (list (cadr cur)))))
747                      (gnus-info-marks folderinfo))
748            (gnus-info-marks folderinfo))))
749       (when (eq readmarks 'unread)
750         (gnus-info-set-read info nil))
751       (when (eq readmarks 'read)
752         (gnus-info-set-read info (gnus-active qualgroup))))
753   t)
754
755 (nnoo-define-skeleton nnmairix)
756
757
758 ;;; === Interactive functions
759
760 (defun nnmairix-create-search-group (server group query threads)
761   "Create on SERVER nnmairix search group GROUP with QUERY.
762 If THREADS is t, include whole threads from found messages.  If
763 called interactively, user will be asked for parameters."
764   (interactive
765    (list
766     (gnus-server-to-method (car (nnmairix-get-server)))
767     (read-string "Group name: ")
768     (read-string "Query: ")
769     (y-or-n-p "Include threads? ")))
770   (when (and (stringp query)
771              (string-match "\\s-" query))
772     (setq query (split-string query)))
773   (when (not (listp query))
774     (setq query (list query)))
775   (when (and server group query)
776     (save-excursion
777       (let ((groupname (gnus-group-prefixed-name group server))
778             info)
779         (set-buffer gnus-group-buffer)
780         (gnus-group-make-group group server)
781         (gnus-group-set-parameter groupname 'query  query)
782         (gnus-group-set-parameter groupname 'threads threads)
783         (nnmairix-update-and-clear-marks groupname)))))
784
785 (defun nnmairix-search-interactive ()
786   "Create mairix search interactively with the minibuffer."
787   (interactive)
788   (let ((char-header nnmairix-interactive-query-parameters)
789         header finished query achar)
790     (while (not finished)
791       (while (not achar)
792         (message "Query (%s): " (nnmairix-create-message-line-for-search))
793           (setq achar (read-char))
794           (when (not (assoc achar char-header))
795             (setq achar nil)))
796       (setq header (read-string
797                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
798         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
799         (setq finished (not (y-or-n-p "Add another search query? "))
800               achar nil))
801     (nnmairix-search
802      (mapconcat 'identity query " ")
803      (car (nnmairix-get-server))
804      (y-or-n-p "Include whole threads? "))))
805
806 (defun nnmairix-create-search-group-from-message ()
807   "Interactively create search group with query based on current message."
808   (interactive)
809   (let ((char-header nnmairix-interactive-query-parameters)
810         (server (nnmairix-backend-to-server gnus-current-select-method))
811          query achar header finished group threads cq)
812     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
813               (not (gnus-buffer-live-p gnus-summary-buffer)))
814       (error "No article or summary buffer"))
815     (when (not server)
816       (error "No nnmairix server found for back end %s:%s"
817              (symbol-name (car gnus-current-select-method))
818              (nth 1 gnus-current-select-method)))
819     (while (not finished)
820       (save-excursion
821         (gnus-summary-toggle-header 1)
822         (while (not achar)
823           (message "Query (%s): " (nnmairix-create-message-line-for-search))
824           (setq achar (read-char))
825           (when (not (assoc achar char-header))
826             (setq achar nil)))
827         (set-buffer gnus-article-buffer)
828         (setq header nil)
829         (when (setq cq (nth 1 (assoc achar char-header)))
830           (setq header
831                 (nnmairix-replace-illegal-chars
832                  (gnus-fetch-field (nth 1 (assoc achar char-header))))))
833         (setq header (read-string
834                       (concat "Match " (nth 3 (assoc achar char-header)) " on: ")
835                       header))
836         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
837         (setq finished (not (y-or-n-p "Add another search query? "))
838               achar nil)))
839     (setq threads (y-or-n-p "Include whole threads? "))
840     (setq group (read-string "Group name: "))
841     (set-buffer gnus-summary-buffer)
842     (message "Creating group %s on server %s with query %s." group
843              (gnus-method-to-server server) (mapconcat 'identity query " "))
844     (nnmairix-create-search-group server group query threads)))
845
846 (defun nnmairix-create-server-and-default-group ()
847   "Interactively create new nnmairix server with default search group.
848 All necessary information will be queried from the user."
849   (interactive)
850   (let* ((name (read-string "Name of the mairix server: "))
851         (server (gnus-completing-read "Back end server"
852                                  (nnmairix-get-valid-servers) t))
853         (mairix (read-string "Command to call mairix: " "mairix"))
854         (defaultgroup (read-string "Default search group: "))
855         (backend (symbol-name (car (gnus-server-to-method server))))
856         (servername (nth 1 (gnus-server-to-method server)))
857         (hidden (and (string-match "^nn\\(imap\\|maildir\\)$" backend)
858                      (y-or-n-p
859                       "Does the back end server work with maildir++ (i.e. hidden directories)? ")))
860         create)
861
862     (apply (intern (format "%s-%s" backend "open-server"))
863            (list servername))
864
865     (when (and hidden
866                (string-match "^\\." defaultgroup))
867       (setq defaultgroup (substring defaultgroup 1)))
868     ;; Create default search group
869     (gnus-group-make-group
870      defaultgroup (list 'nnmairix name  (list 'nnmairix-backend (intern backend))
871                         (list 'nnmairix-backend-server servername)
872                         (list 'nnmairix-mairix-command mairix)
873                         (list 'nnmairix-hidden-folders hidden)
874                         (list 'nnmairix-default-group defaultgroup)))))
875
876 (defun nnmairix-group-change-query-this-group (&optional query)
877   "Set QUERY for group under cursor."
878   (interactive)
879   (let* ((group (gnus-group-group-name))
880          (method (gnus-find-method-for-group group))
881          (oldquery (gnus-group-get-parameter group 'query t)))
882     (if (eq (car method) 'nnmairix)
883         (progn
884           (when (listp oldquery)
885             (setq oldquery (mapconcat 'identity oldquery " ")))
886           (setq query (or query
887                           (read-string "New query: " oldquery)))
888           (when (stringp query)
889             (setq query (split-string query)))
890           (when query
891             (gnus-group-set-parameter group 'query query)
892             (nnmairix-update-and-clear-marks group)))
893       (error "This is no nnmairix group"))))
894
895
896 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
897   "Toggle threads parameter for this group.
898 If THREADS is a positive number, set threads parameter to t.
899 If THREADS is a negative number, set it to nil."
900   (interactive)
901   (let ((group (gnus-group-group-name)))
902     (when (nnmairix-group-toggle-parameter
903            group 'threads "Threads" threads)
904       (nnmairix-update-and-clear-marks group))))
905
906 (defun nnmairix-group-toggle-propmarks-this-group (&optional propmarks)
907   "Toggle marks propagation for this group.
908 If PROPMARKS is a positive number, set parameter to t.
909 If PROPMARKS is a negative number, set it to nil."
910   (interactive)
911   (unless (nnmairix-check-mairix-version "maildirpatch")
912     (error "You need a mairix binary with maildir patch to use this feature.  See docs for details"))
913   (let ((group (gnus-group-group-name)))
914     (when (or (not (string= (gnus-group-short-name group)
915                             (cadr (assoc 'nnmairix-default-group
916                                         (gnus-find-method-for-group group)))))
917               (y-or-n-p "You should not activate marks propagation for the default \
918 search group.  Are you sure? "))
919       (nnmairix-group-toggle-parameter
920        group 'propmarks "Marks propagation" propmarks))))
921
922 (defun nnmairix-group-toggle-allowfast-this-group (&optional allowfast)
923   "Toggle fast entering for this group.
924 If ALLOWFAST is a positive number, set parameter to t.
925 If ALLOWFAST is a negative number, set it to nil."
926   (interactive)
927   (nnmairix-group-toggle-parameter
928    (gnus-group-group-name) 'allow-fast "Fast entering" allowfast))
929
930
931 (defun nnmairix-group-toggle-readmarks-this-group (&optional readmarks)
932   "Toggle read/unread marks for this group.
933 If READMARKS is a positive number, articles will always be read.
934 If READMARKS is a negative number, articles will always be unread.
935 If READMARKS is t or zero, marks will stay unchanged."
936   (interactive)
937   (let*  ((group (gnus-group-group-name))
938           (method (gnus-find-method-for-group group))
939           (readmarks (or readmarks
940                          (gnus-group-get-parameter group 'readmarks))))
941     (if (eq (car method) 'nnmairix)
942         (cond
943          ((or (and (numberp readmarks) (< readmarks 0))
944               (eq readmarks 'read))
945           (gnus-group-set-parameter group 'readmarks 'unread)
946           (nnheader-message 3 "Articles in %s always unread." group))
947          ((or (and (numberp readmarks) (> readmarks 0))
948               (not readmarks))
949               (gnus-group-set-parameter group 'readmarks 'read)
950               (nnheader-message 3 "Articles in %s always read." group))
951          (t
952           (gnus-group-set-parameter group 'readmarks nil)
953           (nnheader-message 3 "Read marks in %s stay unchanged." group)))
954       (error "This is no nnmairix group"))))
955
956
957 (defun nnmairix-search (query &optional server threads)
958   "Sends QUERY to nnmairix backend SERVER, using default its search group.
959
960 Default search group is automatically entered and results are shown.
961 If THREADS is t, enable threads.
962 If THREADS is a negative number, disable threads.
963 Otherwise, leave threads parameter as it is."
964   (interactive (list (read-string "Query: ")))
965   (when (not server)
966     (setq server (car (nnmairix-get-server))))
967   (if (not server)
968       (error "No opened nnmairix server found")
969     (setq server (gnus-server-to-method server)))
970   (nnmairix-open-server (nth 1 server))
971   (let* ((qualgroup (gnus-group-prefixed-name nnmairix-default-group
972                                               (list 'nnmairix (nth 1 server)))))
973     (set-buffer gnus-group-buffer)
974     (when (stringp query)
975       (setq query (split-string query)))
976     (gnus-group-set-parameter qualgroup 'query query)
977     (if (symbolp threads)
978         (when (eq threads 't)
979           (gnus-group-set-parameter qualgroup 'threads t))
980       (when (< threads 0)
981         (gnus-group-set-parameter qualgroup 'threads nil)))
982     (nnmairix-update-and-clear-marks qualgroup)
983     (unless (equal (gnus-active qualgroup) '(1 . 0))
984       (gnus-group-read-group nil t qualgroup))))
985
986 (defun nnmairix-search-thread-this-article ()
987   "Search thread for the current article.
988 This is effectively a shortcut for calling `nnmairix-search'
989 with m:msgid of the current article and enabled threads."
990   (interactive)
991   (let* ((server
992           (nnmairix-backend-to-server gnus-current-select-method))
993          mid)
994     (if server
995         (if (gnus-buffer-live-p gnus-article-buffer)
996             (progn
997               (with-current-buffer gnus-article-buffer
998                 (gnus-summary-toggle-header 1)
999                 (setq mid (message-fetch-field "Message-ID")))
1000               (while (string-match "[<>]" mid)
1001                 (setq mid (replace-match "" t t mid)))
1002               (nnmairix-search (concat "m:" mid) server t))
1003           (message "No article buffer."))
1004       (error "No nnmairix server found for back end %s:%s"
1005              (symbol-name (car gnus-current-select-method))
1006              (nth 1 gnus-current-select-method)))))
1007
1008 (defun nnmairix-search-from-this-article ()
1009   "Search messages from sender of the current article.
1010 This is effectively a shortcut for calling `nnmairix-search' with
1011 f:current_from."
1012   (interactive)
1013   (let* ((server
1014           (nnmairix-backend-to-server gnus-current-select-method))
1015          from)
1016     (if server
1017         (if (gnus-buffer-live-p gnus-article-buffer)
1018             (progn
1019               (with-current-buffer gnus-article-buffer
1020                 (gnus-summary-toggle-header 1)
1021                 (setq from (cadr (gnus-extract-address-components
1022                                   (gnus-fetch-field "From"))))
1023                 (nnmairix-search (concat "f:" from) server -1)))
1024           (message "No article buffer."))
1025       (error "No nnmairix server found for back end %s:%s"
1026              (symbol-name (car gnus-current-select-method))
1027              (nth 1 gnus-current-select-method)))))
1028
1029
1030 (defun nnmairix-purge-old-groups (&optional dontask server)
1031   "Delete mairix search groups which are no longer used.
1032
1033 You may want to call this from time to time if you are creating
1034 and deleting lots of nnmairix groups.  If DONTASK is t, do not ask
1035 before deleting a group on the back end.  SERVER specifies nnmairix server."
1036   (interactive)
1037   (let ((server (or server
1038                     (gnus-server-to-method (car (nnmairix-get-server))))))
1039     (if (nnmairix-open-server (nth 1 server))
1040         (when (nnmairix-call-backend
1041                "request-list" nnmairix-backend-server)
1042           (let (cur qualgroup folder)
1043             (with-current-buffer nntp-server-buffer
1044               (goto-char (point-min))
1045               (while (re-search-forward nnmairix-group-regexp (point-max) t)
1046                 (setq cur (match-string 0)
1047                       qualgroup (gnus-group-prefixed-name
1048                                  (match-string 1) server))
1049                 (when (not (and (gnus-group-entry qualgroup)
1050                                 (string= cur
1051                                          (gnus-group-get-parameter
1052                                           qualgroup 'folder))))
1053                   (when (or dontask
1054                             (y-or-n-p
1055                              (concat "Delete group " cur
1056                                      " on server " nnmairix-backend-server "? ")))
1057                     (nnmairix-call-backend
1058                      "request-delete-group" cur t nnmairix-backend-server)))))))
1059       (message "Couldn't open server %s" (nth 1 server)))))
1060
1061
1062 (defun nnmairix-update-database (&optional servers)
1063   "Call mairix for updating the database for SERVERS.
1064
1065 If SERVERS is nil, do update for all nnmairix servers.  Mairix
1066 will be called asynchronously unless
1067 `nnmairix-mairix-synchronous-update' is t.  Mairix will be called
1068 with `nnmairix-mairix-update-options'."
1069   (interactive)
1070   (let ((servers (or servers
1071                      (nnmairix-get-nnmairix-servers)))
1072         args cur commandsplit)
1073     (while servers
1074       (setq cur (car (pop servers)))
1075       (nnmairix-open-server
1076        (nth 1 (gnus-server-to-method cur)))
1077       (setq commandsplit (split-string nnmairix-mairix-command))
1078       (nnheader-message 7 "Updating mairix database for %s..." cur)
1079       (if nnmairix-mairix-synchronous-update
1080           (progn
1081             (setq args (append (list (car commandsplit) nil
1082                                      (get-buffer nnmairix-mairix-output-buffer)
1083                                      nil)))
1084             (if (> (length commandsplit) 1)
1085                 (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1086               (setq args (append args nnmairix-mairix-update-options)))
1087             (apply 'call-process args)
1088             (nnheader-message 7 "Updating mairix database for %s... done" cur))
1089         (progn
1090           (setq args (append (list cur (get-buffer nnmairix-mairix-output-buffer)
1091                                    (car commandsplit))))
1092           (if (> (length commandsplit) 1)
1093               (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1094             (setq args (append args nnmairix-mairix-update-options)))
1095           (set-process-sentinel (apply 'start-process args)
1096                                 'nnmairix-sentinel-mairix-update-finished))))))
1097
1098 (defun nnmairix-group-delete-recreate-this-group ()
1099   "Deletes and recreates group on the back end.
1100 You can use this function on nnmairix groups which continuously
1101 show wrong article counts."
1102   (interactive)
1103   (let* ((group (gnus-group-group-name))
1104          (method (gnus-find-method-for-group group)))
1105     (unless (eq (car method) 'nnmairix)
1106       (error "This is not a nnmairix group"))
1107     (when (y-or-n-p
1108            (format "Really recreate group %s on the back end? " group))
1109       (nnmairix-delete-recreate-group group)
1110       (gnus-group-get-new-news-this-group))))
1111
1112 (defun nnmairix-propagate-marks (&optional server)
1113   "Propagate marks from nnmairix group to original articles.
1114 Unless SERVER is explicitly specified, will use the last opened
1115 nnmairix server. Only marks from current session will be set."
1116   (interactive)
1117   (if server
1118       (nnmairix-open-server server)
1119     (unless (eq (car gnus-current-select-method) 'nnmairix)
1120       (if nnmairix-current-server
1121           (nnmairix-open-server nnmairix-current-server)
1122         (error "No opened nnmairix server"))))
1123   (if nnmairix-marks-cache
1124       (let (number ogroup number-cache method mid-marks temp)
1125         ;; first we get the article numbers
1126         (catch 'problem
1127           (while (setq ogroup (pop nnmairix-marks-cache))
1128             (while (setq mid-marks (pop (cdr ogroup)))
1129               (setq number
1130                     (cdr
1131                      (gnus-request-head (car mid-marks) (car ogroup))))
1132               (unless number
1133                 (nnheader-message
1134                  3 "Unable to set mark: couldn't determine article number for %s in %s"
1135                  (car mid-marks) (car ogroup))
1136                 (throw 'problem nil))
1137               (setq temp (assoc (car ogroup) number-cache))
1138               (if temp
1139                   (catch 'done
1140                     (dolist (cur (cdr temp))
1141                       (when (equal (cdr cur) (list (nth 1 mid-marks) (nth 2 mid-marks)))
1142                         (nconc (car cur) (list number))
1143                         (throw 'done nil)))
1144                     (nconc temp (list (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))))
1145                 (push (list (car ogroup) (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))
1146                       number-cache)))))
1147         ;; now we set the marks
1148         (with-current-buffer gnus-group-buffer
1149           (nnheader-message 5 "nnmairix: Propagating marks...")
1150           (dolist (cur number-cache)
1151             (setq method (gnus-find-method-for-group (car cur)))
1152             (apply (intern (format "%s-%s"
1153                                    (symbol-name (car method))
1154                                    "request-set-mark"))
1155                    (gnus-group-short-name (car cur))
1156                    (cdr cur)
1157                    (list (nth 1 method)))
1158             (gnus-group-jump-to-group (car cur))
1159             (gnus-group-get-new-news-this-group)))
1160         (nnheader-message 5 "nnmairix: Propagating marks... done"))
1161     (nnheader-message 3 "No marks to propagate.")))
1162
1163 (defun nnmairix-update-groups (servername &optional skipdefault updatedb)
1164   "Update all search groups on SERVERNAME.
1165 If SKIPDEFAULT is t, the default search group will not be
1166 updated.
1167 If UPDATEDB is t, database for SERVERNAME will be updated first."
1168   (interactive (list (gnus-completing-read "Update groups on server"
1169                                 (nnmairix-get-nnmairix-servers))))
1170   (save-excursion
1171     (when (string-match ".*:\\(.*\\)" servername)
1172       (setq servername (match-string 1 servername)))
1173     (if (not (assoc (format "nnmairix:%s" servername)
1174                     (nnmairix-get-nnmairix-servers)))
1175         (nnheader-message 3 "Server %s not opened" servername)
1176       (when updatedb
1177         (let ((nnmairix-mairix-synchronous-update t))
1178           (nnmairix-update-database
1179            (list (list (format "nnmairix:%s" servername))))))
1180       (let ((groups (nnmairix-get-groups-from-server servername))
1181             default)
1182         (when skipdefault
1183           (setq default
1184                 (format "nnmairix+%s:%s"
1185                         servername
1186                         (cadr
1187                          (assoc 'nnmairix-default-group
1188                                 (gnus-server-to-method
1189                                  (format "nnmairix:%s" servername)))))))
1190         (dolist (cur groups)
1191           (unless (and skipdefault
1192                        (string= (car cur) default))
1193             (gnus-group-jump-to-group (car cur))
1194             (gnus-group-mark-group 1)))
1195         (gnus-group-get-new-news-this-group)))))
1196
1197 (defun nnmairix-remove-tick-mark-original-article ()
1198   "Remove tick mark from original article.
1199 Marks propagation has to be enabled for this to work."
1200   (interactive)
1201   (unless (eq (car gnus-current-select-method) 'nnmairix)
1202     (error "Not in a nnmairix group"))
1203   (save-excursion
1204     (let ((mid (mail-header-message-id (gnus-summary-article-header)))
1205           groups cur)
1206       (when mid
1207         (setq groups (nnmairix-determine-original-group-from-registry mid))
1208         (unless (or groups
1209                     nnmairix-only-use-registry)
1210           (setq groups
1211                 (nnmairix-determine-original-group-from-path mid nnmairix-current-server)))
1212         (unless groups
1213           (error "Couldn't find original article"))
1214         (dolist (cur groups)
1215           (push `(,cur (,mid del (tick))) nnmairix-marks-cache))
1216         (nnheader-message 5 "Will remove tick mark for %s upon closing." mid)))))
1217
1218 ;;; ==== Helper functions
1219
1220 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
1221   "Request FOLDER on back end for nnmairix QUALGROUP and article number correction."
1222   (save-excursion
1223     (nnmairix-call-backend "request-group" folder nnmairix-backend-server)
1224     (set-buffer nnmairix-mairix-output-buffer)
1225     (goto-char (point-min))
1226     (re-search-forward "^Matched.*messages")
1227     (nnheader-message 7 (match-string 0))
1228     (set-buffer nntp-server-buffer)
1229     (goto-char (point-min))
1230     (let ((status (read (current-buffer)))
1231           (total (read (current-buffer)))
1232           (low (read (current-buffer)))
1233           (high (read (current-buffer)))
1234           (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1235       (if (= status 211)
1236           (progn
1237             ;; Article number correction
1238             (if (and corr
1239                      (> (+ (car (cddr corr)) high) 0))
1240                 (progn
1241                   (when (car corr) ;Group has changed
1242                     (setq corr
1243                           (list nil
1244                                 (car (cddr corr))
1245                                 (+ (car (cddr corr)) high)))
1246                     (gnus-group-set-parameter
1247                      qualgroup 'numcorr corr))
1248                   (setq low (+ low (cadr corr))
1249                         high (+ high (cadr corr))))
1250               (when (member nnmairix-backend
1251                             nnmairix-delete-and-create-on-change)
1252                 (gnus-group-set-parameter
1253                  qualgroup 'numcorr (list nil 0 high))))
1254             (erase-buffer)
1255             (insert (format "%d %d %d %d %s" status total low high
1256                             (gnus-group-real-name qualgroup)))
1257             t)
1258         (progn
1259           (nnheader-report
1260            'nnmairix "Error calling back end on group %s" folder)
1261           nil)))))
1262
1263 (defun nnmairix-call-mairix-binary (command folder searchquery threads)
1264   "Call mairix binary with COMMAND, using FOLDER and SEARCHQUERY.
1265 If THREADS is non-nil, enable full threads."
1266   (let ((args (cons (car command) '(nil t nil))))
1267     (with-current-buffer
1268        (get-buffer-create nnmairix-mairix-output-buffer)
1269       (erase-buffer)
1270       (when (> (length command) 1)
1271         (setq args (append args (cdr command))))
1272       (when nnmairix-mairix-search-options
1273         (setq args (append args nnmairix-mairix-search-options)))
1274       ;; If we have a patched mairix binary, call it with "-c"
1275       (when (nnmairix-check-mairix-version "maildirpatch")
1276         (setq args (append args '("-c"))))
1277       (when threads
1278         (setq args (append args '("-t"))))
1279       (apply 'call-process
1280              (append args (list "-o" folder) searchquery)))))
1281
1282 (defun nnmairix-call-mairix-binary-raw (command query)
1283   "Call mairix binary with COMMAND and QUERY in raw mode."
1284   (let ((args (cons (car command) '(nil t nil))))
1285     (with-current-buffer
1286        (get-buffer-create nnmairix-mairix-output-buffer)
1287       (erase-buffer)
1288       (when (> (length command) 1)
1289         (setq args (append args (cdr command))))
1290       (setq args (append args '("-r")))
1291       (apply 'call-process
1292              (append args query)))))
1293
1294 (defun nnmairix-get-server ()
1295   "If there exists just one nnmairix server, return its value.
1296 Otherwise, ask user for server."
1297   (let ((openedserver (nnmairix-get-nnmairix-servers)))
1298     (when (not openedserver)
1299       (error "No opened nnmairix server found"))
1300     (if (> (length openedserver) 1)
1301         (progn
1302           (while
1303               (equal '("")
1304                   (setq nnmairix-last-server
1305                         (list (gnus-completing-read "Server" openedserver t
1306                                                (or nnmairix-last-server
1307                                                    "nnmairix:"))))))
1308           nnmairix-last-server)
1309       (car openedserver))))
1310
1311 (defun nnmairix-get-nnmairix-servers (&optional all)
1312   "Return available nnmairix servers.
1313 If ALL is t, return also the unopened/failed ones."
1314   (let ((alist gnus-opened-servers)
1315         server openedserver)
1316     (while alist
1317       (setq server (pop alist))
1318       (when (and server
1319                  (or all
1320                      (eq (cadr server) 'ok))
1321                  (eq (caar server) 'nnmairix)
1322                  (not (member (car server) gnus-ephemeral-servers)))
1323         (setq server
1324               (concat (symbol-name (caar server)) ":" (nth 1 (car server))))
1325         (push (list server) openedserver)))
1326     openedserver))
1327
1328 (defun nnmairix-get-valid-servers ()
1329   "Return list of valid back end servers for nnmairix groups."
1330   (let ((alist gnus-opened-servers)
1331         (mairixservers (nnmairix-get-nnmairix-servers t))
1332         server mserver openedserver occ cur)
1333     ;; Get list of all nnmairix backends (i.e. backends which are
1334     ;; already occupied)
1335     (dolist (cur mairixservers)
1336       (push
1337        (concat
1338         (symbol-name
1339          (cadr (assoc 'nnmairix-backend
1340                       (gnus-server-to-method (car cur)))))
1341          ":"
1342          (cadr (assoc 'nnmairix-backend-server
1343                       (gnus-server-to-method (car cur)))))
1344         occ))
1345     (while alist
1346       (setq server (pop alist))
1347       (setq mserver (gnus-method-to-server (car server)))
1348       ;; If this is the native server, convert it to the real server
1349       ;; name to avoid confusion
1350       (when (string= mserver "native")
1351         (setq mserver (format "%s:%s"
1352                               (caar server)
1353                               (nth 1 (car server)))))
1354       (when (and server
1355                  (eq (cadr server) 'ok)
1356                  (member (caar server) nnmairix-valid-backends)
1357                  (not (member (car server) gnus-ephemeral-servers))
1358                  (not (member (gnus-method-to-server (car server)) occ)))
1359         (push
1360          (list mserver)
1361          openedserver)))
1362     openedserver))
1363
1364 (defun nnmairix-get-groups-from-server (servername)
1365   "Return all groups for nnmairix server SERVERNAME."
1366   (let ((searchstring (format "nnmairix\\+%s:" servername))
1367         groups)
1368     (dolist (cur gnus-newsrc-alist)
1369       (when (string-match searchstring
1370                           (car cur))
1371         (push (list (car cur)) groups)))
1372     groups))
1373
1374 (defun nnmairix-call-backend (func &rest args)
1375   "Call a function FUNC on backend with ARGS."
1376   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
1377
1378 (defun nnmairix-get-backend-folder (group &optional server)
1379   "Return back end GROUP from nnmairix group on SERVER."
1380   (let* ((qualgroup (if server
1381                         (gnus-group-prefixed-name group (list 'nnmairix server))
1382                       group))
1383          (folder (gnus-group-get-parameter qualgroup 'folder)))
1384     folder))
1385
1386 (defun nnmairix-get-numcorr (group &optional server)
1387   "Return values for article number correction nnmairix GROUP on SERVER."
1388   (let* ((qualgroup (if server
1389                         (gnus-group-prefixed-name group (list 'nnmairix server))
1390                       group))
1391          (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1392     corr))
1393
1394
1395 (defun nnmairix-rename-files-consecutively (path)
1396   "Rename all nnml mail files in PATH so that they have consecutive numbers.
1397 This should correct problems of wrong article counts when using
1398 nnmairix with nnml backends."
1399   (let* ((files
1400          (sort
1401           (mapcar 'string-to-number
1402                   (directory-files path nil "[0-9]+" t))
1403           '<))
1404          (lastplusone (car files))
1405          (path (file-name-as-directory path)))
1406     (dolist (cur files)
1407       (when (not (= cur lastplusone))
1408         (rename-file (concat path
1409                              (number-to-string cur))
1410                      (concat path
1411                              (number-to-string lastplusone)))
1412         (setq cur lastplusone))
1413       (setq lastplusone (1+ cur)))))
1414
1415 (defun nnmairix-replace-group-and-numbers (articles backendgroup mairixgroup numc type)
1416   "Replace folder names in Xref header and correct article numbers.
1417 Do this for all ARTICLES on BACKENDGROUP.  Replace using
1418 MAIRIXGROUP.  NUMC contains values for article number correction.
1419 TYPE is either 'nov or 'headers."
1420   (nnheader-message 7 "nnmairix: Rewriting headers...")
1421   (cond
1422    ((eq type 'nov)
1423     (let ((buf (get-buffer-create " *nnmairix buffer*"))
1424           (corr (not (zerop numc)))
1425           (name (buffer-name nntp-server-buffer))
1426           header cur xref)
1427       (with-current-buffer buf
1428         (erase-buffer)
1429         (set-buffer nntp-server-buffer)
1430         (goto-char (point-min))
1431         (mapc
1432          (lambda (article)
1433            (when (or (looking-at (number-to-string article))
1434                      (nnheader-find-nov-line article))
1435              (setq cur (nnheader-parse-nov))
1436              (when corr
1437                (setq article (+ (mail-header-number cur) numc))
1438                (mail-header-set-number cur article))
1439              (setq xref (mail-header-xref cur))
1440              (when (and (stringp xref)
1441                         (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
1442                (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
1443                (mail-header-set-xref cur xref))
1444              (set-buffer buf)
1445              (nnheader-insert-nov cur)
1446              (set-buffer nntp-server-buffer)
1447              (when (not (eobp))
1448                (forward-line 1))))
1449          articles)
1450         (kill-buffer nntp-server-buffer)
1451         (set-buffer buf)
1452         (rename-buffer name)
1453         (setq nntp-server-buffer buf))))
1454    ((and (eq type 'headers)
1455          (not (zerop numc)))
1456     (with-current-buffer nntp-server-buffer
1457       (save-excursion
1458         (goto-char (point-min))
1459         (while (re-search-forward "^[23][0-9]+ \\([0-9]+\\)" nil t)
1460           (replace-match (number-to-string
1461                           (+ (string-to-number (match-string 1)) numc))
1462                          t t nil 1))))))
1463   (nnheader-message 7 "nnmairix: Rewriting headers... done"))
1464
1465 (defun nnmairix-backend-to-server (server)
1466   "Return nnmairix server most probably responsible for back end SERVER.
1467 User will be asked if this cannot be determined.  Result is saved in
1468 parameter 'indexed-servers of corresponding default search
1469 group."
1470   (let ((allservers (nnmairix-get-nnmairix-servers))
1471         mairixserver found defaultgroup)
1472     (if (> (length allservers) 1)
1473         (progn
1474           ;; If there is more than one nnmairix server, we go through them
1475           (while (and allservers (not found))
1476             (setq mairixserver (gnus-server-to-method (car (pop allservers))))
1477             ;; First we look if SERVER is the backend of current nnmairix server
1478             (setq found (and (eq (cadr (assoc 'nnmairix-backend mairixserver))
1479                                  (car server))
1480                              (string= (cadr (assoc 'nnmairix-backend-server mairixserver))
1481                                       (nth 1 server))))
1482             ;; If that's not the case, we look at 'indexed-servers
1483             ;; variable in default search group
1484             (when (not found)
1485               (setq defaultgroup (cadr (assoc 'nnmairix-default-group mairixserver)))
1486               (setq found (member (gnus-method-to-server server)
1487                                   (gnus-group-get-parameter
1488                                    (gnus-group-prefixed-name defaultgroup
1489                                                              mairixserver)
1490                                    'indexed-servers t)))))
1491           ;; If still not found, we ask user
1492           (when (not found)
1493             (setq mairixserver
1494                   (gnus-server-to-method
1495                    (gnus-completing-read
1496                     (format "Cannot determine which nnmairix server indexes %s. Please specify"
1497                             (gnus-method-to-server server))
1498                     (nnmairix-get-nnmairix-servers) nil "nnmairix:")))
1499             ;; Save result in parameter of default search group so that
1500             ;; we don't have to ask again
1501             (setq defaultgroup (gnus-group-prefixed-name
1502                                 (cadr (assoc 'nnmairix-default-group mairixserver)) mairixserver))
1503             (gnus-group-set-parameter
1504              defaultgroup
1505              'indexed-servers
1506              (append (gnus-group-get-parameter defaultgroup 'indexed-servers t)
1507                      (list (gnus-method-to-server server)))))
1508           mairixserver)
1509       ;; If there is just one (or none) nnmairix server:
1510       (gnus-server-to-method (caar allservers)))))
1511
1512
1513 (defun nnmairix-delete-recreate-group (group)
1514   "Delete and recreate folder from GROUP on the back end."
1515   (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1516     (let ((folder (gnus-group-get-parameter group 'folder)))
1517       (if (string-match nnmairix-group-regexp folder)
1518           (progn
1519             (nnmairix-call-backend "open-server"
1520                                    nnmairix-backend-server)
1521             (nnmairix-call-backend "request-delete-group"
1522                                    folder t nnmairix-backend-server)
1523             (nnmairix-call-backend "request-create-group"
1524                                    folder nnmairix-backend-server))
1525         (error "`nnmairix-delete-recreate-group' called on \
1526 non-mairix group.  Check folder parameter")))))
1527
1528 (defun nnmairix-update-and-clear-marks (group &optional method)
1529   "Update group and clear all marks from GROUP using METHOD."
1530   (let ((method (or method
1531                     (gnus-find-method-for-group group)))
1532         (corr (gnus-group-get-parameter group 'numcorr t))
1533         info)
1534     (unless (or (gnus-group-prefixed-p group)
1535                 (not method))
1536       (setq group (gnus-group-prefixed-name group method)))
1537     (if (eq (nth 0 method) 'nnmairix)
1538         (save-excursion
1539           (nnmairix-open-server (nth 1 method))
1540           (set-buffer gnus-group-buffer)
1541           ;; (gnus-group-set-parameter group 'propmarks nil)
1542           (setq info (gnus-get-info group))
1543           ;; Clear active and info
1544           (gnus-set-active group nil)
1545           (gnus-info-clear-data info)
1546           ;; Delete and re-create group if needed
1547           (nnmairix-delete-recreate-group group)
1548           ;; set flag that group has changed for article number correction
1549           (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1550             (when corr
1551               (setcar corr t)
1552               (gnus-group-set-parameter group 'numcorr corr)))
1553           (gnus-group-jump-to-group group)
1554           (gnus-group-get-new-news-this-group))
1555       (error "`nnmairix-update-and-clear-marks' called with non-nnmairix group"))))
1556
1557 (defun nnmairix-sentinel-mairix-update-finished (proc status)
1558   "Sentinel for mairix update process PROC with STATUS."
1559   (if (equal status "finished\n")
1560       (nnheader-message 7 "Updating mairix database for %s... done" proc)
1561     (error "There was an error updating the mairix database for server %s.  \
1562 See %s for details" proc nnmairix-mairix-output-buffer)))
1563
1564 (defun nnmairix-create-message-line-for-search ()
1565   "Create message line for interactive query in minibuffer."
1566   (mapconcat
1567    (function
1568     (lambda (cur)
1569       (format "%c=%s" (car cur) (nth 3 cur))))
1570    nnmairix-interactive-query-parameters ","))
1571
1572 (defun nnmairix-replace-illegal-chars (header)
1573   "Replace illegal characters in HEADER for mairix query."
1574   (when header
1575     (while (string-match "[^-.@/,& [:alnum:]]" header)
1576       (setq header (replace-match "" t t header)))
1577     (while (string-match "[-& ]" header)
1578       (setq header (replace-match "," t t header)))
1579     header))
1580
1581 (defun nnmairix-group-toggle-parameter (group parameter description &optional par)
1582   "Toggle on GROUP a certain PARAMETER.
1583 DESCRIPTION will be shown to the user with the activation
1584 status.  If PAR is a positive number, the group parameter will be
1585 set to t and to nil otherwise."
1586   (let* ((method (gnus-find-method-for-group group))
1587          (par (or par
1588                   (not (gnus-group-get-parameter group parameter)))))
1589     (if (eq (car method) 'nnmairix)
1590         (progn
1591           (when (numberp par)
1592             (setq par (> par 0)))
1593           (gnus-group-set-parameter group parameter par)
1594           (if par
1595               (message "%s activated for group %s" description group)
1596             (message "%s deactivated for group %s" description group))
1597           t)
1598       (error "This is no nnmairix group")
1599       nil)))
1600
1601 ;; Search for original article helper functions
1602
1603 (defun nnmairix-goto-original-article (&optional no-registry)
1604   "Jump to the original group and display article.
1605 The original group of the article is first determined with the
1606 registry (if enabled).  If the registry is not enabled or did not
1607 find the article or the prefix NO-REGISTRY is non-nil, this
1608 function will try to determine the original group form the path
1609 of the mail file.  The path is obtained through another mairix
1610 search in raw mode."
1611   (interactive "P")
1612   (when (not (eq (car gnus-current-select-method) 'nnmairix))
1613     (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
1614       (if (eq (car method) 'nnmairix)
1615           (nnmairix-open-server (nth 1 method))
1616         (error "Not in a nnmairix group"))))
1617   (when (not (gnus-buffer-live-p gnus-article-buffer))
1618     (error "No article buffer available"))
1619   (let ((server (nth 1 gnus-current-select-method))
1620         mid rval group allgroups)
1621     ;; get message id
1622     (with-current-buffer gnus-article-buffer
1623       (gnus-summary-toggle-header 1)
1624       (setq mid (message-fetch-field "Message-ID"))
1625       ;; first check the registry (if available)
1626       (unless no-registry
1627         (setq allgroups (nnmairix-determine-original-group-from-registry mid)))
1628       (unless (or allgroups
1629                   nnmairix-only-use-registry)
1630         ;; registry was not available or did not find article
1631         ;; so we search again with mairix in raw mode to get filename
1632         (setq allgroups
1633               (nnmairix-determine-original-group-from-path mid server))
1634         ;; if available and allowed, add this entry to the registry
1635         (when (and (not no-registry)
1636                    (boundp 'gnus-registry-install)
1637                    gnus-registry-install)
1638           (dolist (cur allgroups)
1639             (unless (gnus-parameter-registry-ignore cur)
1640               (gnus-registry-add-group mid cur)))))
1641       (if (> (length allgroups) 1)
1642           (setq group
1643                 (gnus-completing-read
1644                  "Message exists in more than one group. Choose"
1645                  allgroups t))
1646         (setq group (car allgroups))))
1647     (if group
1648         ;; show article in summary buffer
1649         (nnmairix-show-original-article group mid)
1650       (nnheader-message 3 "Couldn't find original article"))))
1651
1652 (defun nnmairix-determine-original-group-from-registry (mid)
1653   "Try to determinale original group for message-id MID from the registry."
1654   (when (and (boundp 'gnus-registry-install)
1655              gnus-registry-install)
1656     (unless (string-match "^<" mid)
1657       (set mid (concat "<" mid)))
1658     (unless (string-match ">$" mid)
1659       (set mid (concat mid ">")))
1660     (gnus-registry-fetch-groups mid)))
1661
1662 (defun nnmairix-determine-original-group-from-path (mid server)
1663   "Determine original group(s) for message-id MID from the file path.
1664 The file path is obtained through a mairix search for the id on
1665 SERVER."
1666   (nnmairix-open-server server)
1667   (while (string-match "[<>]" mid)
1668     (setq mid (replace-match "" t t mid)))
1669   ;; mairix somehow does not like '$' in message-id
1670   (when (string-match "\\$" mid)
1671     (setq mid (concat mid "=")))
1672   (while (string-match "\\$" mid)
1673     (setq mid (replace-match "=," t t mid)))
1674   (let (allgroups)
1675     (if (zerop (nnmairix-call-mairix-binary-raw
1676                 (split-string nnmairix-mairix-command)
1677                 (list (concat "m:" mid))))
1678         (with-current-buffer nnmairix-mairix-output-buffer
1679           (goto-char (point-min))
1680           (while (re-search-forward "^/.*$" nil t)
1681             (push (nnmairix-get-group-from-file-path (match-string 0))
1682                   allgroups)
1683             (forward-line 1)))
1684       (error "Mairix could not find original article.  See buffer %s for details"
1685              nnmairix-mairix-output-buffer))
1686     allgroups))
1687
1688 (defun nnmairix-get-group-from-file-path (file)
1689   "Get group by parsing the message location FILE."
1690   (let (path filename serverbase group maildirflag allgroups)
1691     (string-match "^\\(.*\\)/\\(.*?\\)$" file)
1692     (setq path (expand-file-name (match-string 1 file)))
1693     (setq filename (match-string 2 file))
1694     ;; when we deal with maildir, remove cur/new/tmp from path
1695     (setq maildirflag (string-match ".+\\..+\\..+" filename))
1696     (when maildirflag
1697       (setq path
1698             (replace-regexp-in-string
1699              ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
1700     ;; we first check nnml and nnmaildir servers
1701     (setq
1702      group
1703      (catch 'found
1704        (dolist (cur gnus-opened-servers)
1705          (when (or (and (not maildirflag)
1706                         (eq (caar cur) 'nnml))
1707                    (and maildirflag
1708                         (eq (caar cur) 'nnmaildir)))
1709            ;; get base path from server
1710            (if maildirflag
1711                (setq serverbase (cadr (assoc 'directory (car cur))))
1712              (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
1713              (unless serverbase
1714                (setq serverbase nnml-directory)))
1715            (setq serverbase (file-name-as-directory
1716                              (expand-file-name serverbase)))
1717            (when (string-match (concat serverbase "\\(.*\\)") path)
1718              ;; looks good - rest of the path should be the group
1719              (setq group (match-string 1 path))
1720              (when (string-match "/$" group)
1721                (setq group (replace-match "" t t group)))
1722              (unless maildirflag
1723                ;; for nnml: convert slashes to dots
1724                (while (string-match "/" group)
1725                  (setq group (replace-match "." t t group))))
1726              (setq group (gnus-group-prefixed-name group (car cur)))
1727              ;; check whether this group actually exists
1728              (when (gnus-group-entry group)
1729                (throw 'found group)))))))
1730     (unless group
1731       ;; we haven't found it yet --> look for nnimap groups. Assume
1732       ;; last element of the path is the group. This might fail since
1733       ;; IMAP servers may present groups to the client in arbitrary
1734       ;; ways...
1735       (string-match "^.*/\\.?\\(.*\\)$" path)
1736       (setq group (match-string 1 path))
1737       ;; convert dots to slashes (nested group)
1738       (while (string-match "\\." group)
1739         (setq group (replace-match "/" t t group)))
1740       (dolist (cur gnus-opened-servers)
1741         (when (eq (caar cur) 'nnimap)
1742           (when (gnus-group-entry
1743                  (gnus-group-prefixed-name group (car cur)))
1744             (push
1745              (gnus-group-prefixed-name group (car cur))
1746              allgroups))))
1747       (if (> (length allgroups) 1)
1748           (setq group (gnus-completing-read
1749                        "Group %s exists on more than one IMAP server. Choose"
1750                        allgroups t))
1751         (setq group (car allgroups))))
1752     group))
1753
1754 (defun nnmairix-show-original-article (group mid)
1755   "Switch to GROUP and display Article with message-id MID."
1756   (unless (string-match "^<" mid)
1757     (set mid (concat "<" mid)))
1758   (unless (string-match ">$" mid)
1759     (set mid (concat mid ">")))
1760   (when (string-match "Summary" (buffer-name (current-buffer)))
1761     (gnus-summary-exit))
1762   (pop-to-buffer gnus-group-buffer)
1763   (gnus-group-jump-to-group group)
1764   (gnus-summary-read-group group 1 t)
1765   (gnus-summary-refer-article mid)
1766   (gnus-summary-limit-to-headers (format "message-id: %s" mid))
1767   (gnus-summary-select-article)
1768   ;; Force redisplay
1769   (gnus-summary-show-article)
1770   (nnheader-message 5 "Switched to group %s." group))
1771
1772 (defun nnmairix-map-range (func range)
1773   "Map function FUNC on all members of RANGE."
1774   (cond
1775    ((numberp range)
1776     (funcall func range))
1777    (t
1778     (mapcar (lambda (cur)
1779               (cond
1780                ((listp cur)
1781                 (cons
1782                  (funcall func (car cur))
1783                  (funcall func (cdr cur))))
1784                ((numberp cur)
1785                 (funcall func cur))))
1786             range))))
1787
1788 (defun nnmairix-check-mairix-version (version &optional server)
1789   "Check mairix VERSION on SERVER.
1790 If VERSION is a number: specifies the minimum version.
1791 If VERSION is a string: must be contained in mairix version output."
1792   (unless server
1793     (setq server nnmairix-current-server))
1794   (let ((versionstring (cadr (assoc server nnmairix-version-output))))
1795     (unless versionstring
1796       ;; call "mairix -V" to get the version string
1797       (with-temp-buffer
1798         (setq versionstring
1799               (let* ((commandsplit (split-string nnmairix-mairix-command))
1800                      (args (append (list (car commandsplit))
1801                                   `(nil t nil) (cdr commandsplit) '("-V"))))
1802               (apply 'call-process args)
1803               (goto-char (point-min))
1804               (re-search-forward "mairix.*")
1805               (match-string 0))))
1806       ;; save version string for current session
1807       (setq nnmairix-version-output
1808             (append nnmairix-version-output
1809                     (list (list server versionstring)))))
1810     (cond
1811      ((stringp version)
1812       (string-match version versionstring))
1813      ((numberp version)
1814       (<= version (string-to-number
1815                    (progn
1816                      (string-match "mairix \\([0-9\\.]+\\)" versionstring)
1817                      (match-string 1 versionstring))))))))
1818
1819 ;; ==== Widget stuff
1820
1821 (defvar nnmairix-widgets)
1822 (defvar nnmairix-widgets-values nil)
1823
1824 (defun nnmairix-widget-search-from-this-article ()
1825   "Create mairix query based on current article using graphical widgets."
1826   (interactive)
1827   (nnmairix-widget-search
1828    (nnmairix-widget-get-values)))
1829
1830 (defun nnmairix-widget-get-values ()
1831   "Create values for editable fields from current article."
1832   (if (not (gnus-buffer-live-p gnus-article-buffer))
1833       (error "No article buffer available")
1834     (save-excursion
1835       (gnus-summary-toggle-header 1)
1836       (set-buffer gnus-article-buffer)
1837       (mapcar
1838        (function
1839         (lambda (field)
1840           (list (car (cddr field))
1841                 (if (car field)
1842                     (nnmairix-replace-illegal-chars
1843                      (gnus-fetch-field (car field)))
1844                   nil))))
1845        nnmairix-widget-fields-list))))
1846
1847
1848 (defun nnmairix-widget-search (&optional mvalues)
1849   "Create mairix query interactively using graphical widgets.
1850 MVALUES may contain values from current article."
1851   (interactive)
1852   ;; Select window for mairix customization
1853   (funcall nnmairix-widget-select-window-function)
1854   ;; generate widgets
1855   (nnmairix-widget-create-query mvalues)
1856   ;; generate Buttons
1857   (widget-create 'push-button
1858                  :notify
1859                  (if mvalues
1860                      (lambda (&rest ignore)
1861                        (nnmairix-widget-send-query nnmairix-widgets
1862                                                    t))
1863                    (lambda (&rest ignore)
1864                      (nnmairix-widget-send-query nnmairix-widgets
1865                                                  nil)))
1866                  "Send Query")
1867   (widget-insert "   ")
1868   (widget-create 'push-button
1869                  :notify
1870                  (if mvalues
1871                      (lambda (&rest ignore)
1872                        (nnmairix-widget-create-group nnmairix-widgets
1873                                                      t))
1874                    (lambda (&rest ignore)
1875                      (nnmairix-widget-create-group nnmairix-widgets
1876                                                    nil)))
1877                  "Create permanent group")
1878   (widget-insert "   ")
1879   (widget-create 'push-button
1880                  :notify (lambda (&rest ignore)
1881                            (kill-buffer nnmairix-customize-query-buffer))
1882                  "Cancel")
1883   (use-local-map widget-keymap)
1884   (widget-setup)
1885   (goto-char (point-min)))
1886
1887 (defun nnmairix-widget-send-query (widgets &optional withvalues)
1888   "Send query from WIDGETS to mairix binary.
1889 If WITHVALUES is t, query is based on current article."
1890   (nnmairix-search
1891    (nnmairix-widget-make-query-from-widgets widgets)
1892    (if withvalues
1893        (gnus-method-to-server
1894         (nnmairix-backend-to-server gnus-current-select-method))
1895      (car (nnmairix-get-server)))
1896    (if (widget-value (cadr (assoc "Threads" widgets)))
1897        t
1898      -1))
1899   (kill-buffer nnmairix-customize-query-buffer))
1900
1901 (defun nnmairix-widget-create-group (widgets &optional withvalues)
1902   "Create nnmairix group based on current widget values WIDGETS.
1903 If WITHVALUES is t, query is based on current article."
1904   (let ((group (read-string "Name of the group: ")))
1905     (when (not (zerop (length group)))
1906       (nnmairix-create-search-group
1907        (if withvalues
1908            (gnus-method-to-server
1909             (nnmairix-backend-to-server gnus-current-select-method))
1910          (car (nnmairix-get-server)))
1911        group
1912        (nnmairix-widget-make-query-from-widgets widgets)
1913        (widget-value (cadr (assoc "Threads" widgets))))))
1914   (kill-buffer nnmairix-customize-query-buffer))
1915
1916
1917 (defun nnmairix-widget-make-query-from-widgets (widgets)
1918   "Create mairix query from widget values WIDGETS."
1919   (let (query temp flag)
1920     ;; first we do the editable fields
1921     (dolist (cur nnmairix-widget-fields-list)
1922       ;; See if checkbox is checked
1923       (when (widget-value
1924              (cadr (assoc (concat "c" (car (cddr cur))) widgets)))
1925         ;; create query for the field
1926         (push
1927          (concat
1928           (nth 1 cur)
1929           ":"
1930           (nnmairix-replace-illegal-chars
1931            (widget-value
1932            (cadr (assoc (concat "e" (car (cddr cur))) widgets)))))
1933          query)))
1934     ;; Flags
1935     (when (member 'flags nnmairix-widget-other)
1936       (setq flag
1937             (mapconcat
1938              (function
1939               (lambda (flag)
1940                 (setq temp
1941                       (widget-value (cadr (assoc (car flag) nnmairix-widgets))))
1942                 (if (string= "yes" temp)
1943                     (cadr flag)
1944                   (if (string= "no" temp)
1945                       (concat "-" (cadr flag))))))
1946              '(("seen" "s") ("replied" "r") ("flagged" "f")) ""))
1947       (when (not (zerop (length flag)))
1948         (push (concat "F:" flag) query)))
1949     ;; return query string
1950     (mapconcat 'identity query " ")))
1951
1952
1953 (defun nnmairix-widget-create-query (&optional values)
1954   "Create widgets for creating mairix queries.
1955 Fill in VALUES if based on an article."
1956   (let (allwidgets)
1957     (when (get-buffer nnmairix-customize-query-buffer)
1958       (kill-buffer nnmairix-customize-query-buffer))
1959     (switch-to-buffer nnmairix-customize-query-buffer)
1960     (kill-all-local-variables)
1961     (erase-buffer)
1962     (widget-insert "Specify your query for Mairix (check boxes for activating fields):\n\n")
1963     (widget-insert "(Whitespaces will be converted to ',' (i.e. AND). Use '/' for OR.)\n\n")
1964 ;    (make-local-variable 'nnmairix-widgets)
1965     (setq nnmairix-widgets (nnmairix-widget-build-editable-fields values))
1966     (when (member 'flags nnmairix-widget-other)
1967       (widget-insert "\nFlags:\n      Seen:     ")
1968       (nnmairix-widget-add "seen"
1969                            'menu-choice
1970                            :value "ignore"
1971                            '(item "yes") '(item "no") '(item "ignore"))
1972       (widget-insert "      Replied:  ")
1973       (nnmairix-widget-add "replied"
1974                            'menu-choice
1975                            :value "ignore"
1976                            '(item "yes") '(item "no") '(item "ignore"))
1977       (widget-insert "      Ticked:   ")
1978       (nnmairix-widget-add "flagged"
1979                            'menu-choice
1980                            :value "ignore"
1981                            '(item "yes") '(item "no") '(item "ignore")))
1982     (when (member 'threads nnmairix-widget-other)
1983       (widget-insert "\n")
1984       (nnmairix-widget-add "Threads" 'checkbox nil))
1985       (widget-insert " Show full threads\n\n")))
1986
1987 (defun nnmairix-widget-build-editable-fields (values)
1988   "Build editable field widgets in `nnmairix-widget-fields-list'.
1989 VALUES may contain values for editable fields from current article."
1990   ;; how can this be done less ugly?
1991   (let ((ret))
1992     (mapc
1993      (function
1994       (lambda (field)
1995         (setq field (car (cddr field)))
1996         (setq ret
1997               (nconc
1998                (list
1999                 (list
2000                  (concat "c" field)
2001                  (widget-create 'checkbox
2002                                 :tag field
2003                                 :notify (lambda (widget &rest ignore)
2004                                           (nnmairix-widget-toggle-activate widget))
2005                                 nil)))
2006                (list
2007                 (list
2008                  (concat "e" field)
2009                  (widget-create 'editable-field
2010                                 :size 60
2011                                 :format (concat " " field ":"
2012                                                 (make-string (- 11 (length field)) ?\ )
2013                                                 "%v")
2014                                 :value (or (cadr (assoc field values)) ""))))
2015                ret))
2016         (widget-insert "\n")
2017         ;; Deactivate editable field
2018         (widget-apply (cadr (nth 1 ret)) :deactivate)))
2019      nnmairix-widget-fields-list)
2020     ret))
2021
2022 (defun nnmairix-widget-add (name &rest args)
2023   "Add a widget NAME with optional ARGS."
2024   (push
2025    (list name
2026          (apply 'widget-create args))
2027    nnmairix-widgets))
2028
2029 (defun nnmairix-widget-toggle-activate (widget)
2030   "Toggle activation status of WIDGET depending on corresponding checkbox value."
2031   (let ((field (widget-get widget :tag)))
2032     (if (widget-value widget)
2033         (widget-apply
2034          (cadr (assoc (concat "e" field) nnmairix-widgets))
2035          :activate)
2036       (widget-apply
2037        (cadr (assoc (concat "e" field) nnmairix-widgets))
2038        :deactivate)))
2039   (widget-setup))
2040
2041 (provide 'nnmairix)
2042
2043 ;;; nnmairix.el ends here