(nnimap-retrieve-which-headers):
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;;         Jim Radford <radford@robby.caltech.edu>
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessery?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57
58 ;;; Code:
59
60 (eval-and-compile
61   (require 'imap))
62
63 (require 'nnoo)
64 (require 'nnmail)
65 (require 'nnheader)
66 (require 'mm-util)
67 (require 'gnus)
68 (require 'gnus-range)
69 (require 'gnus-start)
70 (require 'gnus-int)
71
72 (nnoo-declare nnimap)
73
74 (defconst nnimap-version "nnimap 0.131")
75
76 (defvoo nnimap-address nil
77   "Address of physical IMAP server.  If nil, use the virtual server's name.")
78
79 (defvoo nnimap-server-port nil
80   "Port number on physical IMAP server.
81 If nil, defaults to 993 for SSL connections and 143 otherwise.")
82
83 ;; Splitting variables
84
85 (defvar nnimap-split-crosspost t
86   "If non-nil, do crossposting if several split methods match the mail.
87 If nil, the first match found will be used.")
88
89 (defvar nnimap-split-inbox nil
90   "*Name of mailbox to split mail from.
91
92 Mail is read from this mailbox and split according to rules in
93 `nnimap-split-rules'.
94
95 This can be a string or a list of strings.")
96
97 (defvar nnimap-split-rule nil
98   "*Mail will be split according to theese rules.
99
100 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
101
102 If you'd like, for instance, one mail group for mail from the
103 \"gnus-imap\" mailing list, one group for junk mail and leave
104 everything else in the incoming mailbox, you could do something like
105 this:
106
107 (setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
108                           (\"INBOX.junk\"        \"Subject:.*buy\")))
109
110 As you can see, `nnimap-split-rule' is a list of lists, where the first
111 element in each \"rule\" is the name of the IMAP mailbox, and the
112 second is a regexp that nnimap will try to match on the header to find
113 a fit.
114
115 The second element can also be a function.  In that case, it will be
116 called narrowed to the headers with the first element of the rule as
117 the argument.  It should return a non-nil value if it thinks that the
118 mail belongs in that group.
119
120 This variable can also have a function as its value, the function will
121 be called with the headers narrowed and should return a group where it
122 thinks the article should be splitted to.  See `nnimap-split-fancy'.
123
124 To allow for different split rules on different virtual servers, and
125 even different split rules in different inboxes on the same server,
126 the syntax of this variable have been extended along the lines of:
127
128 (setq nnimap-split-rule
129       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
130                                   (\"junk\"    \"From:.*Simon\")))
131         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
132         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
133                                   (\"junk\"    my-junk-func)))))
134
135 The virtual server name is in fact a regexp, so that the same rules
136 may apply to several servers.  In the example, the servers
137 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
138 the inbox string is also a regexp.  The actual splitting rules are as
139 before, either a function, or a list with group/regexp or
140 group/function elements.")
141
142 (defvar nnimap-split-predicate "UNSEEN UNDELETED"
143   "The predicate used to find articles to split.
144 If you use another IMAP client to peek on articles but always would
145 like nnimap to split them once it's started, you could change this to
146 \"UNDELETED\". Other available predicates are available in
147 RFC2060 section 6.4.4.")
148
149 (defvar nnimap-split-fancy nil
150   "Like `nnmail-split-fancy', which see.")
151
152 ;; Authorization / Privacy variables
153
154 (defvoo nnimap-auth-method nil
155   "Obsolete.")
156
157 (defvoo nnimap-stream nil
158   "How nnimap will connect to the server.
159
160 The default, nil, will try to use the \"best\" method the server can
161 handle.
162
163 Change this if
164
165 1) you want to connect with SSL.  The SSL integration with IMAP is
166    brain-dead so you'll have to tell it specifically.
167
168 2) your server is more capable than your environment -- i.e. your
169    server accept Kerberos login's but you haven't installed the
170    `imtest' program or your machine isn't configured for Kerberos.
171
172 Possible choices: kerberos4, ssl, network")
173
174 (defvoo nnimap-authenticator nil
175   "How nnimap authenticate itself to the server.
176
177 The default, nil, will try to use the \"best\" method the server can
178 handle.
179
180 There is only one reason for fiddling with this variable, and that is
181 if your server is more capable than your environment -- i.e. you
182 connect to a server that accept Kerberos login's but you haven't
183 installed the `imtest' program or your machine isn't configured for
184 Kerberos.
185
186 Possible choices: kerberos4, cram-md5, login, anonymous.")
187
188 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
189   "Directory to keep NOV cache files for nnimap groups.
190 See also `nnimap-nov-file-name'.")
191
192 (defvoo nnimap-nov-file-name "nnimap."
193   "NOV cache base filename.
194 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
195 typical complete file name would be
196 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
197 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
198 `nnmail-use-long-file-names' is nil")
199
200 (defvoo nnimap-nov-file-name-suffix ".novcache"
201   "Suffix for NOV cache base filename.")
202
203 (defvoo nnimap-nov-is-evil nil
204   "If non-nil, nnimap will never generate or use a local nov database for this backend.
205 Using nov databases will speed up header fetching considerably.
206 Unlike other backends, you do not need to take special care if you
207 flip this variable.")
208
209 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
210   "Whether to expunge a group when it is closed.
211 When a IMAP group with articles marked for deletion is closed, this
212 variable determine if nnimap should actually remove the articles or
213 not.
214
215 If always, nnimap always perform a expunge when closing the group.
216 If never, nnimap never expunges articles marked for deletion.
217 If ask, nnimap will ask you if you wish to expunge marked articles.
218
219 When setting this variable to `never', you can only expunge articles
220 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
221
222 (defvoo nnimap-list-pattern "*"
223   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
224 See below for available wildcards.
225
226 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
227 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
228 semantics of this are server specific, on the University of Washington
229 server you can specify a directory.
230
231 Example:
232  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
233
234 There are two wildcards * and %. * matches everything, % matches
235 everything in the current hierarchy.")
236
237 (defvoo nnimap-news-groups nil
238   "IMAP support a news-like mode, also known as bulletin board mode, where replies is sent via IMAP instead of SMTP.
239
240 This variable should contain a regexp matching groups where you wish
241 replies to be stored to the mailbox directly.
242
243 Example:
244   '(\"^[^I][^N][^B][^O][^X].*$\")
245
246 This will match all groups not beginning with \"INBOX\".
247
248 Note that there is nothing technically different between mail-like and
249 news-like mailboxes.  If you wish to have a group with todo items or
250 similar which you wouldn't want to set up a mailing list for, you can
251 use this to make replies go directly to the group.")
252
253 (defvoo nnimap-server-address nil
254   "Obsolete.  Use `nnimap-address'.")
255
256 (defcustom nnimap-authinfo-file "~/.authinfo"
257   "Authorization information for IMAP servers.  In .netrc format."
258   :type
259   '(choice file
260            (repeat :tag "Entries"
261                    :menu-tag "Inline"
262                    (list :format "%v"
263                          :value ("" ("login" . "") ("password" . ""))
264                          (string :tag "Host")
265                          (checklist :inline t
266                                     (cons :format "%v"
267                                           (const :format "" "login")
268                                           (string :format "Login: %v"))
269                                     (cons :format "%v"
270                                           (const :format "" "password")
271                                           (string :format "Password: %v")))))))
272
273 (defcustom nnimap-prune-cache t
274   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
275   :type 'boolean)
276
277 (defvar nnimap-request-list-method 'imap-mailbox-list
278   "Method to use to request a list of all folders from the server.
279 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
280 restrict visible folders.")
281
282 ;; Internal variables:
283
284 (defvar nnimap-debug nil
285   "Name of buffer to record debugging info.
286 For example: (setq nnimap-debug \"*nnimap-debug*\")")
287 (defvar nnimap-current-move-server nil)
288 (defvar nnimap-current-move-group nil)
289 (defvar nnimap-current-move-article nil)
290 (defvar nnimap-length)
291 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
292 (defvar nnimap-progress-how-often 20)
293 (defvar nnimap-counter)
294 (defvar nnimap-callback-callback-function nil
295   "Gnus callback the nnimap asynchronous callback should call.")
296 (defvar nnimap-callback-buffer nil
297   "Which buffer the asynchronous article prefetch callback should work in.")
298 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
299 (defvar nnimap-current-server nil)      ;; Current server
300 (defvar nnimap-server-buffer nil)       ;; Current servers' buffer
301
302 \f
303
304 (nnoo-define-basics nnimap)
305
306 ;; Utility functions:
307
308 (defsubst nnimap-get-server-buffer (server)
309   "Return buffer for SERVER, if nil use current server."
310   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
311
312 (defun nnimap-possibly-change-server (server)
313   "Return buffer for SERVER, changing the current server as a side-effect.
314 If SERVER is nil, uses the current server."
315   (setq nnimap-current-server (or server nnimap-current-server)
316         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
317
318 (defun nnimap-verify-uidvalidity (group server)
319   "Verify stored uidvalidity match current one in GROUP on SERVER."
320   (let* ((gnusgroup (gnus-group-prefixed-name
321                      group (gnus-server-to-method
322                             (format "nnimap:%s" server))))
323          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
324          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity)))
325     (if old-uidvalidity
326         (if (not (equal old-uidvalidity new-uidvalidity))
327             nil ;; uidvalidity clash
328           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
329           t)
330       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
331       t)))
332
333 (defun nnimap-find-minmax-uid (group &optional examine)
334   "Find lowest and highest active article nummber in GROUP.
335 If EXAMINE is non-nil the group is selected read-only."
336   (with-current-buffer nnimap-server-buffer
337     (when (imap-mailbox-select group examine)
338       (let (minuid maxuid)
339         (when (> (imap-mailbox-get 'exists) 0)
340           (imap-fetch "1,*" "UID" nil 'nouidfetch)
341           (imap-message-map (lambda (uid Uid)
342                               (setq minuid (if minuid (min minuid uid) uid)
343                                     maxuid (if maxuid (max maxuid uid) uid)))
344                             'UID))
345         (list (imap-mailbox-get 'exists) minuid maxuid)))))
346   
347 (defun nnimap-possibly-change-group (group &optional server)
348   "Make GROUP the current group, and SERVER the current server."
349   (when (nnimap-possibly-change-server server)
350     (with-current-buffer nnimap-server-buffer
351       (if (or (null group) (imap-current-mailbox-p group))
352           imap-current-mailbox
353         (if (imap-mailbox-select group)
354             (if (or (nnimap-verify-uidvalidity
355                      group (or server nnimap-current-server))
356                     (zerop (imap-mailbox-get 'exists group))
357                     (yes-or-no-p
358                      (format
359                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
360                 imap-current-mailbox
361               (imap-mailbox-unselect)
362               (error "nnimap: Group %s is not uid-valid." group))
363           (nnheader-report 'nnimap (imap-error-text)))))))
364
365 (defun nnimap-replace-whitespace (string)
366   "Return STRING with all whitespace replaced with space."
367   (when string
368     (while (string-match "[\r\n\t]+" string)
369       (setq string (replace-match " " t t string)))
370     string))
371
372 ;; Required backend functions
373
374 (defun nnimap-retrieve-headers-progress ()
375   "Hook to insert NOV line for current article into `nntp-server-buffer'."
376   (and (numberp nnmail-large-newsgroup)
377        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
378        (> nnimap-length nnmail-large-newsgroup)
379        (nnheader-message 6 "nnimap: Retrieving headers... %c"
380                          (nth (/ (% nnimap-counter
381                                     (* (length nnimap-progress-chars)
382                                        nnimap-progress-how-often))
383                                  nnimap-progress-how-often)
384                               nnimap-progress-chars)))
385   (with-current-buffer nntp-server-buffer
386     (let (headers lines chars uid mbx)
387       (with-current-buffer nnimap-server-buffer
388         (setq uid imap-current-message
389               mbx imap-current-mailbox
390               headers (if (imap-capability 'IMAP4rev1)
391                           ;; xxx don't just use car? alist doesn't contain
392                           ;; anything else now, but it might...
393                           (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
394                         (imap-message-get uid 'RFC822.HEADER))
395               lines (imap-body-lines (imap-message-body imap-current-message))
396               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
397       (nnheader-insert-nov
398        (with-temp-buffer
399          (buffer-disable-undo)
400          (insert headers)
401          (nnheader-ms-strip-cr)
402          (nnheader-fold-continuation-lines)
403          (subst-char-in-region (point-min) (point-max) ?\t ? )
404          (let ((head (nnheader-parse-head 'naked)))
405            (mail-header-set-number head uid)
406            (mail-header-set-chars head chars)
407            (mail-header-set-lines head lines)
408            (mail-header-set-xref
409             head (format "%s %s:%d" (system-name) mbx uid))
410            head))))))
411
412 (defun nnimap-retrieve-which-headers (articles fetch-old)
413   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
414   (with-current-buffer nnimap-server-buffer
415     (if (numberp (car-safe articles))
416         (imap-search
417          (concat "UID "
418                  (imap-range-to-message-set
419                   (gnus-compress-sequence
420                    (append (gnus-uncompress-sequence
421                             (and fetch-old
422                                  (cons (if (numberp fetch-old)
423                                            (max 1 (- (car articles) fetch-old))
424                                          1)
425                                        (1- (car articles)))))
426                            articles)))))
427       (mapcar (lambda (msgid)
428                 (imap-search
429                  (format "HEADER Message-Id %s" msgid)))
430               articles))))
431
432 (defun nnimap-group-overview-filename (group server)
433   "Make pathname for GROUP on SERVER."
434   (let ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
435         (file (nnheader-translate-file-chars
436                (concat nnimap-nov-file-name
437                        (if (equal server "")
438                            "unnamed"
439                          server) "." group nnimap-nov-file-name-suffix) t)))
440     (if (or nnmail-use-long-file-names
441             (file-exists-p (concat dir file)))
442         (concat dir file)
443       (concat dir (mm-encode-coding-string
444                    (nnheader-replace-chars-in-string file ?. ?/)
445                    nnmail-pathname-coding-system)))))
446
447 (defun nnimap-retrieve-headers-from-file (group server)
448   (with-current-buffer nntp-server-buffer
449     (let ((nov (nnimap-group-overview-filename group server)))
450       (when (file-exists-p nov)
451         (mm-insert-file-contents nov)
452         (set-buffer-modified-p nil)
453         (let ((min (progn (goto-char (point-min))
454                           (when (not (eobp))
455                             (read (current-buffer)))))
456               (max (progn (goto-char (point-max))
457                           (forward-line -1)
458                           (when (not (bobp))
459                             (read (current-buffer))))))
460           (if (and (numberp min) (numberp max))
461               (cons min max)
462             ;; junk, remove it, it's saved later
463             (erase-buffer)
464             nil))))))
465
466 (defun nnimap-retrieve-headers-from-server (articles group server)
467   (with-current-buffer nnimap-server-buffer
468     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
469           (nnimap-length (gnus-range-length articles))
470           (nnimap-counter 0))
471       (imap-fetch (imap-range-to-message-set articles)
472                   (concat "(UID RFC822.SIZE BODY "
473                           (let ((headers
474                                  (append '(Subject From Date Message-Id
475                                                    References In-Reply-To Xref)
476                                          (copy-sequence
477                                           nnmail-extra-headers))))
478                             (if (imap-capability 'IMAP4rev1)
479                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
480                               (format "RFC822.HEADER.LINES %s)" headers)))))
481       (and (numberp nnmail-large-newsgroup)
482            (> nnimap-length nnmail-large-newsgroup)
483            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
484
485 (defun nnimap-use-nov-p (group server)
486   (or gnus-nov-is-evil nnimap-nov-is-evil
487       (unless (and (gnus-make-directory
488                     (file-name-directory
489                      (nnimap-group-overview-filename group server)))
490                    (file-writable-p
491                     (nnimap-group-overview-filename group server)))
492         (message "nnimap: Nov cache not writable, %s"
493                  (nnimap-group-overview-filename group server)))))
494
495 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
496   (when (nnimap-possibly-change-group group server)
497     (with-current-buffer nntp-server-buffer
498       (erase-buffer)
499       (if (nnimap-use-nov-p group server)
500           (nnimap-retrieve-headers-from-server
501            (gnus-compress-sequence articles) group server)
502         (let (uids cached low high)
503           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
504                       low (car uids)
505                       high (car (last uids)))
506             (if (setq cached (nnimap-retrieve-headers-from-file group server))
507                 (progn
508                   ;; fetch articles with uids before cache block
509                   (when (< low (car cached))
510                     (goto-char (point-min))
511                     (nnimap-retrieve-headers-from-server
512                      (cons low (1- (car cached))) group server))
513                   ;; fetch articles with uids after cache block
514                   (when (> high (cdr cached))
515                     (goto-char (point-max))
516                     (nnimap-retrieve-headers-from-server
517                      (cons (1+ (cdr cached)) high) group server))
518                   (when nnimap-prune-cache
519                     ;; remove nov's for articles which has expired on server
520                     (goto-char (point-min))
521                     (dolist (uid (gnus-set-difference articles uids))
522                       (when (re-search-forward (format "^%d\t" uid) nil t)
523                         (gnus-delete-line)))))
524               ;; nothing cached, fetch whole range from server
525               (nnimap-retrieve-headers-from-server
526                (cons low high) group server))
527             (when (buffer-modified-p)
528               (nnmail-write-region
529                1 (point-max) (nnimap-group-overview-filename group server)
530                nil 'nomesg))
531             (nnheader-nov-delete-outside-range low high))))
532       'nov)))
533
534 (defun nnimap-open-connection (server)
535   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
536                       nnimap-authenticator nnimap-server-buffer))
537       (nnheader-report 'nnimap "Can't open connection to server %s" server)
538     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
539                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
540       (imap-close nnimap-server-buffer)
541       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
542     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
543            (port (if nnimap-server-port
544                      (int-to-string nnimap-server-port)
545                    "imap"))
546            (alist (gnus-netrc-machine list (or nnimap-server-address 
547                                                nnimap-address server)
548                                       port "imap"))
549            (user (gnus-netrc-get alist "login"))
550            (passwd (gnus-netrc-get alist "password")))
551       (if (imap-authenticate user passwd nnimap-server-buffer)
552           (prog1
553               (push (list server nnimap-server-buffer)
554                     nnimap-server-buffer-alist)
555             (nnimap-possibly-change-server server))
556         (imap-close nnimap-server-buffer)
557         (kill-buffer nnimap-server-buffer)
558         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
559
560 (deffoo nnimap-open-server (server &optional defs)
561   (nnheader-init-server-buffer)
562   (if (nnimap-server-opened server)
563       t
564     (unless (assq 'nnimap-server-buffer defs)
565       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
566     ;; translate `nnimap-server-address' to `nnimap-address' in defs
567     ;; for people that configured nnimap with a very old version
568     (unless (assq 'nnimap-address defs)
569       (if (assq 'nnimap-server-address defs)
570           (push (list 'nnimap-address
571                       (cadr (assq 'nnimap-server-address defs))) defs)
572         (push (list 'nnimap-address server) defs)))
573     (nnoo-change-server 'nnimap server defs)
574     (or (and nnimap-server-buffer
575              (imap-opened nnimap-server-buffer))
576         (nnimap-open-connection server))))
577
578 (deffoo nnimap-server-opened (&optional server)
579   "Whether SERVER is opened.
580 If SERVER is the current virtual server, and the connection to the
581 physical server is alive, this function return a non-nil value.  If
582 SERVER is nil, it is treated as the current server."
583   ;; clean up autologouts??
584   (and (or server nnimap-current-server)
585        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
586        (imap-opened (nnimap-get-server-buffer server))))
587
588 (deffoo nnimap-close-server (&optional server)
589   "Close connection to server and free all resources connected to it.
590 Return nil if the server couldn't be closed for some reason."
591   (let ((server (or server nnimap-current-server)))
592     (when (or (nnimap-server-opened server)
593               (imap-opened (nnimap-get-server-buffer server)))
594       (imap-close (nnimap-get-server-buffer server))
595       (kill-buffer (nnimap-get-server-buffer server))
596       (setq nnimap-server-buffer nil
597             nnimap-current-server nil
598             nnimap-server-buffer-alist
599             (delq server nnimap-server-buffer-alist)))
600     (nnoo-close-server 'nnimap server)))
601
602 (deffoo nnimap-request-close ()
603   "Close connection to all servers and free all resources that the backend have reserved.
604 All buffers that have been created by that
605 backend should be killed.  (Not the nntp-server-buffer, though.) This
606 function is generally only called when Gnus is shutting down."
607   (mapcar (lambda (server) (nnimap-close-server (car server)))
608           nnimap-server-buffer-alist)
609   (setq nnimap-server-buffer-alist nil))
610
611 (deffoo nnimap-status-message (&optional server)
612   "This function returns the last error message from server."
613   (when (nnimap-possibly-change-server server)
614     (nnoo-status-message 'nnimap server)))
615
616 (defun nnimap-demule (string)
617   (funcall (if (and (fboundp 'string-as-multibyte)
618                     (subrp (symbol-function 'string-as-multibyte)))
619                'string-as-multibyte
620              'identity)
621            (or string "")))
622
623 (defun nnimap-callback ()
624   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
625   (with-current-buffer nnimap-callback-buffer
626     (insert
627      (with-current-buffer nnimap-server-buffer
628        (nnimap-demule
629         (if (imap-capability 'IMAP4rev1) 
630             ;; xxx don't just use car? alist doesn't contain
631             ;; anything else now, but it might...
632             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
633           (imap-message-get (imap-current-message) 'RFC822)))))
634     (nnheader-ms-strip-cr)
635     (funcall nnimap-callback-callback-function t)))
636
637 (defun nnimap-request-article-part (article part prop &optional
638                                             group server to-buffer detail)
639   (when (nnimap-possibly-change-group group server)
640     (let ((article (if (stringp article)
641                        (car-safe (imap-search
642                                   (format "HEADER Message-Id %s" article)
643                                   nnimap-server-buffer))
644                      article)))
645       (when article
646         (gnus-message 9 "nnimap: Fetching (part of) article %d..." article)
647         (if (not nnheader-callback-function)
648             (with-current-buffer (or to-buffer nntp-server-buffer)
649               (erase-buffer)
650               (let ((data (imap-fetch article part prop nil
651                                       nnimap-server-buffer)))
652                 (insert (nnimap-demule (if detail
653                                            (nth 2 (car data))
654                                          data))))
655               (nnheader-ms-strip-cr)
656               (gnus-message 9 "nnimap: Fetching (part of) article %d...done"
657                             article)
658               (if (bobp)
659                   (nnheader-report 'nnimap "No such article: %s"
660                                    (imap-error-text nnimap-server-buffer))
661                 (cons group article)))
662           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
663           (setq nnimap-callback-callback-function nnheader-callback-function
664                 nnimap-callback-buffer nntp-server-buffer)
665           (imap-fetch-asynch article part nil nnimap-server-buffer)
666           (cons group article))))))
667
668 (deffoo nnimap-asynchronous-p ()
669   t)
670
671 (deffoo nnimap-request-article (article &optional group server to-buffer)
672   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
673       (nnimap-request-article-part
674        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
675     (nnimap-request-article-part
676      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
677
678 (deffoo nnimap-request-head (article &optional group server to-buffer)
679   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
680       (nnimap-request-article-part
681        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
682     (nnimap-request-article-part
683      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
684
685 (deffoo nnimap-request-body (article &optional group server to-buffer)
686   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
687       (nnimap-request-article-part
688        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
689     (nnimap-request-article-part
690      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
691
692 (deffoo nnimap-request-group (group &optional server fast)
693   (nnimap-request-update-info-internal
694    group
695    (gnus-get-info (gnus-group-prefixed-name
696                    group (gnus-server-to-method (format "nnimap:%s" server))))
697    server)
698   (when (nnimap-possibly-change-group group server)
699     (let (info)
700       (cond (fast group)
701             ((null (setq info (nnimap-find-minmax-uid group t)))
702              (nnheader-report 'nnimap "Could not get active info for %s"
703                               group))
704             (t
705              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
706                               (max 1 (or (nth 1 info) 1))
707                               (or (nth 2 info) 0) group)
708              (nnheader-report 'nnimap "Group %s selected" group)
709              t)))))
710
711 (defun nnimap-close-group (group &optional server)
712   (with-current-buffer nnimap-server-buffer
713     (when (and (imap-opened)
714                (nnimap-possibly-change-group group server))
715       (case nnimap-expunge-on-close
716         ('always (imap-mailbox-expunge)
717                  (imap-mailbox-close))
718         ('ask (if (and (imap-search "DELETED")
719                        (gnus-y-or-n-p (format
720                                        "Expunge articles in group `%s'? "
721                                        imap-current-mailbox)))
722                   (progn (imap-mailbox-expunge)
723                          (imap-mailbox-close))
724                 (imap-mailbox-unselect)))
725         (t (imap-mailbox-unselect)))
726       (not imap-current-mailbox))))
727
728 (defun nnimap-pattern-to-list-arguments (pattern)
729   (mapcar (lambda (p)
730             (cons (car-safe p) (or (cdr-safe p) p)))
731           (if (and (listp pattern)
732                    (listp (cdr pattern)))
733               pattern
734             (list pattern))))
735
736 (deffoo nnimap-request-list (&optional server)
737   (when (nnimap-possibly-change-server server)
738     (with-current-buffer nntp-server-buffer
739       (erase-buffer))
740     (gnus-message 5 "nnimap: Generating active list%s..."
741                   (if (> (length server) 0) (concat " for " server) ""))
742     (with-current-buffer nnimap-server-buffer
743       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
744         (dolist (mbx (funcall nnimap-request-list-method
745                               (cdr pattern) (car pattern)))
746           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
747               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
748                 (when info
749                   (with-current-buffer nntp-server-buffer
750                    (insert (format "\"%s\" %d %d y\n"
751                                    mbx (or (nth 2 info) 0)
752                                    (max 1 (or (nth 1 info) 1)))))))))))
753     (gnus-message 5 "nnimap: Generating active list%s...done"
754                   (if (> (length server) 0) (concat " for " server) ""))
755     t))
756
757 (deffoo nnimap-request-post (&optional server)
758   (let ((success t))
759     (dolist (mbx (message-unquote-tokens
760                   (message-tokenize-header
761                    (message-fetch-field "Newsgroups") ", ")) success)
762       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
763         (or (gnus-active to-newsgroup)
764             (gnus-activate-group to-newsgroup)
765             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
766                                        to-newsgroup))
767                 (or (and (gnus-request-create-group
768                           to-newsgroup gnus-command-method)
769                          (gnus-activate-group to-newsgroup nil nil
770                                               gnus-command-method))
771                     (error "Couldn't create group %s" to-newsgroup)))
772             (error "No such group: %s" to-newsgroup))
773         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
774           (setq success nil))))))
775
776 ;; Optional backend functions
777
778 (deffoo nnimap-retrieve-groups (groups &optional server)
779   (when (nnimap-possibly-change-server server)
780     (gnus-message 5 "nnimap: Checking mailboxes...")
781     (with-current-buffer nntp-server-buffer
782       (erase-buffer)
783       (dolist (group groups)
784         (gnus-message 7 "nnimap: Checking mailbox %s" group)
785         (or (member "\\NoSelect"
786                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
787             (let ((info (nnimap-find-minmax-uid group 'examine)))
788               (insert (format "\"%s\" %d %d y\n" group
789                               (or (nth 2 info) 0)
790                               (max 1 (or (nth 1 info) 1))))))))
791     (gnus-message 5 "nnimap: Checking mailboxes...done")
792     'active))
793
794 (deffoo nnimap-request-update-info-internal (group info &optional server)
795   (when (nnimap-possibly-change-group group server)
796     (when info;; xxx what does this mean? should we create a info?
797       (with-current-buffer nnimap-server-buffer
798         (gnus-message 5 "nnimap: Updating info for %s..."
799                       (gnus-info-group info))
800         
801         (when (nnimap-mark-permanent-p 'read)
802           (let (seen unseen)
803             ;; read info could contain articles marked unread by other
804             ;; imap clients!  we correct this
805             (setq seen (gnus-uncompress-range (gnus-info-read info))
806                   unseen (imap-search "UNSEEN UNDELETED")
807                   seen (gnus-set-difference seen unseen)
808                   ;; seen might lack articles marked as read by other
809                   ;; imap clients! we correct this
810                   seen (append seen (imap-search "SEEN"))
811                   ;; remove dupes
812                   seen (sort seen '<)
813                   seen (gnus-compress-sequence seen t)
814                   ;; we can't return '(1) since this isn't a "list of ranges",
815                   ;; and we can't return '((1)) since g-list-of-unread-articles
816                   ;; is buggy so we return '((1 . 1)).
817                   seen (if (and (integerp (car seen))
818                                 (null (cdr seen)))
819                            (list (cons (car seen) (car seen)))
820                          seen))
821             (gnus-info-set-read info seen)))
822
823         (mapcar (lambda (pred)
824                   (when (and (nnimap-mark-permanent-p (cdr pred))
825                              (member (nnimap-mark-to-flag (cdr pred))
826                                      (imap-mailbox-get 'flags)))
827                     (gnus-info-set-marks
828                      info
829                      (nnimap-update-alist-soft
830                       (cdr pred)
831                       (gnus-compress-sequence
832                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
833                       (gnus-info-marks info))
834                      t)))
835                 gnus-article-mark-lists)
836         
837         (gnus-message 5 "nnimap: Updating info for %s...done"
838                       (gnus-info-group info))
839
840         info))))
841
842 (deffoo nnimap-request-type (group &optional article)
843   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
844       'news
845     'mail))
846
847 (deffoo nnimap-request-set-mark (group actions &optional server)
848   (when (nnimap-possibly-change-group group server)
849     (with-current-buffer nnimap-server-buffer
850       (let (action)
851         (gnus-message 7 "nnimap: Setting marks in %s..." group)
852         (while (setq action (pop actions))
853           (let ((range (nth 0 action))
854                 (what  (nth 1 action))
855                 (cmdmarks (nth 2 action))
856                 marks)
857             ;; cache flags are pointless on the server
858             (setq cmdmarks (delq 'cache cmdmarks))
859             ;; flag dormant articles as ticked
860             (if (memq 'dormant cmdmarks)
861                 (setq cmdmarks (cons 'tick cmdmarks)))
862             ;; remove stuff we are forbidden to store
863             (mapcar (lambda (mark)
864                       (if (imap-message-flag-permanent-p
865                            (nnimap-mark-to-flag mark))
866                           (setq marks (cons mark marks))))
867                     cmdmarks)
868             (when (and range marks)
869               (cond ((eq what 'del)
870                      (imap-message-flags-del
871                       (imap-range-to-message-set range)
872                       (nnimap-mark-to-flag marks nil t)))
873                     ((eq what 'add)
874                      (imap-message-flags-add
875                       (imap-range-to-message-set range)
876                       (nnimap-mark-to-flag marks nil t)))
877                     ((eq what 'set)
878                      (imap-message-flags-set
879                       (imap-range-to-message-set range)
880                       (nnimap-mark-to-flag marks nil t)))))))
881         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
882   nil)
883
884 (defun nnimap-split-fancy ()
885   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
886   (let ((nnmail-split-fancy nnimap-split-fancy))
887     (nnmail-split-fancy)))
888
889 (defun nnimap-split-to-groups (rules)
890   ;; tries to match all rules in nnimap-split-rule against content of
891   ;; nntp-server-buffer, returns a list of groups that matched.
892   (with-current-buffer nntp-server-buffer
893     ;; Fold continuation lines.
894     (goto-char (point-min))
895     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
896       (replace-match " " t t))
897     (if (functionp rules)
898         (funcall rules)
899       (let (to-groups regrepp)
900         (catch 'split-done
901           (dolist (rule rules to-groups)
902             (let ((group (car rule))
903                   (regexp (cadr rule)))
904               (goto-char (point-min))
905               (when (and (if (stringp regexp)
906                              (progn
907                                (setq regrepp (string-match "\\\\[0-9&]" group))
908                                (re-search-forward regexp nil t))
909                            (funcall regexp group))
910                          ;; Don't enter the article into the same group twice.
911                          (not (assoc group to-groups)))
912                 (push (if regrepp
913                           (nnmail-expand-newtext group)
914                         group)
915                       to-groups)
916                 (or nnimap-split-crosspost
917                     (throw 'split-done to-groups))))))))))
918   
919 (defun nnimap-assoc-match (key alist)
920   (let (element)
921     (while (and alist (not element))
922       (if (string-match (car (car alist)) key)
923           (setq element (car alist)))
924       (setq alist (cdr alist)))
925     element))
926
927 (defun nnimap-split-find-rule (server inbox)
928   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
929            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
930       ;; extended format
931       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
932                                             server nnimap-split-rule))))
933     nnimap-split-rule))
934
935 (defun nnimap-split-find-inbox (server)
936   (if (listp nnimap-split-inbox)
937       nnimap-split-inbox
938     (list nnimap-split-inbox)))
939
940 (defun nnimap-split-articles (&optional group server)
941   (when (nnimap-possibly-change-server server)
942     (with-current-buffer nnimap-server-buffer
943       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
944         ;; iterate over inboxes
945         (while (and (setq inbox (pop inboxes))
946                     (nnimap-possibly-change-group inbox));; SELECT
947           ;; find split rule for this server / inbox
948           (when (setq rule (nnimap-split-find-rule server inbox))
949             ;; iterate over articles
950             (dolist (article (imap-search nnimap-split-predicate))
951               (when (nnimap-request-head article)
952                 ;; copy article to right group(s)
953                 (setq removeorig nil)
954                 (dolist (to-group (nnimap-split-to-groups rule))
955                   (if (imap-message-copy (number-to-string article)
956                                          to-group nil 'nocopyuid)
957                       (progn
958                         (message "IMAP split moved %s:%s:%d to %s" server inbox
959                                  article to-group)
960                         (setq removeorig t)
961                         ;; Add the group-art list to the history list.
962                         (push (list (cons to-group 0)) nnmail-split-history))
963                     (message "IMAP split failed to move %s:%s:%d to %s" server
964                              inbox article to-group)))
965                 ;; remove article if it was successfully copied somewhere
966                 (and removeorig
967                      (imap-message-flags-add (format "%d" article)
968                                              "\\Seen \\Deleted")))))
969           (when (imap-mailbox-select inbox);; just in case
970             ;; todo: UID EXPUNGE (if available) to remove splitted articles
971             (imap-mailbox-expunge)
972             (imap-mailbox-close)))
973         t))))
974
975 (deffoo nnimap-request-scan (&optional group server)
976   (nnimap-split-articles group server))
977
978 (deffoo nnimap-request-newgroups (date &optional server)
979   (when (nnimap-possibly-change-server server)
980     (with-current-buffer nntp-server-buffer
981       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
982                     (if (> (length server) 0) " on " "") server)
983       (erase-buffer)
984       (dolist (pattern (nnimap-pattern-to-list-arguments
985                         nnimap-list-pattern))
986         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
987                                         nnimap-server-buffer))
988           (or (member-if (lambda (mailbox)
989                            (string= (downcase mailbox) "\\noselect"))
990                          (imap-mailbox-get 'list-flags mbx
991                                            nnimap-server-buffer))
992               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
993                 (when info
994                  (insert (format "\"%s\" %d %d y\n"
995                                  mbx (or (nth 2 info) 0)
996                                  (max 1 (or (nth 1 info) 1)))))))))
997       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
998                     (if (> (length server) 0) " on " "") server))
999     t))
1000       
1001 (deffoo nnimap-request-create-group (group &optional server args)
1002   (when (nnimap-possibly-change-server server)
1003     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1004         (imap-mailbox-create group nnimap-server-buffer))))
1005
1006 (defun nnimap-time-substract (time1 time2)
1007   "Return TIME for TIME1 - TIME2."
1008   (let* ((ms (- (car time1) (car time2)))
1009          (ls (- (nth 1 time1) (nth 1 time2))))
1010     (if (< ls 0)
1011         (list (- ms 1) (+ (expt 2 16) ls))
1012       (list ms ls))))
1013
1014 (defun nnimap-date-days-ago (daysago)
1015   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1016   (let ((date (format-time-string "%d-%b-%Y"
1017                                   (nnimap-time-substract
1018                                    (current-time)
1019                                    (days-to-time daysago)))))
1020     (if (eq ?0 (string-to-char date))
1021         (substring date 1)
1022       date)))
1023
1024 (defun nnimap-request-expire-articles-progress ()
1025   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1026                 imap-current-message))
1027
1028 ;; Notice that we don't actually delete anything, we just mark them deleted.
1029 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1030   (let ((artseq (gnus-compress-sequence articles)))
1031     (when (and artseq (nnimap-possibly-change-group group server))
1032       (with-current-buffer nnimap-server-buffer
1033         (if force
1034             (and (imap-message-flags-add
1035                   (imap-range-to-message-set artseq) "\\Deleted")
1036                  (setq articles nil))
1037           (let ((days (or (and nnmail-expiry-wait-function
1038                                (funcall nnmail-expiry-wait-function group))
1039                           nnmail-expiry-wait)))
1040             (cond ((eq days 'immediate)
1041                    (and (imap-message-flags-add
1042                          (imap-range-to-message-set artseq) "\\Deleted")
1043                         (setq articles nil)))
1044                   ((numberp days)
1045                    (let ((oldarts (imap-search
1046                                    (format "UID %s NOT SINCE %s"
1047                                            (imap-range-to-message-set artseq)
1048                                            (nnimap-date-days-ago days))))
1049                          (imap-fetch-data-hook
1050                           '(nnimap-request-expire-articles-progress)))
1051                      (and oldarts
1052                           (imap-message-flags-add
1053                            (imap-range-to-message-set
1054                             (gnus-compress-sequence oldarts))
1055                            "\\Deleted")
1056                           (setq articles (gnus-set-difference
1057                                           articles oldarts)))))))))))
1058   ;; return articles not deleted
1059   articles)
1060
1061 (deffoo nnimap-request-move-article (article group server
1062                                              accept-form &optional last)
1063   (when (nnimap-possibly-change-server server)
1064     (save-excursion
1065       (let ((buf (get-buffer-create " *nnimap move*"))
1066             (nnimap-current-move-article article)
1067             (nnimap-current-move-group group)
1068             (nnimap-current-move-server nnimap-current-server)
1069             result)
1070         (and (nnimap-request-article article group server)
1071              (save-excursion
1072                (set-buffer buf)
1073                (buffer-disable-undo (current-buffer))
1074                (insert-buffer-substring nntp-server-buffer)
1075                (setq result (eval accept-form))
1076                (kill-buffer buf)
1077                result)
1078              (nnimap-request-expire-articles (list article) group server t))
1079         result))))
1080   
1081 (deffoo nnimap-request-accept-article (group &optional server last)
1082   (when (nnimap-possibly-change-server server)
1083     (let (uid)
1084       (if (setq uid
1085                 (if (string= nnimap-current-server nnimap-current-move-server)
1086                     ;; moving article within same server, speed it up...
1087                     (and (nnimap-possibly-change-group
1088                           nnimap-current-move-group)
1089                          (imap-message-copy (number-to-string
1090                                              nnimap-current-move-article)
1091                                             group 'dontcreate nil
1092                                             nnimap-server-buffer))
1093                   ;; turn into rfc822 format (\r\n eol's)
1094                   (with-current-buffer (current-buffer)
1095                     (goto-char (point-min))
1096                     (while (search-forward "\n" nil t)
1097                       (replace-match "\r\n")))
1098                   ;; this 'or' is for Cyrus server bug
1099                   (or (null (imap-current-mailbox nnimap-server-buffer))
1100                       (imap-mailbox-unselect nnimap-server-buffer))
1101                   (imap-message-append group (current-buffer) nil nil
1102                                        nnimap-server-buffer)))
1103           (cons group (nth 1 uid))
1104         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1105
1106 (deffoo nnimap-request-delete-group (group force &optional server)
1107   (when (nnimap-possibly-change-server server)
1108     (with-current-buffer nnimap-server-buffer
1109       (if force
1110           (or (null (imap-mailbox-status group 'uidvalidity))
1111               (imap-mailbox-delete group))
1112         ;; UNSUBSCRIBE?
1113         t))))
1114
1115 (deffoo nnimap-request-rename-group (group new-name &optional server)
1116   (when (nnimap-possibly-change-server server)
1117     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1118
1119 (defun nnimap-expunge (mailbox server)
1120   (when (nnimap-possibly-change-group mailbox server)
1121     (imap-mailbox-expunge nnimap-server-buffer)))
1122
1123 (defun nnimap-acl-get (mailbox server)
1124   (when (nnimap-possibly-change-server server)
1125     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1126
1127 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1128   (when (nnimap-possibly-change-server (cadr method))
1129     (unless (imap-capability 'ACL nnimap-server-buffer)
1130       (error "Your server does not support ACL editing"))
1131     (with-current-buffer nnimap-server-buffer
1132       ;; delete all removed identifiers
1133       (mapcar (lambda (old-acl)
1134                 (unless (assoc (car old-acl) new-acls)
1135                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1136                       (error "Can't delete ACL for %s" (car old-acl)))))
1137               old-acls)
1138       ;; set all changed acl's
1139       (mapcar (lambda (new-acl)
1140                 (let ((new-rights (cdr new-acl))
1141                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1142                   (unless (and old-rights new-rights
1143                                (string= old-rights new-rights))
1144                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1145                         (error "Can't set ACL for %s to %s" (car new-acl)
1146                                new-rights)))))
1147               new-acls)
1148       t)))
1149
1150 \f
1151 ;;; Internal functions
1152
1153 ;;
1154 ;; This is confusing.
1155 ;;
1156 ;; mark      => read, tick, draft, reply etc
1157 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1158 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1159 ;;
1160 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1161 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1162 ;;
1163
1164 (defconst nnimap-mark-to-predicate-alist
1165   (mapcar
1166    (lambda (pair)                       ; cdr is the mark
1167      (or (assoc (cdr pair)
1168                 '((read . "SEEN")
1169                   (tick . "FLAGGED")
1170                   (draft . "DRAFT")
1171                   (reply . "ANSWERED")))
1172          (cons (cdr pair)
1173                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1174    (cons '(read . read) gnus-article-mark-lists)))
1175
1176 (defun nnimap-mark-to-predicate (pred)
1177   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1178 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1179 to be used within a IMAP SEARCH query."
1180   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1181
1182 (defconst nnimap-mark-to-flag-alist
1183   (mapcar
1184    (lambda (pair)
1185      (or (assoc (cdr pair)
1186                 '((read . "\\Seen")
1187                   (tick . "\\Flagged")
1188                   (draft . "\\Draft")
1189                   (reply . "\\Answered")))
1190          (cons (cdr pair)
1191                (format "gnus-%s" (symbol-name (cdr pair))))))
1192    (cons '(read . read) gnus-article-mark-lists)))
1193
1194 (defun nnimap-mark-to-flag-1 (preds)
1195   (if (and (not (null preds)) (listp preds))
1196       (cons (nnimap-mark-to-flag (car preds))
1197             (nnimap-mark-to-flag (cdr preds)))
1198     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1199
1200 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1201   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1202 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1203 be used in a STORE FLAGS command."
1204   (let ((result (nnimap-mark-to-flag-1 preds)))
1205     (setq result (if (and (or make-string always-list)
1206                           (not (listp result)))
1207                      (list result)
1208                    result))
1209     (if make-string
1210         (mapconcat (lambda (flag)
1211                      (if (listp flag)
1212                          (mapconcat 'identity flag " ")
1213                        flag))
1214                    result " ")
1215       result)))
1216
1217 (defun nnimap-mark-permanent-p (mark &optional group)
1218   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1219   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1220
1221 (defun nnimap-remassoc (key alist)
1222   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1223 The modified LIST is returned.  If the first member
1224 of LIST has a car that is `equal' to KEY, there is no way to remove it
1225 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1226 sure of changing the value of `foo'."
1227   (when alist
1228     (if (equal key (caar alist))
1229         (cdr alist)
1230       (setcdr alist (nnimap-remassoc key (cdr alist)))
1231       alist)))
1232   
1233 (defun nnimap-update-alist-soft (key value alist)
1234   (if value
1235       (cons (cons key value) (nnimap-remassoc key alist))
1236     (nnimap-remassoc key alist)))
1237
1238 (when nnimap-debug
1239   (require 'trace)
1240   (buffer-disable-undo (get-buffer-create nnimap-debug))
1241   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1242         '(
1243           nnimap-possibly-change-server
1244           nnimap-verify-uidvalidity
1245           nnimap-find-minmax-uid
1246           nnimap-possibly-change-group
1247           ;;nnimap-replace-whitespace
1248           nnimap-retrieve-headers-progress
1249           nnimap-retrieve-which-headers
1250           nnimap-group-overview-filename
1251           nnimap-retrieve-headers-from-file
1252           nnimap-retrieve-headers-from-server
1253           nnimap-retrieve-headers
1254           nnimap-open-connection
1255           nnimap-open-server
1256           nnimap-server-opened
1257           nnimap-close-server
1258           nnimap-request-close
1259           nnimap-status-message
1260           ;;nnimap-demule
1261           nnimap-request-article-part
1262           nnimap-request-article
1263           nnimap-request-head
1264           nnimap-request-body
1265           nnimap-request-group
1266           nnimap-close-group
1267           nnimap-pattern-to-list-arguments
1268           nnimap-request-list
1269           nnimap-request-post
1270           nnimap-retrieve-groups
1271           nnimap-request-update-info-internal
1272           nnimap-request-type
1273           nnimap-request-set-mark
1274           nnimap-split-to-groups
1275           nnimap-split-find-rule
1276           nnimap-split-find-inbox
1277           nnimap-split-articles
1278           nnimap-request-scan
1279           nnimap-request-newgroups
1280           nnimap-request-create-group
1281           nnimap-time-substract
1282           nnimap-date-days-ago
1283           nnimap-request-expire-articles-progress
1284           nnimap-request-expire-articles
1285           nnimap-request-move-article
1286           nnimap-request-accept-article
1287           nnimap-request-delete-group
1288           nnimap-request-rename-group
1289           gnus-group-nnimap-expunge
1290           gnus-group-nnimap-edit-acl
1291           gnus-group-nnimap-edit-acl-done
1292           nnimap-group-mode-hook
1293           nnimap-mark-to-predicate
1294           nnimap-mark-to-flag-1
1295           nnimap-mark-to-flag
1296           nnimap-mark-permanent-p
1297           nnimap-remassoc
1298           nnimap-update-alist-soft
1299           )))
1300
1301 (provide 'nnimap)
1302
1303 ;;; nnimap.el ends here