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