(nnimap-retrieve-headers-progress): Fold continuation
[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          (nnheader-fold-continuation-lines)
388          (subst-char-in-region (point-min) (point-max) ?\t ? )
389          (let ((head (nnheader-parse-head 'naked)))
390            (mail-header-set-number head uid)
391            (mail-header-set-chars head chars)
392            (mail-header-set-lines head lines)
393            (mail-header-set-xref
394             head (format "%s %s:%d" (system-name) mbx uid))
395            head))))))
396
397 (defun nnimap-retrieve-which-headers (articles fetch-old)
398   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
399   (with-current-buffer nnimap-server-buffer
400     (if (numberp (car-safe articles))
401         (imap-search
402          (concat "UID "
403                  (nnimap-range-to-string
404                   (gnus-compress-sequence
405                    (append (gnus-uncompress-sequence
406                             (and fetch-old
407                                  (cons (if (numberp fetch-old)
408                                            (max 1 (- (car articles) fetch-old))
409                                          1)
410                                        (1- (car articles)))))
411                            articles)))))
412       (mapcar (lambda (msgid)
413                 (imap-search
414                  (format "HEADER Message-Id %s" msgid)))
415               articles))))
416
417 (defun nnimap-group-overview-filename (group server)
418   "Make pathname for GROUP on SERVER."
419   (let ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
420         (file (nnheader-translate-file-chars
421                (concat nnimap-nov-file-name
422                        (if (equal server "")
423                            "unnamed"
424                          server) "." group nnimap-nov-file-name-suffix) t)))
425     (if (or nnmail-use-long-file-names
426             (file-exists-p (concat dir file)))
427         (concat dir file)
428       (concat dir (mm-encode-coding-string
429                    (nnheader-replace-chars-in-string file ?. ?/)
430                    nnmail-pathname-coding-system)))))
431
432 (defun nnimap-retrieve-headers-from-file (group server)
433   (with-current-buffer nntp-server-buffer
434     (let ((nov (nnimap-group-overview-filename group server)))
435       (when (file-exists-p nov)
436         (mm-insert-file-contents nov)
437         (set-buffer-modified-p nil)
438         (let ((min (progn (goto-char (point-min))
439                           (when (not (eobp))
440                             (read (current-buffer)))))
441               (max (progn (goto-char (point-max))
442                           (forward-line -1)
443                           (when (not (bobp))
444                             (read (current-buffer))))))
445           (if (and (numberp min) (numberp max))
446               (cons min max)
447             ;; junk, remove it, it's saved later
448             (erase-buffer)
449             nil))))))
450
451 (defun nnimap-retrieve-headers-from-server (articles group server)
452   (with-current-buffer nnimap-server-buffer
453     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
454           (nnimap-length (gnus-range-length articles))
455           (nnimap-counter 0))
456       (imap-fetch (nnimap-range-to-string articles)
457                   (concat "(UID RFC822.SIZE BODY "
458                           (let ((headers
459                                  (append '(Subject From Date Message-Id
460                                                    References In-Reply-To Xref)
461                                          (copy-sequence
462                                           nnmail-extra-headers))))
463                             (if (imap-capability 'IMAP4rev1)
464                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
465                               (format "RFC822.HEADER.LINES %s)" headers)))))
466       (and (numberp nnmail-large-newsgroup)
467            (> nnimap-length nnmail-large-newsgroup)
468            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
469
470 (defun nnimap-use-nov-p (group server)
471   (or gnus-nov-is-evil nnimap-nov-is-evil
472       (unless (and (gnus-make-directory
473                     (file-name-directory
474                      (nnimap-group-overview-filename group server)))
475                    (file-writable-p
476                     (nnimap-group-overview-filename group server)))
477         (message "nnimap: Nov cache not writable, %s"
478                  (nnimap-group-overview-filename group server)))))
479
480 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
481   (when (nnimap-possibly-change-group group server)
482     (with-current-buffer nntp-server-buffer
483       (erase-buffer)
484       (if (nnimap-use-nov-p group server)
485           (nnimap-retrieve-headers-from-server
486            (gnus-compress-sequence articles) group server)
487         (let (uids cached low high)
488           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
489                       low (car uids)
490                       high (car (last uids)))
491             (if (setq cached (nnimap-retrieve-headers-from-file group server))
492                 (progn
493                   ;; fetch articles with uids before cache block
494                   (when (< low (car cached))
495                     (goto-char (point-min))
496                     (nnimap-retrieve-headers-from-server
497                      (cons low (1- (car cached))) group server))
498                   ;; fetch articles with uids after cache block
499                   (when (> high (cdr cached))
500                     (goto-char (point-max))
501                     (nnimap-retrieve-headers-from-server
502                      (cons (1+ (cdr cached)) high) group server))
503                   (when nnimap-prune-cache
504                     ;; remove nov's for articles which has expired on server
505                     (goto-char (point-min))
506                     (dolist (uid (gnus-set-difference articles uids))
507                       (when (re-search-forward (format "^%d\t" uid) nil t)
508                         (gnus-delete-line)))))
509               ;; nothing cached, fetch whole range from server
510               (nnimap-retrieve-headers-from-server
511                (cons low high) group server))
512             (when (buffer-modified-p)
513               (nnmail-write-region
514                1 (point-max) (nnimap-group-overview-filename group server)
515                nil 'nomesg))
516             (nnheader-nov-delete-outside-range low high))))
517       'nov)))
518
519 (defun nnimap-open-connection (server)
520   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
521                       nnimap-authenticator nnimap-server-buffer))
522       (nnheader-report 'nnimap "Can't open connection to server %s" server)
523     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
524                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
525       (imap-close nnimap-server-buffer)
526       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
527     (let (list alist user passwd)
528       (and (fboundp 'gnus-parse-netrc)
529            (setq list (gnus-parse-netrc nnimap-authinfo-file)
530                  alist (or (and (gnus-netrc-get
531                                  (gnus-netrc-machine list server) "machine")
532                                 (gnus-netrc-machine list server))
533                            (gnus-netrc-machine list nnimap-address))
534                  user (gnus-netrc-get alist "login")
535                  passwd (gnus-netrc-get alist "password")))
536       (if (imap-authenticate user passwd nnimap-server-buffer)
537           (prog1
538               (push (list server nnimap-server-buffer)
539                     nnimap-server-buffer-alist)
540             (nnimap-possibly-change-server server))
541         (imap-close nnimap-server-buffer)
542         (kill-buffer nnimap-server-buffer)
543         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
544
545 (deffoo nnimap-open-server (server &optional defs)
546   (nnheader-init-server-buffer)
547   (if (nnimap-server-opened server)
548       t
549     (unless (assq 'nnimap-server-buffer defs)
550       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
551     ;; translate `nnimap-server-address' to `nnimap-address' in defs
552     ;; for people that configured nnimap with a very old version
553     (unless (assq 'nnimap-address defs)
554       (if (assq 'nnimap-server-address defs)
555           (push (list 'nnimap-address
556                       (cadr (assq 'nnimap-server-address defs))) defs)
557         (push (list 'nnimap-address server) defs)))
558     (nnoo-change-server 'nnimap server defs)
559     (or (and nnimap-server-buffer
560              (imap-opened nnimap-server-buffer))
561         (nnimap-open-connection server))))
562
563 (deffoo nnimap-server-opened (&optional server)
564   "Whether SERVER is opened.
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 it.
575 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 backend have reserved.
589 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                   (with-current-buffer nntp-server-buffer
718                    (insert (format "\"%s\" %d %d y\n"
719                                    mbx (or (nth 2 info) 0)
720                                    (max 1 (or (nth 1 info) 1)))))))))))
721     (gnus-message 5 "nnimap: Generating active list%s...done"
722                   (if (> (length server) 0) (concat " for " server) ""))
723     t))
724
725 (deffoo nnimap-request-post (&optional server)
726   (let ((success t))
727     (dolist  (mbx (message-tokenize-header
728                    (message-fetch-field "Newsgroups")) success)
729       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
730         (or (gnus-active to-newsgroup)
731             (gnus-activate-group to-newsgroup)
732             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
733                                        to-newsgroup))
734                 (or (and (gnus-request-create-group
735                           to-newsgroup gnus-command-method)
736                          (gnus-activate-group to-newsgroup nil nil
737                                               gnus-command-method))
738                     (error "Couldn't create group %s" to-newsgroup)))
739             (error "No such group: %s" to-newsgroup))
740         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
741           (setq success nil))))))
742
743 ;; Optional backend functions
744
745 (deffoo nnimap-retrieve-groups (groups &optional server)
746   (when (nnimap-possibly-change-server server)
747     (gnus-message 5 "nnimap: Checking mailboxes...")
748     (with-current-buffer nntp-server-buffer
749       (erase-buffer)
750       (dolist (group groups)
751         (gnus-message 7 "nnimap: Checking mailbox %s" group)
752         (or (member "\\NoSelect"
753                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
754             (let ((info (nnimap-find-minmax-uid group 'examine)))
755               (insert (format "\"%s\" %d %d y\n" group
756                               (or (nth 2 info) 0)
757                               (max 1 (or (nth 1 info) 1))))))))
758     (gnus-message 5 "nnimap: Checking mailboxes...done")
759     'active))
760
761 (deffoo nnimap-request-update-info-internal (group info &optional server)
762   (when (nnimap-possibly-change-group group server)
763     (when info;; xxx what does this mean? should we create a info?
764       (with-current-buffer nnimap-server-buffer
765         (gnus-message 5 "nnimap: Updating info for %s..."
766                       (gnus-info-group info))
767         
768         (when (nnimap-mark-permanent-p 'read)
769           (let (seen unseen)
770             ;; read info could contain articles marked unread by other
771             ;; imap clients!  we correct this
772             (setq seen (gnus-uncompress-range (gnus-info-read info))
773                   unseen (imap-search "UNSEEN UNDELETED")
774                   seen (gnus-set-difference seen unseen)
775                   ;; seen might lack articles marked as read by other
776                   ;; imap clients! we correct this
777                   seen (append seen (imap-search "SEEN"))
778                   ;; remove dupes
779                   seen (sort seen '<)
780                   seen (gnus-compress-sequence seen t)
781                   ;; we can't return '(1) since this isn't a "list of ranges",
782                   ;; and we can't return '((1)) since g-list-of-unread-articles
783                   ;; is buggy so we return '((1 . 1)).
784                   seen (if (and (integerp (car seen))
785                                 (null (cdr seen)))
786                            (list (cons (car seen) (car seen)))
787                          seen))
788             (gnus-info-set-read info seen)))
789
790         (mapcar (lambda (pred)
791                   (when (and (nnimap-mark-permanent-p (cdr pred))
792                              (member (nnimap-mark-to-flag (cdr pred))
793                                      (imap-mailbox-get 'flags)))
794                     (gnus-info-set-marks
795                      info
796                      (nnimap-update-alist-soft
797                       (cdr pred)
798                       (gnus-compress-sequence
799                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
800                       (gnus-info-marks info))
801                      t)))
802                 gnus-article-mark-lists)
803         
804         (gnus-message 5 "nnimap: Updating info for %s...done"
805                       (gnus-info-group info))
806
807         info))))
808
809 (deffoo nnimap-request-type (group &optional article)
810   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
811       'news
812     'mail))
813
814 (deffoo nnimap-request-set-mark (group actions &optional server)
815   (when (nnimap-possibly-change-group group server)
816     (with-current-buffer nnimap-server-buffer
817       (let (action)
818         (gnus-message 7 "nnimap: Setting marks in %s..." group)
819         (while (setq action (pop actions))
820           (let ((range (nth 0 action))
821                 (what  (nth 1 action))
822                 (cmdmarks (nth 2 action))
823                 marks)
824             ;; cache flags are pointless on the server
825             (setq cmdmarks (delq 'cache cmdmarks))
826             ;; flag dormant articles as ticked
827             (if (memq 'dormant cmdmarks)
828                 (setq cmdmarks (cons 'tick cmdmarks)))
829             ;; remove stuff we are forbidden to store
830             (mapcar (lambda (mark)
831                       (if (imap-message-flag-permanent-p
832                            (nnimap-mark-to-flag mark))
833                           (setq marks (cons mark marks))))
834                     cmdmarks)
835             (when (and range marks)
836               (cond ((eq what 'del)
837                      (imap-message-flags-del
838                       (nnimap-range-to-string range)
839                       (nnimap-mark-to-flag marks nil t)))
840                     ((eq what 'add)
841                      (imap-message-flags-add
842                       (nnimap-range-to-string range)
843                       (nnimap-mark-to-flag marks nil t)))
844                     ((eq what 'set)
845                      (imap-message-flags-set
846                       (nnimap-range-to-string range)
847                       (nnimap-mark-to-flag marks nil t)))))))
848         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
849   nil)
850
851 (defun nnimap-split-fancy ()
852   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
853   (let ((nnmail-split-fancy nnimap-split-fancy))
854     (nnmail-split-fancy)))
855
856 (defun nnimap-split-to-groups (rules)
857   ;; tries to match all rules in nnimap-split-rule against content of
858   ;; nntp-server-buffer, returns a list of groups that matched.
859   (with-current-buffer nntp-server-buffer
860     ;; Fold continuation lines.
861     (goto-char (point-min))
862     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
863       (replace-match " " t t))
864     (if (functionp rules)
865         (funcall rules)
866       (let (to-groups regrepp)
867         (catch 'split-done
868           (dolist (rule rules to-groups)
869             (let ((group (car rule))
870                   (regexp (cadr rule)))
871               (goto-char (point-min))
872               (when (and (if (stringp regexp)
873                              (progn
874                                (setq regrepp (string-match "\\\\[0-9&]" group))
875                                (re-search-forward regexp nil t))
876                            (funcall regexp group))
877                          ;; Don't enter the article into the same group twice.
878                          (not (assoc group to-groups)))
879                 (push (if regrepp
880                           (nnmail-expand-newtext group)
881                         group)
882                       to-groups)
883                 (or nnimap-split-crosspost
884                     (throw 'split-done to-groups))))))))))
885   
886 (defun nnimap-split-find-rule (server inbox)
887   nnimap-split-rule)
888
889 (defun nnimap-split-find-inbox (server)
890   (if (listp nnimap-split-inbox)
891       nnimap-split-inbox
892     (list nnimap-split-inbox)))
893
894 (defun nnimap-split-articles (&optional group server)
895   (when (nnimap-possibly-change-server server)
896     (with-current-buffer nnimap-server-buffer
897       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
898         ;; iterate over inboxes
899         (while (and (setq inbox (pop inboxes))
900                     (nnimap-possibly-change-group inbox));; SELECT
901           ;; find split rule for this server / inbox
902           (when (setq rule (nnimap-split-find-rule server inbox))
903             ;; iterate over articles
904             (dolist (article (imap-search nnimap-split-predicate))
905               (when (nnimap-request-head article)
906                 ;; copy article to right group(s)
907                 (setq removeorig nil)
908                 (dolist (to-group (nnimap-split-to-groups rule))
909                   (if (imap-message-copy (number-to-string article)
910                                          to-group nil 'nocopyuid)
911                       (progn
912                         (message "IMAP split moved %s:%s:%d to %s" server inbox
913                                  article to-group)
914                         (setq removeorig t)
915                         ;; Add the group-art list to the history list.
916                         (push (list (cons to-group 0)) nnmail-split-history))
917                     (message "IMAP split failed to move %s:%s:%d to %s" server
918                              inbox article to-group)))
919                 ;; remove article if it was successfully copied somewhere
920                 (and removeorig
921                      (imap-message-flags-add (format "%d" article)
922                                              "\\Seen \\Deleted")))))
923           (when (imap-mailbox-select inbox);; just in case
924             ;; todo: UID EXPUNGE (if available) to remove splitted articles
925             (imap-mailbox-expunge)
926             (imap-mailbox-close)))
927         t))))
928
929 (deffoo nnimap-request-scan (&optional group server)
930   (nnimap-split-articles group server))
931
932 (deffoo nnimap-request-newgroups (date &optional server)
933   (when (nnimap-possibly-change-server server)
934     (with-current-buffer nntp-server-buffer
935       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
936                     (if (> (length server) 0) " on " "") server)
937       (erase-buffer)
938       (dolist (pattern (nnimap-pattern-to-list-arguments
939                         nnimap-list-pattern))
940         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil 
941                                         nnimap-server-buffer))
942           (or (member-if (lambda (mailbox)
943                            (string= (downcase mailbox) "\\noselect"))
944                          (imap-mailbox-get 'list-flags mbx
945                                            nnimap-server-buffer))
946               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
947                 (when info
948                  (insert (format "\"%s\" %d %d y\n"
949                                  mbx (or (nth 2 info) 0)
950                                  (max 1 (or (nth 1 info) 1)))))))))
951       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
952                     (if (> (length server) 0) " on " "") server))
953     t))
954       
955 (deffoo nnimap-request-create-group (group &optional server args)
956   (when (nnimap-possibly-change-server server)
957     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
958         (imap-mailbox-create group nnimap-server-buffer))))
959
960 (defun nnimap-time-substract (time1 time2)
961   "Return TIME for TIME1 - TIME2."
962   (let* ((ms (- (car time1) (car time2)))
963          (ls (- (nth 1 time1) (nth 1 time2))))
964     (if (< ls 0)
965         (list (- ms 1) (+ (expt 2 16) ls))
966       (list ms ls))))
967
968 (defun nnimap-date-days-ago (daysago)
969   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
970   (let ((date (format-time-string "%d-%b-%Y"
971                                   (nnimap-time-substract
972                                    (current-time)
973                                    (days-to-time daysago)))))
974     (if (eq ?0 (string-to-char date))
975         (substring date 1)
976       date)))
977
978 (defun nnimap-request-expire-articles-progress ()
979   (gnus-message 5 "nnimap: Marking article %d for deletion..."
980                 imap-current-message))
981
982 ;; Notice that we don't actually delete anything, we just mark them deleted.
983 (deffoo nnimap-request-expire-articles (articles group &optional server force)
984   (let ((artseq (gnus-compress-sequence articles)))
985     (when (and artseq (nnimap-possibly-change-group group server))
986       (with-current-buffer nnimap-server-buffer
987         (if force
988             (and (imap-message-flags-add
989                   (nnimap-range-to-string artseq) "\\Deleted")
990                  (setq articles nil))
991           (let ((days (or (and nnmail-expiry-wait-function
992                                (funcall nnmail-expiry-wait-function group))
993                           nnmail-expiry-wait)))
994             (cond ((eq days 'immediate)
995                    (and (imap-message-flags-add
996                          (nnimap-range-to-string artseq) "\\Deleted")
997                         (setq articles nil)))
998                   ((numberp days)
999                    (let ((oldarts (imap-search
1000                                    (format "UID %s NOT SINCE %s"
1001                                            (nnimap-range-to-string artseq)
1002                                            (nnimap-date-days-ago days))))
1003                          (imap-fetch-data-hook
1004                           '(nnimap-request-expire-articles-progress)))
1005                      (and oldarts
1006                           (imap-message-flags-add
1007                            (nnimap-range-to-string
1008                             (gnus-compress-sequence oldarts))
1009                            "\\Deleted")
1010                           (setq articles (gnus-set-difference
1011                                           articles oldarts)))))))))))
1012   ;; return articles not deleted
1013   articles)
1014
1015 (deffoo nnimap-request-move-article (article group server
1016                                              accept-form &optional last)
1017   (when (nnimap-possibly-change-server server)
1018     (save-excursion
1019       (let ((buf (get-buffer-create " *nnimap move*"))
1020             (nnimap-current-move-article article)
1021             (nnimap-current-move-group group)
1022             (nnimap-current-move-server nnimap-current-server)
1023             result)
1024         (and (nnimap-request-article article group server)
1025              (save-excursion
1026                (set-buffer buf)
1027                (buffer-disable-undo (current-buffer))
1028                (insert-buffer-substring nntp-server-buffer)
1029                (setq result (eval accept-form))
1030                (kill-buffer buf)
1031                result)
1032              (nnimap-request-expire-articles (list article) group server t))
1033         result))))
1034   
1035 (deffoo nnimap-request-accept-article (group &optional server last)
1036   (when (nnimap-possibly-change-server server)
1037     (let (uid)
1038       (if (setq uid
1039                 (if (string= nnimap-current-server nnimap-current-move-server)
1040                     ;; moving article within same server, speed it up...
1041                     (and (nnimap-possibly-change-group
1042                           nnimap-current-move-group)
1043                          (imap-message-copy (number-to-string
1044                                              nnimap-current-move-article)
1045                                             group 'dontcreate nil
1046                                             nnimap-server-buffer))
1047                   ;; turn into rfc822 format (\r\n eol's)
1048                   (with-current-buffer (current-buffer)
1049                     (goto-char (point-min))
1050                     (while (search-forward "\n" nil t)
1051                       (replace-match "\r\n")))
1052                   ;; next line for Cyrus server bug
1053                   (imap-mailbox-unselect nnimap-server-buffer)
1054                   (imap-message-append group (current-buffer) nil nil
1055                                        nnimap-server-buffer)))
1056           (cons group (nth 1 uid))
1057         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1058
1059 (deffoo nnimap-request-delete-group (group force &optional server)
1060   (when (nnimap-possibly-change-server server)
1061     (with-current-buffer nnimap-server-buffer
1062       (if force
1063           (or (null (imap-mailbox-status group 'uidvalidity))
1064               (imap-mailbox-delete group))
1065         ;; UNSUBSCRIBE?
1066         t))))
1067
1068 (deffoo nnimap-request-rename-group (group new-name &optional server)
1069   (when (nnimap-possibly-change-server server)
1070     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1071
1072 (defun nnimap-expunge (mailbox server)
1073   (when (nnimap-possibly-change-group mailbox server)
1074     (imap-mailbox-expunge nnimap-server-buffer)))
1075
1076 (defun nnimap-acl-get (mailbox server)
1077   (when (nnimap-possibly-change-server server)
1078     (imap-mailbox-acl-get mailbox nnimap-server-buffer)))
1079
1080 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1081   (when (nnimap-possibly-change-server (cadr method))
1082     (unless (imap-capability 'ACL nnimap-server-buffer)
1083       (error "Your server does not support ACL editing"))
1084     (with-current-buffer nnimap-server-buffer
1085       ;; delete all removed identifiers
1086       (mapcar (lambda (old-acl)
1087                 (unless (assoc (car old-acl) new-acls)
1088                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1089                       (error "Can't delete ACL for %s" (car old-acl)))))
1090               old-acls)
1091       ;; set all changed acl's
1092       (mapcar (lambda (new-acl)
1093                 (let ((new-rights (cdr new-acl))
1094                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1095                   (unless (and old-rights new-rights
1096                                (string= old-rights new-rights))
1097                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1098                         (error "Can't set ACL for %s to %s" (car new-acl)
1099                                new-rights)))))
1100               new-acls)
1101       t)))
1102
1103 \f
1104 ;;; Internal functions
1105
1106 ;;
1107 ;; This is confusing.
1108 ;;
1109 ;; mark      => read, tick, draft, reply etc
1110 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1111 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1112 ;;
1113 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1114 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1115 ;;
1116
1117 (defconst nnimap-mark-to-predicate-alist
1118   (mapcar
1119    (lambda (pair)                       ; cdr is the mark
1120      (or (assoc (cdr pair)
1121                 '((read . "SEEN")
1122                   (tick . "FLAGGED")
1123                   (draft . "DRAFT")
1124                   (reply . "ANSWERED")))
1125          (cons (cdr pair)
1126                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1127    (cons '(read . read) gnus-article-mark-lists)))
1128
1129 (defun nnimap-mark-to-predicate (pred)
1130   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1131 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1132 to be used within a IMAP SEARCH query."
1133   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1134
1135 (defconst nnimap-mark-to-flag-alist
1136   (mapcar
1137    (lambda (pair)
1138      (or (assoc (cdr pair)
1139                 '((read . "\\Seen")
1140                   (tick . "\\Flagged")
1141                   (draft . "\\Draft")
1142                   (reply . "\\Answered")))
1143          (cons (cdr pair)
1144                (format "gnus-%s" (symbol-name (cdr pair))))))
1145    (cons '(read . read) gnus-article-mark-lists)))
1146
1147 (defun nnimap-mark-to-flag-1 (preds)
1148   (if (and (not (null preds)) (listp preds))
1149       (cons (nnimap-mark-to-flag (car preds))
1150             (nnimap-mark-to-flag (cdr preds)))
1151     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1152
1153 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1154   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1155 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1156 be used in a STORE FLAGS command."
1157   (let ((result (nnimap-mark-to-flag-1 preds)))
1158     (setq result (if (and (or make-string always-list)
1159                           (not (listp result)))
1160                      (list result)
1161                    result))
1162     (if make-string
1163         (mapconcat (lambda (flag)
1164                      (if (listp flag)
1165                          (mapconcat 'identity flag " ")
1166                        flag))
1167                    result " ")
1168       result)))
1169
1170 (defun nnimap-mark-permanent-p (mark &optional group)
1171   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1172   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1173
1174 (defun nnimap-remassoc (key alist)
1175   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1176 The modified LIST is returned.  If the first member
1177 of LIST has a car that is `equal' to KEY, there is no way to remove it
1178 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1179 sure of changing the value of `foo'."
1180   (when alist
1181     (if (equal key (caar alist))
1182         (cdr alist)
1183       (setcdr alist (nnimap-remassoc key (cdr alist)))
1184       alist)))
1185   
1186 (defun nnimap-update-alist-soft (key value alist)
1187   (if value
1188       (cons (cons key value) (nnimap-remassoc key alist))
1189     (nnimap-remassoc key alist)))
1190
1191 (defun nnimap-range-to-string (range)
1192   (mapconcat
1193    (lambda (item)
1194      (if (consp item)
1195          (format "%d:%d"
1196                  (car item) (cdr item))
1197        (format "%d" item)))
1198    (if (and (listp range) (not (listp (cdr range))))
1199        (list range);; make (1 . 2) into ((1 . 2))
1200      range)
1201    ","))
1202
1203 (when nnimap-debug
1204   (require 'trace)
1205   (buffer-disable-undo (get-buffer-create nnimap-debug))
1206   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1207         '(
1208           nnimap-possibly-change-server
1209           nnimap-verify-uidvalidity
1210           nnimap-find-minmax-uid
1211           nnimap-possibly-change-group
1212           ;;nnimap-replace-whitespace
1213           nnimap-retrieve-headers-progress
1214           nnimap-retrieve-which-headers
1215           nnimap-group-overview-filename
1216           nnimap-retrieve-headers-from-file
1217           nnimap-retrieve-headers-from-server
1218           nnimap-retrieve-headers
1219           nnimap-open-connection
1220           nnimap-open-server
1221           nnimap-server-opened
1222           nnimap-close-server
1223           nnimap-request-close
1224           nnimap-status-message
1225           ;;nnimap-demule
1226           nnimap-request-article-part
1227           nnimap-request-article
1228           nnimap-request-head
1229           nnimap-request-body
1230           nnimap-request-group
1231           nnimap-close-group
1232           nnimap-pattern-to-list-arguments
1233           nnimap-request-list
1234           nnimap-request-post
1235           nnimap-retrieve-groups
1236           nnimap-request-update-info-internal
1237           nnimap-request-type
1238           nnimap-request-set-mark
1239           nnimap-split-to-groups
1240           nnimap-split-find-rule
1241           nnimap-split-find-inbox
1242           nnimap-split-articles
1243           nnimap-request-scan
1244           nnimap-request-newgroups
1245           nnimap-request-create-group
1246           nnimap-time-substract
1247           nnimap-date-days-ago
1248           nnimap-request-expire-articles-progress
1249           nnimap-request-expire-articles
1250           nnimap-request-move-article
1251           nnimap-request-accept-article
1252           nnimap-request-delete-group
1253           nnimap-request-rename-group
1254           gnus-group-nnimap-expunge
1255           gnus-group-nnimap-edit-acl
1256           gnus-group-nnimap-edit-acl-done
1257           nnimap-group-mode-hook
1258           nnimap-mark-to-predicate
1259           nnimap-mark-to-flag-1
1260           nnimap-mark-to-flag
1261           nnimap-mark-permanent-p
1262           nnimap-remassoc
1263           nnimap-update-alist-soft
1264           nnimap-range-to-string
1265           )))
1266
1267 (provide 'nnimap)
1268
1269 ;;; nnimap.el ends here