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