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