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