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