Bind RET and TAB on images for better UX.
[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 "1:*" "UID" nil 'nouidfetch)
592             (imap-message-map
593              (lambda (uid Uid)
594                (setq minuid (if minuid (min minuid uid) uid)
595                      maxuid (if maxuid (max maxuid uid) uid)))
596              'UID))
597           (list (imap-mailbox-get 'exists) minuid maxuid))))))
598
599 (defun nnimap-possibly-change-group (group &optional server)
600   "Make GROUP the current group, and SERVER the current server."
601   (when (nnimap-possibly-change-server server)
602     (let ((decoded-group (nnimap-decode-group-name group)))
603       (with-current-buffer nnimap-server-buffer
604         (if (or (null group) (imap-current-mailbox-p decoded-group))
605             imap-current-mailbox        ; Note: utf-7 encoded.
606           (if (imap-mailbox-select decoded-group)
607               (if (or (nnimap-verify-uidvalidity
608                        group (or server nnimap-current-server))
609                       (zerop (imap-mailbox-get 'exists decoded-group))
610                       t ;; for OGnus to see if ignoring uidvalidity
611                       ;; changes has any bad effects.
612                       (yes-or-no-p
613                        (format
614                         "nnimap: Group %s is not uidvalid.  Continue? "
615                         decoded-group)))
616                   imap-current-mailbox  ; Note: utf-7 encoded.
617                 (imap-mailbox-unselect)
618                 (error "nnimap: Group %s is not uid-valid" decoded-group))
619             (nnheader-report 'nnimap (imap-error-text))))))))
620
621 (defun nnimap-replace-whitespace (string)
622   "Return STRING with all whitespace replaced with space."
623   (when string
624     (while (string-match "[\r\n\t]+" string)
625       (setq string (replace-match " " t t string)))
626     string))
627
628 ;; Required backend functions
629
630 (defun nnimap-retrieve-headers-progress ()
631   "Hook to insert NOV line for current article into `nntp-server-buffer'."
632   (and (numberp nnmail-large-newsgroup)
633        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
634        (> nnimap-length nnmail-large-newsgroup)
635        (nnheader-message 6 "nnimap: Retrieving headers... %c"
636                          (nth (/ (% nnimap-counter
637                                     (* (length nnimap-progress-chars)
638                                        nnimap-progress-how-often))
639                                  nnimap-progress-how-often)
640                               nnimap-progress-chars)))
641   (with-current-buffer nntp-server-buffer
642     (let (headers lines chars uid mbx)
643       (with-current-buffer nnimap-server-buffer
644         (setq uid imap-current-message
645               mbx (nnimap-encode-group-name (imap-current-mailbox))
646               headers (if (imap-capability 'IMAP4rev1)
647                           ;; xxx don't just use car? alist doesn't contain
648                           ;; anything else now, but it might...
649                           (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
650                         (imap-message-get uid 'RFC822.HEADER))
651               lines (imap-body-lines (imap-message-body imap-current-message))
652               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
653       (nnheader-insert-nov
654        ;; At this stage, we only have bytes, so let's use unibyte buffers
655        ;; to make it more clear.
656        (mm-with-unibyte-buffer
657          (buffer-disable-undo)
658          ;; headers can be nil if article is write-only
659          (when headers (insert headers))
660          (let ((head (nnheader-parse-naked-head uid)))
661            (mail-header-set-number head uid)
662            (mail-header-set-chars head chars)
663            (mail-header-set-lines head lines)
664            (mail-header-set-xref
665             head (format "%s %s:%d" (system-name) mbx uid))
666            head))))))
667
668 (defun nnimap-retrieve-which-headers (articles fetch-old)
669   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
670   (with-current-buffer nnimap-server-buffer
671     (if (numberp (car-safe articles))
672         (imap-search
673          (concat "UID "
674                  (imap-range-to-message-set
675                   (gnus-compress-sequence
676                    (append (gnus-uncompress-sequence
677                             (and fetch-old
678                                  (cons (if (numberp fetch-old)
679                                            (max 1 (- (car articles) fetch-old))
680                                          1)
681                                        (1- (car articles)))))
682                            articles)))))
683       (mapcar (lambda (msgid)
684                 (imap-search
685                  (format "HEADER Message-Id \"%s\"" msgid)))
686               articles))))
687
688 (defun nnimap-group-overview-filename (group server)
689   "Make file name for GROUP on SERVER."
690   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
691          (uidvalidity (gnus-group-get-parameter
692                        (nnimap-group-prefixed-name group server)
693                        'uidvalidity))
694          (name (nnheader-translate-file-chars
695                 (concat nnimap-nov-file-name
696                         (if (equal server "")
697                             "unnamed"
698                           server) "." group nnimap-nov-file-name-suffix) t))
699          (nameuid (nnheader-translate-file-chars
700                    (concat nnimap-nov-file-name
701                            (if (equal server "")
702                                "unnamed"
703                              server) "." group "." uidvalidity
704                            nnimap-nov-file-name-suffix) t))
705          (oldfile (if (or nnmail-use-long-file-names
706                           (file-exists-p (expand-file-name name dir)))
707                       (expand-file-name name dir)
708                     (expand-file-name
709                      (mm-encode-coding-string
710                       (nnheader-replace-chars-in-string name ?. ?/)
711                       nnmail-pathname-coding-system)
712                      dir)))
713          (newfile (if (or nnmail-use-long-file-names
714                           (file-exists-p (expand-file-name nameuid dir)))
715                       (expand-file-name nameuid dir)
716                     (expand-file-name
717                      (mm-encode-coding-string
718                       (nnheader-replace-chars-in-string nameuid ?. ?/)
719                       nnmail-pathname-coding-system)
720                      dir))))
721     (when (and (file-exists-p oldfile) (not (file-exists-p newfile)))
722       (message "nnimap: Upgrading novcache filename...")
723       (sit-for 1)
724       (gnus-make-directory (file-name-directory newfile))
725       (unless (ignore-errors (rename-file oldfile newfile) t)
726         (if (ignore-errors (copy-file oldfile newfile) t)
727             (delete-file oldfile)
728           (error "Can't rename `%s' to `%s'" oldfile newfile))))
729     newfile))
730
731 (defun nnimap-retrieve-headers-from-file (group server)
732   (with-current-buffer nntp-server-buffer
733     (let ((nov (nnimap-group-overview-filename group server)))
734       (when (file-exists-p nov)
735         (mm-insert-file-contents nov)
736         (set-buffer-modified-p nil)
737         (let ((min (ignore-errors (goto-char (point-min))
738                                   (read (current-buffer))))
739               (max (ignore-errors (goto-char (point-max))
740                                   (forward-line -1)
741                                   (read (current-buffer)))))
742           (if (and (numberp min) (numberp max))
743               (cons min max)
744             ;; junk, remove it, it's saved later
745             (erase-buffer)
746             nil))))))
747
748 (defun nnimap-retrieve-headers-from-server (articles group server)
749   (with-current-buffer nnimap-server-buffer
750     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
751           (nnimap-length (gnus-range-length articles))
752           (nnimap-counter 0))
753       (imap-fetch (imap-range-to-message-set articles)
754                   (concat "(UID RFC822.SIZE BODY "
755                           (let ((headers
756                                  (append '(Subject From Date Message-Id
757                                                    References In-Reply-To Xref)
758                                          (copy-sequence
759                                           nnmail-extra-headers))))
760                             (if (imap-capability 'IMAP4rev1)
761                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
762                               (format "RFC822.HEADER.LINES %s)" headers)))))
763       (with-current-buffer nntp-server-buffer
764         (sort-numeric-fields 1 (point-min) (point-max)))
765       (and (numberp nnmail-large-newsgroup)
766            (> nnimap-length nnmail-large-newsgroup)
767            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
768
769 (defun nnimap-dont-use-nov-p (group server)
770   (or gnus-nov-is-evil nnimap-nov-is-evil
771       (unless (and (gnus-make-directory
772                     (file-name-directory
773                      (nnimap-group-overview-filename group server)))
774                    (file-writable-p
775                     (nnimap-group-overview-filename group server)))
776         (message "nnimap: Nov cache not writable, %s"
777                  (nnimap-group-overview-filename group server)))))
778
779 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
780   (when (nnimap-possibly-change-group group server)
781     (with-current-buffer nntp-server-buffer
782       (erase-buffer)
783       (if (nnimap-dont-use-nov-p group server)
784           (nnimap-retrieve-headers-from-server
785            (gnus-compress-sequence articles) group server)
786         (let (uids cached low high)
787           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
788                       low (car uids)
789                       high (car (last uids)))
790             (if (setq cached (nnimap-retrieve-headers-from-file group server))
791                 (progn
792                   ;; fetch articles with uids before cache block
793                   (when (< low (car cached))
794                     (goto-char (point-min))
795                     (nnimap-retrieve-headers-from-server
796                      (cons low (1- (car cached))) group server))
797                   ;; fetch articles with uids after cache block
798                   (when (> high (cdr cached))
799                     (goto-char (point-max))
800                     (nnimap-retrieve-headers-from-server
801                      (cons (1+ (cdr cached)) high) group server))
802                   (when nnimap-prune-cache
803                     ;; remove nov's for articles which has expired on server
804                     (goto-char (point-min))
805                     (dolist (uid (gnus-set-difference articles uids))
806                       (when (re-search-forward (format "^%d\t" uid) nil t)
807                         (gnus-delete-line)))))
808               ;; nothing cached, fetch whole range from server
809               (nnimap-retrieve-headers-from-server
810                (cons low high) group server))
811             (when (buffer-modified-p)
812               (nnmail-write-region
813                (point-min) (point-max)
814                (nnimap-group-overview-filename group server) nil 'nomesg))
815             (nnheader-nov-delete-outside-range low high))))
816       'nov)))
817
818 (declare-function netrc-parse "netrc" (file))
819 (declare-function netrc-machine-user-or-password "netrc"
820                   (mode authinfo-file-or-list machines ports defaults))
821
822 (defun nnimap-open-connection (server)
823   ;; Note: `nnimap-open-server' that calls this function binds
824   ;; `imap-logout-timeout' to `nnimap-logout-timeout'.
825   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
826                       nnimap-authenticator nnimap-server-buffer))
827       (nnheader-report 'nnimap "Can't open connection to server %s" server)
828     (require 'netrc)
829     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
830                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
831       (imap-close nnimap-server-buffer)
832       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
833     (let* ((list (progn (gnus-message 7 "Parsing authinfo file `%s'."
834                                       nnimap-authinfo-file)
835                         (netrc-parse nnimap-authinfo-file)))
836            (port (if nnimap-server-port
837                      (int-to-string nnimap-server-port)
838                    "imap"))
839            (auth-info
840             (auth-source-user-or-password '("login" "password") server port))
841            (auth-user (nth 0 auth-info))
842            (auth-passwd (nth 1 auth-info))
843            (user (or
844                   auth-user ; this is preferred to netrc-*
845                   (netrc-machine-user-or-password
846                    "login"
847                    list
848                    (list server
849                          (or nnimap-server-address
850                              nnimap-address))
851                    (list port)
852                    (list "imap" "imaps" "143" "993"))))
853            (passwd (or
854                     auth-passwd ; this is preferred to netrc-*
855                     (netrc-machine-user-or-password
856                      "password"
857                      list
858                      (list server
859                            (or nnimap-server-address
860                                nnimap-address))
861                      (list port)
862                      (list "imap" "imaps" "143" "993")))))
863       (if (imap-authenticate user passwd nnimap-server-buffer)
864           (prog2
865               (setq nnimap-server-buffer-alist
866                     (nnimap-remove-server-from-buffer-alist
867                      server
868                      nnimap-server-buffer-alist))
869               (push (list server nnimap-server-buffer)
870                     nnimap-server-buffer-alist)
871             (imap-id nnimap-id nnimap-server-buffer)
872             (nnimap-possibly-change-server server))
873         (imap-close nnimap-server-buffer)
874         (kill-buffer nnimap-server-buffer)
875         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
876
877 (deffoo nnimap-open-server (server &optional defs)
878   (nnheader-init-server-buffer)
879   (if (nnimap-server-opened server)
880       t
881     (unless (assq 'nnimap-server-buffer defs)
882       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
883     ;; translate `nnimap-server-address' to `nnimap-address' in defs
884     ;; for people that configured nnimap with a very old version
885     (unless (assq 'nnimap-address defs)
886       (if (assq 'nnimap-server-address defs)
887           (push (list 'nnimap-address
888                       (cadr (assq 'nnimap-server-address defs))) defs)
889         (push (list 'nnimap-address server) defs)))
890     (nnoo-change-server 'nnimap server defs)
891     (or nnimap-server-buffer
892         (setq nnimap-server-buffer (cadr (assq 'nnimap-server-buffer defs))))
893     (with-current-buffer (get-buffer-create nnimap-server-buffer)
894       (nnoo-change-server 'nnimap server defs))
895     (let ((imap-logout-timeout nnimap-logout-timeout))
896       (or (and nnimap-server-buffer
897                (imap-opened nnimap-server-buffer)
898                (if (with-current-buffer nnimap-server-buffer
899                      (memq imap-state '(auth selected examine)))
900                    t
901                  (imap-close nnimap-server-buffer)
902                  (nnimap-open-connection server)))
903           (nnimap-open-connection server)))))
904
905 (deffoo nnimap-server-opened (&optional server)
906   "Whether SERVER is opened.
907 If SERVER is the current virtual server, and the connection to the
908 physical server is alive, this function return a non-nil value.  If
909 SERVER is nil, it is treated as the current server."
910   ;; clean up autologouts??
911   (and (or server nnimap-current-server)
912        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
913        (imap-opened (nnimap-get-server-buffer server))))
914
915 (deffoo nnimap-close-server (&optional server)
916   "Close connection to server and free all resources connected to it.
917 Return nil if the server couldn't be closed for some reason."
918   (let ((server (or server nnimap-current-server))
919         (imap-logout-timeout nnimap-logout-timeout))
920     (when (or (nnimap-server-opened server)
921               (imap-opened (nnimap-get-server-buffer server)))
922       (imap-close (nnimap-get-server-buffer server))
923       (kill-buffer (nnimap-get-server-buffer server))
924       (setq nnimap-server-buffer nil
925             nnimap-current-server nil
926             nnimap-server-buffer-alist
927             (nnimap-remove-server-from-buffer-alist
928              server
929              nnimap-server-buffer-alist)))
930     (nnoo-close-server 'nnimap server)))
931
932 (deffoo nnimap-request-close ()
933   "Close connection to all servers and free all resources that the backend have reserved.
934 All buffers that have been created by that
935 backend should be killed.  (Not the nntp-server-buffer, though.) This
936 function is generally only called when Gnus is shutting down."
937   (mapc (lambda (server) (nnimap-close-server (car server)))
938         nnimap-server-buffer-alist)
939   (setq nnimap-server-buffer-alist nil))
940
941 (deffoo nnimap-status-message (&optional server)
942   "This function returns the last error message from server."
943   (when (nnimap-possibly-change-server server)
944     (nnoo-status-message 'nnimap server)))
945
946 ;; We used to use a string-as-multibyte here, but it is really incorrect.
947 ;; This function is used when we're about to insert a unibyte string
948 ;; into a potentially multibyte buffer.  The string is either an article
949 ;; header or body (or both?), undecoded.  When Emacs is asked to convert
950 ;; a unibyte string to multibyte, it may either use the equivalent of
951 ;; nothing (e.g. non-Mule XEmacs), string-make-unibyte (i.e. decode using
952 ;; locale), string-as-multibyte (decode using emacs-internal coding system)
953 ;; or string-to-multibyte (keep the data undecoded as a sequence of bytes).
954 ;; Only the last one preserves the data such that we can reliably later on
955 ;; decode the text using the mime info.
956 (defalias 'nnimap-demule 'mm-string-to-multibyte)
957
958 (defun nnimap-make-callback (article gnus-callback buffer)
959   "Return a callback function."
960   `(lambda ()
961      (nnimap-callback ,article ,gnus-callback ,buffer)))
962
963 (defun nnimap-callback (article gnus-callback buffer)
964   (when (eq article (imap-current-message))
965     (remove-hook 'imap-fetch-data-hook
966                  (nnimap-make-callback article gnus-callback buffer))
967     (with-current-buffer buffer
968       (insert
969        (with-current-buffer nnimap-server-buffer
970          (nnimap-demule
971           (if (imap-capability 'IMAP4rev1)
972               ;; xxx don't just use car? alist doesn't contain
973               ;; anything else now, but it might...
974               (nth 2 (car (imap-message-get article 'BODYDETAIL)))
975             (imap-message-get article 'RFC822)))))
976       (nnheader-ms-strip-cr)
977       (funcall gnus-callback t))))
978
979 (defun nnimap-request-article-part (article part prop &optional
980                                             group server to-buffer detail)
981   (when (nnimap-possibly-change-group group server)
982     (let ((article (if (stringp article)
983                        (car-safe (imap-search
984                                   (format "HEADER Message-Id \"%s\"" article)
985                                   nnimap-server-buffer))
986                      article)))
987       (when article
988         (gnus-message 10 "nnimap: Fetching (part of) article %d from %s..."
989                       article (or (nnimap-decode-group-name group)
990                                   (imap-current-mailbox)
991                                   (nnimap-decode-group-name
992                                    gnus-newsgroup-name)))
993         (if (not nnheader-callback-function)
994             (with-current-buffer (or to-buffer nntp-server-buffer)
995               (erase-buffer)
996               (let ((data (imap-fetch article part prop nil
997                                       nnimap-server-buffer)))
998                 ;; data can be nil if article is write-only
999                 (when data
1000                   (insert (nnimap-demule (if detail
1001                                              (nth 2 (car data))
1002                                            data)))))
1003               (nnheader-ms-strip-cr)
1004               (gnus-message
1005                10 "nnimap: Fetching (part of) article %d from %s...done"
1006                article (or (nnimap-decode-group-name group)
1007                            (imap-current-mailbox)
1008                            (nnimap-decode-group-name gnus-newsgroup-name)))
1009               (if (bobp)
1010                   (nnheader-report 'nnimap "No such article %d in %s: %s"
1011                                    article (or (nnimap-decode-group-name group)
1012                                                (imap-current-mailbox)
1013                                                (nnimap-decode-group-name
1014                                                 gnus-newsgroup-name))
1015                                    (imap-error-text nnimap-server-buffer))
1016                 (cons group article)))
1017           (add-hook 'imap-fetch-data-hook
1018                     (nnimap-make-callback article
1019                                           nnheader-callback-function
1020                                           nntp-server-buffer))
1021           (imap-fetch-asynch article part nil nnimap-server-buffer)
1022           (cons group article))))))
1023
1024 (deffoo nnimap-asynchronous-p ()
1025   t)
1026
1027 (deffoo nnimap-request-article (article &optional group server to-buffer)
1028   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
1029       (nnimap-request-article-part
1030        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
1031     (nnimap-request-article-part
1032      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
1033
1034 (deffoo nnimap-request-head (article &optional group server to-buffer)
1035   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
1036       (nnimap-request-article-part
1037        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
1038     (nnimap-request-article-part
1039      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
1040
1041 (deffoo nnimap-request-body (article &optional group server to-buffer)
1042   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
1043       (nnimap-request-article-part
1044        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
1045     (nnimap-request-article-part
1046      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
1047
1048 (deffoo nnimap-request-group (group &optional server fast)
1049   (nnimap-request-update-info-internal
1050    group
1051    (gnus-get-info (nnimap-group-prefixed-name group server))
1052    server)
1053   (when (nnimap-possibly-change-group group server)
1054     (nnimap-before-find-minmax-bugworkaround)
1055     (let (info)
1056       (cond (fast group)
1057             ((null (setq info (nnimap-find-minmax-uid group t)))
1058              (nnheader-report 'nnimap "Could not get active info for %s"
1059                               group))
1060             (t
1061              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
1062                               (max 1 (or (nth 1 info) 1))
1063                               (or (nth 2 info) 0) group)
1064              (nnheader-report 'nnimap "Group %s selected" group)
1065              t)))))
1066
1067 (defun nnimap-update-unseen (group &optional server)
1068   "Update the unseen count in `nnimap-mailbox-info'."
1069   (gnus-sethash
1070    (gnus-group-prefixed-name group server)
1071    (let ((old (gnus-gethash-safe (gnus-group-prefixed-name group server)
1072                                  nnimap-mailbox-info)))
1073      (list (nth 0 old) (nth 1 old)
1074            (imap-mailbox-status (nnimap-decode-group-name group)
1075                                 'unseen nnimap-server-buffer)))
1076    nnimap-mailbox-info))
1077
1078 (defun nnimap-close-group (group &optional server)
1079   (with-current-buffer nnimap-server-buffer
1080     (when (and (imap-opened)
1081                (nnimap-possibly-change-group group server))
1082       (nnimap-update-unseen group server)
1083       (case nnimap-expunge-on-close
1084         (always (progn
1085                   (imap-mailbox-expunge nnimap-close-asynchronous)
1086                   (unless nnimap-dont-close
1087                     (imap-mailbox-close nnimap-close-asynchronous))))
1088         (ask (if (and (imap-search "DELETED")
1089                       (gnus-y-or-n-p (format "Expunge articles in group `%s'? "
1090                                              (imap-current-mailbox))))
1091                  (progn
1092                    (imap-mailbox-expunge nnimap-close-asynchronous)
1093                    (unless nnimap-dont-close
1094                      (imap-mailbox-close nnimap-close-asynchronous)))
1095                (imap-mailbox-unselect)))
1096         (t (imap-mailbox-unselect)))
1097       (not imap-current-mailbox))))
1098
1099 (defun nnimap-pattern-to-list-arguments (pattern)
1100   (mapcar (lambda (p)
1101             (cons (car-safe p) (or (cdr-safe p) p)))
1102           (if (and (listp pattern)
1103                    (listp (cdr pattern)))
1104               pattern
1105             (list pattern))))
1106
1107 (deffoo nnimap-request-list (&optional server)
1108   (when (nnimap-possibly-change-server server)
1109     (with-current-buffer nntp-server-buffer
1110       (erase-buffer))
1111     (gnus-message 5 "nnimap: Generating active list%s..."
1112                   (if (> (length server) 0) (concat " for " server) ""))
1113     (nnimap-before-find-minmax-bugworkaround)
1114     (with-current-buffer nnimap-server-buffer
1115       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
1116         (dolist (mbx (funcall nnimap-request-list-method
1117                               (cdr pattern) (car pattern)))
1118           (unless (member "\\noselect"
1119                           (mapcar #'downcase
1120                                   (imap-mailbox-get 'list-flags mbx)))
1121             (let* ((encoded-mbx (nnimap-encode-group-name mbx))
1122                    (info (nnimap-find-minmax-uid encoded-mbx 'examine)))
1123               (when info
1124                 (with-current-buffer nntp-server-buffer
1125                   (insert (format "\"%s\" %d %d y\n"
1126                                   encoded-mbx (or (nth 2 info) 0)
1127                                   (max 1 (or (nth 1 info) 1)))))))))))
1128     (gnus-message 5 "nnimap: Generating active list%s...done"
1129                   (if (> (length server) 0) (concat " for " server) ""))
1130     t))
1131
1132 (deffoo nnimap-request-post (&optional server)
1133   (let ((success t))
1134     (dolist (mbx (message-unquote-tokens
1135                   (message-tokenize-header
1136                    (message-fetch-field "Newsgroups") ", ")) success)
1137       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1138         (or (gnus-active to-newsgroup)
1139             (gnus-activate-group to-newsgroup)
1140             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1141                                        to-newsgroup))
1142                 (or (and (gnus-request-create-group
1143                           to-newsgroup gnus-command-method)
1144                          (gnus-activate-group to-newsgroup nil nil
1145                                               gnus-command-method))
1146                     (error "Couldn't create group %s" to-newsgroup)))
1147             (error "No such group: %s" to-newsgroup))
1148         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
1149           (setq success nil))))))
1150
1151 ;; Optional backend functions
1152
1153 (defun nnimap-string-lessp-numerical (s1 s2)
1154   "Return t if first arg string is less than second in numerical order."
1155   (cond ((string= s1 s2)
1156          nil)
1157         ((> (length s1) (length s2))
1158          nil)
1159         ((< (length s1) (length s2))
1160          t)
1161         ((< (string-to-number (substring s1 0 1))
1162             (string-to-number (substring s2 0 1)))
1163          t)
1164         ((> (string-to-number (substring s1 0 1))
1165             (string-to-number (substring s2 0 1)))
1166          nil)
1167         (t
1168          (nnimap-string-lessp-numerical (substring s1 1) (substring s2 1)))))
1169
1170 (deffoo nnimap-retrieve-groups (groups &optional server)
1171   (when (nnimap-possibly-change-server server)
1172     (gnus-message 5 "nnimap: Checking mailboxes...")
1173     (with-current-buffer nntp-server-buffer
1174       (erase-buffer)
1175       (nnimap-before-find-minmax-bugworkaround)
1176       (let (asyncgroups slowgroups decoded-group)
1177         (if (null nnimap-retrieve-groups-asynchronous)
1178             (setq slowgroups groups)
1179           (dolist (group groups)
1180             (setq decoded-group (nnimap-decode-group-name group))
1181             (gnus-message 9 "nnimap: Quickly checking mailbox %s"
1182                           decoded-group)
1183             (add-to-list (if (gnus-group-get-parameter
1184                               (nnimap-group-prefixed-name group)
1185                               'imap-status)
1186                              'asyncgroups
1187                            'slowgroups)
1188                          (list group (imap-mailbox-status-asynch
1189                                       decoded-group
1190                                       '(uidvalidity uidnext unseen)
1191                                       nnimap-server-buffer))))
1192           (dolist (asyncgroup asyncgroups)
1193             (let* ((group (nth 0 asyncgroup))
1194                    (tag   (nth 1 asyncgroup))
1195                    (gnusgroup (nnimap-group-prefixed-name group))
1196                    (saved-uidvalidity (gnus-group-get-parameter gnusgroup
1197                                                                 'uidvalidity))
1198                    (saved-imap-status (gnus-group-get-parameter gnusgroup
1199                                                                 'imap-status))
1200                    (saved-info (and saved-imap-status
1201                                     (split-string saved-imap-status " "))))
1202               (setq decoded-group (nnimap-decode-group-name group))
1203               (when (imap-ok-p (imap-wait-for-tag tag nnimap-server-buffer))
1204                 (if (or (not (equal
1205                               saved-uidvalidity
1206                               (imap-mailbox-get 'uidvalidity decoded-group
1207                                                 nnimap-server-buffer)))
1208                         (not (equal
1209                               (nth 0 saved-info)
1210                               (imap-mailbox-get 'uidnext decoded-group
1211                                                 nnimap-server-buffer))))
1212                     (push (list group) slowgroups)
1213                   (gnus-sethash
1214                    (gnus-group-prefixed-name group server)
1215                    (list (imap-mailbox-get 'uidvalidity
1216                                            decoded-group nnimap-server-buffer)
1217                          (imap-mailbox-get 'uidnext
1218                                            decoded-group nnimap-server-buffer)
1219                          (imap-mailbox-get 'unseen
1220                                            decoded-group nnimap-server-buffer))
1221                    nnimap-mailbox-info)
1222                   (insert (format "\"%s\" %s %s y\n" group
1223                                   (nth 2 saved-info)
1224                                   (nth 1 saved-info))))))))
1225         (dolist (group slowgroups)
1226           (if nnimap-retrieve-groups-asynchronous
1227               (setq group (car group)))
1228           (setq decoded-group (nnimap-decode-group-name group))
1229           (gnus-message 7 "nnimap: Mailbox %s modified" decoded-group)
1230           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags decoded-group
1231                                                      nnimap-server-buffer))
1232               (let* ((gnusgroup (nnimap-group-prefixed-name group))
1233                      (status (imap-mailbox-status
1234                               decoded-group '(uidvalidity uidnext unseen)
1235                               nnimap-server-buffer))
1236                      (info (nnimap-find-minmax-uid group 'examine))
1237                      (min-uid (max 1 (or (nth 1 info) 1)))
1238                      (max-uid (or (nth 2 info) 0)))
1239                 (when (> (or (imap-mailbox-get 'recent decoded-group
1240                                                nnimap-server-buffer) 0)
1241                          0)
1242                   (push (list (cons decoded-group 0)) nnmail-split-history))
1243                 (insert (format "\"%s\" %d %d y\n" group max-uid min-uid))
1244                 (gnus-sethash
1245                  (gnus-group-prefixed-name group server)
1246                  status
1247                  nnimap-mailbox-info)
1248                 (if (not (equal (nth 0 status)
1249                                 (gnus-group-get-parameter gnusgroup
1250                                                           'uidvalidity)))
1251                     (nnimap-verify-uidvalidity group nnimap-current-server))
1252                 ;; The imap-status parameter is a string on the form
1253                 ;; "<uidnext> <min-uid> <max-uid>".
1254                 (gnus-group-add-parameter
1255                  gnusgroup
1256                  (cons 'imap-status
1257                        (format "%s %s %s" (nth 1 status) min-uid max-uid))))))))
1258     (gnus-message 5 "nnimap: Checking mailboxes...done")
1259     'active))
1260
1261 (deffoo nnimap-request-update-info-internal (group info &optional server)
1262   (when (nnimap-possibly-change-group group server)
1263     (when info ;; xxx what does this mean? should we create a info?
1264       (with-current-buffer nnimap-server-buffer
1265         (gnus-message 5 "nnimap: Updating info for %s..."
1266                       (nnimap-decode-group-name (gnus-info-group info)))
1267
1268         (when (nnimap-mark-permanent-p 'read)
1269           (let (seen unseen)
1270             ;; read info could contain articles marked unread by other
1271             ;; imap clients!  we correct this
1272             (setq unseen (gnus-compress-sequence
1273                           (imap-search "UNSEEN UNDELETED"))
1274                   seen (gnus-range-difference (gnus-info-read info) unseen)
1275                   seen (gnus-range-add seen
1276                                        (gnus-compress-sequence
1277                                         (imap-search "SEEN")))
1278                   seen (if (and (integerp (car seen))
1279                                 (null (cdr seen)))
1280                            (list (cons (car seen) (car seen)))
1281                          seen))
1282             (gnus-info-set-read info seen)))
1283
1284         (dolist (pred gnus-article-mark-lists)
1285           (when (or (eq (cdr pred) 'recent)
1286                     (and (nnimap-mark-permanent-p (cdr pred))
1287                          (member (nnimap-mark-to-flag (cdr pred))
1288                                  (imap-mailbox-get 'flags))))
1289             (gnus-info-set-marks
1290              info
1291              (gnus-update-alist-soft
1292               (cdr pred)
1293               (gnus-compress-sequence
1294                (imap-search (nnimap-mark-to-predicate (cdr pred))))
1295               (gnus-info-marks info))
1296              t)))
1297
1298         (when nnimap-importantize-dormant
1299           ;; nnimap mark dormant article as ticked too (for other clients)
1300           ;; so we remove that mark for gnus since we support dormant
1301           (gnus-info-set-marks
1302            info
1303            (gnus-update-alist-soft
1304             'tick
1305             (gnus-remove-from-range
1306              (cdr-safe (assoc 'tick (gnus-info-marks info)))
1307              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
1308             (gnus-info-marks info))
1309            t))
1310
1311         (gnus-message 5 "nnimap: Updating info for %s...done"
1312                       (nnimap-decode-group-name (gnus-info-group info)))
1313
1314         info))))
1315
1316 (deffoo nnimap-request-type (group &optional article)
1317   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
1318       'news
1319     'mail))
1320
1321 (deffoo nnimap-request-set-mark (group actions &optional server)
1322   (when (nnimap-possibly-change-group group server)
1323     (with-current-buffer nnimap-server-buffer
1324       (let (action)
1325         (gnus-message 7 "nnimap: Setting marks in %s..."
1326                       (nnimap-decode-group-name group))
1327         (while (setq action (pop actions))
1328           (let ((range (nth 0 action))
1329                 (what  (nth 1 action))
1330                 (cmdmarks (nth 2 action))
1331                 marks)
1332             ;; bookmark can't be stored (not list/range
1333             (setq cmdmarks (delq 'bookmark cmdmarks))
1334             ;; killed can't be stored (not list/range
1335             (setq cmdmarks (delq 'killed cmdmarks))
1336             ;; unsent are for nndraft groups only
1337             (setq cmdmarks (delq 'unsent cmdmarks))
1338             ;; cache flags are pointless on the server
1339             (setq cmdmarks (delq 'cache cmdmarks))
1340             ;; seen flags are local to each gnus
1341             (setq cmdmarks (delq 'seen cmdmarks))
1342             ;; recent marks can't be set
1343             (setq cmdmarks (delq 'recent cmdmarks))
1344             (when nnimap-importantize-dormant
1345               ;; flag dormant articles as ticked
1346               (if (memq 'dormant cmdmarks)
1347                   (setq cmdmarks (cons 'tick cmdmarks))))
1348             ;; remove stuff we are forbidden to store
1349             (mapc (lambda (mark)
1350                     (if (imap-message-flag-permanent-p
1351                          (nnimap-mark-to-flag mark))
1352                         (setq marks (cons mark marks))))
1353                   cmdmarks)
1354             (when (and range marks)
1355               (cond ((eq what 'del)
1356                      (imap-message-flags-del
1357                       (imap-range-to-message-set range)
1358                       (nnimap-mark-to-flag marks nil t)))
1359                     ((eq what 'add)
1360                      (imap-message-flags-add
1361                       (imap-range-to-message-set range)
1362                       (nnimap-mark-to-flag marks nil t)))
1363                     ((eq what 'set)
1364                      (imap-message-flags-set
1365                       (imap-range-to-message-set range)
1366                       (nnimap-mark-to-flag marks nil t)))))))
1367         (gnus-message 7 "nnimap: Setting marks in %s...done"
1368                       (nnimap-decode-group-name group)))))
1369   nil)
1370
1371 (defun nnimap-split-fancy ()
1372   "Like the function `nnmail-split-fancy', but uses `nnimap-split-fancy'."
1373   (let ((nnmail-split-fancy nnimap-split-fancy))
1374     (nnmail-split-fancy)))
1375
1376 (defun nnimap-split-to-groups (rules)
1377   ;; tries to match all rules in nnimap-split-rule against content of
1378   ;; nntp-server-buffer, returns a list of groups that matched.
1379   ;; Note: This function takes and returns decoded group names.
1380   (with-current-buffer nntp-server-buffer
1381     ;; Fold continuation lines.
1382     (goto-char (point-min))
1383     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1384       (replace-match " " t t))
1385     (if (functionp rules)
1386         (funcall rules)
1387       (let (to-groups regrepp)
1388         (catch 'split-done
1389           (dolist (rule rules to-groups)
1390             (let ((group (car rule))
1391                   (regexp (cadr rule)))
1392               (goto-char (point-min))
1393               (when (and (if (stringp regexp)
1394                              (progn
1395                                (if (not (stringp group))
1396                                    (setq group (eval group))
1397                                  (setq regrepp
1398                                        (string-match "\\\\[0-9&]" group)))
1399                                (re-search-forward regexp nil t))
1400                            (funcall regexp group))
1401                          ;; Don't enter the article into the same group twice.
1402                          (not (assoc group to-groups)))
1403                 (push (if regrepp
1404                           (nnmail-expand-newtext group)
1405                         group)
1406                       to-groups)
1407                 (or nnimap-split-crosspost
1408                     (throw 'split-done to-groups))))))))))
1409
1410 (defun nnimap-assoc-match (key alist)
1411   (let (element)
1412     (while (and alist (not element))
1413       (if (string-match (car (car alist)) key)
1414           (setq element (car alist)))
1415       (setq alist (cdr alist)))
1416     element))
1417
1418 (defun nnimap-split-find-rule (server inbox)
1419   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1420            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1421       ;; extended format
1422       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match
1423                                             server nnimap-split-rule))))
1424     nnimap-split-rule))
1425
1426 (defun nnimap-split-find-inbox (server)
1427   (if (listp nnimap-split-inbox)
1428       nnimap-split-inbox
1429     (list nnimap-split-inbox)))
1430
1431 (defun nnimap-split-articles (&optional group server)
1432   ;; Note: Assumes decoded group names in nnimap-split-inbox,
1433   ;; nnimap-split-rule, nnimap-split-fancy, and nnmail-split-history.
1434   (when (nnimap-possibly-change-server server)
1435     (with-current-buffer nnimap-server-buffer
1436       (let (rule inbox removeorig
1437             (inboxes (nnimap-split-find-inbox server)))
1438         ;; iterate over inboxes
1439         (while (and (setq inbox (pop inboxes))
1440                     (nnimap-possibly-change-group
1441                      (nnimap-encode-group-name inbox))) ;; SELECT
1442           ;; find split rule for this server / inbox
1443           (when (setq rule (nnimap-split-find-rule server inbox))
1444             ;; iterate over articles
1445             (dolist (article (imap-search nnimap-split-predicate))
1446               (when (if (if (eq nnimap-split-download-body 'default)
1447                             nnimap-split-download-body-default
1448                           nnimap-split-download-body)
1449                         (and (nnimap-request-article article)
1450                              (with-current-buffer nntp-server-buffer (mail-narrow-to-head)))
1451                       (nnimap-request-head article))
1452                 ;; copy article to right group(s)
1453                 (setq removeorig nil)
1454                 (dolist (to-group (nnimap-split-to-groups rule))
1455                   (cond ((eq to-group 'junk)
1456                          (message "IMAP split removed %s:%s:%d" server inbox
1457                                   article)
1458                          (setq removeorig t))
1459                         ((imap-message-copy (number-to-string article)
1460                                             to-group nil 'nocopyuid)
1461                          (message "IMAP split moved %s:%s:%d to %s" server
1462                                   inbox article to-group)
1463                          (setq removeorig t)
1464                          (when nnmail-cache-accepted-message-ids
1465                            (with-current-buffer nntp-server-buffer
1466                              (let (msgid)
1467                                (and (setq msgid
1468                                           (nnmail-fetch-field "message-id"))
1469                                     (nnmail-cache-insert msgid
1470                                                          (nnimap-encode-group-name to-group)
1471                                                          (nnmail-fetch-field "subject"))))))
1472                          ;; Add the group-art list to the history list.
1473                          (push (list (cons to-group 0)) nnmail-split-history))
1474                         (t
1475                          (message "IMAP split failed to move %s:%s:%d to %s"
1476                                   server inbox article to-group))))
1477                 (if (if (eq nnimap-split-download-body 'default)
1478                         nnimap-split-download-body-default
1479                       nnimap-split-download-body)
1480                     (widen))
1481                 ;; remove article if it was successfully copied somewhere
1482                 (and removeorig
1483                      (imap-message-flags-add (format "%d" article)
1484                                              "\\Seen \\Deleted")))))
1485           (when (imap-mailbox-select inbox) ;; just in case
1486             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1487             (imap-mailbox-expunge)
1488             (imap-mailbox-close)))
1489         (when nnmail-cache-accepted-message-ids
1490           (nnmail-cache-close))
1491         t))))
1492
1493 (deffoo nnimap-request-scan (&optional group server)
1494   (nnimap-split-articles group server))
1495
1496 (deffoo nnimap-request-newgroups (date &optional server)
1497   (when (nnimap-possibly-change-server server)
1498     (with-current-buffer nntp-server-buffer
1499       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1500                     (if (> (length server) 0) " on " "") server)
1501       (erase-buffer)
1502       (nnimap-before-find-minmax-bugworkaround)
1503       (dolist (pattern (nnimap-pattern-to-list-arguments
1504                         nnimap-list-pattern))
1505         (dolist (mbx (funcall nnimap-request-list-method (cdr pattern) (car pattern) nil
1506                               nnimap-server-buffer))
1507           (or (catch 'found
1508                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1509                                                    nnimap-server-buffer))
1510                   (if (string= (downcase mailbox) "\\noselect")
1511                       (throw 'found t)))
1512                 nil)
1513               (let* ((encoded-mbx (nnimap-encode-group-name mbx))
1514                      (info (nnimap-find-minmax-uid encoded-mbx 'examine)))
1515                 (when info
1516                   (insert (format "\"%s\" %d %d y\n"
1517                                   encoded-mbx (or (nth 2 info) 0)
1518                                   (max 1 (or (nth 1 info) 1)))))))))
1519       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1520                     (if (> (length server) 0) " on " "") server))
1521     t))
1522
1523 (deffoo nnimap-request-create-group (group &optional server args)
1524   (when (nnimap-possibly-change-server server)
1525     (let ((decoded-group (nnimap-decode-group-name group)))
1526       (or (imap-mailbox-status decoded-group 'uidvalidity nnimap-server-buffer)
1527           (imap-mailbox-create decoded-group nnimap-server-buffer)
1528           (nnheader-report 'nnimap "%S"
1529                            (imap-error-text nnimap-server-buffer))))))
1530
1531 (defun nnimap-time-substract (time1 time2)
1532   "Return TIME for TIME1 - TIME2."
1533   (let* ((ms (- (car time1) (car time2)))
1534          (ls (- (nth 1 time1) (nth 1 time2))))
1535     (if (< ls 0)
1536         (list (- ms 1) (+ (expt 2 16) ls))
1537       (list ms ls))))
1538
1539 (eval-when-compile (require 'parse-time))
1540 (defun nnimap-date-days-ago (daysago)
1541   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1542   (require 'parse-time)
1543   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1544          (date (format-time-string
1545                 (format "%%d-%s-%%Y"
1546                         (capitalize (car (rassoc (nth 4 (decode-time time))
1547                                                  parse-time-months))))
1548                 time)))
1549     (if (eq ?0 (string-to-char date))
1550         (substring date 1)
1551       date)))
1552
1553 (defun nnimap-request-expire-articles-progress ()
1554   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1555                 imap-current-message))
1556
1557 (defun nnimap-expiry-target (arts group server)
1558   (unless (eq nnmail-expiry-target 'delete)
1559     (with-temp-buffer
1560       (dolist (art arts)
1561         (nnimap-request-article art group server (current-buffer))
1562         ;; hints for optimization in `nnimap-request-accept-article'
1563         (let ((nnimap-current-move-article art)
1564               (nnimap-current-move-group group)
1565               (nnimap-current-move-server server))
1566           (nnmail-expiry-target-group nnmail-expiry-target group))))
1567     ;; It is not clear if `nnmail-expiry-target' somehow cause the
1568     ;; current group to be changed or not, so we make sure here.
1569     (nnimap-possibly-change-group group server)))
1570
1571 ;; Notice that we don't actually delete anything, we just mark them deleted.
1572 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1573   (let ((artseq (gnus-compress-sequence articles)))
1574     (when (and artseq (nnimap-possibly-change-group group server))
1575       (with-current-buffer nnimap-server-buffer
1576         (let ((days (or (and nnmail-expiry-wait-function
1577                              (funcall nnmail-expiry-wait-function group))
1578                         nnmail-expiry-wait)))
1579           (cond ((or force (eq days 'immediate))
1580                  (let ((oldarts (imap-search
1581                                  (concat "UID "
1582                                          (imap-range-to-message-set artseq)))))
1583                    (when oldarts
1584                      (nnimap-expiry-target oldarts group server)
1585                      (when (imap-message-flags-add
1586                             (imap-range-to-message-set
1587                              (gnus-compress-sequence oldarts)) "\\Deleted")
1588                        (setq articles (gnus-set-difference
1589                                        articles oldarts))))))
1590                 ((and nnimap-search-uids-not-since-is-evil (numberp days))
1591                  (let* ((all-new-articles
1592                          (gnus-compress-sequence
1593                           (imap-search (format "SINCE %s"
1594                                                (nnimap-date-days-ago days)))))
1595                         (oldartseq
1596                          (gnus-range-difference artseq all-new-articles))
1597                         (oldarts (gnus-uncompress-range oldartseq)))
1598                    (when oldarts
1599                      (nnimap-expiry-target oldarts group server)
1600                      (when (imap-message-flags-add
1601                             (imap-range-to-message-set oldartseq)
1602                             "\\Deleted")
1603                        (setq articles (gnus-set-difference
1604                                        articles oldarts))))))
1605                 ((numberp days)
1606                  (let ((oldarts (imap-search
1607                                  (format nnimap-expunge-search-string
1608                                          (imap-range-to-message-set artseq)
1609                                          (nnimap-date-days-ago days))))
1610                        (imap-fetch-data-hook
1611                         '(nnimap-request-expire-articles-progress)))
1612                    (when oldarts
1613                      (nnimap-expiry-target oldarts group server)
1614                      (when (imap-message-flags-add
1615                             (imap-range-to-message-set
1616                              (gnus-compress-sequence oldarts)) "\\Deleted")
1617                        (setq articles (gnus-set-difference
1618                                        articles oldarts)))))))))))
1619   ;; return articles not deleted
1620   articles)
1621
1622 (deffoo nnimap-request-move-article (article group server accept-form
1623                                              &optional last move-is-internal)
1624   (when (nnimap-possibly-change-server server)
1625     (save-excursion
1626       (let ((buf (get-buffer-create " *nnimap move*"))
1627             (nnimap-current-move-article article)
1628             (nnimap-current-move-group group)
1629             (nnimap-current-move-server nnimap-current-server)
1630             result)
1631         (gnus-message 10 "nnimap-request-move-article: this is an %s move"
1632                       (if move-is-internal
1633                           "internal"
1634                         "external"))
1635         ;; request the article only when the move is NOT internal
1636         (and (or move-is-internal
1637                  (nnimap-request-article article group server))
1638              (with-current-buffer buf
1639                (buffer-disable-undo (current-buffer))
1640                (insert-buffer-substring nntp-server-buffer)
1641                (setq result (eval accept-form))
1642                (kill-buffer buf)
1643                result)
1644              (nnimap-possibly-change-group group server)
1645              (imap-message-flags-add
1646               (imap-range-to-message-set (list article))
1647               "\\Deleted" 'silent nnimap-server-buffer))
1648         result))))
1649
1650 (deffoo nnimap-request-accept-article (group &optional server last)
1651   (when (nnimap-possibly-change-server server)
1652     (let (uid)
1653       (if (setq uid
1654                 (if (string= nnimap-current-server nnimap-current-move-server)
1655                     ;; moving article within same server, speed it up...
1656                     (and (nnimap-possibly-change-group
1657                           nnimap-current-move-group)
1658                          (imap-message-copy (number-to-string
1659                                              nnimap-current-move-article)
1660                                             (nnimap-decode-group-name group)
1661                                             'dontcreate nil
1662                                             nnimap-server-buffer))
1663                   (with-current-buffer (current-buffer)
1664                     (goto-char (point-min))
1665                     ;; remove any 'From blabla' lines, some IMAP servers
1666                     ;; reject the entire message otherwise.
1667                     (when (looking-at "^From[^:]")
1668                       (delete-region (point) (progn (forward-line) (point))))
1669                     ;; turn into rfc822 format (\r\n eol's)
1670                     (while (search-forward "\n" nil t)
1671                       (replace-match "\r\n"))
1672                     (when nnmail-cache-accepted-message-ids
1673                       (nnmail-cache-insert (nnmail-fetch-field "message-id")
1674                                            group
1675                                            (nnmail-fetch-field "subject"))))
1676                   (when (and last nnmail-cache-accepted-message-ids)
1677                     (nnmail-cache-close))
1678                   ;; this 'or' is for Cyrus server bug
1679                   (or (null (imap-current-mailbox nnimap-server-buffer))
1680                       (imap-mailbox-unselect nnimap-server-buffer))
1681                   (imap-message-append (nnimap-decode-group-name group)
1682                                        (current-buffer) nil nil
1683                                        nnimap-server-buffer)))
1684           (cons group (nth 1 uid))
1685         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1686
1687 (deffoo nnimap-request-delete-group (group force &optional server)
1688   (when (nnimap-possibly-change-server server)
1689     (setq group (nnimap-decode-group-name group))
1690     (when (string= group (imap-current-mailbox nnimap-server-buffer))
1691       (imap-mailbox-unselect nnimap-server-buffer))
1692     (with-current-buffer nnimap-server-buffer
1693       (if force
1694           (or (null (imap-mailbox-status group 'uidvalidity))
1695               (imap-mailbox-delete group))
1696         ;; UNSUBSCRIBE?
1697         t))))
1698
1699 (deffoo nnimap-request-rename-group (group new-name &optional server)
1700   (when (nnimap-possibly-change-server server)
1701     (imap-mailbox-rename (nnimap-decode-group-name group)
1702                          (nnimap-decode-group-name new-name)
1703                          nnimap-server-buffer)))
1704
1705 (defun nnimap-expunge (mailbox server)
1706   (when (nnimap-possibly-change-group mailbox server)
1707     (imap-mailbox-expunge nil nnimap-server-buffer)))
1708
1709 (defun nnimap-acl-get (mailbox server)
1710   (when (nnimap-possibly-change-server server)
1711     (and (imap-capability 'ACL nnimap-server-buffer)
1712          (imap-mailbox-acl-get (nnimap-decode-group-name mailbox)
1713                                nnimap-server-buffer))))
1714
1715 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1716   (when (nnimap-possibly-change-server (cadr method))
1717     (unless (imap-capability 'ACL nnimap-server-buffer)
1718       (error "Your server does not support ACL editing"))
1719     (with-current-buffer nnimap-server-buffer
1720       ;; delete all removed identifiers
1721       (mapc (lambda (old-acl)
1722               (unless (assoc (car old-acl) new-acls)
1723                 (or (imap-mailbox-acl-delete (car old-acl)
1724                                              (nnimap-decode-group-name mailbox))
1725                     (error "Can't delete ACL for %s" (car old-acl)))))
1726             old-acls)
1727       ;; set all changed acl's
1728       (mapc (lambda (new-acl)
1729               (let ((new-rights (cdr new-acl))
1730                     (old-rights (cdr (assoc (car new-acl) old-acls))))
1731                 (unless (and old-rights new-rights
1732                              (string= old-rights new-rights))
1733                   (or (imap-mailbox-acl-set (car new-acl) new-rights
1734                                             (nnimap-decode-group-name mailbox))
1735                       (error "Can't set ACL for %s to %s" (car new-acl)
1736                              new-rights)))))
1737             new-acls)
1738       t)))
1739
1740 \f
1741 ;;; Internal functions
1742
1743 ;;
1744 ;; This is confusing.
1745 ;;
1746 ;; mark      => read, tick, draft, reply etc
1747 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1748 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1749 ;;
1750 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1751 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1752 ;;
1753
1754 (defconst nnimap-mark-to-predicate-alist
1755   (mapcar
1756    (lambda (pair)                       ; cdr is the mark
1757      (or (assoc (cdr pair)
1758                 '((read . "SEEN")
1759                   (tick . "FLAGGED")
1760                   (draft . "DRAFT")
1761                   (recent . "RECENT")
1762                   (reply . "ANSWERED")))
1763          (cons (cdr pair)
1764                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1765    (cons '(read . read) gnus-article-mark-lists)))
1766
1767 (defun nnimap-mark-to-predicate (pred)
1768   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1769 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1770 to be used within a IMAP SEARCH query."
1771   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1772
1773 (defconst nnimap-mark-to-flag-alist
1774   (mapcar
1775    (lambda (pair)
1776      (or (assoc (cdr pair)
1777                 '((read . "\\Seen")
1778                   (tick . "\\Flagged")
1779                   (draft . "\\Draft")
1780                   (recent . "\\Recent")
1781                   (reply . "\\Answered")))
1782          (cons (cdr pair)
1783                (format "gnus-%s" (symbol-name (cdr pair))))))
1784    (cons '(read . read) gnus-article-mark-lists)))
1785
1786 (defun nnimap-mark-to-flag-1 (preds)
1787   (if (and (not (null preds)) (listp preds))
1788       (cons (nnimap-mark-to-flag (car preds))
1789             (nnimap-mark-to-flag (cdr preds)))
1790     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1791
1792 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1793   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1794 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1795 be used in a STORE FLAGS command."
1796   (let ((result (nnimap-mark-to-flag-1 preds)))
1797     (setq result (if (and (or make-string always-list)
1798                           (not (listp result)))
1799                      (list result)
1800                    result))
1801     (if make-string
1802         (mapconcat (lambda (flag)
1803                      (if (listp flag)
1804                          (mapconcat 'identity flag " ")
1805                        flag))
1806                    result " ")
1807       result)))
1808
1809 (defun nnimap-mark-permanent-p (mark &optional group)
1810   "Return t if MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1811   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1812
1813 (provide 'nnimap)
1814
1815 ;;; nnimap.el ends here