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