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