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