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