(nnimap-request-newgroups): Eschew member-if.
[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 (catch 'found
1001                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1002                                                    nnimap-server-buffer))
1003                   (if (string= (downcase mailbox) "\\noselect")
1004                       (throw 'found t)))
1005                 nil)
1006               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1007                 (when info
1008                  (insert (format "\"%s\" %d %d y\n"
1009                                  mbx (or (nth 2 info) 0)
1010                                  (max 1 (or (nth 1 info) 1)))))))))
1011       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1012                     (if (> (length server) 0) " on " "") server))
1013     t))
1014       
1015 (deffoo nnimap-request-create-group (group &optional server args)
1016   (when (nnimap-possibly-change-server server)
1017     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1018         (imap-mailbox-create group nnimap-server-buffer))))
1019
1020 (defun nnimap-time-substract (time1 time2)
1021   "Return TIME for TIME1 - TIME2."
1022   (let* ((ms (- (car time1) (car time2)))
1023          (ls (- (nth 1 time1) (nth 1 time2))))
1024     (if (< ls 0)
1025         (list (- ms 1) (+ (expt 2 16) ls))
1026       (list ms ls))))
1027
1028 (defun nnimap-date-days-ago (daysago)
1029   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1030   (let ((date (format-time-string "%d-%b-%Y"
1031                                   (nnimap-time-substract
1032                                    (current-time)
1033                                    (days-to-time daysago)))))
1034     (if (eq ?0 (string-to-char date))
1035         (substring date 1)
1036       date)))
1037
1038 (defun nnimap-request-expire-articles-progress ()
1039   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1040                 imap-current-message))
1041
1042 ;; Notice that we don't actually delete anything, we just mark them deleted.
1043 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1044   (let ((artseq (gnus-compress-sequence articles)))
1045     (when (and artseq (nnimap-possibly-change-group group server))
1046       (with-current-buffer nnimap-server-buffer
1047         (if force
1048             (and (imap-message-flags-add
1049                   (imap-range-to-message-set artseq) "\\Deleted")
1050                  (setq articles nil))
1051           (let ((days (or (and nnmail-expiry-wait-function
1052                                (funcall nnmail-expiry-wait-function group))
1053                           nnmail-expiry-wait)))
1054             (cond ((eq days 'immediate)
1055                    (and (imap-message-flags-add
1056                          (imap-range-to-message-set artseq) "\\Deleted")
1057                         (setq articles nil)))
1058                   ((numberp days)
1059                    (let ((oldarts (imap-search
1060                                    (format "UID %s NOT SINCE %s"
1061                                            (imap-range-to-message-set artseq)
1062                                            (nnimap-date-days-ago days))))
1063                          (imap-fetch-data-hook
1064                           '(nnimap-request-expire-articles-progress)))
1065                      (and oldarts
1066                           (imap-message-flags-add
1067                            (imap-range-to-message-set
1068                             (gnus-compress-sequence oldarts))
1069                            "\\Deleted")
1070                           (setq articles (gnus-set-difference
1071                                           articles oldarts)))))))))))
1072   ;; return articles not deleted
1073   articles)
1074
1075 (deffoo nnimap-request-move-article (article group server
1076                                              accept-form &optional last)
1077   (when (nnimap-possibly-change-server server)
1078     (save-excursion
1079       (let ((buf (get-buffer-create " *nnimap move*"))
1080             (nnimap-current-move-article article)
1081             (nnimap-current-move-group group)
1082             (nnimap-current-move-server nnimap-current-server)
1083             result)
1084         (and (nnimap-request-article article group server)
1085              (save-excursion
1086                (set-buffer buf)
1087                (buffer-disable-undo (current-buffer))
1088                (insert-buffer-substring nntp-server-buffer)
1089                (setq result (eval accept-form))
1090                (kill-buffer buf)
1091                result)
1092              (nnimap-request-expire-articles (list article) group server t))
1093         result))))
1094   
1095 (deffoo nnimap-request-accept-article (group &optional server last)
1096   (when (nnimap-possibly-change-server server)
1097     (let (uid)
1098       (if (setq uid
1099                 (if (string= nnimap-current-server nnimap-current-move-server)
1100                     ;; moving article within same server, speed it up...
1101                     (and (nnimap-possibly-change-group
1102                           nnimap-current-move-group)
1103                          (imap-message-copy (number-to-string
1104                                              nnimap-current-move-article)
1105                                             group 'dontcreate nil
1106                                             nnimap-server-buffer))
1107                   ;; turn into rfc822 format (\r\n eol's)
1108                   (with-current-buffer (current-buffer)
1109                     (goto-char (point-min))
1110                     (while (search-forward "\n" nil t)
1111                       (replace-match "\r\n")))
1112                   ;; this 'or' is for Cyrus server bug
1113                   (or (null (imap-current-mailbox nnimap-server-buffer))
1114                       (imap-mailbox-unselect nnimap-server-buffer))
1115                   (imap-message-append group (current-buffer) nil nil
1116                                        nnimap-server-buffer)))
1117           (cons group (nth 1 uid))
1118         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1119
1120 (deffoo nnimap-request-delete-group (group force &optional server)
1121   (when (nnimap-possibly-change-server server)
1122     (with-current-buffer nnimap-server-buffer
1123       (if force
1124           (or (null (imap-mailbox-status group 'uidvalidity))
1125               (imap-mailbox-delete group))
1126         ;; UNSUBSCRIBE?
1127         t))))
1128
1129 (deffoo nnimap-request-rename-group (group new-name &optional server)
1130   (when (nnimap-possibly-change-server server)
1131     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1132
1133 (defun nnimap-expunge (mailbox server)
1134   (when (nnimap-possibly-change-group mailbox server)
1135     (imap-mailbox-expunge nnimap-server-buffer)))
1136
1137 (defun nnimap-acl-get (mailbox server)
1138   (when (nnimap-possibly-change-server server)
1139     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1140
1141 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1142   (when (nnimap-possibly-change-server (cadr method))
1143     (unless (imap-capability 'ACL nnimap-server-buffer)
1144       (error "Your server does not support ACL editing"))
1145     (with-current-buffer nnimap-server-buffer
1146       ;; delete all removed identifiers
1147       (mapcar (lambda (old-acl)
1148                 (unless (assoc (car old-acl) new-acls)
1149                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1150                       (error "Can't delete ACL for %s" (car old-acl)))))
1151               old-acls)
1152       ;; set all changed acl's
1153       (mapcar (lambda (new-acl)
1154                 (let ((new-rights (cdr new-acl))
1155                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1156                   (unless (and old-rights new-rights
1157                                (string= old-rights new-rights))
1158                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1159                         (error "Can't set ACL for %s to %s" (car new-acl)
1160                                new-rights)))))
1161               new-acls)
1162       t)))
1163
1164 \f
1165 ;;; Internal functions
1166
1167 ;;
1168 ;; This is confusing.
1169 ;;
1170 ;; mark      => read, tick, draft, reply etc
1171 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1172 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1173 ;;
1174 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1175 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1176 ;;
1177
1178 (defconst nnimap-mark-to-predicate-alist
1179   (mapcar
1180    (lambda (pair)                       ; cdr is the mark
1181      (or (assoc (cdr pair)
1182                 '((read . "SEEN")
1183                   (tick . "FLAGGED")
1184                   (draft . "DRAFT")
1185                   (reply . "ANSWERED")))
1186          (cons (cdr pair)
1187                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1188    (cons '(read . read) gnus-article-mark-lists)))
1189
1190 (defun nnimap-mark-to-predicate (pred)
1191   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1192 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1193 to be used within a IMAP SEARCH query."
1194   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1195
1196 (defconst nnimap-mark-to-flag-alist
1197   (mapcar
1198    (lambda (pair)
1199      (or (assoc (cdr pair)
1200                 '((read . "\\Seen")
1201                   (tick . "\\Flagged")
1202                   (draft . "\\Draft")
1203                   (reply . "\\Answered")))
1204          (cons (cdr pair)
1205                (format "gnus-%s" (symbol-name (cdr pair))))))
1206    (cons '(read . read) gnus-article-mark-lists)))
1207
1208 (defun nnimap-mark-to-flag-1 (preds)
1209   (if (and (not (null preds)) (listp preds))
1210       (cons (nnimap-mark-to-flag (car preds))
1211             (nnimap-mark-to-flag (cdr preds)))
1212     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1213
1214 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1215   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1216 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1217 be used in a STORE FLAGS command."
1218   (let ((result (nnimap-mark-to-flag-1 preds)))
1219     (setq result (if (and (or make-string always-list)
1220                           (not (listp result)))
1221                      (list result)
1222                    result))
1223     (if make-string
1224         (mapconcat (lambda (flag)
1225                      (if (listp flag)
1226                          (mapconcat 'identity flag " ")
1227                        flag))
1228                    result " ")
1229       result)))
1230
1231 (defun nnimap-mark-permanent-p (mark &optional group)
1232   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1233   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1234
1235 (defun nnimap-remassoc (key alist)
1236   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1237 The modified LIST is returned.  If the first member
1238 of LIST has a car that is `equal' to KEY, there is no way to remove it
1239 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1240 sure of changing the value of `foo'."
1241   (when alist
1242     (if (equal key (caar alist))
1243         (cdr alist)
1244       (setcdr alist (nnimap-remassoc key (cdr alist)))
1245       alist)))
1246   
1247 (defun nnimap-update-alist-soft (key value alist)
1248   (if value
1249       (cons (cons key value) (nnimap-remassoc key alist))
1250     (nnimap-remassoc key alist)))
1251
1252 (when nnimap-debug
1253   (require 'trace)
1254   (buffer-disable-undo (get-buffer-create nnimap-debug))
1255   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1256         '(
1257           nnimap-possibly-change-server
1258           nnimap-verify-uidvalidity
1259           nnimap-find-minmax-uid
1260           nnimap-before-find-minmax-bugworkaround
1261           nnimap-possibly-change-group
1262           ;;nnimap-replace-whitespace
1263           nnimap-retrieve-headers-progress
1264           nnimap-retrieve-which-headers
1265           nnimap-group-overview-filename
1266           nnimap-retrieve-headers-from-file
1267           nnimap-retrieve-headers-from-server
1268           nnimap-retrieve-headers
1269           nnimap-open-connection
1270           nnimap-open-server
1271           nnimap-server-opened
1272           nnimap-close-server
1273           nnimap-request-close
1274           nnimap-status-message
1275           ;;nnimap-demule
1276           nnimap-request-article-part
1277           nnimap-request-article
1278           nnimap-request-head
1279           nnimap-request-body
1280           nnimap-request-group
1281           nnimap-close-group
1282           nnimap-pattern-to-list-arguments
1283           nnimap-request-list
1284           nnimap-request-post
1285           nnimap-retrieve-groups
1286           nnimap-request-update-info-internal
1287           nnimap-request-type
1288           nnimap-request-set-mark
1289           nnimap-split-to-groups
1290           nnimap-split-find-rule
1291           nnimap-split-find-inbox
1292           nnimap-split-articles
1293           nnimap-request-scan
1294           nnimap-request-newgroups
1295           nnimap-request-create-group
1296           nnimap-time-substract
1297           nnimap-date-days-ago
1298           nnimap-request-expire-articles-progress
1299           nnimap-request-expire-articles
1300           nnimap-request-move-article
1301           nnimap-request-accept-article
1302           nnimap-request-delete-group
1303           nnimap-request-rename-group
1304           gnus-group-nnimap-expunge
1305           gnus-group-nnimap-edit-acl
1306           gnus-group-nnimap-edit-acl-done
1307           nnimap-group-mode-hook
1308           nnimap-mark-to-predicate
1309           nnimap-mark-to-flag-1
1310           nnimap-mark-to-flag
1311           nnimap-mark-permanent-p
1312           nnimap-remassoc
1313           nnimap-update-alist-soft
1314           )))
1315
1316 (provide 'nnimap)
1317
1318 ;;; nnimap.el ends here