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