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