Embiggen pictures slightly.
[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 "$ t") 'nnmairix-search-thread-this-article)
192   (define-key gnus-summary-mode-map
193     (kbd "$ f") 'nnmairix-search-from-this-article)
194   (define-key gnus-summary-mode-map
195     (kbd "$ m") 'nnmairix-widget-search-from-this-article)
196   (define-key gnus-summary-mode-map
197     (kbd "$ g") 'nnmairix-create-search-group-from-message)
198   (define-key gnus-summary-mode-map
199     (kbd "$ o") 'nnmairix-goto-original-article)
200   (define-key gnus-summary-mode-map
201     (kbd "$ 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     (when (eq rval 'nov)
566       (nnmairix-replace-group-and-numbers articles folder group numcorr)
567       rval)))
568
569 (deffoo nnmairix-request-article (article &optional group server to-buffer)
570   (when server (nnmairix-open-server server))
571   (let ((folder (nnmairix-get-backend-folder group server))
572         (corr (nnmairix-get-numcorr group server)))
573     (when (and
574            (numberp article)
575            corr
576            (not (zerop (cadr corr))))
577       (setq article (- article (cadr corr))))
578     (nnmairix-call-backend
579      "request-article" article folder nnmairix-backend-server to-buffer))
580   t)
581
582 (deffoo nnmairix-request-list (&optional server)
583   (when server (nnmairix-open-server server))
584   (if (nnmairix-call-backend "request-list" nnmairix-backend-server)
585       (let (cpoint cur qualgroup folder)
586         (with-current-buffer nntp-server-buffer
587           (goto-char (point-min))
588           (setq cpoint (point))
589           (while (re-search-forward nnmairix-group-regexp (point-max) t)
590             (setq cur (match-string 1)
591                   qualgroup (gnus-group-prefixed-name cur
592                                                       (list 'nnmairix server)))
593             (if (and (gnus-group-entry qualgroup)
594                      (string= (match-string 0)
595                               (gnus-group-get-parameter qualgroup 'folder)))
596                 (progn
597                   (replace-match cur)
598                   (delete-region cpoint (point-at-bol))
599                   (forward-line)
600                   (setq cpoint (point)))
601               (forward-line)))
602           (delete-region cpoint (point-max)))
603         t)
604     nil))
605
606 ;; Silence byte-compiler.
607 (defvar gnus-registry-install)
608 (autoload 'gnus-registry-fetch-group "gnus-registry")
609 (autoload 'gnus-registry-fetch-groups "gnus-registry")
610 (autoload 'gnus-registry-add-group "gnus-registry")
611
612 (deffoo nnmairix-request-set-mark (group actions &optional server)
613   (when server
614     (nnmairix-open-server server))
615   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
616          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
617          (propto (gnus-group-get-parameter qualgroup 'propto t))
618          (corr (nnmairix-get-numcorr group server))
619          (folder (nnmairix-get-backend-folder group server)))
620     (save-excursion
621       (dolist (cur actions)
622         (let ((type (nth 1 cur))
623               (cmdmarks (nth 2 cur))
624               (range (gnus-uncompress-range (nth 0 cur)))
625               mid ogroup number method temp)
626           (when (and corr
627                      (not (zerop (cadr corr))))
628             (setq range (mapcar (lambda (arg)
629                                   (- arg (cadr corr)))
630                                 range)))
631           (when propmarks
632             (nnheader-message 7 "nnmairix: Setting marks...")
633               (dolist (article range)
634                 ;; get article (header) and extract message id
635                 ;; we try to determine as many original articles as possible
636                 (catch 'problem
637                   (nnmairix-call-backend "open-server" nnmairix-backend-server)
638                   (unless (gnus-request-head
639                            article
640                            (gnus-group-prefixed-name
641                             folder
642                             (list nnmairix-backend nnmairix-backend-server)))
643                     (nnheader-message
644                      3 "Unable to set mark: couldn't fetch article header for article number %d"
645                      article)
646                     (throw 'problem nil))
647                   (set-buffer nntp-server-buffer)
648                   (goto-char (point-min))
649                   (let ((case-fold-search t))
650                     (re-search-forward "^message-id:.*\\(<.+>\\)" nil t))
651                   (setq mid (match-string 1))
652                   (unless mid
653                     (nnheader-message
654                      3 "Unable to set mark: article number %d has no message-id header"
655                      article)
656                     (throw 'problem nil))
657                   ;; get original group. First try registry, then file path
658                   (setq ogroup
659                         (nnmairix-determine-original-group-from-registry mid))
660                   (unless (or ogroup
661                               nnmairix-only-use-registry)
662                     (setq ogroup
663                           (nnmairix-determine-original-group-from-path
664                            mid nnmairix-current-server))
665                     ;; if available and allowed, add this entry to the registry
666                     (when (and (boundp 'gnus-registry-install)
667                                gnus-registry-install)
668                       (dolist (cur ogroup)
669                         (unless (gnus-parameter-registry-ignore cur)
670                           (gnus-registry-add-group mid cur)))))
671                   (unless ogroup
672                     (nnheader-message
673                      3 "Unable to set mark: couldn't find original group for %s" mid)
674                     (throw 'problem nil))
675                   ;; store original groups with mid's. We cannot get
676                   ;; the article number immediately since this would
677                   ;; generate problems with maildir (articles might
678                   ;; get moved from /new to /cur and further marks
679                   ;; could then not be set)
680                   (dolist (cur ogroup)
681                     (setq temp (assoc cur
682                                       nnmairix-marks-cache))
683                     (if temp
684                         (nconc temp (list (list mid type cmdmarks)))
685                       (push (list cur (list mid type cmdmarks))
686                             nnmairix-marks-cache)))))
687               (nnheader-message 7 "nnmairix: Setting marks... done")))))))
688
689 (deffoo nnmairix-close-group (group &optional server)
690   (when server
691     (nnmairix-open-server server))
692   (let* ((qualgroup (gnus-group-prefixed-name group (list 'nnmairix nnmairix-current-server)))
693          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
694          method)
695     (when (and propmarks
696                nnmairix-marks-cache)
697       (when (or (eq nnmairix-propagate-marks-upon-close t)
698                 (and (eq nnmairix-propagate-marks-upon-close 'ask)
699                      (y-or-n-p "Propagate marks to original articles? ")))
700       (with-current-buffer gnus-group-buffer
701         (nnmairix-propagate-marks)
702         ;; update mairix group
703         (gnus-group-jump-to-group qualgroup)
704         (gnus-group-get-new-news-this-group))))))
705
706 (autoload 'nnimap-request-update-info-internal "nnimap")
707
708 (deffoo nnmairix-request-update-info (group info &optional server)
709 ;; propagate info from underlying IMAP folder to nnmairix group
710 ;; This is currently experimental and must be explicitly activated
711 ;; with nnmairix-propagate-marks-to-nnmairix-group
712   (when server
713     (nnmairix-open-server server))
714   (let* ((qualgroup (gnus-group-prefixed-name
715                     group
716                     (list 'nnmairix nnmairix-current-server)))
717          (readmarks (gnus-group-get-parameter qualgroup 'readmarks))
718          (propmarks (gnus-group-get-parameter qualgroup 'propmarks))
719          (folder (nnmairix-get-backend-folder group server))
720          (corr (nnmairix-get-numcorr group server))
721          (docorr (and corr (not (zerop (cadr corr)))))
722          (folderinfo `(,group 1 ((1 . 1))))
723          readrange marks)
724       (when (and propmarks
725                  nnmairix-propagate-marks-to-nnmairix-groups)
726         ;; these groups are not subscribed, so we have to ask the back end directly
727         (if (eq nnmairix-backend 'nnimap)
728             (nnimap-request-update-info-internal folder folderinfo nnmairix-backend-server)
729           (nnmairix-call-backend "request-update-info" folder folderinfo nnmairix-backend-server))
730         ;; set range of read articles
731         (gnus-info-set-read
732          info
733          (if docorr
734              (nnmairix-map-range
735               `(lambda (x) (+ x ,(cadr corr)))
736               (gnus-info-read folderinfo))
737            (gnus-info-read folderinfo)))
738         ;; set other marks
739         (gnus-info-set-marks
740          info
741          (if docorr
742              (mapcar (lambda (cur)
743                          (cons
744                           (car cur)
745                           (nnmairix-map-range
746                            `(lambda (x) (+ x ,(cadr corr)))
747                            (list (cadr cur)))))
748                      (gnus-info-marks folderinfo))
749            (gnus-info-marks folderinfo))))
750       (when (eq readmarks 'unread)
751         (gnus-info-set-read info nil))
752       (when (eq readmarks 'read)
753         (gnus-info-set-read info (gnus-active qualgroup))))
754   t)
755
756 (nnoo-define-skeleton nnmairix)
757
758
759 ;;; === Interactive functions
760
761 (defun nnmairix-create-search-group (server group query threads)
762   "Create on SERVER nnmairix search group GROUP with QUERY.
763 If THREADS is t, include whole threads from found messages.  If
764 called interactively, user will be asked for parameters."
765   (interactive
766    (list
767     (gnus-server-to-method (car (nnmairix-get-server)))
768     (read-string "Group name: ")
769     (read-string "Query: ")
770     (y-or-n-p "Include threads? ")))
771   (when (and (stringp query)
772              (string-match "\\s-" query))
773     (setq query (split-string query)))
774   (when (not (listp query))
775     (setq query (list query)))
776   (when (and server group query)
777     (save-excursion
778       (let ((groupname (gnus-group-prefixed-name group server))
779             info)
780         (set-buffer gnus-group-buffer)
781         (gnus-group-make-group group server)
782         (gnus-group-set-parameter groupname 'query  query)
783         (gnus-group-set-parameter groupname 'threads threads)
784         (nnmairix-update-and-clear-marks groupname)))))
785
786 (defun nnmairix-search-interactive ()
787   "Create mairix search interactively with the minibuffer."
788   (interactive)
789   (let ((char-header nnmairix-interactive-query-parameters)
790         header finished query achar)
791     (while (not finished)
792       (while (not achar)
793         (message "Query (%s): " (nnmairix-create-message-line-for-search))
794           (setq achar (read-char))
795           (when (not (assoc achar char-header))
796             (setq achar nil)))
797       (setq header (read-string
798                     (concat "Match " (nth 3 (assoc achar char-header)) " on: ")))
799         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
800         (setq finished (not (y-or-n-p "Add another search query? "))
801               achar nil))
802     (nnmairix-search
803      (mapconcat 'identity query " ")
804      (car (nnmairix-get-server))
805      (y-or-n-p "Include whole threads? "))))
806
807 (defun nnmairix-create-search-group-from-message ()
808   "Interactively create search group with query based on current message."
809   (interactive)
810   (let ((char-header nnmairix-interactive-query-parameters)
811         (server (nnmairix-backend-to-server gnus-current-select-method))
812          query achar header finished group threads cq)
813     (when (or (not (gnus-buffer-live-p gnus-article-buffer))
814               (not (gnus-buffer-live-p gnus-summary-buffer)))
815       (error "No article or summary buffer"))
816     (when (not server)
817       (error "No nnmairix server found for back end %s:%s"
818              (symbol-name (car gnus-current-select-method))
819              (nth 1 gnus-current-select-method)))
820     (while (not finished)
821       (save-excursion
822         (gnus-summary-toggle-header 1)
823         (while (not achar)
824           (message "Query (%s): " (nnmairix-create-message-line-for-search))
825           (setq achar (read-char))
826           (when (not (assoc achar char-header))
827             (setq achar nil)))
828         (set-buffer gnus-article-buffer)
829         (setq header nil)
830         (when (setq cq (nth 1 (assoc achar char-header)))
831           (setq header
832                 (nnmairix-replace-illegal-chars
833                  (gnus-fetch-field (nth 1 (assoc achar char-header))))))
834         (setq header (read-string
835                       (concat "Match " (nth 3 (assoc achar char-header)) " on: ")
836                       header))
837         (push  (concat (nth 2 (assoc achar char-header)) ":" header) query)
838         (setq finished (not (y-or-n-p "Add another search query? "))
839               achar nil)))
840     (setq threads (y-or-n-p "Include whole threads? "))
841     (setq group (read-string "Group name: "))
842     (set-buffer gnus-summary-buffer)
843     (message "Creating group %s on server %s with query %s." group
844              (gnus-method-to-server server) (mapconcat 'identity query " "))
845     (nnmairix-create-search-group server group query threads)))
846
847 (defun nnmairix-create-server-and-default-group ()
848   "Interactively create new nnmairix server with default search group.
849 All necessary information will be queried from the user."
850   (interactive)
851   (let* ((name (read-string "Name of the mairix server: "))
852         (server (completing-read "Back end server (TAB for completion): "
853                                  (nnmairix-get-valid-servers) nil 1))
854         (mairix (read-string "Command to call mairix: " "mairix"))
855         (defaultgroup (read-string "Default search group: "))
856         (backend (symbol-name (car (gnus-server-to-method server))))
857         (servername (nth 1 (gnus-server-to-method server)))
858         (hidden (and (string-match "^nn\\(imap\\|maildir\\)$" backend)
859                      (y-or-n-p
860                       "Does the back end server work with maildir++ (i.e. hidden directories)? ")))
861         create)
862
863     (apply (intern (format "%s-%s" backend "open-server"))
864            (list servername))
865
866     (when (and hidden
867                (string-match "^\\." defaultgroup))
868       (setq defaultgroup (substring defaultgroup 1)))
869     ;; Create default search group
870     (gnus-group-make-group
871      defaultgroup (list 'nnmairix name  (list 'nnmairix-backend (intern backend))
872                         (list 'nnmairix-backend-server servername)
873                         (list 'nnmairix-mairix-command mairix)
874                         (list 'nnmairix-hidden-folders hidden)
875                         (list 'nnmairix-default-group defaultgroup)))))
876
877 (defun nnmairix-group-change-query-this-group (&optional query)
878   "Set QUERY for group under cursor."
879   (interactive)
880   (let* ((group (gnus-group-group-name))
881          (method (gnus-find-method-for-group group))
882          (oldquery (gnus-group-get-parameter group 'query t)))
883     (if (eq (car method) 'nnmairix)
884         (progn
885           (when (listp oldquery)
886             (setq oldquery (mapconcat 'identity oldquery " ")))
887           (setq query (or query
888                           (read-string "New query: " oldquery)))
889           (when (stringp query)
890             (setq query (split-string query)))
891           (when query
892             (gnus-group-set-parameter group 'query query)
893             (nnmairix-update-and-clear-marks group)))
894       (error "This is no nnmairix group"))))
895
896
897 (defun nnmairix-group-toggle-threads-this-group (&optional threads)
898   "Toggle threads parameter for this group.
899 If THREADS is a positive number, set threads parameter to t.
900 If THREADS is a negative number, set it to nil."
901   (interactive)
902   (let ((group (gnus-group-group-name)))
903     (when (nnmairix-group-toggle-parameter
904            group 'threads "Threads" threads)
905       (nnmairix-update-and-clear-marks group))))
906
907 (defun nnmairix-group-toggle-propmarks-this-group (&optional propmarks)
908   "Toggle marks propagation for this group.
909 If PROPMARKS is a positive number, set parameter to t.
910 If PROPMARKS is a negative number, set it to nil."
911   (interactive)
912   (unless (nnmairix-check-mairix-version "maildirpatch")
913     (error "You need a mairix binary with maildir patch to use this feature.  See docs for details"))
914   (let ((group (gnus-group-group-name)))
915     (when (or (not (string= (gnus-group-short-name group)
916                             (cadr (assoc 'nnmairix-default-group
917                                         (gnus-find-method-for-group group)))))
918               (y-or-n-p "You should not activate marks propagation for the default \
919 search group.  Are you sure? "))
920       (nnmairix-group-toggle-parameter
921        group 'propmarks "Marks propagation" propmarks))))
922
923 (defun nnmairix-group-toggle-allowfast-this-group (&optional allowfast)
924   "Toggle fast entering for this group.
925 If ALLOWFAST is a positive number, set parameter to t.
926 If ALLOWFAST is a negative number, set it to nil."
927   (interactive)
928   (nnmairix-group-toggle-parameter
929    (gnus-group-group-name) 'allow-fast "Fast entering" allowfast))
930
931
932 (defun nnmairix-group-toggle-readmarks-this-group (&optional readmarks)
933   "Toggle read/unread marks for this group.
934 If READMARKS is a positive number, articles will always be read.
935 If READMARKS is a negative number, articles will always be unread.
936 If READMARKS is t or zero, marks will stay unchanged."
937   (interactive)
938   (let*  ((group (gnus-group-group-name))
939           (method (gnus-find-method-for-group group))
940           (readmarks (or readmarks
941                          (gnus-group-get-parameter group 'readmarks))))
942     (if (eq (car method) 'nnmairix)
943         (cond
944          ((or (and (numberp readmarks) (< readmarks 0))
945               (eq readmarks 'read))
946           (gnus-group-set-parameter group 'readmarks 'unread)
947           (nnheader-message 3 "Articles in %s always unread." group))
948          ((or (and (numberp readmarks) (> readmarks 0))
949               (not readmarks))
950               (gnus-group-set-parameter group 'readmarks 'read)
951               (nnheader-message 3 "Articles in %s always read." group))
952          (t
953           (gnus-group-set-parameter group 'readmarks nil)
954           (nnheader-message 3 "Read marks in %s stay unchanged." group)))
955       (error "This is no nnmairix group"))))
956
957
958 (defun nnmairix-search (query &optional server threads)
959   "Sends QUERY to nnmairix backend SERVER, using default its search group.
960
961 Default search group is automatically entered and results are shown.
962 If THREADS is t, enable threads.
963 If THREADS is a negative number, disable threads.
964 Otherwise, leave threads parameter as it is."
965   (interactive (list (read-string "Query: ")))
966   (when (not server)
967     (setq server (car (nnmairix-get-server))))
968   (if (not server)
969       (error "No opened nnmairix server found")
970     (setq server (gnus-server-to-method server)))
971   (nnmairix-open-server (nth 1 server))
972   (let* ((qualgroup (gnus-group-prefixed-name nnmairix-default-group
973                                               (list 'nnmairix (nth 1 server)))))
974     (set-buffer gnus-group-buffer)
975     (when (stringp query)
976       (setq query (split-string query)))
977     (gnus-group-set-parameter qualgroup 'query query)
978     (if (symbolp threads)
979         (when (eq threads 't)
980           (gnus-group-set-parameter qualgroup 'threads t))
981       (when (< threads 0)
982         (gnus-group-set-parameter qualgroup 'threads nil)))
983     (nnmairix-update-and-clear-marks qualgroup)
984     (unless (equal (gnus-active qualgroup) '(1 . 0))
985       (gnus-group-read-group nil t qualgroup))))
986
987 (defun nnmairix-search-thread-this-article ()
988   "Search thread for the current article.
989 This is effectively a shortcut for calling `nnmairix-search'
990 with m:msgid of the current article and enabled threads."
991   (interactive)
992   (let* ((server
993           (nnmairix-backend-to-server gnus-current-select-method))
994          mid)
995     (if server
996         (if (gnus-buffer-live-p gnus-article-buffer)
997             (progn
998               (with-current-buffer gnus-article-buffer
999                 (gnus-summary-toggle-header 1)
1000                 (setq mid (message-fetch-field "Message-ID")))
1001               (while (string-match "[<>]" mid)
1002                 (setq mid (replace-match "" t t mid)))
1003               (nnmairix-search (concat "m:" mid) server t))
1004           (message "No article buffer."))
1005       (error "No nnmairix server found for back end %s:%s"
1006              (symbol-name (car gnus-current-select-method))
1007              (nth 1 gnus-current-select-method)))))
1008
1009 (defun nnmairix-search-from-this-article ()
1010   "Search messages from sender of the current article.
1011 This is effectively a shortcut for calling `nnmairix-search' with
1012 f:current_from."
1013   (interactive)
1014   (let* ((server
1015           (nnmairix-backend-to-server gnus-current-select-method))
1016          from)
1017     (if server
1018         (if (gnus-buffer-live-p gnus-article-buffer)
1019             (progn
1020               (with-current-buffer gnus-article-buffer
1021                 (gnus-summary-toggle-header 1)
1022                 (setq from (cadr (gnus-extract-address-components
1023                                   (gnus-fetch-field "From"))))
1024                 (nnmairix-search (concat "f:" from) server -1)))
1025           (message "No article buffer."))
1026       (error "No nnmairix server found for back end %s:%s"
1027              (symbol-name (car gnus-current-select-method))
1028              (nth 1 gnus-current-select-method)))))
1029
1030
1031 (defun nnmairix-purge-old-groups (&optional dontask server)
1032   "Delete mairix search groups which are no longer used.
1033
1034 You may want to call this from time to time if you are creating
1035 and deleting lots of nnmairix groups.  If DONTASK is t, do not ask
1036 before deleting a group on the back end.  SERVER specifies nnmairix server."
1037   (interactive)
1038   (let ((server (or server
1039                     (gnus-server-to-method (car (nnmairix-get-server))))))
1040     (if (nnmairix-open-server (nth 1 server))
1041         (when (nnmairix-call-backend
1042                "request-list" nnmairix-backend-server)
1043           (let (cur qualgroup folder)
1044             (with-current-buffer nntp-server-buffer
1045               (goto-char (point-min))
1046               (while (re-search-forward nnmairix-group-regexp (point-max) t)
1047                 (setq cur (match-string 0)
1048                       qualgroup (gnus-group-prefixed-name
1049                                  (match-string 1) server))
1050                 (when (not (and (gnus-group-entry qualgroup)
1051                                 (string= cur
1052                                          (gnus-group-get-parameter
1053                                           qualgroup 'folder))))
1054                   (when (or dontask
1055                             (y-or-n-p
1056                              (concat "Delete group " cur
1057                                      " on server " nnmairix-backend-server "? ")))
1058                     (nnmairix-call-backend
1059                      "request-delete-group" cur t nnmairix-backend-server)))))))
1060       (message "Couldn't open server %s" (nth 1 server)))))
1061
1062
1063 (defun nnmairix-update-database (&optional servers)
1064   "Call mairix for updating the database for SERVERS.
1065
1066 If SERVERS is nil, do update for all nnmairix servers.  Mairix
1067 will be called asynchronously unless
1068 `nnmairix-mairix-synchronous-update' is t.  Mairix will be called
1069 with `nnmairix-mairix-update-options'."
1070   (interactive)
1071   (let ((servers (or servers
1072                      (nnmairix-get-nnmairix-servers)))
1073         args cur commandsplit)
1074     (while servers
1075       (setq cur (car (pop servers)))
1076       (nnmairix-open-server
1077        (nth 1 (gnus-server-to-method cur)))
1078       (setq commandsplit (split-string nnmairix-mairix-command))
1079       (nnheader-message 7 "Updating mairix database for %s..." cur)
1080       (if nnmairix-mairix-synchronous-update
1081           (progn
1082             (setq args (append (list (car commandsplit) nil
1083                                      (get-buffer nnmairix-mairix-output-buffer)
1084                                      nil)))
1085             (if (> (length commandsplit) 1)
1086                 (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1087               (setq args (append args nnmairix-mairix-update-options)))
1088             (apply 'call-process args)
1089             (nnheader-message 7 "Updating mairix database for %s... done" cur))
1090         (progn
1091           (setq args (append (list cur (get-buffer nnmairix-mairix-output-buffer)
1092                                    (car commandsplit))))
1093           (if (> (length commandsplit) 1)
1094               (setq args (append args (cdr commandsplit) nnmairix-mairix-update-options))
1095             (setq args (append args nnmairix-mairix-update-options)))
1096           (set-process-sentinel (apply 'start-process args)
1097                                 'nnmairix-sentinel-mairix-update-finished))))))
1098
1099 (defun nnmairix-group-delete-recreate-this-group ()
1100   "Deletes and recreates group on the back end.
1101 You can use this function on nnmairix groups which continuously
1102 show wrong article counts."
1103   (interactive)
1104   (let* ((group (gnus-group-group-name))
1105          (method (gnus-find-method-for-group group)))
1106     (unless (eq (car method) 'nnmairix)
1107       (error "This is not a nnmairix group"))
1108     (when (y-or-n-p
1109            (format "Really recreate group %s on the back end? " group))
1110       (nnmairix-delete-recreate-group group)
1111       (gnus-group-get-new-news-this-group))))
1112
1113 (defun nnmairix-propagate-marks (&optional server)
1114   "Propagate marks from nnmairix group to original articles.
1115 Unless SERVER is explicitly specified, will use the last opened
1116 nnmairix server. Only marks from current session will be set."
1117   (interactive)
1118   (if server
1119       (nnmairix-open-server server)
1120     (unless (eq (car gnus-current-select-method) 'nnmairix)
1121       (if nnmairix-current-server
1122           (nnmairix-open-server nnmairix-current-server)
1123         (error "No opened nnmairix server"))))
1124   (if nnmairix-marks-cache
1125       (let (number ogroup number-cache method mid-marks temp)
1126         ;; first we get the article numbers
1127         (catch 'problem
1128           (while (setq ogroup (pop nnmairix-marks-cache))
1129             (while (setq mid-marks (pop (cdr ogroup)))
1130               (setq number
1131                     (cdr
1132                      (gnus-request-head (car mid-marks) (car ogroup))))
1133               (unless number
1134                 (nnheader-message
1135                  3 "Unable to set mark: couldn't determine article number for %s in %s"
1136                  (car mid-marks) (car ogroup))
1137                 (throw 'problem nil))
1138               (setq temp (assoc (car ogroup) number-cache))
1139               (if temp
1140                   (catch 'done
1141                     (dolist (cur (cdr temp))
1142                       (when (equal (cdr cur) (list (nth 1 mid-marks) (nth 2 mid-marks)))
1143                         (nconc (car cur) (list number))
1144                         (throw 'done nil)))
1145                     (nconc temp (list (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))))
1146                 (push (list (car ogroup) (list (list number) (nth 1 mid-marks) (nth 2 mid-marks)))
1147                       number-cache)))))
1148         ;; now we set the marks
1149         (with-current-buffer gnus-group-buffer
1150           (nnheader-message 5 "nnmairix: Propagating marks...")
1151           (dolist (cur number-cache)
1152             (setq method (gnus-find-method-for-group (car cur)))
1153             (apply (intern (format "%s-%s"
1154                                    (symbol-name (car method))
1155                                    "request-set-mark"))
1156                    (gnus-group-short-name (car cur))
1157                    (cdr cur)
1158                    (list (nth 1 method)))
1159             (gnus-group-jump-to-group (car cur))
1160             (gnus-group-get-new-news-this-group)))
1161         (nnheader-message 5 "nnmairix: Propagating marks... done"))
1162     (nnheader-message 3 "No marks to propagate.")))
1163
1164 (defun nnmairix-update-groups (servername &optional skipdefault updatedb)
1165   "Update all search groups on SERVERNAME.
1166 If SKIPDEFAULT is t, the default search group will not be
1167 updated.
1168 If UPDATEDB is t, database for SERVERNAME will be updated first."
1169   (interactive (list (completing-read "Update groups on server: "
1170                                 (nnmairix-get-nnmairix-servers))))
1171   (save-excursion
1172     (when (string-match ".*:\\(.*\\)" servername)
1173       (setq servername (match-string 1 servername)))
1174     (if (not (assoc (format "nnmairix:%s" servername)
1175                     (nnmairix-get-nnmairix-servers)))
1176         (nnheader-message 3 "Server %s not opened" servername)
1177       (when updatedb
1178         (let ((nnmairix-mairix-synchronous-update t))
1179           (nnmairix-update-database
1180            (list (list (format "nnmairix:%s" servername))))))
1181       (let ((groups (nnmairix-get-groups-from-server servername))
1182             default)
1183         (when skipdefault
1184           (setq default
1185                 (format "nnmairix+%s:%s"
1186                         servername
1187                         (cadr
1188                          (assoc 'nnmairix-default-group
1189                                 (gnus-server-to-method
1190                                  (format "nnmairix:%s" servername)))))))
1191         (dolist (cur groups)
1192           (unless (and skipdefault
1193                        (string= (car cur) default))
1194             (gnus-group-jump-to-group (car cur))
1195             (gnus-group-mark-group 1)))
1196         (gnus-group-get-new-news-this-group)))))
1197
1198 (defun nnmairix-remove-tick-mark-original-article ()
1199   "Remove tick mark from original article.
1200 Marks propagation has to be enabled for this to work."
1201   (interactive)
1202   (unless (eq (car gnus-current-select-method) 'nnmairix)
1203     (error "Not in a nnmairix group"))
1204   (save-excursion
1205     (let ((mid (mail-header-message-id (gnus-summary-article-header)))
1206           groups cur)
1207       (when mid
1208         (setq groups (nnmairix-determine-original-group-from-registry mid))
1209         (unless (or groups
1210                     nnmairix-only-use-registry)
1211           (setq groups
1212                 (nnmairix-determine-original-group-from-path mid nnmairix-current-server)))
1213         (unless groups
1214           (error "Couldn't find original article"))
1215         (dolist (cur groups)
1216           (push `(,cur (,mid del (tick))) nnmairix-marks-cache))
1217         (nnheader-message 5 "Will remove tick mark for %s upon closing." mid)))))
1218
1219 ;;; ==== Helper functions
1220
1221 (defun nnmairix-request-group-with-article-number-correction (folder qualgroup)
1222   "Request FOLDER on back end for nnmairix QUALGROUP and article number correction."
1223   (save-excursion
1224     (nnmairix-call-backend "request-group" folder nnmairix-backend-server)
1225     (set-buffer nnmairix-mairix-output-buffer)
1226     (goto-char (point-min))
1227     (re-search-forward "^Matched.*messages")
1228     (nnheader-message 7 (match-string 0))
1229     (set-buffer nntp-server-buffer)
1230     (goto-char (point-min))
1231     (let ((status (read (current-buffer)))
1232           (total (read (current-buffer)))
1233           (low (read (current-buffer)))
1234           (high (read (current-buffer)))
1235           (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1236       (if (= status 211)
1237           (progn
1238             ;; Article number correction
1239             (if (and corr
1240                      (> (+ (car (cddr corr)) high) 0))
1241                 (progn
1242                   (when (car corr) ;Group has changed
1243                     (setq corr
1244                           (list nil
1245                                 (car (cddr corr))
1246                                 (+ (car (cddr corr)) high)))
1247                     (gnus-group-set-parameter
1248                      qualgroup 'numcorr corr))
1249                   (setq low (+ low (cadr corr))
1250                         high (+ high (cadr corr))))
1251               (when (member nnmairix-backend
1252                             nnmairix-delete-and-create-on-change)
1253                 (gnus-group-set-parameter
1254                  qualgroup 'numcorr (list nil 0 high))))
1255             (erase-buffer)
1256             (insert (format "%d %d %d %d %s" status total low high
1257                             (gnus-group-real-name qualgroup)))
1258             t)
1259         (progn
1260           (nnheader-report
1261            'nnmairix "Error calling back end on group %s" folder)
1262           nil)))))
1263
1264 (defun nnmairix-call-mairix-binary (command folder searchquery threads)
1265   "Call mairix binary with COMMAND, using FOLDER and SEARCHQUERY.
1266 If THREADS is non-nil, enable full threads."
1267   (let ((args (cons (car command) '(nil t nil))))
1268     (with-current-buffer
1269        (get-buffer-create nnmairix-mairix-output-buffer)
1270       (erase-buffer)
1271       (when (> (length command) 1)
1272         (setq args (append args (cdr command))))
1273       (when nnmairix-mairix-search-options
1274         (setq args (append args nnmairix-mairix-search-options)))
1275       ;; If we have a patched mairix binary, call it with "-c"
1276       (when (nnmairix-check-mairix-version "maildirpatch")
1277         (setq args (append args '("-c"))))
1278       (when threads
1279         (setq args (append args '("-t"))))
1280       (apply 'call-process
1281              (append args (list "-o" folder) searchquery)))))
1282
1283 (defun nnmairix-call-mairix-binary-raw (command query)
1284   "Call mairix binary with COMMAND and QUERY in raw mode."
1285   (let ((args (cons (car command) '(nil t nil))))
1286     (with-current-buffer
1287        (get-buffer-create nnmairix-mairix-output-buffer)
1288       (erase-buffer)
1289       (when (> (length command) 1)
1290         (setq args (append args (cdr command))))
1291       (setq args (append args '("-r")))
1292       (apply 'call-process
1293              (append args query)))))
1294
1295 (defun nnmairix-get-server ()
1296   "If there exists just one nnmairix server, return its value.
1297 Otherwise, ask user for server."
1298   (let ((openedserver (nnmairix-get-nnmairix-servers)))
1299     (when (not openedserver)
1300       (error "No opened nnmairix server found"))
1301     (if (> (length openedserver) 1)
1302         (progn
1303           (while
1304               (equal '("")
1305                   (setq nnmairix-last-server
1306                         (list (completing-read "Server: " openedserver nil 1
1307                                                (or nnmairix-last-server
1308                                                    "nnmairix:"))))))
1309           nnmairix-last-server)
1310       (car openedserver))))
1311
1312 (defun nnmairix-get-nnmairix-servers (&optional all)
1313   "Return available nnmairix servers.
1314 If ALL is t, return also the unopened/failed ones."
1315   (let ((alist gnus-opened-servers)
1316         server openedserver)
1317     (while alist
1318       (setq server (pop alist))
1319       (when (and server
1320                  (or all
1321                      (eq (cadr server) 'ok))
1322                  (eq (caar server) 'nnmairix)
1323                  (not (member (car server) gnus-ephemeral-servers)))
1324         (setq server
1325               (concat (symbol-name (caar server)) ":" (nth 1 (car server))))
1326         (push (list server) openedserver)))
1327     openedserver))
1328
1329 (defun nnmairix-get-valid-servers ()
1330   "Return list of valid back end servers for nnmairix groups."
1331   (let ((alist gnus-opened-servers)
1332         (mairixservers (nnmairix-get-nnmairix-servers t))
1333         server mserver openedserver occ cur)
1334     ;; Get list of all nnmairix backends (i.e. backends which are
1335     ;; already occupied)
1336     (dolist (cur mairixservers)
1337       (push
1338        (concat
1339         (symbol-name
1340          (cadr (assoc 'nnmairix-backend
1341                       (gnus-server-to-method (car cur)))))
1342          ":"
1343          (cadr (assoc 'nnmairix-backend-server
1344                       (gnus-server-to-method (car cur)))))
1345         occ))
1346     (while alist
1347       (setq server (pop alist))
1348       (setq mserver (gnus-method-to-server (car server)))
1349       ;; If this is the native server, convert it to the real server
1350       ;; name to avoid confusion
1351       (when (string= mserver "native")
1352         (setq mserver (format "%s:%s"
1353                               (caar server)
1354                               (nth 1 (car server)))))
1355       (when (and server
1356                  (eq (cadr server) 'ok)
1357                  (member (caar server) nnmairix-valid-backends)
1358                  (not (member (car server) gnus-ephemeral-servers))
1359                  (not (member (gnus-method-to-server (car server)) occ)))
1360         (push
1361          (list mserver)
1362          openedserver)))
1363     openedserver))
1364
1365 (defun nnmairix-get-groups-from-server (servername)
1366   "Return all groups for nnmairix server SERVERNAME."
1367   (let ((searchstring (format "nnmairix\\+%s:" servername))
1368         groups)
1369     (dolist (cur gnus-newsrc-alist)
1370       (when (string-match searchstring
1371                           (car cur))
1372         (push (list (car cur)) groups)))
1373     groups))
1374
1375 (defun nnmairix-call-backend (func &rest args)
1376   "Call a function FUNC on backend with ARGS."
1377   (apply (intern (format "%s-%s" (symbol-name nnmairix-backend) func)) args))
1378
1379 (defun nnmairix-get-backend-folder (group &optional server)
1380   "Return back end GROUP from nnmairix group on SERVER."
1381   (let* ((qualgroup (if server
1382                         (gnus-group-prefixed-name group (list 'nnmairix server))
1383                       group))
1384          (folder (gnus-group-get-parameter qualgroup 'folder)))
1385     folder))
1386
1387 (defun nnmairix-get-numcorr (group &optional server)
1388   "Return values for article number correction nnmairix GROUP on SERVER."
1389   (let* ((qualgroup (if server
1390                         (gnus-group-prefixed-name group (list 'nnmairix server))
1391                       group))
1392          (corr (gnus-group-get-parameter qualgroup 'numcorr t)))
1393     corr))
1394
1395
1396 (defun nnmairix-rename-files-consecutively (path)
1397   "Rename all nnml mail files in PATH so that they have consecutive numbers.
1398 This should correct problems of wrong article counts when using
1399 nnmairix with nnml backends."
1400   (let* ((files
1401          (sort
1402           (mapcar 'string-to-number
1403                   (directory-files path nil "[0-9]+" t))
1404           '<))
1405          (lastplusone (car files))
1406          (path (file-name-as-directory path)))
1407     (dolist (cur files)
1408       (when (not (= cur lastplusone))
1409         (rename-file (concat path
1410                              (number-to-string cur))
1411                      (concat path
1412                              (number-to-string lastplusone)))
1413         (setq cur lastplusone))
1414       (setq lastplusone (1+ cur)))))
1415
1416 (defun nnmairix-replace-group-and-numbers (articles backendgroup mairixgroup numc)
1417   "Replace folder names in Xref header and correct article numbers.
1418 Do this for all ARTICLES on BACKENDGROUP.  Replace using
1419 MAIRIXGROUP.  NUMC contains values for article number correction."
1420   (let ((buf (get-buffer-create " *nnmairix buffer*"))
1421         (corr (not (zerop numc)))
1422         (name (buffer-name nntp-server-buffer))
1423         header cur xref)
1424     (with-current-buffer buf
1425       (erase-buffer)
1426       (set-buffer nntp-server-buffer)
1427       (goto-char (point-min))
1428       (nnheader-message 7 "nnmairix: Rewriting headers...")
1429       (mapc
1430        (lambda (article)
1431          (when (or (looking-at (number-to-string article))
1432                    (nnheader-find-nov-line article))
1433            (setq cur (nnheader-parse-nov))
1434            (when corr
1435              (setq article (+ (mail-header-number cur) numc))
1436              (mail-header-set-number cur article))
1437            (setq xref (mail-header-xref cur))
1438            (when (and (stringp xref)
1439                       (string-match (format "[ \t]%s:[0-9]+" backendgroup) xref))
1440              (setq xref (replace-match (format " %s:%d" mairixgroup article) t nil xref))
1441              (mail-header-set-xref cur xref))
1442            (set-buffer buf)
1443            (nnheader-insert-nov cur)
1444            (set-buffer nntp-server-buffer)
1445            (when (not (eobp))
1446              (forward-line 1))))
1447        articles)
1448       (nnheader-message 7 "nnmairix: Rewriting headers... done")
1449       (kill-buffer nntp-server-buffer)
1450       (set-buffer buf)
1451       (rename-buffer name)
1452       (setq nntp-server-buffer buf))))
1453
1454 (defun nnmairix-backend-to-server (server)
1455   "Return nnmairix server most probably responsible for back end SERVER.
1456 User will be asked if this cannot be determined.  Result is saved in
1457 parameter 'indexed-servers of corresponding default search
1458 group."
1459   (let ((allservers (nnmairix-get-nnmairix-servers))
1460         mairixserver found defaultgroup)
1461     (if (> (length allservers) 1)
1462         (progn
1463           ;; If there is more than one nnmairix server, we go through them
1464           (while (and allservers (not found))
1465             (setq mairixserver (gnus-server-to-method (car (pop allservers))))
1466             ;; First we look if SERVER is the backend of current nnmairix server
1467             (setq found (and (eq (cadr (assoc 'nnmairix-backend mairixserver))
1468                                  (car server))
1469                              (string= (cadr (assoc 'nnmairix-backend-server mairixserver))
1470                                       (nth 1 server))))
1471             ;; If that's not the case, we look at 'indexed-servers
1472             ;; variable in default search group
1473             (when (not found)
1474               (setq defaultgroup (cadr (assoc 'nnmairix-default-group mairixserver)))
1475               (setq found (member (gnus-method-to-server server)
1476                                   (gnus-group-get-parameter
1477                                    (gnus-group-prefixed-name defaultgroup
1478                                                              mairixserver)
1479                                    'indexed-servers t)))))
1480           ;; If still not found, we ask user
1481           (when (not found)
1482             (setq mairixserver
1483                   (gnus-server-to-method
1484                    (completing-read
1485                     (format "Cannot determine which nnmairix server indexes %s. Please specify: "
1486                             (gnus-method-to-server server))
1487                     (nnmairix-get-nnmairix-servers) nil nil "nnmairix:")))
1488             ;; Save result in parameter of default search group so that
1489             ;; we don't have to ask again
1490             (setq defaultgroup (gnus-group-prefixed-name
1491                                 (cadr (assoc 'nnmairix-default-group mairixserver)) mairixserver))
1492             (gnus-group-set-parameter
1493              defaultgroup
1494              'indexed-servers
1495              (append (gnus-group-get-parameter defaultgroup 'indexed-servers t)
1496                      (list (gnus-method-to-server server)))))
1497           mairixserver)
1498       ;; If there is just one (or none) nnmairix server:
1499       (gnus-server-to-method (caar allservers)))))
1500
1501
1502 (defun nnmairix-delete-recreate-group (group)
1503   "Delete and recreate folder from GROUP on the back end."
1504   (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1505     (let ((folder (gnus-group-get-parameter group 'folder)))
1506       (if (string-match nnmairix-group-regexp folder)
1507           (progn
1508             (nnmairix-call-backend "open-server"
1509                                    nnmairix-backend-server)
1510             (nnmairix-call-backend "request-delete-group"
1511                                    folder t nnmairix-backend-server)
1512             (nnmairix-call-backend "request-create-group"
1513                                    folder nnmairix-backend-server))
1514         (error "`nnmairix-delete-recreate-group' called on \
1515 non-mairix group.  Check folder parameter")))))
1516
1517 (defun nnmairix-update-and-clear-marks (group &optional method)
1518   "Update group and clear all marks from GROUP using METHOD."
1519   (let ((method (or method
1520                     (gnus-find-method-for-group group)))
1521         (corr (gnus-group-get-parameter group 'numcorr t))
1522         info)
1523     (unless (or (gnus-group-prefixed-p group)
1524                 (not method))
1525       (setq group (gnus-group-prefixed-name group method)))
1526     (if (eq (nth 0 method) 'nnmairix)
1527         (save-excursion
1528           (nnmairix-open-server (nth 1 method))
1529           (set-buffer gnus-group-buffer)
1530           ;; (gnus-group-set-parameter group 'propmarks nil)
1531           (setq info (gnus-get-info group))
1532           ;; Clear active and info
1533           (gnus-set-active group nil)
1534           (gnus-info-clear-data info)
1535           ;; Delete and re-create group if needed
1536           (nnmairix-delete-recreate-group group)
1537           ;; set flag that group has changed for article number correction
1538           (when (member nnmairix-backend nnmairix-delete-and-create-on-change)
1539             (when corr
1540               (setcar corr t)
1541               (gnus-group-set-parameter group 'numcorr corr)))
1542           (gnus-group-jump-to-group group)
1543           (gnus-group-get-new-news-this-group))
1544       (error "`nnmairix-update-and-clear-marks' called with non-nnmairix group"))))
1545
1546 (defun nnmairix-sentinel-mairix-update-finished (proc status)
1547   "Sentinel for mairix update process PROC with STATUS."
1548   (if (equal status "finished\n")
1549       (nnheader-message 7 "Updating mairix database for %s... done" proc)
1550     (error "There was an error updating the mairix database for server %s.  \
1551 See %s for details" proc nnmairix-mairix-output-buffer)))
1552
1553 (defun nnmairix-create-message-line-for-search ()
1554   "Create message line for interactive query in minibuffer."
1555   (mapconcat
1556    (function
1557     (lambda (cur)
1558       (format "%c=%s" (car cur) (nth 3 cur))))
1559    nnmairix-interactive-query-parameters ","))
1560
1561 (defun nnmairix-replace-illegal-chars (header)
1562   "Replace illegal characters in HEADER for mairix query."
1563   (when header
1564     (if (> emacs-major-version 20)
1565         (while (string-match "[^-.@/,& [:alnum:]]" header)
1566           (setq header (replace-match "" t t header)))
1567       (while (string-match "[[]{}:<>]" header)
1568         (setq header (replace-match "" t t header))))
1569     (while (string-match "[-& ]" header)
1570       (setq header (replace-match "," t t header)))
1571   header))
1572
1573 (defun nnmairix-group-toggle-parameter (group parameter description &optional par)
1574   "Toggle on GROUP a certain PARAMETER.
1575 DESCRIPTION will be shown to the user with the activation
1576 status.  If PAR is a positive number, the group parameter will be
1577 set to t and to nil otherwise."
1578   (let* ((method (gnus-find-method-for-group group))
1579          (par (or par
1580                   (not (gnus-group-get-parameter group parameter)))))
1581     (if (eq (car method) 'nnmairix)
1582         (progn
1583           (when (numberp par)
1584             (setq par (> par 0)))
1585           (gnus-group-set-parameter group parameter par)
1586           (if par
1587               (message "%s activated for group %s" description group)
1588             (message "%s deactivated for group %s" description group))
1589           t)
1590       (error "This is no nnmairix group")
1591       nil)))
1592
1593 ;; Search for original article helper functions
1594
1595 (defun nnmairix-goto-original-article (&optional no-registry)
1596   "Jump to the original group and display article.
1597 The original group of the article is first determined with the
1598 registry (if enabled).  If the registry is not enabled or did not
1599 find the article or the prefix NO-REGISTRY is non-nil, this
1600 function will try to determine the original group form the path
1601 of the mail file.  The path is obtained through another mairix
1602 search in raw mode."
1603   (interactive "P")
1604   (when (not (eq (car gnus-current-select-method) 'nnmairix))
1605     (let ((method (gnus-find-method-for-group gnus-newsgroup-name)))
1606       (if (eq (car method) 'nnmairix)
1607           (nnmairix-open-server (nth 1 method))
1608         (error "Not in a nnmairix group"))))
1609   (when (not (gnus-buffer-live-p gnus-article-buffer))
1610     (error "No article buffer available"))
1611   (let ((server (nth 1 gnus-current-select-method))
1612         mid rval group allgroups)
1613     ;; get message id
1614     (with-current-buffer gnus-article-buffer
1615       (gnus-summary-toggle-header 1)
1616       (setq mid (message-fetch-field "Message-ID"))
1617       ;; first check the registry (if available)
1618       (unless no-registry
1619         (setq allgroups (nnmairix-determine-original-group-from-registry mid)))
1620       (unless (or allgroups
1621                   nnmairix-only-use-registry)
1622         ;; registry was not available or did not find article
1623         ;; so we search again with mairix in raw mode to get filename
1624         (setq allgroups
1625               (nnmairix-determine-original-group-from-path mid server))
1626         ;; if available and allowed, add this entry to the registry
1627         (when (and (not no-registry)
1628                    (boundp 'gnus-registry-install)
1629                    gnus-registry-install)
1630           (dolist (cur allgroups)
1631             (unless (gnus-parameter-registry-ignore cur)
1632               (gnus-registry-add-group mid cur)))))
1633       (if (> (length allgroups) 1)
1634           (setq group
1635                 (completing-read
1636                  "Message exists in more than one group. Choose: "
1637                  allgroups nil t))
1638         (setq group (car allgroups))))
1639     (if group
1640         ;; show article in summary buffer
1641         (nnmairix-show-original-article group mid)
1642       (nnheader-message 3 "Couldn't find original article"))))
1643
1644 (defun nnmairix-determine-original-group-from-registry (mid)
1645   "Try to determinale original group for message-id MID from the registry."
1646   (when (and (boundp 'gnus-registry-install)
1647              gnus-registry-install)
1648     (unless (string-match "^<" mid)
1649       (set mid (concat "<" mid)))
1650     (unless (string-match ">$" mid)
1651       (set mid (concat mid ">")))
1652     (gnus-registry-fetch-groups mid)))
1653
1654 (defun nnmairix-determine-original-group-from-path (mid server)
1655   "Determine original group(s) for message-id MID from the file path.
1656 The file path is obtained through a mairix search for the id on
1657 SERVER."
1658   (nnmairix-open-server server)
1659   (while (string-match "[<>]" mid)
1660     (setq mid (replace-match "" t t mid)))
1661   ;; mairix somehow does not like '$' in message-id
1662   (when (string-match "\\$" mid)
1663     (setq mid (concat mid "=")))
1664   (while (string-match "\\$" mid)
1665     (setq mid (replace-match "=," t t mid)))
1666   (let (allgroups)
1667     (if (zerop (nnmairix-call-mairix-binary-raw
1668                 (split-string nnmairix-mairix-command)
1669                 (list (concat "m:" mid))))
1670         (with-current-buffer nnmairix-mairix-output-buffer
1671           (goto-char (point-min))
1672           (while (re-search-forward "^/.*$" nil t)
1673             (push (nnmairix-get-group-from-file-path (match-string 0))
1674                   allgroups)
1675             (forward-line 1)))
1676       (error "Mairix could not find original article.  See buffer %s for details"
1677              nnmairix-mairix-output-buffer))
1678     allgroups))
1679
1680 (defun nnmairix-get-group-from-file-path (file)
1681   "Get group by parsing the message location FILE."
1682   (let (path filename serverbase group maildirflag allgroups)
1683     (string-match "^\\(.*\\)/\\(.*?\\)$" file)
1684     (setq path (expand-file-name (match-string 1 file)))
1685     (setq filename (match-string 2 file))
1686     ;; when we deal with maildir, remove cur/new/tmp from path
1687     (setq maildirflag (string-match ".+\\..+\\..+" filename))
1688     (when maildirflag
1689       (setq path
1690             (replace-regexp-in-string
1691              ".*\\(/cur\\|/new\\|/tmp\\)$" "" path t t 1)))
1692     ;; we first check nnml and nnmaildir servers
1693     (setq
1694      group
1695      (catch 'found
1696        (dolist (cur gnus-opened-servers)
1697          (when (or (and (not maildirflag)
1698                         (eq (caar cur) 'nnml))
1699                    (and maildirflag
1700                         (eq (caar cur) 'nnmaildir)))
1701            ;; get base path from server
1702            (if maildirflag
1703                (setq serverbase (cadr (assoc 'directory (car cur))))
1704              (setq serverbase (cadr (assoc 'nnml-directory (car cur))))
1705              (unless serverbase
1706                (setq serverbase nnml-directory)))
1707            (setq serverbase (file-name-as-directory
1708                              (expand-file-name serverbase)))
1709            (when (string-match (concat serverbase "\\(.*\\)") path)
1710              ;; looks good - rest of the path should be the group
1711              (setq group (match-string 1 path))
1712              (when (string-match "/$" group)
1713                (setq group (replace-match "" t t group)))
1714              (unless maildirflag
1715                ;; for nnml: convert slashes to dots
1716                (while (string-match "/" group)
1717                  (setq group (replace-match "." t t group))))
1718              (setq group (gnus-group-prefixed-name group (car cur)))
1719              ;; check whether this group actually exists
1720              (when (gnus-group-entry group)
1721                (throw 'found group)))))))
1722     (unless group
1723       ;; we haven't found it yet --> look for nnimap groups. Assume
1724       ;; last element of the path is the group. This might fail since
1725       ;; IMAP servers may present groups to the client in arbitrary
1726       ;; ways...
1727       (string-match "^.*/\\.?\\(.*\\)$" path)
1728       (setq group (match-string 1 path))
1729       ;; convert dots to slashes (nested group)
1730       (while (string-match "\\." group)
1731         (setq group (replace-match "/" t t group)))
1732       (dolist (cur gnus-opened-servers)
1733         (when (eq (caar cur) 'nnimap)
1734           (when (gnus-group-entry
1735                  (gnus-group-prefixed-name group (car cur)))
1736             (push
1737              (gnus-group-prefixed-name group (car cur))
1738              allgroups))))
1739       (if (> (length allgroups) 1)
1740           (setq group (completing-read
1741                        "Group %s exists on more than one IMAP server. Choose: "
1742                        allgroups nil t))
1743         (setq group (car allgroups))))
1744     group))
1745
1746 (defun nnmairix-show-original-article (group mid)
1747   "Switch to GROUP and display Article with message-id MID."
1748   (unless (string-match "^<" mid)
1749     (set mid (concat "<" mid)))
1750   (unless (string-match ">$" mid)
1751     (set mid (concat mid ">")))
1752   (when (string-match "Summary" (buffer-name (current-buffer)))
1753     (gnus-summary-exit))
1754   (pop-to-buffer gnus-group-buffer)
1755   (gnus-group-jump-to-group group)
1756   (gnus-summary-read-group group 1 t)
1757   (gnus-summary-refer-article mid)
1758   (gnus-summary-limit-to-headers (format "message-id: %s" mid))
1759   (gnus-summary-select-article)
1760   ;; Force redisplay
1761   (gnus-summary-show-article)
1762   (nnheader-message 5 "Switched to group %s." group))
1763
1764 (defun nnmairix-map-range (func range)
1765   "Map function FUNC on all members of RANGE."
1766   (cond
1767    ((numberp range)
1768     (funcall func range))
1769    (t
1770     (mapcar (lambda (cur)
1771               (cond
1772                ((listp cur)
1773                 (cons
1774                  (funcall func (car cur))
1775                  (funcall func (cdr cur))))
1776                ((numberp cur)
1777                 (funcall func cur))))
1778             range))))
1779
1780 (defun nnmairix-check-mairix-version (version &optional server)
1781   "Check mairix VERSION on SERVER.
1782 If VERSION is a number: specifies the minimum version.
1783 If VERSION is a string: must be contained in mairix version output."
1784   (unless server
1785     (setq server nnmairix-current-server))
1786   (let ((versionstring (cadr (assoc server nnmairix-version-output))))
1787     (unless versionstring
1788       ;; call "mairix -V" to get the version string
1789       (with-temp-buffer
1790         (setq versionstring
1791               (let* ((commandsplit (split-string nnmairix-mairix-command))
1792                      (args (append (list (car commandsplit))
1793                                   `(nil t nil) (cdr commandsplit) '("-V"))))
1794               (apply 'call-process args)
1795               (goto-char (point-min))
1796               (re-search-forward "mairix.*")
1797               (match-string 0))))
1798       ;; save version string for current session
1799       (setq nnmairix-version-output
1800             (append nnmairix-version-output
1801                     (list (list server versionstring)))))
1802     (cond
1803      ((stringp version)
1804       (string-match version versionstring))
1805      ((numberp version)
1806       (<= version (string-to-number
1807                    (progn
1808                      (string-match "mairix \\([0-9\\.]+\\)" versionstring)
1809                      (match-string 1 versionstring))))))))
1810
1811 ;; ==== Widget stuff
1812
1813 (defvar nnmairix-widgets)
1814 (defvar nnmairix-widgets-values nil)
1815
1816 (defun nnmairix-widget-search-from-this-article ()
1817   "Create mairix query based on current article using graphical widgets."
1818   (interactive)
1819   (nnmairix-widget-search
1820    (nnmairix-widget-get-values)))
1821
1822 (defun nnmairix-widget-get-values ()
1823   "Create values for editable fields from current article."
1824   (if (not (gnus-buffer-live-p gnus-article-buffer))
1825       (error "No article buffer available")
1826     (save-excursion
1827       (gnus-summary-toggle-header 1)
1828       (set-buffer gnus-article-buffer)
1829       (mapcar
1830        (function
1831         (lambda (field)
1832           (list (car (cddr field))
1833                 (if (car field)
1834                     (nnmairix-replace-illegal-chars
1835                      (gnus-fetch-field (car field)))
1836                   nil))))
1837        nnmairix-widget-fields-list))))
1838
1839
1840 (defun nnmairix-widget-search (&optional mvalues)
1841   "Create mairix query interactively using graphical widgets.
1842 MVALUES may contain values from current article."
1843   (interactive)
1844   ;; Select window for mairix customization
1845   (funcall nnmairix-widget-select-window-function)
1846   ;; generate widgets
1847   (nnmairix-widget-create-query mvalues)
1848   ;; generate Buttons
1849   (widget-create 'push-button
1850                  :notify
1851                  (if mvalues
1852                      (lambda (&rest ignore)
1853                        (nnmairix-widget-send-query nnmairix-widgets
1854                                                    t))
1855                    (lambda (&rest ignore)
1856                      (nnmairix-widget-send-query nnmairix-widgets
1857                                                  nil)))
1858                  "Send Query")
1859   (widget-insert "   ")
1860   (widget-create 'push-button
1861                  :notify
1862                  (if mvalues
1863                      (lambda (&rest ignore)
1864                        (nnmairix-widget-create-group nnmairix-widgets
1865                                                      t))
1866                    (lambda (&rest ignore)
1867                      (nnmairix-widget-create-group nnmairix-widgets
1868                                                    nil)))
1869                  "Create permanent group")
1870   (widget-insert "   ")
1871   (widget-create 'push-button
1872                  :notify (lambda (&rest ignore)
1873                            (kill-buffer nnmairix-customize-query-buffer))
1874                  "Cancel")
1875   (use-local-map widget-keymap)
1876   (widget-setup)
1877   (goto-char (point-min)))
1878
1879 (defun nnmairix-widget-send-query (widgets &optional withvalues)
1880   "Send query from WIDGETS to mairix binary.
1881 If WITHVALUES is t, query is based on current article."
1882   (nnmairix-search
1883    (nnmairix-widget-make-query-from-widgets widgets)
1884    (if withvalues
1885        (gnus-method-to-server
1886         (nnmairix-backend-to-server gnus-current-select-method))
1887      (car (nnmairix-get-server)))
1888    (if (widget-value (cadr (assoc "Threads" widgets)))
1889        t
1890      -1))
1891   (kill-buffer nnmairix-customize-query-buffer))
1892
1893 (defun nnmairix-widget-create-group (widgets &optional withvalues)
1894   "Create nnmairix group based on current widget values WIDGETS.
1895 If WITHVALUES is t, query is based on current article."
1896   (let ((group (read-string "Name of the group: ")))
1897     (when (not (zerop (length group)))
1898       (nnmairix-create-search-group
1899        (if withvalues
1900            (gnus-method-to-server
1901             (nnmairix-backend-to-server gnus-current-select-method))
1902          (car (nnmairix-get-server)))
1903        group
1904        (nnmairix-widget-make-query-from-widgets widgets)
1905        (widget-value (cadr (assoc "Threads" widgets))))))
1906   (kill-buffer nnmairix-customize-query-buffer))
1907
1908
1909 (defun nnmairix-widget-make-query-from-widgets (widgets)
1910   "Create mairix query from widget values WIDGETS."
1911   (let (query temp flag)
1912     ;; first we do the editable fields
1913     (dolist (cur nnmairix-widget-fields-list)
1914       ;; See if checkbox is checked
1915       (when (widget-value
1916              (cadr (assoc (concat "c" (car (cddr cur))) widgets)))
1917         ;; create query for the field
1918         (push
1919          (concat
1920           (nth 1 cur)
1921           ":"
1922           (nnmairix-replace-illegal-chars
1923            (widget-value
1924            (cadr (assoc (concat "e" (car (cddr cur))) widgets)))))
1925          query)))
1926     ;; Flags
1927     (when (member 'flags nnmairix-widget-other)
1928       (setq flag
1929             (mapconcat
1930              (function
1931               (lambda (flag)
1932                 (setq temp
1933                       (widget-value (cadr (assoc (car flag) nnmairix-widgets))))
1934                 (if (string= "yes" temp)
1935                     (cadr flag)
1936                   (if (string= "no" temp)
1937                       (concat "-" (cadr flag))))))
1938              '(("seen" "s") ("replied" "r") ("flagged" "f")) ""))
1939       (when (not (zerop (length flag)))
1940         (push (concat "F:" flag) query)))
1941     ;; return query string
1942     (mapconcat 'identity query " ")))
1943
1944
1945 (defun nnmairix-widget-create-query (&optional values)
1946   "Create widgets for creating mairix queries.
1947 Fill in VALUES if based on an article."
1948   (let (allwidgets)
1949     (when (get-buffer nnmairix-customize-query-buffer)
1950       (kill-buffer nnmairix-customize-query-buffer))
1951     (switch-to-buffer nnmairix-customize-query-buffer)
1952     (kill-all-local-variables)
1953     (erase-buffer)
1954     (widget-insert "Specify your query for Mairix (check boxes for activating fields):\n\n")
1955     (widget-insert "(Whitespaces will be converted to ',' (i.e. AND). Use '/' for OR.)\n\n")
1956 ;    (make-local-variable 'nnmairix-widgets)
1957     (setq nnmairix-widgets (nnmairix-widget-build-editable-fields values))
1958     (when (member 'flags nnmairix-widget-other)
1959       (widget-insert "\nFlags:\n      Seen:     ")
1960       (nnmairix-widget-add "seen"
1961                            'menu-choice
1962                            :value "ignore"
1963                            '(item "yes") '(item "no") '(item "ignore"))
1964       (widget-insert "      Replied:  ")
1965       (nnmairix-widget-add "replied"
1966                            'menu-choice
1967                            :value "ignore"
1968                            '(item "yes") '(item "no") '(item "ignore"))
1969       (widget-insert "      Ticked:   ")
1970       (nnmairix-widget-add "flagged"
1971                            'menu-choice
1972                            :value "ignore"
1973                            '(item "yes") '(item "no") '(item "ignore")))
1974     (when (member 'threads nnmairix-widget-other)
1975       (widget-insert "\n")
1976       (nnmairix-widget-add "Threads" 'checkbox nil))
1977       (widget-insert " Show full threads\n\n")))
1978
1979 (defun nnmairix-widget-build-editable-fields (values)
1980   "Build editable field widgets in `nnmairix-widget-fields-list'.
1981 VALUES may contain values for editable fields from current article."
1982   ;; how can this be done less ugly?
1983   (let ((ret))
1984     (mapc
1985      (function
1986       (lambda (field)
1987         (setq field (car (cddr field)))
1988         (setq ret
1989               (nconc
1990                (list
1991                 (list
1992                  (concat "c" field)
1993                  (widget-create 'checkbox
1994                                 :tag field
1995                                 :notify (lambda (widget &rest ignore)
1996                                           (nnmairix-widget-toggle-activate widget))
1997                                 nil)))
1998                (list
1999                 (list
2000                  (concat "e" field)
2001                  (widget-create 'editable-field
2002                                 :size 60
2003                                 :format (concat " " field ":"
2004                                                 (make-string (- 11 (length field)) ?\ )
2005                                                 "%v")
2006                                 :value (or (cadr (assoc field values)) ""))))
2007                ret))
2008         (widget-insert "\n")
2009         ;; Deactivate editable field
2010         (widget-apply (cadr (nth 1 ret)) :deactivate)))
2011      nnmairix-widget-fields-list)
2012     ret))
2013
2014 (defun nnmairix-widget-add (name &rest args)
2015   "Add a widget NAME with optional ARGS."
2016   (push
2017    (list name
2018          (apply 'widget-create args))
2019    nnmairix-widgets))
2020
2021 (defun nnmairix-widget-toggle-activate (widget)
2022   "Toggle activation status of WIDGET depending on corresponding checkbox value."
2023   (let ((field (widget-get widget :tag)))
2024     (if (widget-value widget)
2025         (widget-apply
2026          (cadr (assoc (concat "e" field) nnmairix-widgets))
2027          :activate)
2028       (widget-apply
2029        (cadr (assoc (concat "e" field) nnmairix-widgets))
2030        :deactivate)))
2031   (widget-setup))
2032
2033 (provide 'nnmairix)
2034
2035 ;;; nnmairix.el ends here