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