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