cd14bc987880245f40788f76e8ce7f77df757cb5
[elisp/gnus.git-] / 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-when-compile (require 'cl))
61 (eval-when-compile (require 'gnus-clfns))
62 (eval-and-compile (require 'imap))
63
64 (require 'nnoo)
65 (require 'nnmail)
66 (require 'nnheader)
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-fold-continuation-lines)
400          (subst-char-in-region (point-min) (point-max) ?\t ? )
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                  (nnimap-range-to-string
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 (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         (nnheader-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 (nnimap-range-to-string 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                 (when data
653                   (insert (nnimap-demule (if detail
654                                              (nth 2 (car data))
655                                            data)))
656                   (nnheader-ms-strip-cr)
657                   (gnus-message 9
658                                 "nnimap: Fetching (part of) article %d...done"
659                                 article)
660                   (if (bobp)
661                       (nnheader-report 'nnimap "No such article: %s"
662                                        (imap-error-text nnimap-server-buffer))
663                     (cons group article)))))
664           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
665           (setq nnimap-callback-callback-function nnheader-callback-function
666                 nnimap-callback-buffer nntp-server-buffer)
667           (imap-fetch-asynch article part nil nnimap-server-buffer)
668           (cons group article))))))
669
670 (deffoo nnimap-asynchronous-p ()
671   t)
672
673 (deffoo nnimap-request-article (article &optional group server to-buffer)
674   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
675       (nnimap-request-article-part
676        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
677     (nnimap-request-article-part
678      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
679
680 (deffoo nnimap-request-head (article &optional group server to-buffer)
681   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
682       (nnimap-request-article-part
683        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
684     (nnimap-request-article-part
685      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
686
687 (deffoo nnimap-request-body (article &optional group server to-buffer)
688   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
689       (nnimap-request-article-part
690        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
691     (nnimap-request-article-part
692      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
693
694 (deffoo nnimap-request-group (group &optional server fast)
695   (nnimap-request-update-info-internal
696    group
697    (gnus-get-info (gnus-group-prefixed-name
698                    group (gnus-server-to-method (format "nnimap:%s" server))))
699    server)
700   (when (nnimap-possibly-change-group group server)
701     (let (info)
702       (cond (fast group)
703             ((null (setq info (nnimap-find-minmax-uid group t)))
704              (nnheader-report 'nnimap "Could not get active info for %s"
705                               group))
706             (t
707              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
708                               (max 1 (or (nth 1 info) 1))
709                               (or (nth 2 info) 0) group)
710              (nnheader-report 'nnimap "Group %s selected" group)
711              t)))))
712
713 (defun nnimap-close-group (group &optional server)
714   (with-current-buffer nnimap-server-buffer
715     (when (and (imap-opened)
716                (nnimap-possibly-change-group group server))
717       (case nnimap-expunge-on-close
718         ('always (imap-mailbox-expunge)
719                  (imap-mailbox-close))
720         ('ask (if (and (imap-search "DELETED")
721                        (gnus-y-or-n-p (format
722                                        "Expunge articles in group `%s'? "
723                                        imap-current-mailbox)))
724                   (progn (imap-mailbox-expunge)
725                          (imap-mailbox-close))
726                 (imap-mailbox-unselect)))
727         (t (imap-mailbox-unselect)))
728       (not imap-current-mailbox))))
729
730 (defun nnimap-pattern-to-list-arguments (pattern)
731   (mapcar (lambda (p)
732             (cons (car-safe p) (or (cdr-safe p) p)))
733           (if (and (listp pattern)
734                    (listp (cdr pattern)))
735               pattern
736             (list pattern))))
737
738 (deffoo nnimap-request-list (&optional server)
739   (when (nnimap-possibly-change-server server)
740     (with-current-buffer nntp-server-buffer
741       (erase-buffer))
742     (gnus-message 5 "nnimap: Generating active list%s..."
743                   (if (> (length server) 0) (concat " for " server) ""))
744     (with-current-buffer nnimap-server-buffer
745       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
746         (dolist (mbx (funcall nnimap-request-list-method
747                               (cdr pattern) (car pattern)))
748           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
749               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
750                 (when info
751                   (with-current-buffer nntp-server-buffer
752                    (insert (format "\"%s\" %d %d y\n"
753                                    mbx (or (nth 2 info) 0)
754                                    (max 1 (or (nth 1 info) 1)))))))))))
755     (gnus-message 5 "nnimap: Generating active list%s...done"
756                   (if (> (length server) 0) (concat " for " server) ""))
757     t))
758
759 (deffoo nnimap-request-post (&optional server)
760   (let ((success t))
761     (dolist (mbx (message-unquote-tokens
762                   (message-tokenize-header
763                    (message-fetch-field "Newsgroups") ", ")) success)
764       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
765         (or (gnus-active to-newsgroup)
766             (gnus-activate-group to-newsgroup)
767             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
768                                        to-newsgroup))
769                 (or (and (gnus-request-create-group
770                           to-newsgroup gnus-command-method)
771                          (gnus-activate-group to-newsgroup nil nil
772                                               gnus-command-method))
773                     (error "Couldn't create group %s" to-newsgroup)))
774             (error "No such group: %s" to-newsgroup))
775         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
776           (setq success nil))))))
777
778 ;; Optional backend functions
779
780 (deffoo nnimap-retrieve-groups (groups &optional server)
781   (when (nnimap-possibly-change-server server)
782     (gnus-message 5 "nnimap: Checking mailboxes...")
783     (with-current-buffer nntp-server-buffer
784       (erase-buffer)
785       (dolist (group groups)
786         (gnus-message 7 "nnimap: Checking mailbox %s" group)
787         (or (member "\\NoSelect"
788                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
789             (let ((info (nnimap-find-minmax-uid group 'examine)))
790               (insert (format "\"%s\" %d %d y\n" group
791                               (or (nth 2 info) 0)
792                               (max 1 (or (nth 1 info) 1))))))))
793     (gnus-message 5 "nnimap: Checking mailboxes...done")
794     'active))
795
796 (deffoo nnimap-request-update-info-internal (group info &optional server)
797   (when (nnimap-possibly-change-group group server)
798     (when info;; xxx what does this mean? should we create a info?
799       (with-current-buffer nnimap-server-buffer
800         (gnus-message 5 "nnimap: Updating info for %s..."
801                       (gnus-info-group info))
802         
803         (when (nnimap-mark-permanent-p 'read)
804           (let (seen unseen)
805             ;; read info could contain articles marked unread by other
806             ;; imap clients!  we correct this
807             (setq seen (gnus-uncompress-range (gnus-info-read info))
808                   unseen (imap-search "UNSEEN UNDELETED")
809                   seen (gnus-set-difference seen unseen)
810                   ;; seen might lack articles marked as read by other
811                   ;; imap clients! we correct this
812                   seen (append seen (imap-search "SEEN"))
813                   ;; remove dupes
814                   seen (sort seen '<)
815                   seen (gnus-compress-sequence seen t)
816                   ;; we can't return '(1) since this isn't a "list of ranges",
817                   ;; and we can't return '((1)) since g-list-of-unread-articles
818                   ;; is buggy so we return '((1 . 1)).
819                   seen (if (and (integerp (car seen))
820                                 (null (cdr seen)))
821                            (list (cons (car seen) (car seen)))
822                          seen))
823             (gnus-info-set-read info seen)))
824
825         (mapcar (lambda (pred)
826                   (when (and (nnimap-mark-permanent-p (cdr pred))
827                              (member (nnimap-mark-to-flag (cdr pred))
828                                      (imap-mailbox-get 'flags)))
829                     (gnus-info-set-marks
830                      info
831                      (nnimap-update-alist-soft
832                       (cdr pred)
833                       (gnus-compress-sequence
834                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
835                       (gnus-info-marks info))
836                      t)))
837                 gnus-article-mark-lists)
838         
839         (gnus-message 5 "nnimap: Updating info for %s...done"
840                       (gnus-info-group info))
841
842         info))))
843
844 (deffoo nnimap-request-type (group &optional article)
845   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
846       'news
847     'mail))
848
849 (deffoo nnimap-request-set-mark (group actions &optional server)
850   (when (nnimap-possibly-change-group group server)
851     (with-current-buffer nnimap-server-buffer
852       (let (action)
853         (gnus-message 7 "nnimap: Setting marks in %s..." group)
854         (while (setq action (pop actions))
855           (let ((range (nth 0 action))
856                 (what  (nth 1 action))
857                 (cmdmarks (nth 2 action))
858                 marks)
859             ;; cache flags are pointless on the server
860             (setq cmdmarks (delq 'cache cmdmarks))
861             ;; flag dormant articles as ticked
862             (if (memq 'dormant cmdmarks)
863                 (setq cmdmarks (cons 'tick cmdmarks)))
864             ;; remove stuff we are forbidden to store
865             (mapcar (lambda (mark)
866                       (if (imap-message-flag-permanent-p
867                            (nnimap-mark-to-flag mark))
868                           (setq marks (cons mark marks))))
869                     cmdmarks)
870             (when (and range marks)
871               (cond ((eq what 'del)
872                      (imap-message-flags-del
873                       (nnimap-range-to-string range)
874                       (nnimap-mark-to-flag marks nil t)))
875                     ((eq what 'add)
876                      (imap-message-flags-add
877                       (nnimap-range-to-string range)
878                       (nnimap-mark-to-flag marks nil t)))
879                     ((eq what 'set)
880                      (imap-message-flags-set
881                       (nnimap-range-to-string range)
882                       (nnimap-mark-to-flag marks nil t)))))))
883         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
884   nil)
885
886 (defun nnimap-split-fancy ()
887   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
888   (let ((nnmail-split-fancy nnimap-split-fancy))
889     (nnmail-split-fancy)))
890
891 (defun nnimap-split-to-groups (rules)
892   ;; tries to match all rules in nnimap-split-rule against content of
893   ;; nntp-server-buffer, returns a list of groups that matched.
894   (with-current-buffer nntp-server-buffer
895     ;; Fold continuation lines.
896     (goto-char (point-min))
897     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
898       (replace-match " " t t))
899     (if (functionp rules)
900         (funcall rules)
901       (let (to-groups regrepp)
902         (catch 'split-done
903           (dolist (rule rules to-groups)
904             (let ((group (car rule))
905                   (regexp (cadr rule)))
906               (goto-char (point-min))
907               (when (and (if (stringp regexp)
908                              (progn
909                                (setq regrepp (string-match "\\\\[0-9&]" group))
910                                (re-search-forward regexp nil t))
911                            (funcall regexp group))
912                          ;; Don't enter the article into the same group twice.
913                          (not (assoc group to-groups)))
914                 (push (if regrepp
915                           (nnmail-expand-newtext group)
916                         group)
917                       to-groups)
918                 (or nnimap-split-crosspost
919                     (throw 'split-done to-groups))))))))))
920   
921 (defun nnimap-assoc-match (key alist)
922   (let (element)
923     (while (and alist (not element))
924       (if (string-match (car (car alist)) key)
925           (setq element (car alist)))
926       (setq alist (cdr alist)))
927     element))
928
929 (defun nnimap-split-find-rule (server inbox)
930   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
931            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
932       ;; extended format
933       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
934                                             server nnimap-split-rule))))
935     nnimap-split-rule))
936
937 (defun nnimap-split-find-inbox (server)
938   (if (listp nnimap-split-inbox)
939       nnimap-split-inbox
940     (list nnimap-split-inbox)))
941
942 (defun nnimap-split-articles (&optional group server)
943   (when (nnimap-possibly-change-server server)
944     (with-current-buffer nnimap-server-buffer
945       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
946         ;; iterate over inboxes
947         (while (and (setq inbox (pop inboxes))
948                     (nnimap-possibly-change-group inbox));; SELECT
949           ;; find split rule for this server / inbox
950           (when (setq rule (nnimap-split-find-rule server inbox))
951             ;; iterate over articles
952             (dolist (article (imap-search nnimap-split-predicate))
953               (when (nnimap-request-head article)
954                 ;; copy article to right group(s)
955                 (setq removeorig nil)
956                 (dolist (to-group (nnimap-split-to-groups rule))
957                   (if (imap-message-copy (number-to-string article)
958                                          to-group nil 'nocopyuid)
959                       (progn
960                         (message "IMAP split moved %s:%s:%d to %s" server inbox
961                                  article to-group)
962                         (setq removeorig t)
963                         ;; Add the group-art list to the history list.
964                         (push (list (cons to-group 0)) nnmail-split-history))
965                     (message "IMAP split failed to move %s:%s:%d to %s" server
966                              inbox article to-group)))
967                 ;; remove article if it was successfully copied somewhere
968                 (and removeorig
969                      (imap-message-flags-add (format "%d" article)
970                                              "\\Seen \\Deleted")))))
971           (when (imap-mailbox-select inbox);; just in case
972             ;; todo: UID EXPUNGE (if available) to remove splitted articles
973             (imap-mailbox-expunge)
974             (imap-mailbox-close)))
975         t))))
976
977 (deffoo nnimap-request-scan (&optional group server)
978   (nnimap-split-articles group server))
979
980 (deffoo nnimap-request-newgroups (date &optional server)
981   (when (nnimap-possibly-change-server server)
982     (with-current-buffer nntp-server-buffer
983       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
984                     (if (> (length server) 0) " on " "") server)
985       (erase-buffer)
986       (dolist (pattern (nnimap-pattern-to-list-arguments
987                         nnimap-list-pattern))
988         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
989                                         nnimap-server-buffer))
990           (or (member-if (lambda (mailbox)
991                            (string= (downcase mailbox) "\\noselect"))
992                          (imap-mailbox-get 'list-flags mbx
993                                            nnimap-server-buffer))
994               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
995                 (when info
996                   (insert (format "\"%s\" %d %d y\n"
997                                   mbx (or (nth 2 info) 0)
998                                   (max 1 (or (nth 1 info) 1)))))))))
999       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1000                     (if (> (length server) 0) " on " "") server))
1001     t))
1002       
1003 (deffoo nnimap-request-create-group (group &optional server args)
1004   (when (nnimap-possibly-change-server server)
1005     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1006         (imap-mailbox-create group nnimap-server-buffer))))
1007
1008 (defun nnimap-time-substract (time1 time2)
1009   "Return TIME for TIME1 - TIME2."
1010   (let* ((ms (- (car time1) (car time2)))
1011          (ls (- (nth 1 time1) (nth 1 time2))))
1012     (if (< ls 0)
1013         (list (- ms 1) (+ (expt 2 16) ls))
1014       (list ms ls))))
1015
1016 (defun nnimap-date-days-ago (daysago)
1017   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1018   (let ((date (format-time-string "%d-%b-%Y"
1019                                   (nnimap-time-substract
1020                                    (current-time)
1021                                    (days-to-time daysago)))))
1022     (if (eq ?0 (string-to-char date))
1023         (substring date 1)
1024       date)))
1025
1026 (defun nnimap-request-expire-articles-progress ()
1027   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1028                 imap-current-message))
1029
1030 ;; Notice that we don't actually delete anything, we just mark them deleted.
1031 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1032   (let ((artseq (gnus-compress-sequence articles)))
1033     (when (and artseq (nnimap-possibly-change-group group server))
1034       (with-current-buffer nnimap-server-buffer
1035         (if force
1036             (and (imap-message-flags-add
1037                   (nnimap-range-to-string artseq) "\\Deleted")
1038                  (setq articles nil))
1039           (let ((days (or (and nnmail-expiry-wait-function
1040                                (funcall nnmail-expiry-wait-function group))
1041                           nnmail-expiry-wait)))
1042             (cond ((eq days 'immediate)
1043                    (and (imap-message-flags-add
1044                          (nnimap-range-to-string artseq) "\\Deleted")
1045                         (setq articles nil)))
1046                   ((numberp days)
1047                    (let ((oldarts (imap-search
1048                                    (format "UID %s NOT SINCE %s"
1049                                            (nnimap-range-to-string artseq)
1050                                            (nnimap-date-days-ago days))))
1051                          (imap-fetch-data-hook
1052                           '(nnimap-request-expire-articles-progress)))
1053                      (and oldarts
1054                           (imap-message-flags-add
1055                            (nnimap-range-to-string
1056                             (gnus-compress-sequence oldarts))
1057                            "\\Deleted")
1058                           (setq articles (gnus-set-difference
1059                                           articles oldarts)))))))))))
1060   ;; return articles not deleted
1061   articles)
1062
1063 (deffoo nnimap-request-move-article (article group server
1064                                              accept-form &optional last)
1065   (when (nnimap-possibly-change-server server)
1066     (save-excursion
1067       (let ((buf (get-buffer-create " *nnimap move*"))
1068             (nnimap-current-move-article article)
1069             (nnimap-current-move-group group)
1070             (nnimap-current-move-server nnimap-current-server)
1071             result)
1072         (and (nnimap-request-article article group server)
1073              (save-excursion
1074                (set-buffer buf)
1075                (buffer-disable-undo (current-buffer))
1076                (insert-buffer-substring nntp-server-buffer)
1077                (setq result (eval accept-form))
1078                (kill-buffer buf)
1079                result)
1080              (nnimap-request-expire-articles (list article) group server t))
1081         result))))
1082   
1083 (deffoo nnimap-request-accept-article (group &optional server last)
1084   (when (nnimap-possibly-change-server server)
1085     (let (uid)
1086       (if (setq uid
1087                 (if (string= nnimap-current-server nnimap-current-move-server)
1088                     ;; moving article within same server, speed it up...
1089                     (and (nnimap-possibly-change-group
1090                           nnimap-current-move-group)
1091                          (imap-message-copy (number-to-string
1092                                              nnimap-current-move-article)
1093                                             group 'dontcreate nil
1094                                             nnimap-server-buffer))
1095                   ;; turn into rfc822 format (\r\n eol's)
1096                   (with-current-buffer (current-buffer)
1097                     (goto-char (point-min))
1098                     (while (search-forward "\n" nil t)
1099                       (replace-match "\r\n")))
1100                   ;; this 'or' is for Cyrus server bug
1101                   (or (null (imap-current-mailbox nnimap-server-buffer))
1102                       (imap-mailbox-unselect nnimap-server-buffer))
1103                   (imap-message-append group (current-buffer) nil nil
1104                                        nnimap-server-buffer)))
1105           (cons group (nth 1 uid))
1106         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1107
1108 (deffoo nnimap-request-delete-group (group force &optional server)
1109   (when (nnimap-possibly-change-server server)
1110     (with-current-buffer nnimap-server-buffer
1111       (if force
1112           (or (null (imap-mailbox-status group 'uidvalidity))
1113               (imap-mailbox-delete group))
1114         ;; UNSUBSCRIBE?
1115         t))))
1116
1117 (deffoo nnimap-request-rename-group (group new-name &optional server)
1118   (when (nnimap-possibly-change-server server)
1119     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1120
1121 (defun nnimap-expunge (mailbox server)
1122   (when (nnimap-possibly-change-group mailbox server)
1123     (imap-mailbox-expunge nnimap-server-buffer)))
1124
1125 (defun nnimap-acl-get (mailbox server)
1126   (when (nnimap-possibly-change-server server)
1127     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1128
1129 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1130   (when (nnimap-possibly-change-server (cadr method))
1131     (unless (imap-capability 'ACL nnimap-server-buffer)
1132       (error "Your server does not support ACL editing"))
1133     (with-current-buffer nnimap-server-buffer
1134       ;; delete all removed identifiers
1135       (mapcar (lambda (old-acl)
1136                 (unless (assoc (car old-acl) new-acls)
1137                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1138                       (error "Can't delete ACL for %s" (car old-acl)))))
1139               old-acls)
1140       ;; set all changed acl's
1141       (mapcar (lambda (new-acl)
1142                 (let ((new-rights (cdr new-acl))
1143                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1144                   (unless (and old-rights new-rights
1145                                (string= old-rights new-rights))
1146                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1147                         (error "Can't set ACL for %s to %s" (car new-acl)
1148                                new-rights)))))
1149               new-acls)
1150       t)))
1151
1152 \f
1153 ;;; Internal functions
1154
1155 ;;
1156 ;; This is confusing.
1157 ;;
1158 ;; mark      => read, tick, draft, reply etc
1159 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1160 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1161 ;;
1162 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1163 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1164 ;;
1165
1166 (defconst nnimap-mark-to-predicate-alist
1167   (mapcar
1168    (lambda (pair)                       ; cdr is the mark
1169      (or (assoc (cdr pair)
1170                 '((read . "SEEN")
1171                   (tick . "FLAGGED")
1172                   (draft . "DRAFT")
1173                   (reply . "ANSWERED")))
1174          (cons (cdr pair)
1175                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1176    (cons '(read . read) gnus-article-mark-lists)))
1177
1178 (defun nnimap-mark-to-predicate (pred)
1179   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1180 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1181 to be used within a IMAP SEARCH query."
1182   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1183
1184 (defconst nnimap-mark-to-flag-alist
1185   (mapcar
1186    (lambda (pair)
1187      (or (assoc (cdr pair)
1188                 '((read . "\\Seen")
1189                   (tick . "\\Flagged")
1190                   (draft . "\\Draft")
1191                   (reply . "\\Answered")))
1192          (cons (cdr pair)
1193                (format "gnus-%s" (symbol-name (cdr pair))))))
1194    (cons '(read . read) gnus-article-mark-lists)))
1195
1196 (defun nnimap-mark-to-flag-1 (preds)
1197   (if (and (not (null preds)) (listp preds))
1198       (cons (nnimap-mark-to-flag (car preds))
1199             (nnimap-mark-to-flag (cdr preds)))
1200     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1201
1202 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1203   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1204 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1205 be used in a STORE FLAGS command."
1206   (let ((result (nnimap-mark-to-flag-1 preds)))
1207     (setq result (if (and (or make-string always-list)
1208                           (not (listp result)))
1209                      (list result)
1210                    result))
1211     (if make-string
1212         (mapconcat (lambda (flag)
1213                      (if (listp flag)
1214                          (mapconcat 'identity flag " ")
1215                        flag))
1216                    result " ")
1217       result)))
1218
1219 (defun nnimap-mark-permanent-p (mark &optional group)
1220   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1221   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1222
1223 (defun nnimap-remassoc (key alist)
1224   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1225 The modified LIST is returned.  If the first member
1226 of LIST has a car that is `equal' to KEY, there is no way to remove it
1227 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1228 sure of changing the value of `foo'."
1229   (when alist
1230     (if (equal key (caar alist))
1231         (cdr alist)
1232       (setcdr alist (nnimap-remassoc key (cdr alist)))
1233       alist)))
1234   
1235 (defun nnimap-update-alist-soft (key value alist)
1236   (if value
1237       (cons (cons key value) (nnimap-remassoc key alist))
1238     (nnimap-remassoc key alist)))
1239
1240 (defun nnimap-range-to-string (range)
1241   (mapconcat
1242    (lambda (item)
1243      (if (consp item)
1244          (format "%d:%d"
1245                  (car item) (cdr item))
1246        (format "%d" item)))
1247    (if (and (listp range) (not (listp (cdr range))))
1248        (list range);; make (1 . 2) into ((1 . 2))
1249      range)
1250    ","))
1251
1252 (when nnimap-debug
1253   (require 'trace)
1254   (buffer-disable-undo (get-buffer-create nnimap-debug))
1255   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1256         '(
1257           nnimap-possibly-change-server
1258           nnimap-verify-uidvalidity
1259           nnimap-find-minmax-uid
1260           nnimap-possibly-change-group
1261           ;;nnimap-replace-whitespace
1262           nnimap-retrieve-headers-progress
1263           nnimap-retrieve-which-headers
1264           nnimap-group-overview-filename
1265           nnimap-retrieve-headers-from-file
1266           nnimap-retrieve-headers-from-server
1267           nnimap-retrieve-headers
1268           nnimap-open-connection
1269           nnimap-open-server
1270           nnimap-server-opened
1271           nnimap-close-server
1272           nnimap-request-close
1273           nnimap-status-message
1274           ;;nnimap-demule
1275           nnimap-request-article-part
1276           nnimap-request-article
1277           nnimap-request-head
1278           nnimap-request-body
1279           nnimap-request-group
1280           nnimap-close-group
1281           nnimap-pattern-to-list-arguments
1282           nnimap-request-list
1283           nnimap-request-post
1284           nnimap-retrieve-groups
1285           nnimap-request-update-info-internal
1286           nnimap-request-type
1287           nnimap-request-set-mark
1288           nnimap-split-to-groups
1289           nnimap-split-find-rule
1290           nnimap-split-find-inbox
1291           nnimap-split-articles
1292           nnimap-request-scan
1293           nnimap-request-newgroups
1294           nnimap-request-create-group
1295           nnimap-time-substract
1296           nnimap-date-days-ago
1297           nnimap-request-expire-articles-progress
1298           nnimap-request-expire-articles
1299           nnimap-request-move-article
1300           nnimap-request-accept-article
1301           nnimap-request-delete-group
1302           nnimap-request-rename-group
1303           gnus-group-nnimap-expunge
1304           gnus-group-nnimap-edit-acl
1305           gnus-group-nnimap-edit-acl-done
1306           nnimap-group-mode-hook
1307           nnimap-mark-to-predicate
1308           nnimap-mark-to-flag-1
1309           nnimap-mark-to-flag
1310           nnimap-mark-permanent-p
1311           nnimap-remassoc
1312           nnimap-update-alist-soft
1313           nnimap-range-to-string
1314           )))
1315
1316 (provide 'nnimap)
1317
1318 ;;; nnimap.el ends here