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