699ef5d8d14a8175c35b98d55e4332af89a14d31
[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);; "*nnimap-debug*")
285 (defvar nnimap-current-move-server nil)
286 (defvar nnimap-current-move-group nil)
287 (defvar nnimap-current-move-article nil)
288 (defvar nnimap-length)
289 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
290 (defvar nnimap-progress-how-often 20)
291 (defvar nnimap-counter)
292 (defvar nnimap-callback-callback-function nil
293   "Gnus callback the nnimap asynchronous callback should call.")
294 (defvar nnimap-callback-buffer nil
295   "Which buffer the asynchronous article prefetch callback should work in.")
296 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
297 (defvar nnimap-current-server nil)      ;; Current server
298 (defvar nnimap-server-buffer nil)       ;; Current servers' buffer
299
300 \f
301
302 (nnoo-define-basics nnimap)
303
304 ;; Utility functions:
305
306 (defsubst nnimap-get-server-buffer (server)
307   "Return buffer for SERVER, if nil use current server."
308   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
309
310 (defun nnimap-possibly-change-server (server)
311   "Return buffer for SERVER, changing the current server as a side-effect.
312 If SERVER is nil, uses the current server."
313   (setq nnimap-current-server (or server nnimap-current-server)
314         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
315
316 (defun nnimap-verify-uidvalidity (group server)
317   "Verify stored uidvalidity match current one in GROUP on SERVER."
318   (let* ((gnusgroup (gnus-group-prefixed-name
319                      group (gnus-server-to-method
320                             (format "nnimap:%s" server))))
321          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
322          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity)))
323     (if old-uidvalidity
324         (if (not (equal old-uidvalidity new-uidvalidity))
325             nil ;; uidvalidity clash
326           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
327           t)
328       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
329       t)))
330
331 (defun nnimap-find-minmax-uid (group &optional examine)
332   "Find lowest and highest active article nummber in GROUP.
333 If EXAMINE is non-nil the group is selected read-only."
334   (with-current-buffer nnimap-server-buffer
335     (when (imap-mailbox-select group examine)
336       (let (minuid maxuid)
337         (when (> (imap-mailbox-get 'exists) 0)
338           (imap-fetch "1,*" "UID" nil 'nouidfetch)
339           (imap-message-map (lambda (uid Uid)
340                               (setq minuid (if minuid (min minuid uid) uid)
341                                     maxuid (if maxuid (max maxuid uid) uid)))
342                             'UID))
343         (list (imap-mailbox-get 'exists) minuid maxuid)))))
344   
345 (defun nnimap-possibly-change-group (group &optional server)
346   "Make GROUP the current group, and SERVER the current server."
347   (when (nnimap-possibly-change-server server)
348     (with-current-buffer nnimap-server-buffer
349       (if (or (null group) (imap-current-mailbox-p group))
350           imap-current-mailbox
351         (if (imap-mailbox-select group)
352             (if (or (nnimap-verify-uidvalidity
353                      group (or server nnimap-current-server))
354                     (zerop (imap-mailbox-get 'exists group))
355                     (yes-or-no-p
356                      (format
357                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
358                 imap-current-mailbox
359               (imap-mailbox-unselect)
360               (error "nnimap: Group %s is not uid-valid." group))
361           (nnheader-report 'nnimap (imap-error-text)))))))
362
363 (defun nnimap-replace-whitespace (string)
364   "Return STRING with all whitespace replaced with space."
365   (when string
366     (while (string-match "[\r\n\t]+" string)
367       (setq string (replace-match " " t t string)))
368     string))
369
370 ;; Required backend functions
371
372 (defun nnimap-retrieve-headers-progress ()
373   "Hook to insert NOV line for current article into `nntp-server-buffer'."
374   (and (numberp nnmail-large-newsgroup)
375        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
376        (> nnimap-length nnmail-large-newsgroup)
377        (nnheader-message 6 "nnimap: Retrieving headers... %c"
378                          (nth (/ (% nnimap-counter
379                                     (* (length nnimap-progress-chars)
380                                        nnimap-progress-how-often))
381                                  nnimap-progress-how-often)
382                               nnimap-progress-chars)))
383   (with-current-buffer nntp-server-buffer
384     (let (headers lines chars uid mbx)
385       (with-current-buffer nnimap-server-buffer
386         (setq uid imap-current-message
387               mbx imap-current-mailbox
388               headers (if (imap-capability 'IMAP4rev1)
389                           ;; xxx don't just use car? alist doesn't contain
390                           ;; anything else now, but it might...
391                           (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
392                         (imap-message-get uid 'RFC822.HEADER))
393               lines (imap-body-lines (imap-message-body imap-current-message))
394               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
395       (nnheader-insert-nov
396        (with-temp-buffer
397          (buffer-disable-undo)
398          (insert headers)
399          (nnheader-ms-strip-cr)
400          (nnheader-fold-continuation-lines)
401          (subst-char-in-region (point-min) (point-max) ?\t ? )
402          (let ((head (nnheader-parse-head 'naked)))
403            (mail-header-set-number head uid)
404            (mail-header-set-chars head chars)
405            (mail-header-set-lines head lines)
406            (mail-header-set-xref
407             head (format "%s %s:%d" (system-name) mbx uid))
408            head))))))
409
410 (defun nnimap-retrieve-which-headers (articles fetch-old)
411   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
412   (with-current-buffer nnimap-server-buffer
413     (if (numberp (car-safe articles))
414         (imap-search
415          (concat "UID "
416                  (nnimap-range-to-string
417                   (gnus-compress-sequence
418                    (append (gnus-uncompress-sequence
419                             (and fetch-old
420                                  (cons (if (numberp fetch-old)
421                                            (max 1 (- (car articles) fetch-old))
422                                          1)
423                                        (1- (car articles)))))
424                            articles)))))
425       (mapcar (lambda (msgid)
426                 (imap-search
427                  (format "HEADER Message-Id %s" msgid)))
428               articles))))
429
430 (defun nnimap-group-overview-filename (group server)
431   "Make pathname for GROUP on SERVER."
432   (let ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
433         (file (nnheader-translate-file-chars
434                (concat nnimap-nov-file-name
435                        (if (equal server "")
436                            "unnamed"
437                          server) "." group nnimap-nov-file-name-suffix) t)))
438     (if (or nnmail-use-long-file-names
439             (file-exists-p (concat dir file)))
440         (concat dir file)
441       (concat dir (mm-encode-coding-string
442                    (nnheader-replace-chars-in-string file ?. ?/)
443                    nnmail-pathname-coding-system)))))
444
445 (defun nnimap-retrieve-headers-from-file (group server)
446   (with-current-buffer nntp-server-buffer
447     (let ((nov (nnimap-group-overview-filename group server)))
448       (when (file-exists-p nov)
449         (mm-insert-file-contents nov)
450         (set-buffer-modified-p nil)
451         (let ((min (progn (goto-char (point-min))
452                           (when (not (eobp))
453                             (read (current-buffer)))))
454               (max (progn (goto-char (point-max))
455                           (forward-line -1)
456                           (when (not (bobp))
457                             (read (current-buffer))))))
458           (if (and (numberp min) (numberp max))
459               (cons min max)
460             ;; junk, remove it, it's saved later
461             (erase-buffer)
462             nil))))))
463
464 (defun nnimap-retrieve-headers-from-server (articles group server)
465   (with-current-buffer nnimap-server-buffer
466     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
467           (nnimap-length (gnus-range-length articles))
468           (nnimap-counter 0))
469       (imap-fetch (nnimap-range-to-string articles)
470                   (concat "(UID RFC822.SIZE BODY "
471                           (let ((headers
472                                  (append '(Subject From Date Message-Id
473                                                    References In-Reply-To Xref)
474                                          (copy-sequence
475                                           nnmail-extra-headers))))
476                             (if (imap-capability 'IMAP4rev1)
477                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
478                               (format "RFC822.HEADER.LINES %s)" headers)))))
479       (and (numberp nnmail-large-newsgroup)
480            (> nnimap-length nnmail-large-newsgroup)
481            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
482
483 (defun nnimap-use-nov-p (group server)
484   (or gnus-nov-is-evil nnimap-nov-is-evil
485       (unless (and (gnus-make-directory
486                     (file-name-directory
487                      (nnimap-group-overview-filename group server)))
488                    (file-writable-p
489                     (nnimap-group-overview-filename group server)))
490         (message "nnimap: Nov cache not writable, %s"
491                  (nnimap-group-overview-filename group server)))))
492
493 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
494   (when (nnimap-possibly-change-group group server)
495     (with-current-buffer nntp-server-buffer
496       (erase-buffer)
497       (if (nnimap-use-nov-p group server)
498           (nnimap-retrieve-headers-from-server
499            (gnus-compress-sequence articles) group server)
500         (let (uids cached low high)
501           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
502                       low (car uids)
503                       high (car (last uids)))
504             (if (setq cached (nnimap-retrieve-headers-from-file group server))
505                 (progn
506                   ;; fetch articles with uids before cache block
507                   (when (< low (car cached))
508                     (goto-char (point-min))
509                     (nnimap-retrieve-headers-from-server
510                      (cons low (1- (car cached))) group server))
511                   ;; fetch articles with uids after cache block
512                   (when (> high (cdr cached))
513                     (goto-char (point-max))
514                     (nnimap-retrieve-headers-from-server
515                      (cons (1+ (cdr cached)) high) group server))
516                   (when nnimap-prune-cache
517                     ;; remove nov's for articles which has expired on server
518                     (goto-char (point-min))
519                     (dolist (uid (gnus-set-difference articles uids))
520                       (when (re-search-forward (format "^%d\t" uid) nil t)
521                         (gnus-delete-line)))))
522               ;; nothing cached, fetch whole range from server
523               (nnimap-retrieve-headers-from-server
524                (cons low high) group server))
525             (when (buffer-modified-p)
526               (nnmail-write-region
527                1 (point-max) (nnimap-group-overview-filename group server)
528                nil 'nomesg))
529             (nnheader-nov-delete-outside-range low high))))
530       'nov)))
531
532 (defun nnimap-open-connection (server)
533   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
534                       nnimap-authenticator nnimap-server-buffer))
535       (nnheader-report 'nnimap "Can't open connection to server %s" server)
536     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
537                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
538       (imap-close nnimap-server-buffer)
539       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
540     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
541            (port (if nnimap-server-port
542                      (int-to-string nnimap-server-port)
543                    "imap"))
544            (alist (or (gnus-netrc-machine list server port "imap")
545                       (gnus-netrc-machine list nnimap-address port "imap")))
546            (user (gnus-netrc-get alist "login"))
547            (passwd (gnus-netrc-get alist "password")))
548       (if (imap-authenticate user passwd nnimap-server-buffer)
549           (prog1
550               (push (list server nnimap-server-buffer)
551                     nnimap-server-buffer-alist)
552             (nnimap-possibly-change-server server))
553         (imap-close nnimap-server-buffer)
554         (kill-buffer nnimap-server-buffer)
555         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
556
557 (deffoo nnimap-open-server (server &optional defs)
558   (nnheader-init-server-buffer)
559   (if (nnimap-server-opened server)
560       t
561     (unless (assq 'nnimap-server-buffer defs)
562       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
563     ;; translate `nnimap-server-address' to `nnimap-address' in defs
564     ;; for people that configured nnimap with a very old version
565     (unless (assq 'nnimap-address defs)
566       (if (assq 'nnimap-server-address defs)
567           (push (list 'nnimap-address
568                       (cadr (assq 'nnimap-server-address defs))) defs)
569         (push (list 'nnimap-address server) defs)))
570     (nnoo-change-server 'nnimap server defs)
571     (or (and nnimap-server-buffer
572              (imap-opened nnimap-server-buffer))
573         (nnimap-open-connection server))))
574
575 (deffoo nnimap-server-opened (&optional server)
576   "Whether SERVER is opened.
577 If SERVER is the current virtual server, and the connection to the
578 physical server is alive, this function return a non-nil value.  If
579 SERVER is nil, it is treated as the current server."
580   ;; clean up autologouts??
581   (and (or server nnimap-current-server)
582        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
583        (imap-opened (nnimap-get-server-buffer server))))
584
585 (deffoo nnimap-close-server (&optional server)
586   "Close connection to server and free all resources connected to it.
587 Return nil if the server couldn't be closed for some reason."
588   (let ((server (or server nnimap-current-server)))
589     (when (or (nnimap-server-opened server)
590               (imap-opened (nnimap-get-server-buffer server)))
591       (imap-close (nnimap-get-server-buffer server))
592       (kill-buffer (nnimap-get-server-buffer server))
593       (setq nnimap-server-buffer nil
594             nnimap-current-server nil
595             nnimap-server-buffer-alist
596             (delq server nnimap-server-buffer-alist)))
597     (nnoo-close-server 'nnimap server)))
598
599 (deffoo nnimap-request-close ()
600   "Close connection to all servers and free all resources that the backend have reserved.
601 All buffers that have been created by that
602 backend should be killed.  (Not the nntp-server-buffer, though.) This
603 function is generally only called when Gnus is shutting down."
604   (mapcar (lambda (server) (nnimap-close-server (car server)))
605           nnimap-server-buffer-alist)
606   (setq nnimap-server-buffer-alist nil))
607
608 (deffoo nnimap-status-message (&optional server)
609   "This function returns the last error message from server."
610   (when (nnimap-possibly-change-server server)
611     (nnoo-status-message 'nnimap server)))
612
613 (defun nnimap-demule (string)
614   (funcall (if (and (fboundp 'string-as-multibyte)
615                     (subrp (symbol-function 'string-as-multibyte)))
616                'string-as-multibyte
617              'identity)
618            (or string "")))
619
620 (defun nnimap-callback ()
621   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
622   (with-current-buffer nnimap-callback-buffer
623     (insert
624      (with-current-buffer nnimap-server-buffer
625        (nnimap-demule
626         (if (imap-capability 'IMAP4rev1) 
627             ;; xxx don't just use car? alist doesn't contain
628             ;; anything else now, but it might...
629             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
630           (imap-message-get (imap-current-message) 'RFC822)))))
631     (nnheader-ms-strip-cr)
632     (funcall nnimap-callback-callback-function t)))
633
634 (defun nnimap-request-article-part (article part prop &optional
635                                             group server to-buffer detail)
636   (when (nnimap-possibly-change-group group server)
637     (let ((article (if (stringp article)
638                        (car-safe (imap-search
639                                   (format "HEADER Message-Id %s" article)
640                                   nnimap-server-buffer))
641                      article)))
642       (when article
643         (gnus-message 9 "nnimap: Fetching (part of) article %d..." article)
644         (if (not nnheader-callback-function)
645             (with-current-buffer (or to-buffer nntp-server-buffer)
646               (erase-buffer)
647               (let ((data (imap-fetch article part prop nil
648                                       nnimap-server-buffer)))
649                 (insert (nnimap-demule (if detail
650                                            (nth 2 (car data))
651                                          data))))
652               (nnheader-ms-strip-cr)
653               (gnus-message 9 "nnimap: Fetching (part of) article %d...done"
654                             article)
655               (if (bobp)
656                   (nnheader-report 'nnimap "No such article: %s"
657                                    (imap-error-text nnimap-server-buffer))
658                 (cons group article)))
659           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
660           (setq nnimap-callback-callback-function nnheader-callback-function
661                 nnimap-callback-buffer nntp-server-buffer)
662           (imap-fetch-asynch article part nil nnimap-server-buffer)
663           (cons group article))))))
664
665 (deffoo nnimap-asynchronous-p ()
666   t)
667
668 (deffoo nnimap-request-article (article &optional group server to-buffer)
669   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
670       (nnimap-request-article-part
671        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
672     (nnimap-request-article-part
673      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
674
675 (deffoo nnimap-request-head (article &optional group server to-buffer)
676   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
677       (nnimap-request-article-part
678        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
679     (nnimap-request-article-part
680      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
681
682 (deffoo nnimap-request-body (article &optional group server to-buffer)
683   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
684       (nnimap-request-article-part
685        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
686     (nnimap-request-article-part
687      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
688
689 (deffoo nnimap-request-group (group &optional server fast)
690   (nnimap-request-update-info-internal
691    group
692    (gnus-get-info (gnus-group-prefixed-name
693                    group (gnus-server-to-method (format "nnimap:%s" server))))
694    server)
695   (when (nnimap-possibly-change-group group server)
696     (let (info)
697       (cond (fast group)
698             ((null (setq info (nnimap-find-minmax-uid group t)))
699              (nnheader-report 'nnimap "Could not get active info for %s"
700                               group))
701             (t
702              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
703                               (max 1 (or (nth 1 info) 1))
704                               (or (nth 2 info) 0) group)
705              (nnheader-report 'nnimap "Group %s selected" group)
706              t)))))
707
708 (defun nnimap-close-group (group &optional server)
709   (with-current-buffer nnimap-server-buffer
710     (when (and (imap-opened)
711                (nnimap-possibly-change-group group server))
712       (case nnimap-expunge-on-close
713         ('always (imap-mailbox-expunge)
714                  (imap-mailbox-close))
715         ('ask (if (and (imap-search "DELETED")
716                        (gnus-y-or-n-p (format
717                                        "Expunge articles in group `%s'? "
718                                        imap-current-mailbox)))
719                   (progn (imap-mailbox-expunge)
720                          (imap-mailbox-close))
721                 (imap-mailbox-unselect)))
722         (t (imap-mailbox-unselect)))
723       (not imap-current-mailbox))))
724
725 (defun nnimap-pattern-to-list-arguments (pattern)
726   (mapcar (lambda (p)
727             (cons (car-safe p) (or (cdr-safe p) p)))
728           (if (and (listp pattern)
729                    (listp (cdr pattern)))
730               pattern
731             (list pattern))))
732
733 (deffoo nnimap-request-list (&optional server)
734   (when (nnimap-possibly-change-server server)
735     (with-current-buffer nntp-server-buffer
736       (erase-buffer))
737     (gnus-message 5 "nnimap: Generating active list%s..."
738                   (if (> (length server) 0) (concat " for " server) ""))
739     (with-current-buffer nnimap-server-buffer
740       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
741         (dolist (mbx (funcall nnimap-request-list-method
742                               (cdr pattern) (car pattern)))
743           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
744               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
745                 (when info
746                   (with-current-buffer nntp-server-buffer
747                    (insert (format "\"%s\" %d %d y\n"
748                                    mbx (or (nth 2 info) 0)
749                                    (max 1 (or (nth 1 info) 1)))))))))))
750     (gnus-message 5 "nnimap: Generating active list%s...done"
751                   (if (> (length server) 0) (concat " for " server) ""))
752     t))
753
754 (deffoo nnimap-request-post (&optional server)
755   (let ((success t))
756     (dolist (mbx (message-unquote-tokens
757                   (message-tokenize-header
758                    (message-fetch-field "Newsgroups") ", ")) success)
759       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
760         (or (gnus-active to-newsgroup)
761             (gnus-activate-group to-newsgroup)
762             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
763                                        to-newsgroup))
764                 (or (and (gnus-request-create-group
765                           to-newsgroup gnus-command-method)
766                          (gnus-activate-group to-newsgroup nil nil
767                                               gnus-command-method))
768                     (error "Couldn't create group %s" to-newsgroup)))
769             (error "No such group: %s" to-newsgroup))
770         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
771           (setq success nil))))))
772
773 ;; Optional backend functions
774
775 (deffoo nnimap-retrieve-groups (groups &optional server)
776   (when (nnimap-possibly-change-server server)
777     (gnus-message 5 "nnimap: Checking mailboxes...")
778     (with-current-buffer nntp-server-buffer
779       (erase-buffer)
780       (dolist (group groups)
781         (gnus-message 7 "nnimap: Checking mailbox %s" group)
782         (or (member "\\NoSelect"
783                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
784             (let ((info (nnimap-find-minmax-uid group 'examine)))
785               (insert (format "\"%s\" %d %d y\n" group
786                               (or (nth 2 info) 0)
787                               (max 1 (or (nth 1 info) 1))))))))
788     (gnus-message 5 "nnimap: Checking mailboxes...done")
789     'active))
790
791 (deffoo nnimap-request-update-info-internal (group info &optional server)
792   (when (nnimap-possibly-change-group group server)
793     (when info;; xxx what does this mean? should we create a info?
794       (with-current-buffer nnimap-server-buffer
795         (gnus-message 5 "nnimap: Updating info for %s..."
796                       (gnus-info-group info))
797         
798         (when (nnimap-mark-permanent-p 'read)
799           (let (seen unseen)
800             ;; read info could contain articles marked unread by other
801             ;; imap clients!  we correct this
802             (setq seen (gnus-uncompress-range (gnus-info-read info))
803                   unseen (imap-search "UNSEEN UNDELETED")
804                   seen (gnus-set-difference seen unseen)
805                   ;; seen might lack articles marked as read by other
806                   ;; imap clients! we correct this
807                   seen (append seen (imap-search "SEEN"))
808                   ;; remove dupes
809                   seen (sort seen '<)
810                   seen (gnus-compress-sequence seen t)
811                   ;; we can't return '(1) since this isn't a "list of ranges",
812                   ;; and we can't return '((1)) since g-list-of-unread-articles
813                   ;; is buggy so we return '((1 . 1)).
814                   seen (if (and (integerp (car seen))
815                                 (null (cdr seen)))
816                            (list (cons (car seen) (car seen)))
817                          seen))
818             (gnus-info-set-read info seen)))
819
820         (mapcar (lambda (pred)
821                   (when (and (nnimap-mark-permanent-p (cdr pred))
822                              (member (nnimap-mark-to-flag (cdr pred))
823                                      (imap-mailbox-get 'flags)))
824                     (gnus-info-set-marks
825                      info
826                      (nnimap-update-alist-soft
827                       (cdr pred)
828                       (gnus-compress-sequence
829                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
830                       (gnus-info-marks info))
831                      t)))
832                 gnus-article-mark-lists)
833         
834         (gnus-message 5 "nnimap: Updating info for %s...done"
835                       (gnus-info-group info))
836
837         info))))
838
839 (deffoo nnimap-request-type (group &optional article)
840   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
841       'news
842     'mail))
843
844 (deffoo nnimap-request-set-mark (group actions &optional server)
845   (when (nnimap-possibly-change-group group server)
846     (with-current-buffer nnimap-server-buffer
847       (let (action)
848         (gnus-message 7 "nnimap: Setting marks in %s..." group)
849         (while (setq action (pop actions))
850           (let ((range (nth 0 action))
851                 (what  (nth 1 action))
852                 (cmdmarks (nth 2 action))
853                 marks)
854             ;; cache flags are pointless on the server
855             (setq cmdmarks (delq 'cache cmdmarks))
856             ;; flag dormant articles as ticked
857             (if (memq 'dormant cmdmarks)
858                 (setq cmdmarks (cons 'tick cmdmarks)))
859             ;; remove stuff we are forbidden to store
860             (mapcar (lambda (mark)
861                       (if (imap-message-flag-permanent-p
862                            (nnimap-mark-to-flag mark))
863                           (setq marks (cons mark marks))))
864                     cmdmarks)
865             (when (and range marks)
866               (cond ((eq what 'del)
867                      (imap-message-flags-del
868                       (nnimap-range-to-string range)
869                       (nnimap-mark-to-flag marks nil t)))
870                     ((eq what 'add)
871                      (imap-message-flags-add
872                       (nnimap-range-to-string range)
873                       (nnimap-mark-to-flag marks nil t)))
874                     ((eq what 'set)
875                      (imap-message-flags-set
876                       (nnimap-range-to-string range)
877                       (nnimap-mark-to-flag marks nil t)))))))
878         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
879   nil)
880
881 (defun nnimap-split-fancy ()
882   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
883   (let ((nnmail-split-fancy nnimap-split-fancy))
884     (nnmail-split-fancy)))
885
886 (defun nnimap-split-to-groups (rules)
887   ;; tries to match all rules in nnimap-split-rule against content of
888   ;; nntp-server-buffer, returns a list of groups that matched.
889   (with-current-buffer nntp-server-buffer
890     ;; Fold continuation lines.
891     (goto-char (point-min))
892     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
893       (replace-match " " t t))
894     (if (functionp rules)
895         (funcall rules)
896       (let (to-groups regrepp)
897         (catch 'split-done
898           (dolist (rule rules to-groups)
899             (let ((group (car rule))
900                   (regexp (cadr rule)))
901               (goto-char (point-min))
902               (when (and (if (stringp regexp)
903                              (progn
904                                (setq regrepp (string-match "\\\\[0-9&]" group))
905                                (re-search-forward regexp nil t))
906                            (funcall regexp group))
907                          ;; Don't enter the article into the same group twice.
908                          (not (assoc group to-groups)))
909                 (push (if regrepp
910                           (nnmail-expand-newtext group)
911                         group)
912                       to-groups)
913                 (or nnimap-split-crosspost
914                     (throw 'split-done to-groups))))))))))
915   
916 (defun nnimap-assoc-match (key alist)
917   (let (element)
918     (while (and alist (not element))
919       (if (string-match (car (car alist)) key)
920           (setq element (car alist)))
921       (setq alist (cdr alist)))
922     element))
923
924 (defun nnimap-split-find-rule (server inbox)
925   (if (listp (cadar nnimap-split-rule)) ;; extended format?
926       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
927                                             server nnimap-split-rule))))
928     nnimap-split-rule))
929
930 (defun nnimap-split-find-inbox (server)
931   (if (listp nnimap-split-inbox)
932       nnimap-split-inbox
933     (list nnimap-split-inbox)))
934
935 (defun nnimap-split-articles (&optional group server)
936   (when (nnimap-possibly-change-server server)
937     (with-current-buffer nnimap-server-buffer
938       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
939         ;; iterate over inboxes
940         (while (and (setq inbox (pop inboxes))
941                     (nnimap-possibly-change-group inbox));; SELECT
942           ;; find split rule for this server / inbox
943           (when (setq rule (nnimap-split-find-rule server inbox))
944             ;; iterate over articles
945             (dolist (article (imap-search nnimap-split-predicate))
946               (when (nnimap-request-head article)
947                 ;; copy article to right group(s)
948                 (setq removeorig nil)
949                 (dolist (to-group (nnimap-split-to-groups rule))
950                   (if (imap-message-copy (number-to-string article)
951                                          to-group nil 'nocopyuid)
952                       (progn
953                         (message "IMAP split moved %s:%s:%d to %s" server inbox
954                                  article to-group)
955                         (setq removeorig t)
956                         ;; Add the group-art list to the history list.
957                         (push (list (cons to-group 0)) nnmail-split-history))
958                     (message "IMAP split failed to move %s:%s:%d to %s" server
959                              inbox article to-group)))
960                 ;; remove article if it was successfully copied somewhere
961                 (and removeorig
962                      (imap-message-flags-add (format "%d" article)
963                                              "\\Seen \\Deleted")))))
964           (when (imap-mailbox-select inbox);; just in case
965             ;; todo: UID EXPUNGE (if available) to remove splitted articles
966             (imap-mailbox-expunge)
967             (imap-mailbox-close)))
968         t))))
969
970 (deffoo nnimap-request-scan (&optional group server)
971   (nnimap-split-articles group server))
972
973 (deffoo nnimap-request-newgroups (date &optional server)
974   (when (nnimap-possibly-change-server server)
975     (with-current-buffer nntp-server-buffer
976       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
977                     (if (> (length server) 0) " on " "") server)
978       (erase-buffer)
979       (dolist (pattern (nnimap-pattern-to-list-arguments
980                         nnimap-list-pattern))
981         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
982                                         nnimap-server-buffer))
983           (or (member-if (lambda (mailbox)
984                            (string= (downcase mailbox) "\\noselect"))
985                          (imap-mailbox-get 'list-flags mbx
986                                            nnimap-server-buffer))
987               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
988                 (when info
989                  (insert (format "\"%s\" %d %d y\n"
990                                  mbx (or (nth 2 info) 0)
991                                  (max 1 (or (nth 1 info) 1)))))))))
992       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
993                     (if (> (length server) 0) " on " "") server))
994     t))
995       
996 (deffoo nnimap-request-create-group (group &optional server args)
997   (when (nnimap-possibly-change-server server)
998     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
999         (imap-mailbox-create group nnimap-server-buffer))))
1000
1001 (defun nnimap-time-substract (time1 time2)
1002   "Return TIME for TIME1 - TIME2."
1003   (let* ((ms (- (car time1) (car time2)))
1004          (ls (- (nth 1 time1) (nth 1 time2))))
1005     (if (< ls 0)
1006         (list (- ms 1) (+ (expt 2 16) ls))
1007       (list ms ls))))
1008
1009 (defun nnimap-date-days-ago (daysago)
1010   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1011   (let ((date (format-time-string "%d-%b-%Y"
1012                                   (nnimap-time-substract
1013                                    (current-time)
1014                                    (days-to-time daysago)))))
1015     (if (eq ?0 (string-to-char date))
1016         (substring date 1)
1017       date)))
1018
1019 (defun nnimap-request-expire-articles-progress ()
1020   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1021                 imap-current-message))
1022
1023 ;; Notice that we don't actually delete anything, we just mark them deleted.
1024 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1025   (let ((artseq (gnus-compress-sequence articles)))
1026     (when (and artseq (nnimap-possibly-change-group group server))
1027       (with-current-buffer nnimap-server-buffer
1028         (if force
1029             (and (imap-message-flags-add
1030                   (nnimap-range-to-string artseq) "\\Deleted")
1031                  (setq articles nil))
1032           (let ((days (or (and nnmail-expiry-wait-function
1033                                (funcall nnmail-expiry-wait-function group))
1034                           nnmail-expiry-wait)))
1035             (cond ((eq days 'immediate)
1036                    (and (imap-message-flags-add
1037                          (nnimap-range-to-string artseq) "\\Deleted")
1038                         (setq articles nil)))
1039                   ((numberp days)
1040                    (let ((oldarts (imap-search
1041                                    (format "UID %s NOT SINCE %s"
1042                                            (nnimap-range-to-string artseq)
1043                                            (nnimap-date-days-ago days))))
1044                          (imap-fetch-data-hook
1045                           '(nnimap-request-expire-articles-progress)))
1046                      (and oldarts
1047                           (imap-message-flags-add
1048                            (nnimap-range-to-string
1049                             (gnus-compress-sequence oldarts))
1050                            "\\Deleted")
1051                           (setq articles (gnus-set-difference
1052                                           articles oldarts)))))))))))
1053   ;; return articles not deleted
1054   articles)
1055
1056 (deffoo nnimap-request-move-article (article group server
1057                                              accept-form &optional last)
1058   (when (nnimap-possibly-change-server server)
1059     (save-excursion
1060       (let ((buf (get-buffer-create " *nnimap move*"))
1061             (nnimap-current-move-article article)
1062             (nnimap-current-move-group group)
1063             (nnimap-current-move-server nnimap-current-server)
1064             result)
1065         (and (nnimap-request-article article group server)
1066              (save-excursion
1067                (set-buffer buf)
1068                (buffer-disable-undo (current-buffer))
1069                (insert-buffer-substring nntp-server-buffer)
1070                (setq result (eval accept-form))
1071                (kill-buffer buf)
1072                result)
1073              (nnimap-request-expire-articles (list article) group server t))
1074         result))))
1075   
1076 (deffoo nnimap-request-accept-article (group &optional server last)
1077   (when (nnimap-possibly-change-server server)
1078     (let (uid)
1079       (if (setq uid
1080                 (if (string= nnimap-current-server nnimap-current-move-server)
1081                     ;; moving article within same server, speed it up...
1082                     (and (nnimap-possibly-change-group
1083                           nnimap-current-move-group)
1084                          (imap-message-copy (number-to-string
1085                                              nnimap-current-move-article)
1086                                             group 'dontcreate nil
1087                                             nnimap-server-buffer))
1088                   ;; turn into rfc822 format (\r\n eol's)
1089                   (with-current-buffer (current-buffer)
1090                     (goto-char (point-min))
1091                     (while (search-forward "\n" nil t)
1092                       (replace-match "\r\n")))
1093                   ;; this 'or' is for Cyrus server bug
1094                   (or (null (imap-current-mailbox nnimap-server-buffer))
1095                       (imap-mailbox-unselect nnimap-server-buffer))
1096                   (imap-message-append group (current-buffer) nil nil
1097                                        nnimap-server-buffer)))
1098           (cons group (nth 1 uid))
1099         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1100
1101 (deffoo nnimap-request-delete-group (group force &optional server)
1102   (when (nnimap-possibly-change-server server)
1103     (with-current-buffer nnimap-server-buffer
1104       (if force
1105           (or (null (imap-mailbox-status group 'uidvalidity))
1106               (imap-mailbox-delete group))
1107         ;; UNSUBSCRIBE?
1108         t))))
1109
1110 (deffoo nnimap-request-rename-group (group new-name &optional server)
1111   (when (nnimap-possibly-change-server server)
1112     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1113
1114 (defun nnimap-expunge (mailbox server)
1115   (when (nnimap-possibly-change-group mailbox server)
1116     (imap-mailbox-expunge nnimap-server-buffer)))
1117
1118 (defun nnimap-acl-get (mailbox server)
1119   (when (nnimap-possibly-change-server server)
1120     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1121
1122 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1123   (when (nnimap-possibly-change-server (cadr method))
1124     (unless (imap-capability 'ACL nnimap-server-buffer)
1125       (error "Your server does not support ACL editing"))
1126     (with-current-buffer nnimap-server-buffer
1127       ;; delete all removed identifiers
1128       (mapcar (lambda (old-acl)
1129                 (unless (assoc (car old-acl) new-acls)
1130                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1131                       (error "Can't delete ACL for %s" (car old-acl)))))
1132               old-acls)
1133       ;; set all changed acl's
1134       (mapcar (lambda (new-acl)
1135                 (let ((new-rights (cdr new-acl))
1136                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1137                   (unless (and old-rights new-rights
1138                                (string= old-rights new-rights))
1139                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1140                         (error "Can't set ACL for %s to %s" (car new-acl)
1141                                new-rights)))))
1142               new-acls)
1143       t)))
1144
1145 \f
1146 ;;; Internal functions
1147
1148 ;;
1149 ;; This is confusing.
1150 ;;
1151 ;; mark      => read, tick, draft, reply etc
1152 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1153 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1154 ;;
1155 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1156 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1157 ;;
1158
1159 (defconst nnimap-mark-to-predicate-alist
1160   (mapcar
1161    (lambda (pair)                       ; cdr is the mark
1162      (or (assoc (cdr pair)
1163                 '((read . "SEEN")
1164                   (tick . "FLAGGED")
1165                   (draft . "DRAFT")
1166                   (reply . "ANSWERED")))
1167          (cons (cdr pair)
1168                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1169    (cons '(read . read) gnus-article-mark-lists)))
1170
1171 (defun nnimap-mark-to-predicate (pred)
1172   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1173 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1174 to be used within a IMAP SEARCH query."
1175   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1176
1177 (defconst nnimap-mark-to-flag-alist
1178   (mapcar
1179    (lambda (pair)
1180      (or (assoc (cdr pair)
1181                 '((read . "\\Seen")
1182                   (tick . "\\Flagged")
1183                   (draft . "\\Draft")
1184                   (reply . "\\Answered")))
1185          (cons (cdr pair)
1186                (format "gnus-%s" (symbol-name (cdr pair))))))
1187    (cons '(read . read) gnus-article-mark-lists)))
1188
1189 (defun nnimap-mark-to-flag-1 (preds)
1190   (if (and (not (null preds)) (listp preds))
1191       (cons (nnimap-mark-to-flag (car preds))
1192             (nnimap-mark-to-flag (cdr preds)))
1193     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1194
1195 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1196   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1197 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1198 be used in a STORE FLAGS command."
1199   (let ((result (nnimap-mark-to-flag-1 preds)))
1200     (setq result (if (and (or make-string always-list)
1201                           (not (listp result)))
1202                      (list result)
1203                    result))
1204     (if make-string
1205         (mapconcat (lambda (flag)
1206                      (if (listp flag)
1207                          (mapconcat 'identity flag " ")
1208                        flag))
1209                    result " ")
1210       result)))
1211
1212 (defun nnimap-mark-permanent-p (mark &optional group)
1213   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1214   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1215
1216 (defun nnimap-remassoc (key alist)
1217   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1218 The modified LIST is returned.  If the first member
1219 of LIST has a car that is `equal' to KEY, there is no way to remove it
1220 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1221 sure of changing the value of `foo'."
1222   (when alist
1223     (if (equal key (caar alist))
1224         (cdr alist)
1225       (setcdr alist (nnimap-remassoc key (cdr alist)))
1226       alist)))
1227   
1228 (defun nnimap-update-alist-soft (key value alist)
1229   (if value
1230       (cons (cons key value) (nnimap-remassoc key alist))
1231     (nnimap-remassoc key alist)))
1232
1233 (defun nnimap-range-to-string (range)
1234   (mapconcat
1235    (lambda (item)
1236      (if (consp item)
1237          (format "%d:%d"
1238                  (car item) (cdr item))
1239        (format "%d" item)))
1240    (if (and (listp range) (not (listp (cdr range))))
1241        (list range);; make (1 . 2) into ((1 . 2))
1242      range)
1243    ","))
1244
1245 (when nnimap-debug
1246   (require 'trace)
1247   (buffer-disable-undo (get-buffer-create nnimap-debug))
1248   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1249         '(
1250           nnimap-possibly-change-server
1251           nnimap-verify-uidvalidity
1252           nnimap-find-minmax-uid
1253           nnimap-possibly-change-group
1254           ;;nnimap-replace-whitespace
1255           nnimap-retrieve-headers-progress
1256           nnimap-retrieve-which-headers
1257           nnimap-group-overview-filename
1258           nnimap-retrieve-headers-from-file
1259           nnimap-retrieve-headers-from-server
1260           nnimap-retrieve-headers
1261           nnimap-open-connection
1262           nnimap-open-server
1263           nnimap-server-opened
1264           nnimap-close-server
1265           nnimap-request-close
1266           nnimap-status-message
1267           ;;nnimap-demule
1268           nnimap-request-article-part
1269           nnimap-request-article
1270           nnimap-request-head
1271           nnimap-request-body
1272           nnimap-request-group
1273           nnimap-close-group
1274           nnimap-pattern-to-list-arguments
1275           nnimap-request-list
1276           nnimap-request-post
1277           nnimap-retrieve-groups
1278           nnimap-request-update-info-internal
1279           nnimap-request-type
1280           nnimap-request-set-mark
1281           nnimap-split-to-groups
1282           nnimap-split-find-rule
1283           nnimap-split-find-inbox
1284           nnimap-split-articles
1285           nnimap-request-scan
1286           nnimap-request-newgroups
1287           nnimap-request-create-group
1288           nnimap-time-substract
1289           nnimap-date-days-ago
1290           nnimap-request-expire-articles-progress
1291           nnimap-request-expire-articles
1292           nnimap-request-move-article
1293           nnimap-request-accept-article
1294           nnimap-request-delete-group
1295           nnimap-request-rename-group
1296           gnus-group-nnimap-expunge
1297           gnus-group-nnimap-edit-acl
1298           gnus-group-nnimap-edit-acl-done
1299           nnimap-group-mode-hook
1300           nnimap-mark-to-predicate
1301           nnimap-mark-to-flag-1
1302           nnimap-mark-to-flag
1303           nnimap-mark-permanent-p
1304           nnimap-remassoc
1305           nnimap-update-alist-soft
1306           nnimap-range-to-string
1307           )))
1308
1309 (provide 'nnimap)
1310
1311 ;;; nnimap.el ends here