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