* nnimap.el (nnimap-need-unselect-to-notice-new-mail)
[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 (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 nil
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 (unless nnimap-dont-close
863                   (imap-mailbox-expunge nnimap-close-asynchronous)
864                   (imap-mailbox-close nnimap-close-asynchronous)))
865         (ask (if (and (imap-search "DELETED")
866                       (gnus-y-or-n-p (format "Expunge articles in group `%s'? "
867                                              imap-current-mailbox)))
868                  (unless nnimap-dont-close
869                    (imap-mailbox-expunge nnimap-close-asynchronous)
870                    (imap-mailbox-close nnimap-close-asynchronous))
871                (imap-mailbox-unselect)))
872         (t (imap-mailbox-unselect)))
873       (not imap-current-mailbox))))
874
875 (defun nnimap-pattern-to-list-arguments (pattern)
876   (mapcar (lambda (p)
877             (cons (car-safe p) (or (cdr-safe p) p)))
878           (if (and (listp pattern)
879                    (listp (cdr pattern)))
880               pattern
881             (list pattern))))
882
883 (deffoo nnimap-request-list (&optional server)
884   (when (nnimap-possibly-change-server server)
885     (with-current-buffer nntp-server-buffer
886       (erase-buffer))
887     (gnus-message 5 "nnimap: Generating active list%s..."
888                   (if (> (length server) 0) (concat " for " server) ""))
889     (nnimap-before-find-minmax-bugworkaround)
890     (with-current-buffer nnimap-server-buffer
891       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
892         (dolist (mbx (funcall nnimap-request-list-method
893                               (cdr pattern) (car pattern)))
894           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
895               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
896                 (when info
897                   (with-current-buffer nntp-server-buffer
898                     (insert (format "\"%s\" %d %d y\n"
899                                     mbx (or (nth 2 info) 0)
900                                     (max 1 (or (nth 1 info) 1)))))))))))
901     (gnus-message 5 "nnimap: Generating active list%s...done"
902                   (if (> (length server) 0) (concat " for " server) ""))
903     t))
904
905 (deffoo nnimap-request-post (&optional server)
906   (let ((success t))
907     (dolist (mbx (message-unquote-tokens
908                   (message-tokenize-header
909                    (message-fetch-field "Newsgroups") ", ")) success)
910       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
911         (or (gnus-active to-newsgroup)
912             (gnus-activate-group to-newsgroup)
913             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
914                                        to-newsgroup))
915                 (or (and (gnus-request-create-group
916                           to-newsgroup gnus-command-method)
917                          (gnus-activate-group to-newsgroup nil nil
918                                               gnus-command-method))
919                     (error "Couldn't create group %s" to-newsgroup)))
920             (error "No such group: %s" to-newsgroup))
921         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
922           (setq success nil))))))
923
924 ;; Optional backend functions
925
926 (deffoo nnimap-retrieve-groups (groups &optional server)
927   (when (nnimap-possibly-change-server server)
928     (gnus-message 5 "nnimap: Checking mailboxes...")
929     (with-current-buffer nntp-server-buffer
930       (erase-buffer)
931       (nnimap-before-find-minmax-bugworkaround)
932       (dolist (group groups)
933         (gnus-message 7 "nnimap: Checking mailbox %s" group)
934         (or (member "\\NoSelect"
935                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
936             (let ((info (nnimap-find-minmax-uid group 'examine)))
937               (when (> (or (imap-mailbox-get 'recent group 
938                                              nnimap-server-buffer) 0)
939                        0)
940                 (push (list (cons group 0)) nnmail-split-history))
941               (insert (format "\"%s\" %d %d y\n" group
942                               (or (nth 2 info) 0)
943                               (max 1 (or (nth 1 info) 1))))))))
944     (gnus-message 5 "nnimap: Checking mailboxes...done")
945     'active))
946
947 (deffoo nnimap-request-update-info-internal (group info &optional server)
948   (when (nnimap-possibly-change-group group server)
949     (when info ;; xxx what does this mean? should we create a info?
950       (with-current-buffer nnimap-server-buffer
951         (gnus-message 5 "nnimap: Updating info for %s..."
952                       (gnus-info-group info))
953
954         (when (nnimap-mark-permanent-p 'read)
955           (let (seen unseen)
956             ;; read info could contain articles marked unread by other
957             ;; imap clients!  we correct this
958             (setq seen (gnus-uncompress-range (gnus-info-read info))
959                   unseen (imap-search "UNSEEN UNDELETED")
960                   seen (gnus-set-difference seen unseen)
961                   ;; seen might lack articles marked as read by other
962                   ;; imap clients! we correct this
963                   seen (append seen (imap-search "SEEN"))
964                   ;; remove dupes
965                   seen (sort seen '<)
966                   seen (gnus-compress-sequence seen t)
967                   ;; we can't return '(1) since this isn't a "list of ranges",
968                   ;; and we can't return '((1)) since g-list-of-unread-articles
969                   ;; is buggy so we return '((1 . 1)).
970                   seen (if (and (integerp (car seen))
971                                 (null (cdr seen)))
972                            (list (cons (car seen) (car seen)))
973                          seen))
974             (gnus-info-set-read info seen)))
975
976         (mapcar (lambda (pred)
977                   (when (or (eq (cdr pred) 'recent)
978                             (and (nnimap-mark-permanent-p (cdr pred))
979                                  (member (nnimap-mark-to-flag (cdr pred))
980                                          (imap-mailbox-get 'flags))))
981                     (gnus-info-set-marks
982                      info
983                      (gnus-update-alist-soft
984                       (cdr pred)
985                       (gnus-compress-sequence
986                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
987                       (gnus-info-marks info))
988                      t)))
989                 gnus-article-mark-lists)
990
991         (when nnimap-importantize-dormant
992       ;; nnimap mark dormant article as ticked too (for other clients)
993           ;; so we remove that mark for gnus since we support dormant
994           (gnus-info-set-marks
995            info
996            (gnus-update-alist-soft
997             'tick
998             (gnus-remove-from-range
999              (cdr-safe (assoc 'tick (gnus-info-marks info)))
1000              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
1001             (gnus-info-marks info))
1002            t))
1003
1004         (gnus-message 5 "nnimap: Updating info for %s...done"
1005                       (gnus-info-group info))
1006
1007         info))))
1008
1009 (deffoo nnimap-request-type (group &optional article)
1010   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
1011       'news
1012     'mail))
1013
1014 (deffoo nnimap-request-set-mark (group actions &optional server)
1015   (when (nnimap-possibly-change-group group server)
1016     (with-current-buffer nnimap-server-buffer
1017       (let (action)
1018         (gnus-message 7 "nnimap: Setting marks in %s..." group)
1019         (while (setq action (pop actions))
1020           (let ((range (nth 0 action))
1021                 (what  (nth 1 action))
1022                 (cmdmarks (nth 2 action))
1023                 marks)
1024             ;; bookmark can't be stored (not list/range
1025             (setq cmdmarks (delq 'bookmark cmdmarks))
1026             ;; killed can't be stored (not list/range
1027             (setq cmdmarks (delq 'killed cmdmarks))
1028             ;; unsent are for nndraft groups only
1029             (setq cmdmarks (delq 'unsent cmdmarks))
1030             ;; cache flags are pointless on the server
1031             (setq cmdmarks (delq 'cache cmdmarks))
1032             ;; seen flags are local to each gnus
1033             (setq cmdmarks (delq 'seen cmdmarks))
1034             ;; recent marks can't be set
1035             (setq cmdmarks (delq 'recent cmdmarks))
1036             (when nnimap-importantize-dormant
1037               ;; flag dormant articles as ticked
1038               (if (memq 'dormant cmdmarks)
1039                   (setq cmdmarks (cons 'tick cmdmarks))))
1040             ;; remove stuff we are forbidden to store
1041             (mapcar (lambda (mark)
1042                       (if (imap-message-flag-permanent-p
1043                            (nnimap-mark-to-flag mark))
1044                           (setq marks (cons mark marks))))
1045                     cmdmarks)
1046             (when (and range marks)
1047               (cond ((eq what 'del)
1048                      (imap-message-flags-del
1049                       (imap-range-to-message-set range)
1050                       (nnimap-mark-to-flag marks nil t)))
1051                     ((eq what 'add)
1052                      (imap-message-flags-add
1053                       (imap-range-to-message-set range)
1054                       (nnimap-mark-to-flag marks nil t)))
1055                     ((eq what 'set)
1056                      (imap-message-flags-set
1057                       (imap-range-to-message-set range)
1058                       (nnimap-mark-to-flag marks nil t)))))))
1059         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
1060   nil)
1061
1062 (defun nnimap-split-fancy ()
1063   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
1064   (let ((nnmail-split-fancy nnimap-split-fancy))
1065     (nnmail-split-fancy)))
1066
1067 (defun nnimap-split-to-groups (rules)
1068   ;; tries to match all rules in nnimap-split-rule against content of
1069   ;; nntp-server-buffer, returns a list of groups that matched.
1070   (with-current-buffer nntp-server-buffer
1071     ;; Fold continuation lines.
1072     (goto-char (point-min))
1073     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1074       (replace-match " " t t))
1075     (if (functionp rules)
1076         (funcall rules)
1077       (let (to-groups regrepp)
1078         (catch 'split-done
1079           (dolist (rule rules to-groups)
1080             (let ((group (car rule))
1081                   (regexp (cadr rule)))
1082               (goto-char (point-min))
1083               (when (and (if (stringp regexp)
1084                              (progn
1085                                (setq regrepp (string-match "\\\\[0-9&]" group))
1086                                (re-search-forward regexp nil t))
1087                            (funcall regexp group))
1088                  ;; Don't enter the article into the same group twice.
1089                          (not (assoc group to-groups)))
1090                 (push (if regrepp
1091                           (nnmail-expand-newtext group)
1092                         group)
1093                       to-groups)
1094                 (or nnimap-split-crosspost
1095                     (throw 'split-done to-groups))))))))))
1096
1097 (defun nnimap-assoc-match (key alist)
1098   (let (element)
1099     (while (and alist (not element))
1100       (if (string-match (car (car alist)) key)
1101           (setq element (car alist)))
1102       (setq alist (cdr alist)))
1103     element))
1104
1105 (defun nnimap-split-find-rule (server inbox)
1106   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1107            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1108       ;; extended format
1109       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match
1110                                             server nnimap-split-rule))))
1111     nnimap-split-rule))
1112
1113 (defun nnimap-split-find-inbox (server)
1114   (if (listp nnimap-split-inbox)
1115       nnimap-split-inbox
1116     (list nnimap-split-inbox)))
1117
1118 (defun nnimap-split-articles (&optional group server)
1119   (when (nnimap-possibly-change-server server)
1120     (with-current-buffer nnimap-server-buffer
1121       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1122         ;; iterate over inboxes
1123         (while (and (setq inbox (pop inboxes))
1124                     (nnimap-possibly-change-group inbox)) ;; SELECT
1125           ;; find split rule for this server / inbox
1126           (when (setq rule (nnimap-split-find-rule server inbox))
1127             ;; iterate over articles
1128             (dolist (article (imap-search nnimap-split-predicate))
1129               (when (nnimap-request-head article)
1130                 ;; copy article to right group(s)
1131                 (setq removeorig nil)
1132                 (dolist (to-group (nnimap-split-to-groups rule))
1133                   (cond ((eq to-group 'junk)
1134                          (message "IMAP split removed %s:%s:%d" server inbox
1135                                   article)
1136                          (setq removeorig t))
1137                         ((imap-message-copy (number-to-string article)
1138                                             to-group nil 'nocopyuid)
1139                          (message "IMAP split moved %s:%s:%d to %s" server
1140                                   inbox article to-group)
1141                          (setq removeorig t)
1142                          ;; Add the group-art list to the history list.
1143                          (push (list (cons to-group 0)) nnmail-split-history))
1144                         (t
1145                          (message "IMAP split failed to move %s:%s:%d to %s"
1146                                   server inbox article to-group))))
1147                 ;; remove article if it was successfully copied somewhere
1148                 (and removeorig
1149                      (imap-message-flags-add (format "%d" article)
1150                                              "\\Seen \\Deleted")))))
1151           (when (imap-mailbox-select inbox) ;; just in case
1152             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1153             (imap-mailbox-expunge)
1154             (imap-mailbox-close)))
1155         t))))
1156
1157 (deffoo nnimap-request-scan (&optional group server)
1158   (nnimap-split-articles group server))
1159
1160 (deffoo nnimap-request-newgroups (date &optional server)
1161   (when (nnimap-possibly-change-server server)
1162     (with-current-buffer nntp-server-buffer
1163       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1164                     (if (> (length server) 0) " on " "") server)
1165       (erase-buffer)
1166       (nnimap-before-find-minmax-bugworkaround)
1167       (dolist (pattern (nnimap-pattern-to-list-arguments
1168                         nnimap-list-pattern))
1169         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil
1170                                         nnimap-server-buffer))
1171           (or (catch 'found
1172                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1173                                                    nnimap-server-buffer))
1174                   (if (string= (downcase mailbox) "\\noselect")
1175                       (throw 'found t)))
1176                 nil)
1177               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1178                 (when info
1179                   (insert (format "\"%s\" %d %d y\n"
1180                                   mbx (or (nth 2 info) 0)
1181                                   (max 1 (or (nth 1 info) 1)))))))))
1182       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1183                     (if (> (length server) 0) " on " "") server))
1184     t))
1185
1186 (deffoo nnimap-request-create-group (group &optional server args)
1187   (when (nnimap-possibly-change-server server)
1188     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1189         (imap-mailbox-create group nnimap-server-buffer))))
1190
1191 (defun nnimap-time-substract (time1 time2)
1192   "Return TIME for TIME1 - TIME2."
1193   (let* ((ms (- (car time1) (car time2)))
1194          (ls (- (nth 1 time1) (nth 1 time2))))
1195     (if (< ls 0)
1196         (list (- ms 1) (+ (expt 2 16) ls))
1197       (list ms ls))))
1198
1199 (defun nnimap-date-days-ago (daysago)
1200   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1201   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1202          (date (format-time-string
1203                 (format "%%d-%s-%%Y"
1204                         (capitalize (car (rassoc (nth 4 (decode-time time))
1205                                                  parse-time-months))))
1206                 time)))
1207     (if (eq ?0 (string-to-char date))
1208         (substring date 1)
1209       date)))
1210
1211 (defun nnimap-request-expire-articles-progress ()
1212   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1213                 imap-current-message))
1214
1215
1216 (defun nnimap-expiry-target (arts group server)
1217   (unless (eq nnmail-expiry-target 'delete)
1218     (with-temp-buffer
1219       (dolist (art (gnus-uncompress-sequence arts))
1220         (nnimap-request-article art group server  (current-buffer))
1221         ;; hints for optimization in `nnimap-request-accept-article'
1222         (let ((nnimap-current-move-article art)
1223               (nnimap-current-move-group group)
1224               (nnimap-current-move-server server))
1225           (nnmail-expiry-target-group nnmail-expiry-target group))))
1226     ;; It is not clear if `nnmail-expiry-target' somehow cause the
1227     ;; current group to be changed or not, so we make sure here.
1228     (nnimap-possibly-change-group group server)))
1229
1230 ;; Notice that we don't actually delete anything, we just mark them deleted.
1231 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1232   (let ((artseq (gnus-compress-sequence articles)))
1233     (when (and artseq (nnimap-possibly-change-group group server))
1234       (with-current-buffer nnimap-server-buffer
1235         (if force
1236             (progn
1237               (nnimap-expiry-target artseq group server)
1238               (when (imap-message-flags-add (imap-range-to-message-set artseq)
1239                                             "\\Deleted")
1240                 (setq articles nil)))
1241           (let ((days (or (and nnmail-expiry-wait-function
1242                                (funcall nnmail-expiry-wait-function group))
1243                           nnmail-expiry-wait)))
1244             (cond ((eq days 'immediate)
1245                    (nnimap-expiry-target artseq group server)
1246                    (when (imap-message-flags-add
1247                           (imap-range-to-message-set artseq) "\\Deleted")
1248                      (setq articles nil)))
1249                   ((numberp days)
1250                    (let ((oldarts (imap-search
1251                                    (format nnimap-expunge-search-string
1252                                            (imap-range-to-message-set artseq)
1253                                            (nnimap-date-days-ago days))))
1254                          (imap-fetch-data-hook
1255                           '(nnimap-request-expire-articles-progress)))
1256                      (nnimap-expiry-target oldarts group server)
1257                      (and oldarts
1258                           (imap-message-flags-add
1259                            (imap-range-to-message-set
1260                             (gnus-compress-sequence oldarts))
1261                            "\\Deleted")
1262                           (setq articles (gnus-set-difference
1263                                           articles oldarts)))))))))))
1264   ;; return articles not deleted
1265   articles)
1266
1267 (deffoo nnimap-request-move-article (article group server
1268                                              accept-form &optional last)
1269   (when (nnimap-possibly-change-server server)
1270     (save-excursion
1271       (let ((buf (get-buffer-create " *nnimap move*"))
1272             (nnimap-current-move-article article)
1273             (nnimap-current-move-group group)
1274             (nnimap-current-move-server nnimap-current-server)
1275             result)
1276         (and (nnimap-request-article article group server)
1277              (save-excursion
1278                (set-buffer buf)
1279                (buffer-disable-undo (current-buffer))
1280                (insert-buffer-substring nntp-server-buffer)
1281                (setq result (eval accept-form))
1282                (kill-buffer buf)
1283                result)
1284              (imap-message-flags-add
1285               (imap-range-to-message-set (list article))
1286               "\\Deleted" 'silent nnimap-server-buffer))
1287         result))))
1288
1289 (deffoo nnimap-request-accept-article (group &optional server last)
1290   (when (nnimap-possibly-change-server server)
1291     (let (uid)
1292       (if (setq uid
1293                 (if (string= nnimap-current-server nnimap-current-move-server)
1294                   ;; moving article within same server, speed it up...
1295                     (and (nnimap-possibly-change-group
1296                           nnimap-current-move-group)
1297                          (imap-message-copy (number-to-string
1298                                              nnimap-current-move-article)
1299                                             group 'dontcreate nil
1300                                             nnimap-server-buffer))
1301                   (with-current-buffer (current-buffer)
1302                     (goto-char (point-min))
1303                   ;; remove any 'From blabla' lines, some IMAP servers
1304                     ;; reject the entire message otherwise.
1305                     (when (looking-at "^From[^:]")
1306                       (kill-region (point) (progn (forward-line) (point))))
1307                     ;; turn into rfc822 format (\r\n eol's)
1308                     (while (search-forward "\n" nil t)
1309                       (replace-match "\r\n")))
1310                   ;; this 'or' is for Cyrus server bug
1311                   (or (null (imap-current-mailbox nnimap-server-buffer))
1312                       (imap-mailbox-unselect nnimap-server-buffer))
1313                   (imap-message-append group (current-buffer) nil nil
1314                                        nnimap-server-buffer)))
1315           (cons group (nth 1 uid))
1316         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1317
1318 (deffoo nnimap-request-delete-group (group force &optional server)
1319   (when (nnimap-possibly-change-server server)
1320     (with-current-buffer nnimap-server-buffer
1321       (if force
1322           (or (null (imap-mailbox-status group 'uidvalidity))
1323               (imap-mailbox-delete group))
1324         ;; UNSUBSCRIBE?
1325         t))))
1326
1327 (deffoo nnimap-request-rename-group (group new-name &optional server)
1328   (when (nnimap-possibly-change-server server)
1329     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1330
1331 (defun nnimap-expunge (mailbox server)
1332   (when (nnimap-possibly-change-group mailbox server)
1333     (imap-mailbox-expunge nil nnimap-server-buffer)))
1334
1335 (defun nnimap-acl-get (mailbox server)
1336   (when (nnimap-possibly-change-server server)
1337     (and (imap-capability 'ACL nnimap-server-buffer)
1338          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1339
1340 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1341   (when (nnimap-possibly-change-server (cadr method))
1342     (unless (imap-capability 'ACL nnimap-server-buffer)
1343       (error "Your server does not support ACL editing"))
1344     (with-current-buffer nnimap-server-buffer
1345       ;; delete all removed identifiers
1346       (mapcar (lambda (old-acl)
1347                 (unless (assoc (car old-acl) new-acls)
1348                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1349                       (error "Can't delete ACL for %s" (car old-acl)))))
1350               old-acls)
1351       ;; set all changed acl's
1352       (mapcar (lambda (new-acl)
1353                 (let ((new-rights (cdr new-acl))
1354                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1355                   (unless (and old-rights new-rights
1356                                (string= old-rights new-rights))
1357                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1358                         (error "Can't set ACL for %s to %s" (car new-acl)
1359                                new-rights)))))
1360               new-acls)
1361       t)))
1362
1363 \f
1364 ;;; Internal functions
1365
1366 ;;
1367 ;; This is confusing.
1368 ;;
1369 ;; mark      => read, tick, draft, reply etc
1370 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1371 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1372 ;;
1373 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1374 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1375 ;;
1376
1377 (defconst nnimap-mark-to-predicate-alist
1378   (mapcar
1379    (lambda (pair)                       ; cdr is the mark
1380      (or (assoc (cdr pair)
1381                 '((read . "SEEN")
1382                   (tick . "FLAGGED")
1383                   (draft . "DRAFT")
1384                   (recent . "RECENT")
1385                   (reply . "ANSWERED")))
1386          (cons (cdr pair)
1387                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1388    (cons '(read . read) gnus-article-mark-lists)))
1389
1390 (defun nnimap-mark-to-predicate (pred)
1391   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1392 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1393 to be used within a IMAP SEARCH query."
1394   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1395
1396 (defconst nnimap-mark-to-flag-alist
1397   (mapcar
1398    (lambda (pair)
1399      (or (assoc (cdr pair)
1400                 '((read . "\\Seen")
1401                   (tick . "\\Flagged")
1402                   (draft . "\\Draft")
1403                   (recent . "\\Recent")
1404                   (reply . "\\Answered")))
1405          (cons (cdr pair)
1406                (format "gnus-%s" (symbol-name (cdr pair))))))
1407    (cons '(read . read) gnus-article-mark-lists)))
1408
1409 (defun nnimap-mark-to-flag-1 (preds)
1410   (if (and (not (null preds)) (listp preds))
1411       (cons (nnimap-mark-to-flag (car preds))
1412             (nnimap-mark-to-flag (cdr preds)))
1413     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1414
1415 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1416   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1417 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1418 be used in a STORE FLAGS command."
1419   (let ((result (nnimap-mark-to-flag-1 preds)))
1420     (setq result (if (and (or make-string always-list)
1421                           (not (listp result)))
1422                      (list result)
1423                    result))
1424     (if make-string
1425         (mapconcat (lambda (flag)
1426                      (if (listp flag)
1427                          (mapconcat 'identity flag " ")
1428                        flag))
1429                    result " ")
1430       result)))
1431
1432 (defun nnimap-mark-permanent-p (mark &optional group)
1433   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1434   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1435
1436 (when nnimap-debug
1437   (require 'trace)
1438   (buffer-disable-undo (get-buffer-create nnimap-debug))
1439   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1440           '(
1441             nnimap-possibly-change-server
1442             nnimap-verify-uidvalidity
1443             nnimap-find-minmax-uid
1444             nnimap-before-find-minmax-bugworkaround
1445             nnimap-possibly-change-group
1446             ;;nnimap-replace-whitespace
1447             nnimap-retrieve-headers-progress
1448             nnimap-retrieve-which-headers
1449             nnimap-group-overview-filename
1450             nnimap-retrieve-headers-from-file
1451             nnimap-retrieve-headers-from-server
1452             nnimap-retrieve-headers
1453             nnimap-open-connection
1454             nnimap-open-server
1455             nnimap-server-opened
1456             nnimap-close-server
1457             nnimap-request-close
1458             nnimap-status-message
1459             ;;nnimap-demule
1460             nnimap-request-article-part
1461             nnimap-request-article
1462             nnimap-request-head
1463             nnimap-request-body
1464             nnimap-request-group
1465             nnimap-close-group
1466             nnimap-pattern-to-list-arguments
1467             nnimap-request-list
1468             nnimap-request-post
1469             nnimap-retrieve-groups
1470             nnimap-request-update-info-internal
1471             nnimap-request-type
1472             nnimap-request-set-mark
1473             nnimap-split-to-groups
1474             nnimap-split-find-rule
1475             nnimap-split-find-inbox
1476             nnimap-split-articles
1477             nnimap-request-scan
1478             nnimap-request-newgroups
1479             nnimap-request-create-group
1480             nnimap-time-substract
1481             nnimap-date-days-ago
1482             nnimap-request-expire-articles-progress
1483             nnimap-request-expire-articles
1484             nnimap-request-move-article
1485             nnimap-request-accept-article
1486             nnimap-request-delete-group
1487             nnimap-request-rename-group
1488             gnus-group-nnimap-expunge
1489             gnus-group-nnimap-edit-acl
1490             gnus-group-nnimap-edit-acl-done
1491             nnimap-group-mode-hook
1492             nnimap-mark-to-predicate
1493             nnimap-mark-to-flag-1
1494             nnimap-mark-to-flag
1495             nnimap-mark-permanent-p
1496             )))
1497
1498 (provide 'nnimap)
1499
1500 ;;; nnimap.el ends here