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