(nnimap-before-find-minmax-bugworkaround): New
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;;         Jim Radford <radford@robby.caltech.edu>
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessery?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57
58 ;;; Code:
59
60 (eval-and-compile
61   (require 'imap))
62
63 (require 'nnoo)
64 (require 'nnmail)
65 (require 'nnheader)
66 (require 'mm-util)
67 (require 'gnus)
68 (require 'gnus-range)
69 (require 'gnus-start)
70 (require 'gnus-int)
71
72 (nnoo-declare nnimap)
73
74 (defconst nnimap-version "nnimap 0.131")
75
76 (defvoo nnimap-address nil
77   "Address of physical IMAP server.  If nil, use the virtual server's name.")
78
79 (defvoo nnimap-server-port nil
80   "Port number on physical IMAP server.
81 If nil, defaults to 993 for SSL connections and 143 otherwise.")
82
83 ;; Splitting variables
84
85 (defvar nnimap-split-crosspost t
86   "If non-nil, do crossposting if several split methods match the mail.
87 If nil, the first match found will be used.")
88
89 (defvar nnimap-split-inbox nil
90   "*Name of mailbox to split mail from.
91
92 Mail is read from this mailbox and split according to rules in
93 `nnimap-split-rules'.
94
95 This can be a string or a list of strings.")
96
97 (defvar nnimap-split-rule nil
98   "*Mail will be split according to theese rules.
99
100 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
101
102 If you'd like, for instance, one mail group for mail from the
103 \"gnus-imap\" mailing list, one group for junk mail and leave
104 everything else in the incoming mailbox, you could do something like
105 this:
106
107 (setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
108                           (\"INBOX.junk\"        \"Subject:.*buy\")))
109
110 As you can see, `nnimap-split-rule' is a list of lists, where the first
111 element in each \"rule\" is the name of the IMAP mailbox, and the
112 second is a regexp that nnimap will try to match on the header to find
113 a fit.
114
115 The second element can also be a function.  In that case, it will be
116 called narrowed to the headers with the first element of the rule as
117 the argument.  It should return a non-nil value if it thinks that the
118 mail belongs in that group.
119
120 This variable can also have a function as its value, the function will
121 be called with the headers narrowed and should return a group where it
122 thinks the article should be splitted to.  See `nnimap-split-fancy'.
123
124 To allow for different split rules on different virtual servers, and
125 even different split rules in different inboxes on the same server,
126 the syntax of this variable have been extended along the lines of:
127
128 (setq nnimap-split-rule
129       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
130                                   (\"junk\"    \"From:.*Simon\")))
131         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
132         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
133                                   (\"junk\"    my-junk-func)))))
134
135 The virtual server name is in fact a regexp, so that the same rules
136 may apply to several servers.  In the example, the servers
137 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
138 the inbox string is also a regexp.  The actual splitting rules are as
139 before, either a function, or a list with group/regexp or
140 group/function elements.")
141
142 (defvar nnimap-split-predicate "UNSEEN UNDELETED"
143   "The predicate used to find articles to split.
144 If you use another IMAP client to peek on articles but always would
145 like nnimap to split them once it's started, you could change this to
146 \"UNDELETED\". Other available predicates are available in
147 RFC2060 section 6.4.4.")
148
149 (defvar nnimap-split-fancy nil
150   "Like `nnmail-split-fancy', which see.")
151
152 ;; Authorization / Privacy variables
153
154 (defvoo nnimap-auth-method nil
155   "Obsolete.")
156
157 (defvoo nnimap-stream nil
158   "How nnimap will connect to the server.
159
160 The default, nil, will try to use the \"best\" method the server can
161 handle.
162
163 Change this if
164
165 1) you want to connect with SSL.  The SSL integration with IMAP is
166    brain-dead so you'll have to tell it specifically.
167
168 2) your server is more capable than your environment -- i.e. your
169    server accept Kerberos login's but you haven't installed the
170    `imtest' program or your machine isn't configured for Kerberos.
171
172 Possible choices: kerberos4, ssl, network")
173
174 (defvoo nnimap-authenticator nil
175   "How nnimap authenticate itself to the server.
176
177 The default, nil, will try to use the \"best\" method the server can
178 handle.
179
180 There is only one reason for fiddling with this variable, and that is
181 if your server is more capable than your environment -- i.e. you
182 connect to a server that accept Kerberos login's but you haven't
183 installed the `imtest' program or your machine isn't configured for
184 Kerberos.
185
186 Possible choices: kerberos4, cram-md5, login, anonymous.")
187
188 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
189   "Directory to keep NOV cache files for nnimap groups.
190 See also `nnimap-nov-file-name'.")
191
192 (defvoo nnimap-nov-file-name "nnimap."
193   "NOV cache base filename.
194 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
195 typical complete file name would be
196 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
197 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
198 `nnmail-use-long-file-names' is nil")
199
200 (defvoo nnimap-nov-file-name-suffix ".novcache"
201   "Suffix for NOV cache base filename.")
202
203 (defvoo nnimap-nov-is-evil nil
204   "If non-nil, nnimap will never generate or use a local nov database for this backend.
205 Using nov databases will speed up header fetching considerably.
206 Unlike other backends, you do not need to take special care if you
207 flip this variable.")
208
209 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
210   "Whether to expunge a group when it is closed.
211 When a IMAP group with articles marked for deletion is closed, this
212 variable determine if nnimap should actually remove the articles or
213 not.
214
215 If always, nnimap always perform a expunge when closing the group.
216 If never, nnimap never expunges articles marked for deletion.
217 If ask, nnimap will ask you if you wish to expunge marked articles.
218
219 When setting this variable to `never', you can only expunge articles
220 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
221
222 (defvoo nnimap-list-pattern "*"
223   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
224 See below for available wildcards.
225
226 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
227 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
228 semantics of this are server specific, on the University of Washington
229 server you can specify a directory.
230
231 Example:
232  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
233
234 There are two wildcards * and %. * matches everything, % matches
235 everything in the current hierarchy.")
236
237 (defvoo nnimap-news-groups nil
238   "IMAP support a news-like mode, also known as bulletin board mode, where replies is sent via IMAP instead of SMTP.
239
240 This variable should contain a regexp matching groups where you wish
241 replies to be stored to the mailbox directly.
242
243 Example:
244   '(\"^[^I][^N][^B][^O][^X].*$\")
245
246 This will match all groups not beginning with \"INBOX\".
247
248 Note that there is nothing technically different between mail-like and
249 news-like mailboxes.  If you wish to have a group with todo items or
250 similar which you wouldn't want to set up a mailing list for, you can
251 use this to make replies go directly to the group.")
252
253 (defvoo nnimap-server-address nil
254   "Obsolete.  Use `nnimap-address'.")
255
256 (defcustom nnimap-authinfo-file "~/.authinfo"
257   "Authorization information for IMAP servers.  In .netrc format."
258   :type
259   '(choice file
260            (repeat :tag "Entries"
261                    :menu-tag "Inline"
262                    (list :format "%v"
263                          :value ("" ("login" . "") ("password" . ""))
264                          (string :tag "Host")
265                          (checklist :inline t
266                                     (cons :format "%v"
267                                           (const :format "" "login")
268                                           (string :format "Login: %v"))
269                                     (cons :format "%v"
270                                           (const :format "" "password")
271                                           (string :format "Password: %v")))))))
272
273 (defcustom nnimap-prune-cache t
274   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
275   :type 'boolean)
276
277 (defvar nnimap-request-list-method 'imap-mailbox-list
278   "Method to use to request a list of all folders from the server.
279 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
280 restrict visible folders.")
281
282 ;; Internal variables:
283
284 (defvar nnimap-debug nil
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-ms-strip-cr)
410          (nnheader-fold-continuation-lines)
411          (subst-char-in-region (point-min) (point-max) ?\t ? )
412          (let ((head (nnheader-parse-head 'naked)))
413            (mail-header-set-number head uid)
414            (mail-header-set-chars head chars)
415            (mail-header-set-lines head lines)
416            (mail-header-set-xref
417             head (format "%s %s:%d" (system-name) mbx uid))
418            head))))))
419
420 (defun nnimap-retrieve-which-headers (articles fetch-old)
421   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
422   (with-current-buffer nnimap-server-buffer
423     (if (numberp (car-safe articles))
424         (imap-search
425          (concat "UID "
426                  (imap-range-to-message-set
427                   (gnus-compress-sequence
428                    (append (gnus-uncompress-sequence
429                             (and fetch-old
430                                  (cons (if (numberp fetch-old)
431                                            (max 1 (- (car articles) fetch-old))
432                                          1)
433                                        (1- (car articles)))))
434                            articles)))))
435       (mapcar (lambda (msgid)
436                 (imap-search
437                  (format "HEADER Message-Id %s" msgid)))
438               articles))))
439
440 (defun nnimap-group-overview-filename (group server)
441   "Make pathname for GROUP on SERVER."
442   (let ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
443         (file (nnheader-translate-file-chars
444                (concat nnimap-nov-file-name
445                        (if (equal server "")
446                            "unnamed"
447                          server) "." group nnimap-nov-file-name-suffix) t)))
448     (if (or nnmail-use-long-file-names
449             (file-exists-p (concat dir file)))
450         (concat dir file)
451       (concat dir (mm-encode-coding-string
452                    (nnheader-replace-chars-in-string file ?. ?/)
453                    nnmail-pathname-coding-system)))))
454
455 (defun nnimap-retrieve-headers-from-file (group server)
456   (with-current-buffer nntp-server-buffer
457     (let ((nov (nnimap-group-overview-filename group server)))
458       (when (file-exists-p nov)
459         (mm-insert-file-contents nov)
460         (set-buffer-modified-p nil)
461         (let ((min (progn (goto-char (point-min))
462                           (when (not (eobp))
463                             (read (current-buffer)))))
464               (max (progn (goto-char (point-max))
465                           (forward-line -1)
466                           (when (not (bobp))
467                             (read (current-buffer))))))
468           (if (and (numberp min) (numberp max))
469               (cons min max)
470             ;; junk, remove it, it's saved later
471             (erase-buffer)
472             nil))))))
473
474 (defun nnimap-retrieve-headers-from-server (articles group server)
475   (with-current-buffer nnimap-server-buffer
476     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
477           (nnimap-length (gnus-range-length articles))
478           (nnimap-counter 0))
479       (imap-fetch (imap-range-to-message-set articles)
480                   (concat "(UID RFC822.SIZE BODY "
481                           (let ((headers
482                                  (append '(Subject From Date Message-Id
483                                                    References In-Reply-To Xref)
484                                          (copy-sequence
485                                           nnmail-extra-headers))))
486                             (if (imap-capability 'IMAP4rev1)
487                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
488                               (format "RFC822.HEADER.LINES %s)" headers)))))
489       (and (numberp nnmail-large-newsgroup)
490            (> nnimap-length nnmail-large-newsgroup)
491            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
492
493 (defun nnimap-use-nov-p (group server)
494   (or gnus-nov-is-evil nnimap-nov-is-evil
495       (unless (and (gnus-make-directory
496                     (file-name-directory
497                      (nnimap-group-overview-filename group server)))
498                    (file-writable-p
499                     (nnimap-group-overview-filename group server)))
500         (message "nnimap: Nov cache not writable, %s"
501                  (nnimap-group-overview-filename group server)))))
502
503 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
504   (when (nnimap-possibly-change-group group server)
505     (with-current-buffer nntp-server-buffer
506       (erase-buffer)
507       (if (nnimap-use-nov-p group server)
508           (nnimap-retrieve-headers-from-server
509            (gnus-compress-sequence articles) group server)
510         (let (uids cached low high)
511           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
512                       low (car uids)
513                       high (car (last uids)))
514             (if (setq cached (nnimap-retrieve-headers-from-file group server))
515                 (progn
516                   ;; fetch articles with uids before cache block
517                   (when (< low (car cached))
518                     (goto-char (point-min))
519                     (nnimap-retrieve-headers-from-server
520                      (cons low (1- (car cached))) group server))
521                   ;; fetch articles with uids after cache block
522                   (when (> high (cdr cached))
523                     (goto-char (point-max))
524                     (nnimap-retrieve-headers-from-server
525                      (cons (1+ (cdr cached)) high) group server))
526                   (when nnimap-prune-cache
527                     ;; remove nov's for articles which has expired on server
528                     (goto-char (point-min))
529                     (dolist (uid (gnus-set-difference articles uids))
530                       (when (re-search-forward (format "^%d\t" uid) nil t)
531                         (gnus-delete-line)))))
532               ;; nothing cached, fetch whole range from server
533               (nnimap-retrieve-headers-from-server
534                (cons low high) group server))
535             (when (buffer-modified-p)
536               (nnmail-write-region
537                1 (point-max) (nnimap-group-overview-filename group server)
538                nil 'nomesg))
539             (nnheader-nov-delete-outside-range low high))))
540       'nov)))
541
542 (defun nnimap-open-connection (server)
543   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
544                       nnimap-authenticator nnimap-server-buffer))
545       (nnheader-report 'nnimap "Can't open connection to server %s" server)
546     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
547                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
548       (imap-close nnimap-server-buffer)
549       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
550     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
551            (port (if nnimap-server-port
552                      (int-to-string nnimap-server-port)
553                    "imap"))
554            (alist (gnus-netrc-machine list (or nnimap-server-address 
555                                                nnimap-address server)
556                                       port "imap"))
557            (user (gnus-netrc-get alist "login"))
558            (passwd (gnus-netrc-get alist "password")))
559       (if (imap-authenticate user passwd nnimap-server-buffer)
560           (prog1
561               (push (list server nnimap-server-buffer)
562                     nnimap-server-buffer-alist)
563             (nnimap-possibly-change-server server))
564         (imap-close nnimap-server-buffer)
565         (kill-buffer nnimap-server-buffer)
566         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
567
568 (deffoo nnimap-open-server (server &optional defs)
569   (nnheader-init-server-buffer)
570   (if (nnimap-server-opened server)
571       t
572     (unless (assq 'nnimap-server-buffer defs)
573       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
574     ;; translate `nnimap-server-address' to `nnimap-address' in defs
575     ;; for people that configured nnimap with a very old version
576     (unless (assq 'nnimap-address defs)
577       (if (assq 'nnimap-server-address defs)
578           (push (list 'nnimap-address
579                       (cadr (assq 'nnimap-server-address defs))) defs)
580         (push (list 'nnimap-address server) defs)))
581     (nnoo-change-server 'nnimap server defs)
582     (or (and nnimap-server-buffer
583              (imap-opened nnimap-server-buffer))
584         (nnimap-open-connection server))))
585
586 (deffoo nnimap-server-opened (&optional server)
587   "Whether SERVER is opened.
588 If SERVER is the current virtual server, and the connection to the
589 physical server is alive, this function return a non-nil value.  If
590 SERVER is nil, it is treated as the current server."
591   ;; clean up autologouts??
592   (and (or server nnimap-current-server)
593        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
594        (imap-opened (nnimap-get-server-buffer server))))
595
596 (deffoo nnimap-close-server (&optional server)
597   "Close connection to server and free all resources connected to it.
598 Return nil if the server couldn't be closed for some reason."
599   (let ((server (or server nnimap-current-server)))
600     (when (or (nnimap-server-opened server)
601               (imap-opened (nnimap-get-server-buffer server)))
602       (imap-close (nnimap-get-server-buffer server))
603       (kill-buffer (nnimap-get-server-buffer server))
604       (setq nnimap-server-buffer nil
605             nnimap-current-server nil
606             nnimap-server-buffer-alist
607             (delq server nnimap-server-buffer-alist)))
608     (nnoo-close-server 'nnimap server)))
609
610 (deffoo nnimap-request-close ()
611   "Close connection to all servers and free all resources that the backend have reserved.
612 All buffers that have been created by that
613 backend should be killed.  (Not the nntp-server-buffer, though.) This
614 function is generally only called when Gnus is shutting down."
615   (mapcar (lambda (server) (nnimap-close-server (car server)))
616           nnimap-server-buffer-alist)
617   (setq nnimap-server-buffer-alist nil))
618
619 (deffoo nnimap-status-message (&optional server)
620   "This function returns the last error message from server."
621   (when (nnimap-possibly-change-server server)
622     (nnoo-status-message 'nnimap server)))
623
624 (defun nnimap-demule (string)
625   (funcall (if (and (fboundp 'string-as-multibyte)
626                     (subrp (symbol-function 'string-as-multibyte)))
627                'string-as-multibyte
628              'identity)
629            (or string "")))
630
631 (defun nnimap-callback ()
632   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
633   (with-current-buffer nnimap-callback-buffer
634     (insert
635      (with-current-buffer nnimap-server-buffer
636        (nnimap-demule
637         (if (imap-capability 'IMAP4rev1) 
638             ;; xxx don't just use car? alist doesn't contain
639             ;; anything else now, but it might...
640             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
641           (imap-message-get (imap-current-message) 'RFC822)))))
642     (nnheader-ms-strip-cr)
643     (funcall nnimap-callback-callback-function t)))
644
645 (defun nnimap-request-article-part (article part prop &optional
646                                             group server to-buffer detail)
647   (when (nnimap-possibly-change-group group server)
648     (let ((article (if (stringp article)
649                        (car-safe (imap-search
650                                   (format "HEADER Message-Id %s" article)
651                                   nnimap-server-buffer))
652                      article)))
653       (when article
654         (gnus-message 10 "nnimap: Fetching (part of) article %d..." article)
655         (if (not nnheader-callback-function)
656             (with-current-buffer (or to-buffer nntp-server-buffer)
657               (erase-buffer)
658               (let ((data (imap-fetch article part prop nil
659                                       nnimap-server-buffer)))
660                 (insert (nnimap-demule (if detail
661                                            (nth 2 (car data))
662                                          data))))
663               (nnheader-ms-strip-cr)
664               (gnus-message 10 "nnimap: Fetching (part of) article %d...done"
665                             article)
666               (if (bobp)
667                   (nnheader-report 'nnimap "No such article: %s"
668                                    (imap-error-text nnimap-server-buffer))
669                 (cons group article)))
670           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
671           (setq nnimap-callback-callback-function nnheader-callback-function
672                 nnimap-callback-buffer nntp-server-buffer)
673           (imap-fetch-asynch article part nil nnimap-server-buffer)
674           (cons group article))))))
675
676 (deffoo nnimap-asynchronous-p ()
677   t)
678
679 (deffoo nnimap-request-article (article &optional group server to-buffer)
680   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
681       (nnimap-request-article-part
682        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
683     (nnimap-request-article-part
684      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
685
686 (deffoo nnimap-request-head (article &optional group server to-buffer)
687   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
688       (nnimap-request-article-part
689        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
690     (nnimap-request-article-part
691      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
692
693 (deffoo nnimap-request-body (article &optional group server to-buffer)
694   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
695       (nnimap-request-article-part
696        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
697     (nnimap-request-article-part
698      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
699
700 (deffoo nnimap-request-group (group &optional server fast)
701   (nnimap-request-update-info-internal
702    group
703    (gnus-get-info (gnus-group-prefixed-name
704                    group (gnus-server-to-method (format "nnimap:%s" server))))
705    server)
706   (when (nnimap-possibly-change-group group server)
707     (nnimap-before-find-minmax-bugworkaround)
708     (let (info)
709       (cond (fast group)
710             ((null (setq info (nnimap-find-minmax-uid group t)))
711              (nnheader-report 'nnimap "Could not get active info for %s"
712                               group))
713             (t
714              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
715                               (max 1 (or (nth 1 info) 1))
716                               (or (nth 2 info) 0) group)
717              (nnheader-report 'nnimap "Group %s selected" group)
718              t)))))
719
720 (defun nnimap-close-group (group &optional server)
721   (with-current-buffer nnimap-server-buffer
722     (when (and (imap-opened)
723                (nnimap-possibly-change-group group server))
724       (case nnimap-expunge-on-close
725         ('always (imap-mailbox-expunge)
726                  (imap-mailbox-close))
727         ('ask (if (and (imap-search "DELETED")
728                        (gnus-y-or-n-p (format
729                                        "Expunge articles in group `%s'? "
730                                        imap-current-mailbox)))
731                   (progn (imap-mailbox-expunge)
732                          (imap-mailbox-close))
733                 (imap-mailbox-unselect)))
734         (t (imap-mailbox-unselect)))
735       (not imap-current-mailbox))))
736
737 (defun nnimap-pattern-to-list-arguments (pattern)
738   (mapcar (lambda (p)
739             (cons (car-safe p) (or (cdr-safe p) p)))
740           (if (and (listp pattern)
741                    (listp (cdr pattern)))
742               pattern
743             (list pattern))))
744
745 (deffoo nnimap-request-list (&optional server)
746   (when (nnimap-possibly-change-server server)
747     (with-current-buffer nntp-server-buffer
748       (erase-buffer))
749     (gnus-message 5 "nnimap: Generating active list%s..."
750                   (if (> (length server) 0) (concat " for " server) ""))
751     (nnimap-before-find-minmax-bugworkaround)
752     (with-current-buffer nnimap-server-buffer
753       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
754         (dolist (mbx (funcall nnimap-request-list-method
755                               (cdr pattern) (car pattern)))
756           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
757               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
758                 (when info
759                   (with-current-buffer nntp-server-buffer
760                    (insert (format "\"%s\" %d %d y\n"
761                                    mbx (or (nth 2 info) 0)
762                                    (max 1 (or (nth 1 info) 1)))))))))))
763     (gnus-message 5 "nnimap: Generating active list%s...done"
764                   (if (> (length server) 0) (concat " for " server) ""))
765     t))
766
767 (deffoo nnimap-request-post (&optional server)
768   (let ((success t))
769     (dolist (mbx (message-unquote-tokens
770                   (message-tokenize-header
771                    (message-fetch-field "Newsgroups") ", ")) success)
772       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
773         (or (gnus-active to-newsgroup)
774             (gnus-activate-group to-newsgroup)
775             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
776                                        to-newsgroup))
777                 (or (and (gnus-request-create-group
778                           to-newsgroup gnus-command-method)
779                          (gnus-activate-group to-newsgroup nil nil
780                                               gnus-command-method))
781                     (error "Couldn't create group %s" to-newsgroup)))
782             (error "No such group: %s" to-newsgroup))
783         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
784           (setq success nil))))))
785
786 ;; Optional backend functions
787
788 (deffoo nnimap-retrieve-groups (groups &optional server)
789   (when (nnimap-possibly-change-server server)
790     (gnus-message 5 "nnimap: Checking mailboxes...")
791     (with-current-buffer nntp-server-buffer
792       (erase-buffer)
793       (nnimap-before-find-minmax-bugworkaround)
794       (dolist (group groups)
795         (gnus-message 7 "nnimap: Checking mailbox %s" group)
796         (or (member "\\NoSelect"
797                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
798             (let ((info (nnimap-find-minmax-uid group 'examine)))
799               (insert (format "\"%s\" %d %d y\n" group
800                               (or (nth 2 info) 0)
801                               (max 1 (or (nth 1 info) 1))))))))
802     (gnus-message 5 "nnimap: Checking mailboxes...done")
803     'active))
804
805 (deffoo nnimap-request-update-info-internal (group info &optional server)
806   (when (nnimap-possibly-change-group group server)
807     (when info;; xxx what does this mean? should we create a info?
808       (with-current-buffer nnimap-server-buffer
809         (gnus-message 5 "nnimap: Updating info for %s..."
810                       (gnus-info-group info))
811         
812         (when (nnimap-mark-permanent-p 'read)
813           (let (seen unseen)
814             ;; read info could contain articles marked unread by other
815             ;; imap clients!  we correct this
816             (setq seen (gnus-uncompress-range (gnus-info-read info))
817                   unseen (imap-search "UNSEEN UNDELETED")
818                   seen (gnus-set-difference seen unseen)
819                   ;; seen might lack articles marked as read by other
820                   ;; imap clients! we correct this
821                   seen (append seen (imap-search "SEEN"))
822                   ;; remove dupes
823                   seen (sort seen '<)
824                   seen (gnus-compress-sequence seen t)
825                   ;; we can't return '(1) since this isn't a "list of ranges",
826                   ;; and we can't return '((1)) since g-list-of-unread-articles
827                   ;; is buggy so we return '((1 . 1)).
828                   seen (if (and (integerp (car seen))
829                                 (null (cdr seen)))
830                            (list (cons (car seen) (car seen)))
831                          seen))
832             (gnus-info-set-read info seen)))
833
834         (mapcar (lambda (pred)
835                   (when (and (nnimap-mark-permanent-p (cdr pred))
836                              (member (nnimap-mark-to-flag (cdr pred))
837                                      (imap-mailbox-get 'flags)))
838                     (gnus-info-set-marks
839                      info
840                      (nnimap-update-alist-soft
841                       (cdr pred)
842                       (gnus-compress-sequence
843                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
844                       (gnus-info-marks info))
845                      t)))
846                 gnus-article-mark-lists)
847         
848         (gnus-message 5 "nnimap: Updating info for %s...done"
849                       (gnus-info-group info))
850
851         info))))
852
853 (deffoo nnimap-request-type (group &optional article)
854   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
855       'news
856     'mail))
857
858 (deffoo nnimap-request-set-mark (group actions &optional server)
859   (when (nnimap-possibly-change-group group server)
860     (with-current-buffer nnimap-server-buffer
861       (let (action)
862         (gnus-message 7 "nnimap: Setting marks in %s..." group)
863         (while (setq action (pop actions))
864           (let ((range (nth 0 action))
865                 (what  (nth 1 action))
866                 (cmdmarks (nth 2 action))
867                 marks)
868             ;; cache flags are pointless on the server
869             (setq cmdmarks (delq 'cache cmdmarks))
870             ;; flag dormant articles as ticked
871             (if (memq 'dormant cmdmarks)
872                 (setq cmdmarks (cons 'tick cmdmarks)))
873             ;; remove stuff we are forbidden to store
874             (mapcar (lambda (mark)
875                       (if (imap-message-flag-permanent-p
876                            (nnimap-mark-to-flag mark))
877                           (setq marks (cons mark marks))))
878                     cmdmarks)
879             (when (and range marks)
880               (cond ((eq what 'del)
881                      (imap-message-flags-del
882                       (imap-range-to-message-set range)
883                       (nnimap-mark-to-flag marks nil t)))
884                     ((eq what 'add)
885                      (imap-message-flags-add
886                       (imap-range-to-message-set range)
887                       (nnimap-mark-to-flag marks nil t)))
888                     ((eq what 'set)
889                      (imap-message-flags-set
890                       (imap-range-to-message-set range)
891                       (nnimap-mark-to-flag marks nil t)))))))
892         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
893   nil)
894
895 (defun nnimap-split-fancy ()
896   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
897   (let ((nnmail-split-fancy nnimap-split-fancy))
898     (nnmail-split-fancy)))
899
900 (defun nnimap-split-to-groups (rules)
901   ;; tries to match all rules in nnimap-split-rule against content of
902   ;; nntp-server-buffer, returns a list of groups that matched.
903   (with-current-buffer nntp-server-buffer
904     ;; Fold continuation lines.
905     (goto-char (point-min))
906     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
907       (replace-match " " t t))
908     (if (functionp rules)
909         (funcall rules)
910       (let (to-groups regrepp)
911         (catch 'split-done
912           (dolist (rule rules to-groups)
913             (let ((group (car rule))
914                   (regexp (cadr rule)))
915               (goto-char (point-min))
916               (when (and (if (stringp regexp)
917                              (progn
918                                (setq regrepp (string-match "\\\\[0-9&]" group))
919                                (re-search-forward regexp nil t))
920                            (funcall regexp group))
921                          ;; Don't enter the article into the same group twice.
922                          (not (assoc group to-groups)))
923                 (push (if regrepp
924                           (nnmail-expand-newtext group)
925                         group)
926                       to-groups)
927                 (or nnimap-split-crosspost
928                     (throw 'split-done to-groups))))))))))
929   
930 (defun nnimap-assoc-match (key alist)
931   (let (element)
932     (while (and alist (not element))
933       (if (string-match (car (car alist)) key)
934           (setq element (car alist)))
935       (setq alist (cdr alist)))
936     element))
937
938 (defun nnimap-split-find-rule (server inbox)
939   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
940            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
941       ;; extended format
942       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match 
943                                             server nnimap-split-rule))))
944     nnimap-split-rule))
945
946 (defun nnimap-split-find-inbox (server)
947   (if (listp nnimap-split-inbox)
948       nnimap-split-inbox
949     (list nnimap-split-inbox)))
950
951 (defun nnimap-split-articles (&optional group server)
952   (when (nnimap-possibly-change-server server)
953     (with-current-buffer nnimap-server-buffer
954       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
955         ;; iterate over inboxes
956         (while (and (setq inbox (pop inboxes))
957                     (nnimap-possibly-change-group inbox));; SELECT
958           ;; find split rule for this server / inbox
959           (when (setq rule (nnimap-split-find-rule server inbox))
960             ;; iterate over articles
961             (dolist (article (imap-search nnimap-split-predicate))
962               (when (nnimap-request-head article)
963                 ;; copy article to right group(s)
964                 (setq removeorig nil)
965                 (dolist (to-group (nnimap-split-to-groups rule))
966                   (if (imap-message-copy (number-to-string article)
967                                          to-group nil 'nocopyuid)
968                       (progn
969                         (message "IMAP split moved %s:%s:%d to %s" server inbox
970                                  article to-group)
971                         (setq removeorig t)
972                         ;; Add the group-art list to the history list.
973                         (push (list (cons to-group 0)) nnmail-split-history))
974                     (message "IMAP split failed to move %s:%s:%d to %s" server
975                              inbox article to-group)))
976                 ;; remove article if it was successfully copied somewhere
977                 (and removeorig
978                      (imap-message-flags-add (format "%d" article)
979                                              "\\Seen \\Deleted")))))
980           (when (imap-mailbox-select inbox);; just in case
981             ;; todo: UID EXPUNGE (if available) to remove splitted articles
982             (imap-mailbox-expunge)
983             (imap-mailbox-close)))
984         t))))
985
986 (deffoo nnimap-request-scan (&optional group server)
987   (nnimap-split-articles group server))
988
989 (deffoo nnimap-request-newgroups (date &optional server)
990   (when (nnimap-possibly-change-server server)
991     (with-current-buffer nntp-server-buffer
992       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
993                     (if (> (length server) 0) " on " "") server)
994       (erase-buffer)
995       (nnimap-before-find-minmax-bugworkaround)
996       (dolist (pattern (nnimap-pattern-to-list-arguments
997                         nnimap-list-pattern))
998         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
999                                         nnimap-server-buffer))
1000           (or (member-if (lambda (mailbox)
1001                            (string= (downcase mailbox) "\\noselect"))
1002                          (imap-mailbox-get 'list-flags mbx
1003                                            nnimap-server-buffer))
1004               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1005                 (when info
1006                  (insert (format "\"%s\" %d %d y\n"
1007                                  mbx (or (nth 2 info) 0)
1008                                  (max 1 (or (nth 1 info) 1)))))))))
1009       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1010                     (if (> (length server) 0) " on " "") server))
1011     t))
1012       
1013 (deffoo nnimap-request-create-group (group &optional server args)
1014   (when (nnimap-possibly-change-server server)
1015     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1016         (imap-mailbox-create group nnimap-server-buffer))))
1017
1018 (defun nnimap-time-substract (time1 time2)
1019   "Return TIME for TIME1 - TIME2."
1020   (let* ((ms (- (car time1) (car time2)))
1021          (ls (- (nth 1 time1) (nth 1 time2))))
1022     (if (< ls 0)
1023         (list (- ms 1) (+ (expt 2 16) ls))
1024       (list ms ls))))
1025
1026 (defun nnimap-date-days-ago (daysago)
1027   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1028   (let ((date (format-time-string "%d-%b-%Y"
1029                                   (nnimap-time-substract
1030                                    (current-time)
1031                                    (days-to-time daysago)))))
1032     (if (eq ?0 (string-to-char date))
1033         (substring date 1)
1034       date)))
1035
1036 (defun nnimap-request-expire-articles-progress ()
1037   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1038                 imap-current-message))
1039
1040 ;; Notice that we don't actually delete anything, we just mark them deleted.
1041 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1042   (let ((artseq (gnus-compress-sequence articles)))
1043     (when (and artseq (nnimap-possibly-change-group group server))
1044       (with-current-buffer nnimap-server-buffer
1045         (if force
1046             (and (imap-message-flags-add
1047                   (imap-range-to-message-set artseq) "\\Deleted")
1048                  (setq articles nil))
1049           (let ((days (or (and nnmail-expiry-wait-function
1050                                (funcall nnmail-expiry-wait-function group))
1051                           nnmail-expiry-wait)))
1052             (cond ((eq days 'immediate)
1053                    (and (imap-message-flags-add
1054                          (imap-range-to-message-set artseq) "\\Deleted")
1055                         (setq articles nil)))
1056                   ((numberp days)
1057                    (let ((oldarts (imap-search
1058                                    (format "UID %s NOT SINCE %s"
1059                                            (imap-range-to-message-set artseq)
1060                                            (nnimap-date-days-ago days))))
1061                          (imap-fetch-data-hook
1062                           '(nnimap-request-expire-articles-progress)))
1063                      (and oldarts
1064                           (imap-message-flags-add
1065                            (imap-range-to-message-set
1066                             (gnus-compress-sequence oldarts))
1067                            "\\Deleted")
1068                           (setq articles (gnus-set-difference
1069                                           articles oldarts)))))))))))
1070   ;; return articles not deleted
1071   articles)
1072
1073 (deffoo nnimap-request-move-article (article group server
1074                                              accept-form &optional last)
1075   (when (nnimap-possibly-change-server server)
1076     (save-excursion
1077       (let ((buf (get-buffer-create " *nnimap move*"))
1078             (nnimap-current-move-article article)
1079             (nnimap-current-move-group group)
1080             (nnimap-current-move-server nnimap-current-server)
1081             result)
1082         (and (nnimap-request-article article group server)
1083              (save-excursion
1084                (set-buffer buf)
1085                (buffer-disable-undo (current-buffer))
1086                (insert-buffer-substring nntp-server-buffer)
1087                (setq result (eval accept-form))
1088                (kill-buffer buf)
1089                result)
1090              (nnimap-request-expire-articles (list article) group server t))
1091         result))))
1092   
1093 (deffoo nnimap-request-accept-article (group &optional server last)
1094   (when (nnimap-possibly-change-server server)
1095     (let (uid)
1096       (if (setq uid
1097                 (if (string= nnimap-current-server nnimap-current-move-server)
1098                     ;; moving article within same server, speed it up...
1099                     (and (nnimap-possibly-change-group
1100                           nnimap-current-move-group)
1101                          (imap-message-copy (number-to-string
1102                                              nnimap-current-move-article)
1103                                             group 'dontcreate nil
1104                                             nnimap-server-buffer))
1105                   ;; turn into rfc822 format (\r\n eol's)
1106                   (with-current-buffer (current-buffer)
1107                     (goto-char (point-min))
1108                     (while (search-forward "\n" nil t)
1109                       (replace-match "\r\n")))
1110                   ;; this 'or' is for Cyrus server bug
1111                   (or (null (imap-current-mailbox nnimap-server-buffer))
1112                       (imap-mailbox-unselect nnimap-server-buffer))
1113                   (imap-message-append group (current-buffer) nil nil
1114                                        nnimap-server-buffer)))
1115           (cons group (nth 1 uid))
1116         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1117
1118 (deffoo nnimap-request-delete-group (group force &optional server)
1119   (when (nnimap-possibly-change-server server)
1120     (with-current-buffer nnimap-server-buffer
1121       (if force
1122           (or (null (imap-mailbox-status group 'uidvalidity))
1123               (imap-mailbox-delete group))
1124         ;; UNSUBSCRIBE?
1125         t))))
1126
1127 (deffoo nnimap-request-rename-group (group new-name &optional server)
1128   (when (nnimap-possibly-change-server server)
1129     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1130
1131 (defun nnimap-expunge (mailbox server)
1132   (when (nnimap-possibly-change-group mailbox server)
1133     (imap-mailbox-expunge nnimap-server-buffer)))
1134
1135 (defun nnimap-acl-get (mailbox server)
1136   (when (nnimap-possibly-change-server server)
1137     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1138
1139 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1140   (when (nnimap-possibly-change-server (cadr method))
1141     (unless (imap-capability 'ACL nnimap-server-buffer)
1142       (error "Your server does not support ACL editing"))
1143     (with-current-buffer nnimap-server-buffer
1144       ;; delete all removed identifiers
1145       (mapcar (lambda (old-acl)
1146                 (unless (assoc (car old-acl) new-acls)
1147                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1148                       (error "Can't delete ACL for %s" (car old-acl)))))
1149               old-acls)
1150       ;; set all changed acl's
1151       (mapcar (lambda (new-acl)
1152                 (let ((new-rights (cdr new-acl))
1153                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1154                   (unless (and old-rights new-rights
1155                                (string= old-rights new-rights))
1156                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1157                         (error "Can't set ACL for %s to %s" (car new-acl)
1158                                new-rights)))))
1159               new-acls)
1160       t)))
1161
1162 \f
1163 ;;; Internal functions
1164
1165 ;;
1166 ;; This is confusing.
1167 ;;
1168 ;; mark      => read, tick, draft, reply etc
1169 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1170 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1171 ;;
1172 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1173 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1174 ;;
1175
1176 (defconst nnimap-mark-to-predicate-alist
1177   (mapcar
1178    (lambda (pair)                       ; cdr is the mark
1179      (or (assoc (cdr pair)
1180                 '((read . "SEEN")
1181                   (tick . "FLAGGED")
1182                   (draft . "DRAFT")
1183                   (reply . "ANSWERED")))
1184          (cons (cdr pair)
1185                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1186    (cons '(read . read) gnus-article-mark-lists)))
1187
1188 (defun nnimap-mark-to-predicate (pred)
1189   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1190 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1191 to be used within a IMAP SEARCH query."
1192   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1193
1194 (defconst nnimap-mark-to-flag-alist
1195   (mapcar
1196    (lambda (pair)
1197      (or (assoc (cdr pair)
1198                 '((read . "\\Seen")
1199                   (tick . "\\Flagged")
1200                   (draft . "\\Draft")
1201                   (reply . "\\Answered")))
1202          (cons (cdr pair)
1203                (format "gnus-%s" (symbol-name (cdr pair))))))
1204    (cons '(read . read) gnus-article-mark-lists)))
1205
1206 (defun nnimap-mark-to-flag-1 (preds)
1207   (if (and (not (null preds)) (listp preds))
1208       (cons (nnimap-mark-to-flag (car preds))
1209             (nnimap-mark-to-flag (cdr preds)))
1210     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1211
1212 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1213   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1214 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1215 be used in a STORE FLAGS command."
1216   (let ((result (nnimap-mark-to-flag-1 preds)))
1217     (setq result (if (and (or make-string always-list)
1218                           (not (listp result)))
1219                      (list result)
1220                    result))
1221     (if make-string
1222         (mapconcat (lambda (flag)
1223                      (if (listp flag)
1224                          (mapconcat 'identity flag " ")
1225                        flag))
1226                    result " ")
1227       result)))
1228
1229 (defun nnimap-mark-permanent-p (mark &optional group)
1230   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1231   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1232
1233 (defun nnimap-remassoc (key alist)
1234   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1235 The modified LIST is returned.  If the first member
1236 of LIST has a car that is `equal' to KEY, there is no way to remove it
1237 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1238 sure of changing the value of `foo'."
1239   (when alist
1240     (if (equal key (caar alist))
1241         (cdr alist)
1242       (setcdr alist (nnimap-remassoc key (cdr alist)))
1243       alist)))
1244   
1245 (defun nnimap-update-alist-soft (key value alist)
1246   (if value
1247       (cons (cons key value) (nnimap-remassoc key alist))
1248     (nnimap-remassoc key alist)))
1249
1250 (when nnimap-debug
1251   (require 'trace)
1252   (buffer-disable-undo (get-buffer-create nnimap-debug))
1253   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1254         '(
1255           nnimap-possibly-change-server
1256           nnimap-verify-uidvalidity
1257           nnimap-find-minmax-uid
1258           nnimap-before-find-minmax-bugworkaround
1259           nnimap-possibly-change-group
1260           ;;nnimap-replace-whitespace
1261           nnimap-retrieve-headers-progress
1262           nnimap-retrieve-which-headers
1263           nnimap-group-overview-filename
1264           nnimap-retrieve-headers-from-file
1265           nnimap-retrieve-headers-from-server
1266           nnimap-retrieve-headers
1267           nnimap-open-connection
1268           nnimap-open-server
1269           nnimap-server-opened
1270           nnimap-close-server
1271           nnimap-request-close
1272           nnimap-status-message
1273           ;;nnimap-demule
1274           nnimap-request-article-part
1275           nnimap-request-article
1276           nnimap-request-head
1277           nnimap-request-body
1278           nnimap-request-group
1279           nnimap-close-group
1280           nnimap-pattern-to-list-arguments
1281           nnimap-request-list
1282           nnimap-request-post
1283           nnimap-retrieve-groups
1284           nnimap-request-update-info-internal
1285           nnimap-request-type
1286           nnimap-request-set-mark
1287           nnimap-split-to-groups
1288           nnimap-split-find-rule
1289           nnimap-split-find-inbox
1290           nnimap-split-articles
1291           nnimap-request-scan
1292           nnimap-request-newgroups
1293           nnimap-request-create-group
1294           nnimap-time-substract
1295           nnimap-date-days-ago
1296           nnimap-request-expire-articles-progress
1297           nnimap-request-expire-articles
1298           nnimap-request-move-article
1299           nnimap-request-accept-article
1300           nnimap-request-delete-group
1301           nnimap-request-rename-group
1302           gnus-group-nnimap-expunge
1303           gnus-group-nnimap-edit-acl
1304           gnus-group-nnimap-edit-acl-done
1305           nnimap-group-mode-hook
1306           nnimap-mark-to-predicate
1307           nnimap-mark-to-flag-1
1308           nnimap-mark-to-flag
1309           nnimap-mark-permanent-p
1310           nnimap-remassoc
1311           nnimap-update-alist-soft
1312           )))
1313
1314 (provide 'nnimap)
1315
1316 ;;; nnimap.el ends here