Importing Pterodactyl Gnus v0.99.
[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 Support escape characters in `message-tokenize-header'
40 ;;   o Split-fancy.
41 ;;   o Support NOV nnmail-extra-headers.
42 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
43 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
44 ;;   o Split up big fetches (1,* header especially) in smaller chunks
45 ;;   o What do I do with gnus-newsgroup-*?
46 ;;   o Tell Gnus about new groups (how can we tell?)
47 ;;   o Respooling (fix Gnus?) (unnecessery?)
48 ;;   o Add support for the following: (if applicable)
49 ;;       request-list-newsgroups, request-regenerate
50 ;;       list-active-group,
51 ;;       request-associate-buffer, request-restore-buffer,
52 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
53 ;;   o Support RFC2221 (Login referrals)
54 ;;   o IMAP2BIS compatibility? (RFC2061)
55 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
56 ;;     .newsrc.eld)
57 ;;   o What about Gnus's article editing, can we support it?
58 ;;   o Use \Draft to support the draft group??
59
60 ;;; Code:
61
62 (eval-and-compile
63   (require 'imap))
64
65 (require 'nnoo)
66 (require 'nnmail)
67 (require 'nnheader)
68 (require 'mm-util)
69 (require 'gnus)
70 (require 'gnus-async)
71 (require 'gnus-range)
72 (require 'gnus-start)
73 (require 'gnus-int)
74
75 (nnoo-declare nnimap)
76
77 (defconst nnimap-version "nnimap 0.131")
78
79 (defvoo nnimap-address nil
80   "Address of physical IMAP server.  If nil, use the virtual server's name.")
81
82 (defvoo nnimap-server-port nil
83   "Port number on physical IMAP server.
84 If nil, defaults to 993 for SSL connections and 143 otherwise.")
85
86 ;; Splitting variables
87
88 (defvar nnimap-split-crosspost t
89   "If non-nil, do crossposting if several split methods match the mail.
90 If nil, the first match found will be used.")
91
92 (defvar nnimap-split-inbox nil
93   "*Name of mailbox to split mail from.
94
95 Mail is read from this mailbox and split according to rules in
96 `nnimap-split-rules'.
97
98 This can be a string or a list of strings.")
99
100 (defvar nnimap-split-rule nil
101   "*Mail will be split according to theese rules.
102
103 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
104
105 If you'd like, for instance, one mail group for mail from the
106 \"gnus-imap\" mailing list, one group for junk mail and leave
107 everything else in the incoming mailbox, you could do something like
108 this:
109
110 (setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
111                           (\"INBOX.junk\"        \"Subject:.*buy\")))
112
113 As you can see, `nnimap-split-rule' is a list of lists, where the first
114 element in each \"rule\" is the name of the IMAP mailbox, and the
115 second is a regexp that nnimap will try to match on the header to find
116 a fit.
117
118 The first element can also be a list. In that case, the first element
119 is the server the second element is the group on that server in which
120 the matching article will be stored.
121
122 The second element can also be a function.  In that case, it will be
123 called narrowed to the headers with the first element of the rule as
124 the argument.  It should return a non-nil value if it thinks that the
125 mail belongs in that group.")
126
127 ;; Authorization / Privacy variables
128
129 (defvoo nnimap-auth-method nil
130   "Obsolete.")
131
132 (defvoo nnimap-stream nil
133   "How nnimap will connect to the server.
134
135 The default, nil, will try to use the \"best\" method the server can
136 handle.
137
138 Change this if
139
140 1) you want to connect with SSL. The SSL integration with IMAP is
141    brain-dead so you'll have to tell it specifically.
142
143 2) your server is more capable than your environment -- i.e. your
144    server accept Kerberos login's but you haven't installed the
145    `imtest' program or your machine isn't configured for Kerberos.
146
147 Possible choices: kerberos4, ssl, network")
148
149 (defvoo nnimap-authenticator nil
150   "How nnimap authenticate itself to the server.
151
152 The default, nil, will try to use the \"best\" method the server can
153 handle.
154
155 There is only one reason for fiddling with this variable, and that is
156 if your server is more capable than your environment -- i.e. you
157 connect to a server that accept Kerberos login's but you haven't
158 installed the `imtest' program or your machine isn't configured for
159 Kerberos.
160
161 Possible choices: kerberos4, cram-md5, login, anonymous.")
162
163 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
164   "Directory to keep NOV cache files for nnimap groups. See also
165 `nnimap-nov-file-name'.")
166
167 (defvoo nnimap-nov-file-name "nnimap."
168   "NOV cache base filename. The group name and
169 `nnimap-nov-file-name-suffix' will be appended. A typical complete
170 file name would be ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
171 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
172 `nnmail-use-long-file-names' is nil")
173
174 (defvoo nnimap-nov-file-name-suffix ".novcache"
175   "Suffix for NOV cache base filename.")
176
177 (defvoo nnimap-nov-is-evil nil
178   "If non-nil, nnimap will never generate or use a local nov database
179 for this backend.  Using nov databases will speed up header fetching
180 considerably. Unlike other backends, you do not need to take special
181 care if you flip this variable.")
182
183 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
184   "When a IMAP group with articles marked for deletion is closed, this
185 variable determine if nnimap should actually remove the articles or
186 not.
187
188 If always, nnimap always perform a expunge when closing the group.
189 If never, nnimap never expunges articles marked for deletion.
190 If ask, nnimap will ask you if you wish to expunge marked articles.
191
192 When setting this variable to `never', you can only expunge articles
193 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
194
195 (defvoo nnimap-list-pattern "*"
196   "A string LIMIT or list of strings with mailbox wildcards used to
197 limit available groups. Se below for available wildcards.
198
199 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
200 REFERENCE will be passed as the first parameter to LIST/LSUB. The
201 semantics of this are server specific, on the University of Washington
202 server you can specify a directory.
203
204 Example:
205  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
206
207 There are two wildcards * and %. * matches everything, % matches
208 everything in the current hierarchy.")
209
210 (defvoo nnimap-news-groups nil
211   "IMAP support a news-like mode, also known as bulletin board mode,
212 where replies is sent via IMAP instead of SMTP.
213
214 This variable should contain a regexp matching groups where you wish
215 replies to be stored to the mailbox directly.
216
217 Example:
218   '(\"^[^I][^N][^B][^O][^X].*$\")
219
220 This will match all groups not beginning with \"INBOX\".
221
222 Note that there is nothing technically different between mail-like and
223 news-like mailboxes. If you wish to have a group with todo items or
224 similar which you wouldn't want to set up a mailing list for, you can
225 use this to make replies go directly to the group.")
226
227 (defvoo nnimap-server-address nil
228   "Obsolete. Use `nnimap-address'.")
229
230 (defcustom nnimap-authinfo-file "~/.authinfo"
231   "Authorization information for IMAP servers.  In .netrc format."
232   :type
233   '(choice file
234            (repeat :tag "Entries"
235                    :menu-tag "Inline"
236                    (list :format "%v"
237                          :value ("" ("login" . "") ("password" . ""))
238                          (string :tag "Host")
239                          (checklist :inline t
240                                     (cons :format "%v"
241                                           (const :format "" "login")
242                                           (string :format "Login: %v"))
243                                     (cons :format "%v"
244                                           (const :format "" "password")
245                                           (string :format "Password: %v")))))))
246
247 (defcustom nnimap-prune-cache t
248   "If non-nil, nnimap check wheter articles still exist on server
249 before using data stored in NOV cache."
250   :type 'boolean)
251
252 (defvar nnimap-request-list-method 'imap-mailbox-list
253   "Method to use to request a list of all folders from the server.
254 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
255 restrict visible folders.")
256
257 ;; Internal variables:
258
259 (defvar nnimap-debug nil) ;; "*nnimap-debug*")
260 (defvar nnimap-current-move-server nil)
261 (defvar nnimap-current-move-group nil)
262 (defvar nnimap-current-move-article nil)
263 (defvar nnimap-length)
264 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
265 (defvar nnimap-progress-how-often 20)
266 (defvar nnimap-counter)
267 (defvar nnimap-callback-callback-function nil
268   "Gnus callback the nnimap asynchronous callback should call.")
269 (defvar nnimap-callback-buffer nil
270   "Which buffer the asynchronous article prefetch callback should work in.")
271
272 ;; Various server variables.
273
274 \f
275 ;; Internal variables.
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 (nnoo-define-basics nnimap)
281
282 ;; Utility functions:
283
284 (defun nnimap-replace-in-string (string regexp to)
285   "Replace substrings in STRING matching REGEXP with TO."
286   (if (string-match regexp string)
287       (concat (substring string 0 (match-beginning 0))
288               to
289               (nnimap-replace-in-string (substring string (match-end 0))
290                                  regexp to))
291     string))
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     (nnheader-insert-nov
372      (with-current-buffer nnimap-server-buffer
373        (vector imap-current-message
374                (nnimap-replace-whitespace
375                 (imap-message-envelope-subject imap-current-message))
376                (nnimap-replace-whitespace
377                 (imap-envelope-from
378                  (car-safe (imap-message-envelope-from
379                             imap-current-message))))
380                (nnimap-replace-whitespace
381                 (imap-message-envelope-date imap-current-message))
382                (nnimap-replace-whitespace
383                 (imap-message-envelope-message-id imap-current-message))
384                (nnimap-replace-whitespace
385                 (let ((str (if (imap-capability 'IMAP4rev1)
386                                (nth 2 (assoc
387                                        "HEADER.FIELDS REFERENCES"
388                                        (imap-message-get
389                                         imap-current-message 'BODYDETAIL)))
390                              (imap-message-get imap-current-message
391                                                'RFC822.HEADER))))
392                   (if (> (length str) (length "References: "))
393                       (substring str (length "References: "))
394                     (if (and (setq str (imap-message-envelope-in-reply-to
395                                         imap-current-message))
396                              (string-match "<[^>]+>" str))
397                         (substring str (match-beginning 0) (match-end 0))))))
398                (imap-message-get imap-current-message 'RFC822.SIZE)
399                (imap-body-lines (imap-message-body imap-current-message))
400                nil ;; xref
401                nil))))) ;; extra-headers
402
403 (defun nnimap-retrieve-which-headers (articles fetch-old)
404   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
405   (with-current-buffer nnimap-server-buffer
406     (if (numberp (car-safe articles))
407         (imap-search
408          (concat "UID "
409                  (nnimap-range-to-string
410                   (gnus-compress-sequence
411                    (append (gnus-uncompress-sequence
412                             (and fetch-old
413                                  (cons (if (numberp fetch-old)
414                                            (max 1 (- (car articles) fetch-old))
415                                          1)
416                                        (1- (car articles)))))
417                            articles)))))
418       (mapcar (lambda (msgid)
419                 (imap-search
420                  (format "HEADER Message-Id %s" msgid)))
421               articles))))
422
423 (defun nnimap-group-overview-filename (group server)
424   "Make pathname for GROUP on SERVER."
425   (let ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
426         (file (nnheader-translate-file-chars
427                (concat nnimap-nov-file-name
428                        (if (equal server "")
429                            "unnamed"
430                          server) "." group nnimap-nov-file-name-suffix) t)))
431     (if (or nnmail-use-long-file-names
432             (file-exists-p (concat dir file)))
433         (concat dir file)
434       (concat dir (mm-encode-coding-string
435                    (nnheader-replace-chars-in-string file ?. ?/)
436                    nnmail-pathname-coding-system)))))
437
438 (defun nnimap-retrieve-headers-from-file (group server)
439   (with-current-buffer nntp-server-buffer
440     (let ((nov (nnimap-group-overview-filename group server)))
441       (when (file-exists-p nov)
442         (mm-insert-file-contents nov)
443         (set-buffer-modified-p nil)
444         (let ((min (progn (goto-char (point-min))
445                           (when (not (eobp))
446                             (read (current-buffer)))))
447               (max (progn (goto-char (point-max))
448                           (forward-line -1)
449                           (when (not (bobp))
450                             (read (current-buffer))))))
451           (if (and (numberp min) (numberp max))
452               (cons min max)
453             ;; junk, remove it, it's saved later
454             (erase-buffer)
455             nil))))))
456
457 (defun nnimap-retrieve-headers-from-server (articles group server)
458   (with-current-buffer nnimap-server-buffer
459     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
460           (nnimap-length (gnus-range-length articles))
461           (nnimap-counter 0))
462       (imap-fetch (nnimap-range-to-string articles)
463                   (concat "(UID RFC822.SIZE ENVELOPE BODY "
464                           (if (imap-capability 'IMAP4rev1)
465                               "BODY.PEEK[HEADER.FIELDS (References)])"
466                             "RFC822.HEADER.LINES (References))")))
467       (and (numberp nnmail-large-newsgroup)
468            (> nnimap-length nnmail-large-newsgroup)
469            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
470
471 (defun nnimap-use-nov-p (group server)
472   (or gnus-nov-is-evil nnimap-nov-is-evil
473       (unless (and (gnus-make-directory
474                     (file-name-directory
475                      (nnimap-group-overview-filename group server)))
476                    (file-writable-p
477                     (nnimap-group-overview-filename group server)))
478         (message "nnimap: Nov cache not writable, %s"
479                  (nnimap-group-overview-filename group server)))))
480
481 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
482   (when (nnimap-possibly-change-group group server)
483     (with-current-buffer nntp-server-buffer
484       (erase-buffer)
485       (if (nnimap-use-nov-p group server)
486           (nnimap-retrieve-headers-from-server
487            (gnus-compress-sequence articles) group server)
488         (let (uids cached low high)
489           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
490                       low (car uids)
491                       high (car (last uids)))
492             (if (setq cached (nnimap-retrieve-headers-from-file group server))
493                 (progn
494                   ;; fetch articles with uids before cache block
495                   (when (< low (car cached))
496                     (goto-char (point-min))
497                     (nnimap-retrieve-headers-from-server
498                      (cons low (1- (car cached))) group server))
499                   ;; fetch articles with uids after cache block
500                   (when (> high (cdr cached))
501                     (goto-char (point-max))
502                     (nnimap-retrieve-headers-from-server
503                      (cons (1+ (cdr cached)) high) group server))
504                   (when nnimap-prune-cache
505                     ;; remove nov's for articles which has expired on server
506                     (goto-char (point-min))
507                     (dolist (uid (gnus-set-difference articles uids))
508                       (when (re-search-forward (format "^%d\t" uid) nil t)
509                         (gnus-delete-line)))))
510               ;; nothing cached, fetch whole range from server
511               (nnimap-retrieve-headers-from-server
512                (cons low high) group server))
513             (when (buffer-modified-p)
514               (nnmail-write-region
515                1 (point-max) (nnimap-group-overview-filename group server)
516                nil 'nomesg))
517             (nnheader-nov-delete-outside-range low high))))
518       'nov)))
519
520 (defun nnimap-open-connection (server)
521   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
522                       nnimap-authenticator nnimap-server-buffer))
523       (nnheader-report 'nnimap "Can't open connection to server %s" server)
524     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
525                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
526       (imap-close nnimap-server-buffer)
527       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
528     (let (list alist user passwd)
529       (and (fboundp 'gnus-parse-netrc)
530            (setq list (gnus-parse-netrc nnimap-authinfo-file)
531                  alist (or (and (gnus-netrc-get
532                                  (gnus-netrc-machine list server) "machine")
533                                 (gnus-netrc-machine list server))
534                            (gnus-netrc-machine list nnimap-address))
535                  user (gnus-netrc-get alist "login")
536                  passwd (gnus-netrc-get alist "password")))
537       (if (imap-authenticate user passwd nnimap-server-buffer)
538           (prog1
539               (push (list server nnimap-server-buffer)
540                     nnimap-server-buffer-alist)
541             (nnimap-possibly-change-server server))
542         (imap-close nnimap-server-buffer)
543         (kill-buffer nnimap-server-buffer)
544         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
545
546 (deffoo nnimap-open-server (server &optional defs)
547   (nnheader-init-server-buffer)
548   (if (nnimap-server-opened server)
549       t
550     (unless (assq 'nnimap-server-buffer defs)
551       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
552     ;; translate `nnimap-server-address' to `nnimap-address' in defs
553     ;; for people that configured nnimap with a very old version
554     (unless (assq 'nnimap-address defs)
555       (if (assq 'nnimap-server-address defs)
556           (push (list 'nnimap-address
557                       (cadr (assq 'nnimap-server-address defs))) defs)
558         (push (list 'nnimap-address server) defs)))
559     (nnoo-change-server 'nnimap server defs)
560     (or (and nnimap-server-buffer
561              (imap-opened nnimap-server-buffer))
562         (nnimap-open-connection server))))
563
564 (deffoo nnimap-server-opened (&optional server)
565   "If SERVER is the current virtual server, and the connection to the
566 physical server is alive, this function return a non-nil value. If
567 SERVER is nil, it is treated as the current server."
568   ;; clean up autologouts??
569   (and (or server nnimap-current-server)
570        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
571        (imap-opened (nnimap-get-server-buffer server))))
572
573 (deffoo nnimap-close-server (&optional server)
574   "Close connection to server and free all resources connected to
575 it. Return nil if the server couldn't be closed for some reason."
576   (let ((server (or server nnimap-current-server)))
577     (when (or (nnimap-server-opened server)
578               (imap-opened (nnimap-get-server-buffer server)))
579       (imap-close (nnimap-get-server-buffer server))
580       (kill-buffer (nnimap-get-server-buffer server))
581       (setq nnimap-server-buffer nil
582             nnimap-current-server nil
583             nnimap-server-buffer-alist
584             (delq server nnimap-server-buffer-alist)))
585     (nnoo-close-server 'nnimap server)))
586
587 (deffoo nnimap-request-close ()
588   "Close connection to all servers and free all resources that the
589 backend have reserved. All buffers that have been created by that
590 backend should be killed. (Not the nntp-server-buffer, though.) This
591 function is generally only called when Gnus is shutting down."
592   (mapcar (lambda (server) (nnimap-close-server (car server)))
593           nnimap-server-buffer-alist)
594   (setq nnimap-server-buffer-alist nil))
595
596 (deffoo nnimap-status-message (&optional server)
597   "This function returns the last error message from server."
598   (when (nnimap-possibly-change-server server)
599     (nnoo-status-message 'nnimap server)))
600
601 (defun nnimap-demule (string)
602   (funcall (if (and (fboundp 'string-as-multibyte)
603                     (subrp (symbol-function 'string-as-multibyte)))
604                'string-as-multibyte
605              'identity)
606            (or string "")))
607
608 (defun nnimap-callback ()
609   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
610   (with-current-buffer nnimap-callback-buffer
611     (insert
612      (with-current-buffer nnimap-server-buffer
613        (nnimap-demule (imap-message-get (imap-current-message) 'RFC822)))) ;xxx
614     (nnheader-ms-strip-cr)
615     (funcall nnimap-callback-callback-function t)))
616
617 (defun nnimap-request-article-part (article part prop
618                                             &optional group server to-buffer)
619   (when (nnimap-possibly-change-group group server)
620     (let ((article (if (stringp article)
621                        (car-safe (imap-search
622                                   (format "HEADER Message-Id %s" article)
623                                   nnimap-server-buffer))
624                      article)))
625       (when article
626         (gnus-message 9 "nnimap: Fetching (part of) article %d..." article)
627         (if (not nnheader-callback-function)
628             (with-current-buffer (or to-buffer nntp-server-buffer)
629               (erase-buffer)
630               (insert (nnimap-demule (imap-fetch article part prop nil
631                                                  nnimap-server-buffer)))
632               (nnheader-ms-strip-cr)
633               (gnus-message 9 "nnimap: Fetching (part of) article %d...done"
634                             article)
635               (if (bobp)
636                   (nnheader-report 'nnimap "No such article: %s"
637                                    (imap-error-text nnimap-server-buffer))
638                 (cons group article)))
639           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
640           (setq nnimap-callback-callback-function nnheader-callback-function
641                 nnimap-callback-buffer nntp-server-buffer)
642           (imap-fetch-asynch article part nil nnimap-server-buffer)
643           (cons group article))))))
644
645 (deffoo nnimap-asynchronous-p ()
646   t)
647
648 (deffoo nnimap-request-article (article &optional group server to-buffer)
649   (nnimap-request-article-part
650    article "RFC822.PEEK" 'RFC822 group server to-buffer))
651
652 (deffoo nnimap-request-head (article &optional group server to-buffer)
653   (nnimap-request-article-part
654    article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer))
655
656 (deffoo nnimap-request-body (article &optional group server to-buffer)
657   (nnimap-request-article-part
658    article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer))
659
660 (deffoo nnimap-request-group (group &optional server fast)
661   (nnimap-request-update-info-internal
662    group
663    (gnus-get-info (gnus-group-prefixed-name
664                    group (gnus-server-to-method (format "nnimap:%s" server))))
665    server)
666   (when (nnimap-possibly-change-group group server)
667     (let (info)
668       (cond (fast group)
669             ((null (setq info (nnimap-find-minmax-uid group t)))
670              (nnheader-report 'nnimap "Could not get active info for %s"
671                               group))
672             (t
673              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
674                               (max 1 (or (nth 1 info) 1))
675                               (or (nth 2 info) 0) group)
676              (nnheader-report 'nnimap "Group %s selected" group)
677              t)))))
678
679 (defun nnimap-close-group (group &optional server)
680   (with-current-buffer nnimap-server-buffer
681     (when (and (imap-opened)
682                (nnimap-possibly-change-group group server))
683       (case nnimap-expunge-on-close
684         ('always (imap-mailbox-expunge)
685                  (imap-mailbox-close))
686         ('ask (if (and (imap-search "DELETED")
687                        (gnus-y-or-n-p (format
688                                        "Expunge articles in group `%s'? "
689                                        imap-current-mailbox)))
690                   (progn (imap-mailbox-expunge)
691                          (imap-mailbox-close))
692                 (imap-mailbox-unselect)))
693         (t (imap-mailbox-unselect)))
694       (not imap-current-mailbox))))
695
696 (defun nnimap-pattern-to-list-arguments (pattern)
697   (mapcar (lambda (p)
698             (cons (car-safe p) (or (cdr-safe p) p)))
699           (if (and (listp pattern)
700                    (listp (cdr pattern)))
701               pattern
702             (list pattern))))
703
704 (deffoo nnimap-request-list (&optional server)
705   (when (nnimap-possibly-change-server server)
706     (with-current-buffer nntp-server-buffer
707       (erase-buffer))
708     (gnus-message 5 "nnimap: Generating active list%s..."
709                   (if (> (length server) 0) (concat " for " server) ""))
710     (with-current-buffer nnimap-server-buffer
711       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
712         (dolist (mbx (funcall nnimap-request-list-method
713                               (cdr pattern) (car pattern)))
714           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
715               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
716                 (when info
717                   ;; Escape SPC in mailboxes xxx relies on gnus internals
718                   (with-current-buffer nntp-server-buffer
719                     (insert (format "%s %d %d y\n"
720                                     (nnimap-replace-in-string mbx " " "\\ ")
721                                     (or (nth 2 info) 0)
722                                     (max 1 (or (nth 1 info) 1)))))))))))
723     (gnus-message 5 "nnimap: Generating active list%s...done"
724                   (if (> (length server) 0) (concat " for " server) ""))
725     t))
726
727 (deffoo nnimap-request-post (&optional server)
728   (let ((success t))
729     (dolist  (mbx (message-tokenize-header
730                    (message-fetch-field "Newsgroups")) success)
731       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
732         (or (gnus-active to-newsgroup)
733             (gnus-activate-group to-newsgroup)
734             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
735                                        to-newsgroup))
736                 (or (and (gnus-request-create-group
737                           to-newsgroup gnus-command-method)
738                          (gnus-activate-group to-newsgroup nil nil
739                                               gnus-command-method))
740                     (error "Couldn't create group %s" to-newsgroup)))
741             (error "No such group: %s" to-newsgroup))
742         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
743           (setq success nil))))))
744
745 ;; Optional backend functions
746
747 (deffoo nnimap-retrieve-groups (groups &optional server)
748   (when (nnimap-possibly-change-server server)
749     (gnus-message 5 "nnimap: Checking mailboxes...")
750     (with-current-buffer nntp-server-buffer
751       (erase-buffer)
752       (dolist (group groups)
753         (gnus-message 7 "nnimap: Checking mailbox %s" group)
754         (or (member "\\NoSelect"
755                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
756             (let ((info (nnimap-find-minmax-uid group 'examine)))
757               ;; Escape SPC in mailboxes xxx relies on gnus internals
758               (insert (format "211 %d %d %d %s\n" (or (nth 0 info) 0)
759                               (max 1 (or (nth 1 info) 1))
760                               (or (nth 2 info) 0)
761                               (nnimap-replace-in-string group " " "\\ ")))))))
762     (gnus-message 5 "nnimap: Checking mailboxes...done")
763     'groups))
764
765 (deffoo nnimap-request-update-info-internal (group info &optional server)
766   (when (nnimap-possibly-change-group group server)
767     (when info ;; xxx what does this mean? should we create a info?
768       (with-current-buffer nnimap-server-buffer
769         (gnus-message 5 "nnimap: Updating info for %s..."
770                       (gnus-info-group info))
771         
772         (when (nnimap-mark-permanent-p 'read)
773           (let (seen unseen)
774             ;; read info could contain articles marked unread by other
775             ;; imap clients!  we correct this
776             (setq seen (gnus-uncompress-range (gnus-info-read info))
777                   unseen (imap-search "UNSEEN UNDELETED")
778                   seen (gnus-set-difference seen unseen)
779                   ;; seen might lack articles marked as read by other
780                   ;; imap clients! we correct this
781                   seen (append seen (imap-search "SEEN"))
782                   ;; remove dupes
783                   seen (sort seen '<)
784                   seen (gnus-compress-sequence seen t)
785                   ;; we can't return '(1) since this isn't a "list of ranges",
786                   ;; and we can't return '((1)) since g-list-of-unread-articles
787                   ;; is buggy so we return '((1 . 1)).
788                   seen (if (and (integerp (car seen))
789                                 (null (cdr seen)))
790                            (list (cons (car seen) (car seen)))
791                          seen))
792             (gnus-info-set-read info seen)))
793
794         (mapc (lambda (pred)
795                 (when (and (nnimap-mark-permanent-p (cdr pred))
796                            (member (nnimap-mark-to-flag (cdr pred))
797                                    (imap-mailbox-get 'flags)))
798                   (gnus-info-set-marks
799                    info
800                    (nnimap-update-alist-soft
801                     (cdr pred)
802                     (gnus-compress-sequence
803                      (imap-search (nnimap-mark-to-predicate (cdr pred))))
804                     (gnus-info-marks info))
805                    t)))
806               gnus-article-mark-lists)
807         
808         (gnus-message 5 "nnimap: Updating info for %s...done"
809                       (gnus-info-group info))
810
811         info))))
812
813 (deffoo nnimap-request-type (group &optional article)
814   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
815       'news
816     'mail))
817
818 (deffoo nnimap-request-set-mark (group actions &optional server)
819   (when (nnimap-possibly-change-group group server)
820     (with-current-buffer nnimap-server-buffer
821       (let (action)
822         (gnus-message 7 "nnimap: Setting marks in %s..." group)
823         (while (setq action (pop actions))
824           (let ((range (nth 0 action))
825                 (what  (nth 1 action))
826                 (cmdmarks (nth 2 action))
827                 marks)
828             ;; cache flags are pointless on the server
829             (setq cmdmarks (delq 'cache cmdmarks))
830             ;; flag dormant articles as ticked
831             (if (memq 'dormant cmdmarks)
832                 (setq cmdmarks (cons 'tick cmdmarks)))
833             ;; remove stuff we are forbidden to store
834             (mapcar (lambda (mark)
835                       (if (imap-message-flag-permanent-p
836                            (nnimap-mark-to-flag mark))
837                           (setq marks (cons mark marks))))
838                     cmdmarks)
839             (when (and range marks)
840               (cond ((eq what 'del)
841                      (imap-message-flags-del
842                       (nnimap-range-to-string range)
843                       (nnimap-mark-to-flag marks nil t)))
844                     ((eq what 'add)
845                      (imap-message-flags-add
846                       (nnimap-range-to-string range)
847                       (nnimap-mark-to-flag marks nil t)))
848                     ((eq what 'set)
849                      (imap-message-flags-set
850                       (nnimap-range-to-string range)
851                       (nnimap-mark-to-flag marks nil t)))))))
852         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
853   nil)
854
855 (defun nnimap-split-to-groups (rules)
856   ;; tries to match all rules in nnimap-split-rule against content of
857   ;; nntp-server-buffer, returns a list of groups that matched.
858   (with-current-buffer nntp-server-buffer
859     ;; Fold continuation lines.
860     (goto-char (point-min))
861     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
862       (replace-match " " t t))
863     (if (functionp rules)
864         (funcall rules)
865       (let (to-groups regrepp)
866         (catch 'split-done
867           (dolist (rule rules to-groups)
868             (let ((group (car rule))
869                   (regexp (cadr rule)))
870               (goto-char (point-min))
871               (when (and (if (stringp regexp)
872                              (progn
873                                (setq regrepp (string-match "\\\\[0-9&]" group))
874                                (re-search-forward regexp nil t))
875                            (funcall regexp group))
876                          ;; Don't enter the article into the same group twice.
877                          (not (assoc group to-groups)))
878                 (push (if regrepp
879                           (nnmail-expand-newtext group)
880                         group)
881                       to-groups)
882                 (or nnimap-split-crosspost
883                     (throw 'split-done to-groups))))))))))
884   
885 (defun nnimap-split-find-rule (server inbox)
886   nnimap-split-rule)
887
888 (defun nnimap-split-find-inbox (server)
889   (if (listp nnimap-split-inbox)
890       nnimap-split-inbox
891     (list nnimap-split-inbox)))
892
893 (defun nnimap-split-articles (&optional group server)
894   (when (nnimap-possibly-change-server server)
895     (with-current-buffer nnimap-server-buffer
896       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
897         ;; iterate over inboxes
898         (while (and (setq inbox (pop inboxes))
899                     (nnimap-possibly-change-group inbox)) ;; SELECT
900           ;; find split rule for this server / inbox
901           (when (setq rule (nnimap-split-find-rule server inbox))
902             ;; iterate over articles
903             (dolist (article (imap-search "UNSEEN UNDELETED"))
904               (when (nnimap-request-head article)
905                 ;; copy article to right group(s)
906                 (setq removeorig nil)
907                 (dolist (to-group (nnimap-split-to-groups rule))
908                   (if (imap-message-copy (number-to-string article)
909                                          to-group nil 'nocopyuid)
910                       (progn
911                         (message "IMAP split moved %s:%s:%d to %s" server inbox
912                                  article to-group)
913                         (setq removeorig t)
914                         ;; Add the group-art list to the history list.
915                         (push (list (cons to-group 0)) nnmail-split-history))
916                     (message "IMAP split failed to move %s:%s:%d to %s" server
917                              inbox article to-group)))
918                 ;; remove article if it was successfully copied somewhere
919                 (and removeorig
920                      (imap-message-flags-add (format "%d" article)
921                                              "\\Seen \\Deleted")))))
922           (when (imap-mailbox-select inbox) ;; just in case
923             ;; todo: UID EXPUNGE (if available) to remove splitted articles
924             (imap-mailbox-expunge)
925             (imap-mailbox-close)))
926         t))))
927
928 (deffoo nnimap-request-scan (&optional group server)
929   (nnimap-split-articles group server))
930
931 (deffoo nnimap-request-newgroups (date &optional server)
932   (when (nnimap-possibly-change-server server)
933     (with-current-buffer nntp-server-buffer
934       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
935                     (if (> (length server) 0) " on " "") server)
936       (erase-buffer)
937       (dolist (pattern (nnimap-pattern-to-list-arguments
938                         nnimap-list-pattern))
939         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
940                                         nnimap-server-buffer))
941           (or (member-if (lambda (mailbox)
942                            (string= (downcase mailbox) "\\noselect"))
943                          (imap-mailbox-get 'list-flags mbx
944                                            nnimap-server-buffer))
945               ;; Escape SPC in mailboxes xxx relies on gnus internals
946               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
947                 (when info
948                   (insert (format "%s %d %d y\n"
949                                   (nnimap-replace-in-string mbx " " "\\ ")
950                                   (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
1132 predicate (a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD
1133 gnus-expire\") 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
1156 flag (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
1173 on articles, in GROUP."
1174   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1175
1176 (defun nnimap-remassoc (key alist)
1177   "Delete by side effect any elements of LIST whose car is
1178 `equal' to KEY.  The modified LIST is returned.  If the first member
1179 of LIST has a car that is `equal' to KEY, there is no way to remove it
1180 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1181 sure of changing the value of `foo'."
1182   (when alist
1183     (if (equal key (caar alist))
1184         (cdr alist)
1185       (setcdr alist (nnimap-remassoc key (cdr alist)))
1186       alist)))
1187   
1188 (defun nnimap-update-alist-soft (key value alist)
1189   (if value
1190       (cons (cons key value) (nnimap-remassoc key alist))
1191     (nnimap-remassoc key alist)))
1192
1193 (defun nnimap-range-to-string (range)
1194   (mapconcat
1195    (lambda (item)
1196      (if (consp item)
1197          (format "%d:%d"
1198                  (car item) (cdr item))
1199        (format "%d" item)))
1200    (if (and (listp range) (not (listp (cdr range))))
1201        (list range) ;; make (1 . 2) into ((1 . 2))
1202      range)
1203    ","))
1204
1205 (when nnimap-debug
1206   (require 'trace)
1207   (buffer-disable-undo (get-buffer-create nnimap-debug))
1208   (mapc (lambda (f) (trace-function-background f nnimap-debug))
1209         '(
1210 nnimap-replace-in-string
1211 nnimap-possibly-change-server
1212 nnimap-verify-uidvalidity
1213 nnimap-find-minmax-uid
1214 nnimap-possibly-change-group
1215 ;nnimap-replace-whitespace
1216 nnimap-retrieve-headers-progress
1217 nnimap-retrieve-which-headers
1218 nnimap-group-overview-filename
1219 nnimap-retrieve-headers-from-file
1220 nnimap-retrieve-headers-from-server
1221 nnimap-retrieve-headers
1222 nnimap-open-connection
1223 nnimap-open-server
1224 nnimap-server-opened
1225 nnimap-close-server
1226 nnimap-request-close
1227 nnimap-status-message
1228 ;nnimap-demule
1229 nnimap-request-article-part
1230 nnimap-request-article
1231 nnimap-request-head
1232 nnimap-request-body
1233 nnimap-request-group
1234 nnimap-close-group
1235 nnimap-pattern-to-list-arguments
1236 nnimap-request-list
1237 nnimap-request-post
1238 nnimap-retrieve-groups
1239 nnimap-request-update-info-internal
1240 nnimap-request-type
1241 nnimap-request-set-mark
1242 nnimap-split-to-groups
1243 nnimap-split-find-rule
1244 nnimap-split-find-inbox
1245 nnimap-split-articles
1246 nnimap-request-scan
1247 nnimap-request-newgroups
1248 nnimap-request-create-group
1249 nnimap-time-substract
1250 nnimap-date-days-ago
1251 nnimap-request-expire-articles-progress
1252 nnimap-request-expire-articles
1253 nnimap-request-move-article
1254 nnimap-request-accept-article
1255 nnimap-request-delete-group
1256 nnimap-request-rename-group
1257 gnus-group-nnimap-expunge
1258 gnus-group-nnimap-edit-acl
1259 gnus-group-nnimap-edit-acl-done
1260 nnimap-group-mode-hook
1261 nnimap-mark-to-predicate
1262 nnimap-mark-to-flag-1
1263 nnimap-mark-to-flag
1264 nnimap-mark-permanent-p
1265 nnimap-remassoc
1266 nnimap-update-alist-soft
1267 nnimap-range-to-string
1268           )))
1269
1270 (provide 'nnimap)
1271
1272 ;;; nnimap.el ends here