452b52359359d5f30c1fd0792202d6e761beb517
[gnus] / lisp / imap.el
1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; imap.el is a elisp library providing an interface for talking to
28 ;; IMAP servers.
29 ;;
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information.  The latter
34 ;; part is layered on top of the previous.
35 ;;
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
39 ;;
40 ;; Global commands:
41 ;;
42 ;; imap-open,       imap-opened,    imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
44 ;;
45 ;; Mailbox commands:
46 ;;
47 ;; imap-mailbox-get,       imap-mailbox-map,         imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search,              imap-mailbox-select,
49 ;; imap-mailbox-examine,   imap-mailbox-unselect,    imap-mailbox-expunge
50 ;; imap-mailbox-close,     imap-mailbox-create,      imap-mailbox-delete
51 ;; imap-mailbox-rename,    imap-mailbox-lsub,        imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get,   imap-mailbox-acl-set,     imap-mailbox-acl-delete
54 ;;
55 ;; Message commands:
56 ;;
57 ;; imap-fetch-asynch,                 imap-fetch,
58 ;; imap-current-message,              imap-list-to-message-set,
59 ;; imap-message-get,                  imap-message-map
60 ;; imap-message-envelope-date,        imap-message-envelope-subject,
61 ;; imap-message-envelope-from,        imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to,    imap-message-envelope-to,
63 ;; imap-message-envelope-cc,          imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body,                 imap-message-flag-permanent-p
66 ;; imap-message-flags-set,            imap-message-flags-del
67 ;; imap-message-flags-add,            imap-message-copyuid
68 ;; imap-message-copy,                 imap-message-appenduid
69 ;; imap-message-append,               imap-envelope-from
70 ;; imap-body-lines
71 ;;
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP.  All functions have
74 ;; additional documentation on how to invoke them.
75 ;;
76 ;; imap.el support RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1), implemented
77 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls), and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'), RFC2971 (ID).  It also
82 ;; take advantage the UNSELECT extension in Cyrus IMAPD.
83 ;;
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day.  Many thanks.
86 ;;
87 ;; This is a transcript of short interactive session for demonstration
88 ;; purposes.
89 ;;
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
92 ;;
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'.  It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
97 ;;
98 ;; (imap-authenticate "myusername" "mypassword")
99 ;; => auth
100 ;;
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
103 ;;
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
106 ;;
107 ;; (imap-mailbox-select "INBOX.nnimap")
108 ;; => "INBOX.nnimap"
109 ;;
110 ;; (imap-mailbox-get 'exists)
111 ;; => 166
112 ;;
113 ;; (imap-mailbox-get 'uidvalidity)
114 ;; => "908992622"
115 ;;
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
117 ;; => (235 236)
118 ;;
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
121 ;;
122 ;; Todo:
123 ;;
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;;   imap-message-* functions.
128 ;; o Send strings as literal if they contain, e.g., ".
129 ;;
130 ;; Revision history:
131 ;;
132 ;;  - 19991218 added starttls/digest-md5 patch,
133 ;;             by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
134 ;;             NB! you need SLIM for starttls.el and digest-md5.el
135 ;;  - 19991023 commited to pgnus
136 ;;
137
138 ;;; Code:
139
140 (eval-when-compile (require 'cl))
141 (eval-and-compile
142   (autoload 'starttls-open-stream "starttls")
143   (autoload 'starttls-negotiate "starttls")
144   (autoload 'sasl-find-mechanism "sasl")
145   (autoload 'digest-md5-parse-digest-challenge "digest-md5")
146   (autoload 'digest-md5-digest-response "digest-md5")
147   (autoload 'digest-md5-digest-uri "digest-md5")
148   (autoload 'digest-md5-challenge "digest-md5")
149   (autoload 'rfc2104-hash "rfc2104")
150   (autoload 'utf7-encode "utf7")
151   (autoload 'utf7-decode "utf7")
152   (autoload 'format-spec "format-spec")
153   (autoload 'format-spec-make "format-spec")
154   (autoload 'open-tls-stream "tls"))
155
156 ;; User variables.
157
158 (defgroup imap nil
159   "Low-level IMAP issues."
160   :version "21.1"
161   :group 'mail)
162
163 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
164                                     "imtest -kp %s %p")
165   "List of strings containing commands for Kerberos 4 authentication.
166 %s is replaced with server hostname, %p with port to connect to, and
167 %l with the value of `imap-default-user'.  The program should accept
168 IMAP commands on stdin and return responses to stdout.  Each entry in
169 the list is tried until a successful connection is made."
170   :group 'imap
171   :type '(repeat string))
172
173 (defcustom imap-gssapi-program (list
174                                 (concat "gsasl --client --connect %s:%p "
175                                         "--imap --application-data "
176                                         "--mechanism GSSAPI "
177                                         "--authentication-id %l")
178                                 "imtest -m gssapi -u %l -p %p %s")
179   "List of strings containing commands for GSSAPI (krb5) authentication.
180 %s is replaced with server hostname, %p with port to connect to, and
181 %l with the value of `imap-default-user'.  The program should accept
182 IMAP commands on stdin and return responses to stdout.  Each entry in
183 the list is tried until a successful connection is made."
184   :group 'imap
185   :type '(repeat string))
186
187 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
188                               "openssl s_client -quiet -ssl2 -connect %s:%p"
189                               "s_client -quiet -ssl3 -connect %s:%p"
190                               "s_client -quiet -ssl2 -connect %s:%p")
191   "A string, or list of strings, containing commands for SSL connections.
192 Within a string, %s is replaced with the server address and %p with
193 port number on server.  The program should accept IMAP commands on
194 stdin and return responses to stdout.  Each entry in the list is tried
195 until a successful connection is made."
196   :group 'imap
197   :type '(choice string
198                  (repeat string)))
199
200 (defcustom imap-shell-program '("ssh %s imapd"
201                                 "rsh %s imapd"
202                                 "ssh %g ssh %s imapd"
203                                 "rsh %g rsh %s imapd")
204   "A list of strings, containing commands for IMAP connection.
205 Within a string, %s is replaced with the server address, %p with port
206 number on server, %g with `imap-shell-host', and %l with
207 `imap-default-user'.  The program should read IMAP commands from stdin
208 and write IMAP response to stdout. Each entry in the list is tried
209 until a successful connection is made."
210   :group 'imap
211   :type '(repeat string))
212
213 (defcustom imap-process-connection-type nil
214   "*Value for `process-connection-type' to use for Kerberos4, GSSAPI and SSL.
215 The `process-connection-type' variable control type of device
216 used to communicate with subprocesses.  Values are nil to use a
217 pipe, or t or `pty' to use a pty.  The value has no effect if the
218 system has no ptys or if all ptys are busy: then a pipe is used
219 in any case.  The value takes effect when a IMAP server is
220 opened, changing it after that has no effect.."
221   :group 'imap
222   :type 'boolean)
223
224 (defcustom imap-use-utf7 t
225   "If non-nil, do utf7 encoding/decoding of mailbox names.
226 Since the UTF7 decoding currently only decodes into ISO-8859-1
227 characters, you may disable this decoding if you need to access UTF7
228 encoded mailboxes which doesn't translate into ISO-8859-1."
229   :group 'imap
230   :type 'boolean)
231
232 (defcustom imap-log nil
233   "If non-nil, a imap session trace is placed in *imap-log* buffer."
234   :group 'imap
235   :type 'boolean)
236
237 (defcustom imap-debug nil
238   "If non-nil, random debug spews are placed in *imap-debug* buffer."
239   :group 'imap
240   :type 'boolean)
241
242 (defcustom imap-shell-host "gateway"
243   "Hostname of rlogin proxy."
244   :group 'imap
245   :type 'string)
246
247 (defcustom imap-default-user (user-login-name)
248   "Default username to use."
249   :group 'imap
250   :type 'string)
251
252 (defcustom imap-read-timeout (if (string-match
253                                   "windows-nt\\|os/2\\|emx\\|cygwin"
254                                   (symbol-name system-type))
255                                  1.0
256                                0.1)
257   "*How long to wait between checking for the end of output.
258 Shorter values mean quicker response, but is more CPU intensive."
259   :type 'number
260   :group 'imap)
261
262 (defcustom imap-store-password nil
263   "If non-nil, store session password without promting."
264   :group 'imap
265   :type 'boolean)
266
267 ;; Various variables.
268
269 (defvar imap-fetch-data-hook nil
270   "Hooks called after receiving each FETCH response.")
271
272 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
273   "Priority of streams to consider when opening connection to server.")
274
275 (defvar imap-stream-alist
276   '((gssapi    imap-gssapi-stream-p    imap-gssapi-open)
277     (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
278     (tls       imap-tls-p              imap-tls-open)
279     (ssl       imap-ssl-p              imap-ssl-open)
280     (network   imap-network-p          imap-network-open)
281     (shell     imap-shell-p            imap-shell-open)
282     (starttls  imap-starttls-p         imap-starttls-open))
283   "Definition of network streams.
284
285 \(NAME CHECK OPEN)
286
287 NAME names the stream, CHECK is a function returning non-nil if the
288 server support the stream and OPEN is a function for opening the
289 stream.")
290
291 (defvar imap-authenticators '(gssapi
292                               kerberos4
293                               digest-md5
294                               cram-md5
295                               sasl
296                               login
297                               anonymous)
298   "Priority of authenticators to consider when authenticating to server.")
299
300 (defvar imap-authenticator-alist
301   '((gssapi     imap-gssapi-auth-p    imap-gssapi-auth)
302     (kerberos4  imap-kerberos4-auth-p imap-kerberos4-auth)
303     (sasl       imap-sasl-auth-p      imap-sasl-auth)
304     (cram-md5   imap-cram-md5-p       imap-cram-md5-auth)
305     (login      imap-login-p          imap-login-auth)
306     (anonymous  imap-anonymous-p      imap-anonymous-auth)
307     (digest-md5 imap-digest-md5-p     imap-digest-md5-auth))
308   "Definition of authenticators.
309
310 \(NAME CHECK AUTHENTICATE)
311
312 NAME names the authenticator.  CHECK is a function returning non-nil if
313 the server support the authenticator and AUTHENTICATE is a function
314 for doing the actual authentication.")
315
316 (defvar imap-error nil
317   "Error codes from the last command.")
318
319 ;; Internal constants.  Change theese and die.
320
321 (defconst imap-default-port 143)
322 (defconst imap-default-ssl-port 993)
323 (defconst imap-default-tls-port 993)
324 (defconst imap-default-stream 'network)
325 (defconst imap-coding-system-for-read 'binary)
326 (defconst imap-coding-system-for-write 'binary)
327 (defconst imap-local-variables '(imap-server
328                                  imap-port
329                                  imap-client-eol
330                                  imap-server-eol
331                                  imap-auth
332                                  imap-stream
333                                  imap-username
334                                  imap-password
335                                  imap-current-mailbox
336                                  imap-current-target-mailbox
337                                  imap-message-data
338                                  imap-capability
339                                  imap-id
340                                  imap-namespace
341                                  imap-state
342                                  imap-reached-tag
343                                  imap-failed-tags
344                                  imap-tag
345                                  imap-process
346                                  imap-calculate-literal-size-first
347                                  imap-mailbox-data))
348 (defconst imap-log-buffer "*imap-log*")
349 (defconst imap-debug-buffer "*imap-debug*")
350
351 ;; Internal variables.
352
353 (defvar imap-stream nil)
354 (defvar imap-auth nil)
355 (defvar imap-server nil)
356 (defvar imap-port nil)
357 (defvar imap-username nil)
358 (defvar imap-password nil)
359 (defvar imap-calculate-literal-size-first nil)
360 (defvar imap-state 'closed
361   "IMAP state.
362 Valid states are `closed', `initial', `nonauth', `auth', `selected'
363 and `examine'.")
364
365 (defvar imap-server-eol "\r\n"
366   "The EOL string sent from the server.")
367
368 (defvar imap-client-eol "\r\n"
369   "The EOL string we send to the server.")
370
371 (defvar imap-current-mailbox nil
372   "Current mailbox name.")
373
374 (defvar imap-current-target-mailbox nil
375   "Current target mailbox for COPY and APPEND commands.")
376
377 (defvar imap-mailbox-data nil
378   "Obarray with mailbox data.")
379
380 (defvar imap-mailbox-prime 997
381   "Length of imap-mailbox-data.")
382
383 (defvar imap-current-message nil
384   "Current message number.")
385
386 (defvar imap-message-data nil
387   "Obarray with message data.")
388
389 (defvar imap-message-prime 997
390   "Length of imap-message-data.")
391
392 (defvar imap-capability nil
393   "Capability for server.")
394
395 (defvar imap-id nil
396   "Identity of server.
397 See RFC 2971.")
398
399 (defvar imap-namespace nil
400   "Namespace for current server.")
401
402 (defvar imap-reached-tag 0
403   "Lower limit on command tags that have been parsed.")
404
405 (defvar imap-failed-tags nil
406   "Alist of tags that failed.
407 Each element is a list with four elements; tag (a integer), response
408 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
409 human readable response text (a string).")
410
411 (defvar imap-tag 0
412   "Command tag number.")
413
414 (defvar imap-process nil
415   "Process.")
416
417 (defvar imap-continuation nil
418   "Non-nil indicates that the server emitted a continuation request.
419 The actual value is really the text on the continuation line.")
420
421 (defvar imap-callbacks nil
422   "List of response tags and callbacks, on the form `(number . function)'.
423 The function should take two arguments, the first the IMAP tag and the
424 second the status (OK, NO, BAD etc) of the command.")
425
426 \f
427 ;; Utility functions:
428
429 (defun imap-remassoc (key alist)
430   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
431 The modified LIST is returned.  If the first member
432 of LIST has a car that is `equal' to KEY, there is no way to remove it
433 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
434 sure of changing the value of `foo'."
435   (when alist
436     (if (equal key (caar alist))
437         (cdr alist)
438       (setcdr alist (imap-remassoc key (cdr alist)))
439       alist)))
440
441 (defsubst imap-disable-multibyte ()
442   "Enable multibyte in the current buffer."
443   (when (fboundp 'set-buffer-multibyte)
444     (set-buffer-multibyte nil)))
445
446 (defsubst imap-utf7-encode (string)
447   (if imap-use-utf7
448       (and string
449            (condition-case ()
450                (utf7-encode string t)
451              (error (message
452                      "imap: Could not UTF7 encode `%s', using it unencoded..."
453                      string)
454                     string)))
455     string))
456
457 (defsubst imap-utf7-decode (string)
458   (if imap-use-utf7
459       (and string
460            (condition-case ()
461                (utf7-decode string t)
462              (error (message
463                      "imap: Could not UTF7 decode `%s', using it undecoded..."
464                      string)
465                     string)))
466     string))
467
468 (defsubst imap-ok-p (status)
469   (if (eq status 'OK)
470       t
471     (setq imap-error status)
472     nil))
473
474 (defun imap-error-text (&optional buffer)
475   (with-current-buffer (or buffer (current-buffer))
476     (nth 3 (car imap-failed-tags))))
477
478 \f
479 ;; Server functions; stream stuff:
480
481 (defun imap-kerberos4-stream-p (buffer)
482   (imap-capability 'AUTH=KERBEROS_V4 buffer))
483
484 (defun imap-kerberos4-open (name buffer server port)
485   (let ((cmds imap-kerberos4-program)
486         cmd done)
487     (while (and (not done) (setq cmd (pop cmds)))
488       (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
489       (erase-buffer)
490       (let* ((port (or port imap-default-port))
491              (coding-system-for-read imap-coding-system-for-read)
492              (coding-system-for-write imap-coding-system-for-write)
493              (process-connection-type imap-process-connection-type)
494              (process (start-process
495                        name buffer shell-file-name shell-command-switch
496                        (format-spec
497                         cmd
498                         (format-spec-make
499                          ?s server
500                          ?p (number-to-string port)
501                          ?l imap-default-user))))
502              response)
503         (when process
504           (with-current-buffer buffer
505             (setq imap-client-eol "\n"
506                   imap-calculate-literal-size-first t)
507             (while (and (memq (process-status process) '(open run))
508                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
509                         (goto-char (point-min))
510                         ;; Athena IMTEST can output SSL verify errors
511                         (or (while (looking-at "^verify error:num=")
512                               (forward-line))
513                             t)
514                         (or (while (looking-at "^TLS connection established")
515                               (forward-line))
516                             t)
517                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
518                         (or (while (looking-at "^C:")
519                               (forward-line))
520                             t)
521                         ;; cyrus 1.6 imtest print "S: " before server greeting
522                         (or (not (looking-at "S: "))
523                             (forward-char 3)
524                             t)
525                         (not (and (imap-parse-greeting)
526                                   ;; success in imtest < 1.6:
527                                   (or (re-search-forward
528                                        "^__\\(.*\\)__\n" nil t)
529                                       ;; success in imtest 1.6:
530                                       (re-search-forward
531                                        "^\\(Authenticat.*\\)" nil t))
532                                   (setq response (match-string 1)))))
533               (accept-process-output process 1)
534               (sit-for 1))
535             (and imap-log
536                  (with-current-buffer (get-buffer-create imap-log-buffer)
537                    (imap-disable-multibyte)
538                    (buffer-disable-undo)
539                    (goto-char (point-max))
540                    (insert-buffer-substring buffer)))
541             (erase-buffer)
542             (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
543                      (if response (concat "done, " response) "failed"))
544             (if (and response (let ((case-fold-search nil))
545                                 (not (string-match "failed" response))))
546                 (setq done process)
547               (if (memq (process-status process) '(open run))
548                   (imap-send-command "LOGOUT"))
549               (delete-process process)
550               nil)))))
551     done))
552
553 (defun imap-gssapi-stream-p (buffer)
554   (imap-capability 'AUTH=GSSAPI buffer))
555
556 (defun imap-gssapi-open (name buffer server port)
557   (let ((cmds imap-gssapi-program)
558         cmd done)
559     (while (and (not done) (setq cmd (pop cmds)))
560       (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
561       (erase-buffer)
562       (let* ((port (or port imap-default-port))
563              (coding-system-for-read imap-coding-system-for-read)
564              (coding-system-for-write imap-coding-system-for-write)
565              (process-connection-type imap-process-connection-type)
566              (process (start-process
567                        name buffer shell-file-name shell-command-switch
568                        (format-spec
569                         cmd
570                         (format-spec-make
571                          ?s server
572                          ?p (number-to-string port)
573                          ?l imap-default-user))))
574              response)
575         (when process
576           (with-current-buffer buffer
577             (setq imap-client-eol "\n"
578                   imap-calculate-literal-size-first t)
579             (while (and (memq (process-status process) '(open run))
580                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
581                         (goto-char (point-min))
582                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
583                         (or (while (looking-at "^C:")
584                               (forward-line))
585                             t)
586                         ;; cyrus 1.6 imtest print "S: " before server greeting
587                         (or (not (looking-at "S: "))
588                             (forward-char 3)
589                             t)
590                         (not (and (imap-parse-greeting)
591                                   ;; success in imtest 1.6:
592                                   (re-search-forward
593                                    (concat "^\\(\\(Authenticat.*\\)\\|\\("
594                                            "Client authentication "
595                                            "finished.*\\)\\)")
596                                    nil t)
597                                   (setq response (match-string 1)))))
598               (accept-process-output process 1)
599               (sit-for 1))
600             (and imap-log
601                  (with-current-buffer (get-buffer-create imap-log-buffer)
602                    (imap-disable-multibyte)
603                    (buffer-disable-undo)
604                    (goto-char (point-max))
605                    (insert-buffer-substring buffer)))
606             (erase-buffer)
607             (message "GSSAPI IMAP connection: %s" (or response "failed"))
608             (if (and response (let ((case-fold-search nil))
609                                 (not (string-match "failed" response))))
610                 (setq done process)
611               (if (memq (process-status process) '(open run))
612                   (imap-send-command "LOGOUT"))
613               (delete-process process)
614               nil)))))
615     done))
616
617 (defun imap-ssl-p (buffer)
618   nil)
619
620 (defun imap-ssl-open (name buffer server port)
621   "Open a SSL connection to server."
622   (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
623                 (list imap-ssl-program)))
624         cmd done)
625     (while (and (not done) (setq cmd (pop cmds)))
626       (message "imap: Opening SSL connection with `%s'..." cmd)
627       (erase-buffer)
628       (let* ((port (or port imap-default-ssl-port))
629              (coding-system-for-read imap-coding-system-for-read)
630              (coding-system-for-write imap-coding-system-for-write)
631              (process-connection-type nil)
632              process)
633         (when (progn
634                 (setq process (start-process
635                                name buffer shell-file-name
636                                shell-command-switch
637                                (format-spec cmd
638                                             (format-spec-make
639                                              ?s server
640                                              ?p (number-to-string port)))))
641                 (process-kill-without-query process)
642                 process)
643           (with-current-buffer buffer
644             (goto-char (point-min))
645             (while (and (memq (process-status process) '(open run))
646                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
647                         (goto-char (point-max))
648                         (forward-line -1)
649                         (not (imap-parse-greeting)))
650               (accept-process-output process 1)
651               (sit-for 1))
652             (and imap-log
653                  (with-current-buffer (get-buffer-create imap-log-buffer)
654                    (imap-disable-multibyte)
655                    (buffer-disable-undo)
656                    (goto-char (point-max))
657                    (insert-buffer-substring buffer)))
658             (erase-buffer)
659             (when (memq (process-status process) '(open run))
660               (setq done process))))))
661     (if done
662         (progn
663           (message "imap: Opening SSL connection with `%s'...done" cmd)
664           done)
665       (message "imap: Opening SSL connection with `%s'...failed" cmd)
666       nil)))
667
668 (defun imap-tls-p (buffer)
669   nil)
670
671 (defun imap-tls-open (name buffer server port)
672   (let* ((port (or port imap-default-tls-port))
673          (coding-system-for-read imap-coding-system-for-read)
674          (coding-system-for-write imap-coding-system-for-write)
675          (process (open-tls-stream name buffer server port)))
676     (when process
677       (while (and (memq (process-status process) '(open run))
678                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
679                   (goto-char (point-max))
680                   (forward-line -1)
681                   (not (imap-parse-greeting)))
682         (accept-process-output process 1)
683         (sit-for 1))
684       (and imap-log
685            (with-current-buffer (get-buffer-create imap-log-buffer)
686              (imap-disable-multibyte)
687              (buffer-disable-undo)
688              (goto-char (point-max))
689              (insert-buffer-substring buffer)))
690       (when (memq (process-status process) '(open run))
691         process))))
692
693 (defun imap-network-p (buffer)
694   t)
695
696 (defun imap-network-open (name buffer server port)
697   (let* ((port (or port imap-default-port))
698          (coding-system-for-read imap-coding-system-for-read)
699          (coding-system-for-write imap-coding-system-for-write)
700          (process (open-network-stream name buffer server port)))
701     (when process
702       (while (and (memq (process-status process) '(open run))
703                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
704                   (goto-char (point-min))
705                   (not (imap-parse-greeting)))
706         (accept-process-output process 1)
707         (sit-for 1))
708       (and imap-log
709            (with-current-buffer (get-buffer-create imap-log-buffer)
710              (imap-disable-multibyte)
711              (buffer-disable-undo)
712              (goto-char (point-max))
713              (insert-buffer-substring buffer)))
714       (when (memq (process-status process) '(open run))
715         process))))
716
717 (defun imap-shell-p (buffer)
718   nil)
719
720 (defun imap-shell-open (name buffer server port)
721   (let ((cmds (if (listp imap-shell-program) imap-shell-program
722                 (list imap-shell-program)))
723         cmd done)
724     (while (and (not done) (setq cmd (pop cmds)))
725       (message "imap: Opening IMAP connection with `%s'..." cmd)
726       (setq imap-client-eol "\n")
727       (let* ((port (or port imap-default-port))
728              (coding-system-for-read imap-coding-system-for-read)
729              (coding-system-for-write imap-coding-system-for-write)
730              (process (start-process
731                        name buffer shell-file-name shell-command-switch
732                        (format-spec
733                         cmd
734                         (format-spec-make
735                          ?s server
736                          ?g imap-shell-host
737                          ?p (number-to-string port)
738                          ?l imap-default-user)))))
739         (when process
740           (while (and (memq (process-status process) '(open run))
741                       (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
742                       (goto-char (point-max))
743                       (forward-line -1)
744                       (not (imap-parse-greeting)))
745             (accept-process-output process 1)
746             (sit-for 1))
747           (and imap-log
748                (with-current-buffer (get-buffer-create imap-log-buffer)
749                  (imap-disable-multibyte)
750                  (buffer-disable-undo)
751                  (goto-char (point-max))
752                  (insert-buffer-substring buffer)))
753           (erase-buffer)
754           (when (memq (process-status process) '(open run))
755             (setq done process)))))
756     (if done
757         (progn
758           (message "imap: Opening IMAP connection with `%s'...done" cmd)
759           done)
760       (message "imap: Opening IMAP connection with `%s'...failed" cmd)
761       nil)))
762
763 (defun imap-starttls-p (buffer)
764   (imap-capability 'STARTTLS buffer))
765
766 (defun imap-starttls-open (name buffer server port)
767   (let* ((port (or port imap-default-port))
768          (coding-system-for-read imap-coding-system-for-read)
769          (coding-system-for-write imap-coding-system-for-write)
770          (process (starttls-open-stream name buffer server port))
771          done tls-info)
772     (message "imap: Connecting with STARTTLS...")
773     (when process
774       (while (and (memq (process-status process) '(open run))
775                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
776                   (goto-char (point-max))
777                   (forward-line -1)
778                   (not (imap-parse-greeting)))
779         (accept-process-output process 1)
780         (sit-for 1))
781       (imap-send-command "STARTTLS")
782       (while (and (memq (process-status process) '(open run))
783                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
784                   (goto-char (point-max))
785                   (forward-line -1)
786                   (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
787         (accept-process-output process 1)
788         (sit-for 1))
789       (and imap-log
790            (with-current-buffer (get-buffer-create imap-log-buffer)
791              (buffer-disable-undo)
792              (goto-char (point-max))
793              (insert-buffer-substring buffer)))
794       (when (and (setq tls-info (starttls-negotiate process))
795                  (memq (process-status process) '(open run)))
796         (setq done process)))
797     (if (stringp tls-info)
798         (message "imap: STARTTLS info: %s" tls-info))
799     (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
800     done))
801
802 ;; Server functions; authenticator stuff:
803
804 (defun imap-interactive-login (buffer loginfunc)
805   "Login to server in BUFFER.
806 LOGINFUNC is passed a username and a password, it should return t if
807 it where successful authenticating itself to the server, nil otherwise.
808 Returns t if login was successful, nil otherwise."
809   (with-current-buffer buffer
810     (make-local-variable 'imap-username)
811     (make-local-variable 'imap-password)
812     (let (user passwd ret)
813       ;;      (condition-case ()
814       (while (or (not user) (not passwd))
815         (setq user (or imap-username
816                        (read-from-minibuffer
817                         (concat "IMAP username for " imap-server
818                                 " (using stream `" (symbol-name imap-stream)
819                                 "'): ")
820                         (or user imap-default-user))))
821         (setq passwd (or imap-password
822                          (read-passwd
823                           (concat "IMAP password for " user "@"
824                                   imap-server " (using authenticator `"
825                                   (symbol-name imap-auth) "'): "))))
826         (when (and user passwd)
827           (if (funcall loginfunc user passwd)
828               (progn
829                 (setq ret t
830                       imap-username user)
831                 (when (and (not imap-password)
832                            (or imap-store-password
833                                (y-or-n-p "Store password for this session? ")))
834                   (setq imap-password passwd)))
835             (message "Login failed...")
836             (setq passwd nil)
837             (setq imap-password nil)
838             (sit-for 1))))
839       ;;        (quit (with-current-buffer buffer
840       ;;                (setq user nil
841       ;;                      passwd nil)))
842       ;;        (error (with-current-buffer buffer
843       ;;                 (setq user nil
844       ;;                       passwd nil))))
845       ret)))
846
847 (defun imap-gssapi-auth-p (buffer)
848   (eq imap-stream 'gssapi))
849
850 (defun imap-gssapi-auth (buffer)
851   (message "imap: Authenticating using GSSAPI...%s"
852            (if (eq imap-stream 'gssapi) "done" "failed"))
853   (eq imap-stream 'gssapi))
854
855 (defun imap-kerberos4-auth-p (buffer)
856   (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
857        (eq imap-stream 'kerberos4)))
858
859 (defun imap-kerberos4-auth (buffer)
860   (message "imap: Authenticating using Kerberos 4...%s"
861            (if (eq imap-stream 'kerberos4) "done" "failed"))
862   (eq imap-stream 'kerberos4))
863
864 (defun imap-cram-md5-p (buffer)
865   (imap-capability 'AUTH=CRAM-MD5 buffer))
866
867 (defun imap-cram-md5-auth (buffer)
868   "Login to server using the AUTH CRAM-MD5 method."
869   (message "imap: Authenticating using CRAM-MD5...")
870   (let ((done (imap-interactive-login
871                buffer
872                (lambda (user passwd)
873                  (imap-ok-p
874                   (imap-send-command-wait
875                    (list
876                     "AUTHENTICATE CRAM-MD5"
877                     (lambda (challenge)
878                       (let* ((decoded (base64-decode-string challenge))
879                              (hash (rfc2104-hash 'md5 64 16 passwd decoded))
880                              (response (concat user " " hash))
881                              (encoded (base64-encode-string response)))
882                         encoded)))))))))
883     (if done
884         (message "imap: Authenticating using CRAM-MD5...done")
885       (message "imap: Authenticating using CRAM-MD5...failed"))))
886
887 (defun imap-login-p (buffer)
888   (and (not (imap-capability 'LOGINDISABLED buffer))
889        (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
890
891 (defun imap-login-auth (buffer)
892   "Login to server using the LOGIN command."
893   (message "imap: Plaintext authentication...")
894   (imap-interactive-login buffer
895                           (lambda (user passwd)
896                             (imap-ok-p (imap-send-command-wait
897                                         (concat "LOGIN \"" user "\" \""
898                                                 passwd "\""))))))
899
900 (defun imap-anonymous-p (buffer)
901   t)
902
903 (defun imap-anonymous-auth (buffer)
904   (message "imap: Logging in anonymously...")
905   (with-current-buffer buffer
906     (imap-ok-p (imap-send-command-wait
907                 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
908                                                      (system-name)) "\"")))))
909
910 (defun imap-sasl-make-mechanisms (buffer)
911   (let ((mecs '()))
912     (mapc (lambda (sym)
913             (let ((name (symbol-name sym)))
914               (if (and (> (length name) 5)
915                        (string-equal "AUTH=" (substring name 0 5 )))
916                   (setq mecs (cons (substring name 5) mecs)))))
917           (imap-capability nil buffer))
918     mecs))
919
920 (defun imap-sasl-auth-p (buffer)
921   (and (condition-case ()
922            (require 'sasl)
923          (error nil))
924        (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
925
926 (defun imap-sasl-auth (buffer)
927   "Login to server using the SASL method."
928   (message "imap: Authenticating using SASL...")
929   (with-current-buffer buffer
930     (make-local-variable 'imap-username)
931     (make-local-variable 'imap-sasl-client)
932     (make-local-variable 'imap-sasl-step)
933     (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
934           logged user)
935       (while (not logged)
936         (setq user (or imap-username
937                        (read-from-minibuffer
938                         (concat "IMAP username for " imap-server " using SASL "
939                                 (sasl-mechanism-name mechanism) ": ")
940                         (or user imap-default-user))))
941         (when user
942           (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
943                 imap-sasl-step (sasl-next-step imap-sasl-client nil))
944           (let ((tag (imap-send-command
945                       (if (sasl-step-data imap-sasl-step)
946                           (format "AUTHENTICATE %s %s"
947                                   (sasl-mechanism-name mechanism)
948                                   (sasl-step-data imap-sasl-step))
949                         (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
950                       buffer)))
951             (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
952               (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
953               (setq imap-continuation nil
954                     imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
955               (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
956                                        (base64-encode-string (sasl-step-data imap-sasl-step) t)
957                                      "")))
958             (if (imap-ok-p (imap-wait-for-tag tag))
959                 (setq imap-username user
960                       logged t)
961               (message "Login failed...")
962               (sit-for 1)))))
963       logged)))
964
965 (defun imap-digest-md5-p (buffer)
966   (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
967        (condition-case ()
968            (require 'digest-md5)
969          (error nil))))
970
971 (defun imap-digest-md5-auth (buffer)
972   "Login to server using the AUTH DIGEST-MD5 method."
973   (message "imap: Authenticating using DIGEST-MD5...")
974   (imap-interactive-login
975    buffer
976    (lambda (user passwd)
977      (let ((tag
978             (imap-send-command
979              (list
980               "AUTHENTICATE DIGEST-MD5"
981               (lambda (challenge)
982                 (digest-md5-parse-digest-challenge
983                  (base64-decode-string challenge))
984                 (let* ((digest-uri
985                         (digest-md5-digest-uri
986                          "imap" (digest-md5-challenge 'realm)))
987                        (response
988                         (digest-md5-digest-response
989                          user passwd digest-uri)))
990                   (base64-encode-string response 'no-line-break))))
991              )))
992        (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
993            nil
994          (setq imap-continuation nil)
995          (imap-send-command-1 "")
996          (imap-ok-p (imap-wait-for-tag tag)))))))
997
998 ;; Server functions:
999
1000 (defun imap-open-1 (buffer)
1001   (with-current-buffer buffer
1002     (erase-buffer)
1003     (setq imap-current-mailbox nil
1004           imap-current-message nil
1005           imap-state 'initial
1006           imap-process (condition-case ()
1007                            (funcall (nth 2 (assq imap-stream
1008                                                  imap-stream-alist))
1009                                     "imap" buffer imap-server imap-port)
1010                          ((error quit) nil)))
1011     (when imap-process
1012       (set-process-filter imap-process 'imap-arrival-filter)
1013       (set-process-sentinel imap-process 'imap-sentinel)
1014       (while (and (eq imap-state 'initial)
1015                   (memq (process-status imap-process) '(open run)))
1016         (message "Waiting for response from %s..." imap-server)
1017         (accept-process-output imap-process 1))
1018       (message "Waiting for response from %s...done" imap-server)
1019       (and (memq (process-status imap-process) '(open run))
1020            imap-process))))
1021
1022 (defun imap-open (server &optional port stream auth buffer)
1023   "Open a IMAP connection to host SERVER at PORT returning a buffer.
1024 If PORT is unspecified, a default value is used (143 except
1025 for SSL which use 993).
1026 STREAM indicates the stream to use, see `imap-streams' for available
1027 streams.  If nil, it choices the best stream the server is capable of.
1028 AUTH indicates authenticator to use, see `imap-authenticators' for
1029 available authenticators.  If nil, it choices the best stream the
1030 server is capable of.
1031 BUFFER can be a buffer or a name of a buffer, which is created if
1032 necessary.  If nil, the buffer name is generated."
1033   (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1034   (with-current-buffer (get-buffer-create buffer)
1035     (if (imap-opened buffer)
1036         (imap-close buffer))
1037     (mapcar 'make-local-variable imap-local-variables)
1038     (imap-disable-multibyte)
1039     (buffer-disable-undo)
1040     (setq imap-server (or server imap-server))
1041     (setq imap-port (or port imap-port))
1042     (setq imap-auth (or auth imap-auth))
1043     (setq imap-stream (or stream imap-stream))
1044     (message "imap: Connecting to %s..." imap-server)
1045     (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1046                 (imap-open-1 buffer)))
1047         (progn
1048           (message "imap: Connecting to %s...failed" imap-server)
1049           nil)
1050       (when (null imap-stream)
1051         ;; Need to choose stream.
1052         (let ((streams imap-streams))
1053           (while (setq stream (pop streams))
1054             ;; OK to use this stream?
1055             (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1056               ;; Stream changed?
1057               (if (not (eq imap-default-stream stream))
1058                   (with-current-buffer (get-buffer-create
1059                                         (generate-new-buffer-name " *temp*"))
1060                     (mapcar 'make-local-variable imap-local-variables)
1061                     (imap-disable-multibyte)
1062                     (buffer-disable-undo)
1063                     (setq imap-server (or server imap-server))
1064                     (setq imap-port (or port imap-port))
1065                     (setq imap-auth (or auth imap-auth))
1066                     (message "imap: Reconnecting with stream `%s'..." stream)
1067                     (if (null (let ((imap-stream stream))
1068                                 (imap-open-1 (current-buffer))))
1069                         (progn
1070                           (kill-buffer (current-buffer))
1071                           (message
1072                            "imap: Reconnecting with stream `%s'...failed"
1073                            stream))
1074                       ;; We're done, kill the first connection
1075                       (imap-close buffer)
1076                       (kill-buffer buffer)
1077                       (rename-buffer buffer)
1078                       (message "imap: Reconnecting with stream `%s'...done"
1079                                stream)
1080                       (setq imap-stream stream)
1081                       (setq imap-capability nil)
1082                       (setq streams nil)))
1083                 ;; We're done
1084                 (message "imap: Connecting to %s...done" imap-server)
1085                 (setq imap-stream stream)
1086                 (setq imap-capability nil)
1087                 (setq streams nil))))))
1088       (when (imap-opened buffer)
1089         (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1090       (when imap-stream
1091         buffer))))
1092
1093 (defun imap-opened (&optional buffer)
1094   "Return non-nil if connection to imap server in BUFFER is open.
1095 If BUFFER is nil then the current buffer is used."
1096   (and (setq buffer (get-buffer (or buffer (current-buffer))))
1097        (buffer-live-p buffer)
1098        (with-current-buffer buffer
1099          (and imap-process
1100               (memq (process-status imap-process) '(open run))))))
1101
1102 (defun imap-authenticate (&optional user passwd buffer)
1103   "Authenticate to server in BUFFER, using current buffer if nil.
1104 It uses the authenticator specified when opening the server.  If the
1105 authenticator requires username/passwords, they are queried from the
1106 user and optionally stored in the buffer.  If USER and/or PASSWD is
1107 specified, the user will not be questioned and the username and/or
1108 password is remembered in the buffer."
1109   (with-current-buffer (or buffer (current-buffer))
1110     (if (not (eq imap-state 'nonauth))
1111         (or (eq imap-state 'auth)
1112             (eq imap-state 'select)
1113             (eq imap-state 'examine))
1114       (make-local-variable 'imap-username)
1115       (make-local-variable 'imap-password)
1116       (if user (setq imap-username user))
1117       (if passwd (setq imap-password passwd))
1118       (if imap-auth
1119           (and (funcall (nth 2 (assq imap-auth
1120                                      imap-authenticator-alist)) buffer)
1121                (setq imap-state 'auth))
1122         ;; Choose authenticator.
1123         (let ((auths imap-authenticators)
1124               auth)
1125           (while (setq auth (pop auths))
1126             ;; OK to use authenticator?
1127             (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1128               (message "imap: Authenticating to `%s' using `%s'..."
1129                        imap-server auth)
1130               (setq imap-auth auth)
1131               (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1132                   (progn
1133                     (message "imap: Authenticating to `%s' using `%s'...done"
1134                              imap-server auth)
1135                     (setq auths nil))
1136                 (message "imap: Authenticating to `%s' using `%s'...failed"
1137                          imap-server auth)))))
1138         imap-state))))
1139
1140 (defun imap-close (&optional buffer)
1141   "Close connection to server in BUFFER.
1142 If BUFFER is nil, the current buffer is used."
1143   (with-current-buffer (or buffer (current-buffer))
1144     (when (imap-opened)
1145       (condition-case nil
1146           (imap-send-command-wait "LOGOUT")
1147         (quit nil)))
1148     (when (and imap-process
1149                (memq (process-status imap-process) '(open run)))
1150       (delete-process imap-process))
1151     (setq imap-current-mailbox nil
1152           imap-current-message nil
1153           imap-process nil)
1154     (erase-buffer)
1155     t))
1156
1157 (defun imap-capability (&optional identifier buffer)
1158   "Return a list of identifiers which server in BUFFER support.
1159 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1160 If BUFFER is nil, the current buffer is assumed."
1161   (with-current-buffer (or buffer (current-buffer))
1162     (unless imap-capability
1163       (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1164         (setq imap-capability '(IMAP2))))
1165     (if identifier
1166         (memq (intern (upcase (symbol-name identifier))) imap-capability)
1167       imap-capability)))
1168
1169 (defun imap-id (&optional list-of-values buffer)
1170   "Identify client to server in BUFFER, and return server identity.
1171 LIST-OF-VALUES is nil, or a plist with identifier and value
1172 strings to send to the server to identify the client.
1173
1174 Return a list of identifiers which server in BUFFER support, or
1175 nil if it doesn't support ID or returns no information.
1176
1177 If BUFFER is nil, the current buffer is assumed."
1178   (with-current-buffer (or buffer (current-buffer))
1179     (when (and (imap-capability 'ID)
1180                (imap-ok-p (imap-send-command-wait
1181                            (if (null list-of-values)
1182                                "ID NIL"
1183                              (concat "ID (" (mapconcat (lambda (el)
1184                                                          (concat "\"" el "\""))
1185                                                        list-of-values
1186                                                        " ") ")")))))
1187       imap-id)))
1188
1189 (defun imap-namespace (&optional buffer)
1190   "Return a namespace hierarchy at server in BUFFER.
1191 If BUFFER is nil, the current buffer is assumed."
1192   (with-current-buffer (or buffer (current-buffer))
1193     (unless imap-namespace
1194       (when (imap-capability 'NAMESPACE)
1195         (imap-send-command-wait "NAMESPACE")))
1196     imap-namespace))
1197
1198 (defun imap-send-command-wait (command &optional buffer)
1199   (imap-wait-for-tag (imap-send-command command buffer) buffer))
1200
1201 \f
1202 ;; Mailbox functions:
1203
1204 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1205   (with-current-buffer (or buffer (current-buffer))
1206     (if imap-mailbox-data
1207         (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1208              propname value)
1209       (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1210              propname value mailbox (current-buffer)))
1211     t))
1212
1213 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1214   (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1215        propname))
1216
1217 (defun imap-mailbox-get (propname &optional mailbox buffer)
1218   (let ((mailbox (imap-utf7-encode mailbox)))
1219     (with-current-buffer (or buffer (current-buffer))
1220       (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1221
1222 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1223   (with-current-buffer (or buffer (current-buffer))
1224     (let (result)
1225       (mapatoms
1226        (lambda (s)
1227          (push (funcall func (if mailbox-decoder
1228                                  (funcall mailbox-decoder (symbol-name s))
1229                                (symbol-name s))) result))
1230        imap-mailbox-data)
1231       result)))
1232
1233 (defun imap-mailbox-map (func &optional buffer)
1234   "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1235 Function should take a mailbox name (a string) as
1236 the only argument."
1237   (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1238
1239 (defun imap-current-mailbox (&optional buffer)
1240   (with-current-buffer (or buffer (current-buffer))
1241     (imap-utf7-decode imap-current-mailbox)))
1242
1243 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1244   (and (string= mailbox imap-current-mailbox)
1245        (or (and examine
1246                 (eq imap-state 'examine))
1247            (and (not examine)
1248                 (eq imap-state 'selected)))))
1249
1250 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1251   (with-current-buffer (or buffer (current-buffer))
1252     (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1253
1254 (defun imap-mailbox-select-1 (mailbox &optional examine)
1255   "Select MAILBOX on server in BUFFER.
1256 If EXAMINE is non-nil, do a read-only select."
1257   (if (imap-current-mailbox-p-1 mailbox examine)
1258       imap-current-mailbox
1259     (setq imap-current-mailbox mailbox)
1260     (if (imap-ok-p (imap-send-command-wait
1261                     (concat (if examine "EXAMINE" "SELECT") " \""
1262                             mailbox "\"")))
1263         (progn
1264           (setq imap-message-data (make-vector imap-message-prime 0)
1265                 imap-state (if examine 'examine 'selected))
1266           imap-current-mailbox)
1267       ;; Failed SELECT/EXAMINE unselects current mailbox
1268       (setq imap-current-mailbox nil))))
1269
1270 (defun imap-mailbox-select (mailbox &optional examine buffer)
1271   (with-current-buffer (or buffer (current-buffer))
1272     (imap-utf7-decode
1273      (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1274
1275 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1276   (with-current-buffer (or buffer (current-buffer))
1277     (imap-mailbox-select-1 mailbox 'examine)))
1278
1279 (defun imap-mailbox-examine (mailbox &optional buffer)
1280   "Examine MAILBOX on server in BUFFER."
1281   (imap-mailbox-select mailbox 'examine buffer))
1282
1283 (defun imap-mailbox-unselect (&optional buffer)
1284   "Close current folder in BUFFER, without expunging articles."
1285   (with-current-buffer (or buffer (current-buffer))
1286     (when (or (eq imap-state 'auth)
1287               (and (imap-capability 'UNSELECT)
1288                    (imap-ok-p (imap-send-command-wait "UNSELECT")))
1289               (and (imap-ok-p
1290                     (imap-send-command-wait (concat "EXAMINE \""
1291                                                     imap-current-mailbox
1292                                                     "\"")))
1293                    (imap-ok-p (imap-send-command-wait "CLOSE"))))
1294       (setq imap-current-mailbox nil
1295             imap-message-data nil
1296             imap-state 'auth)
1297       t)))
1298
1299 (defun imap-mailbox-expunge (&optional asynch buffer)
1300   "Expunge articles in current folder in BUFFER.
1301 If ASYNCH, do not wait for succesful completion of the command.
1302 If BUFFER is nil the current buffer is assumed."
1303   (with-current-buffer (or buffer (current-buffer))
1304     (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1305       (if asynch
1306           (imap-send-command "EXPUNGE")
1307       (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1308
1309 (defun imap-mailbox-close (&optional asynch buffer)
1310   "Expunge articles and close current folder in BUFFER.
1311 If ASYNCH, do not wait for succesful completion of the command.
1312 If BUFFER is nil the current buffer is assumed."
1313   (with-current-buffer (or buffer (current-buffer))
1314     (when imap-current-mailbox
1315       (if asynch
1316           (imap-add-callback (imap-send-command "CLOSE")
1317                              `(lambda (tag status)
1318                                 (message "IMAP mailbox `%s' closed... %s"
1319                                          imap-current-mailbox status)
1320                                 (when (eq ,imap-current-mailbox
1321                                           imap-current-mailbox)
1322                                   ;; Don't wipe out data if another mailbox
1323                                   ;; was selected...
1324                                   (setq imap-current-mailbox nil
1325                                         imap-message-data nil
1326                                         imap-state 'auth))))
1327         (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1328           (setq imap-current-mailbox nil
1329                 imap-message-data nil
1330                 imap-state 'auth)))
1331       t)))
1332
1333 (defun imap-mailbox-create-1 (mailbox)
1334   (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1335
1336 (defun imap-mailbox-create (mailbox &optional buffer)
1337   "Create MAILBOX on server in BUFFER.
1338 If BUFFER is nil the current buffer is assumed."
1339   (with-current-buffer (or buffer (current-buffer))
1340     (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1341
1342 (defun imap-mailbox-delete (mailbox &optional buffer)
1343   "Delete MAILBOX on server in BUFFER.
1344 If BUFFER is nil the current buffer is assumed."
1345   (let ((mailbox (imap-utf7-encode mailbox)))
1346     (with-current-buffer (or buffer (current-buffer))
1347       (imap-ok-p
1348        (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1349
1350 (defun imap-mailbox-rename (oldname newname &optional buffer)
1351   "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1352 If BUFFER is nil the current buffer is assumed."
1353   (let ((oldname (imap-utf7-encode oldname))
1354         (newname (imap-utf7-encode newname)))
1355     (with-current-buffer (or buffer (current-buffer))
1356       (imap-ok-p
1357        (imap-send-command-wait (list "RENAME \"" oldname "\" "
1358                                      "\"" newname "\""))))))
1359
1360 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1361   "Return a list of subscribed mailboxes on server in BUFFER.
1362 If ROOT is non-nil, only list matching mailboxes.  If ADD-DELIMITER is
1363 non-nil, a hierarchy delimiter is added to root.  REFERENCE is a
1364 implementation-specific string that has to be passed to lsub command."
1365   (with-current-buffer (or buffer (current-buffer))
1366     ;; Make sure we know the hierarchy separator for root's hierarchy
1367     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1368       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1369                                       (imap-utf7-encode root) "\"")))
1370     ;; clear list data (NB not delimiter and other stuff)
1371     (imap-mailbox-map-1 (lambda (mailbox)
1372                           (imap-mailbox-put 'lsub nil mailbox)))
1373     (when (imap-ok-p
1374            (imap-send-command-wait
1375             (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1376                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1377                     "%\"")))
1378       (let (out)
1379         (imap-mailbox-map-1 (lambda (mailbox)
1380                               (when (imap-mailbox-get-1 'lsub mailbox)
1381                                 (push (imap-utf7-decode mailbox) out))))
1382         (nreverse out)))))
1383
1384 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1385   "Return a list of mailboxes matching ROOT on server in BUFFER.
1386 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1387 root.  REFERENCE is a implementation-specific string that has to be
1388 passed to list command."
1389   (with-current-buffer (or buffer (current-buffer))
1390     ;; Make sure we know the hierarchy separator for root's hierarchy
1391     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1392       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1393                                       (imap-utf7-encode root) "\"")))
1394     ;; clear list data (NB not delimiter and other stuff)
1395     (imap-mailbox-map-1 (lambda (mailbox)
1396                           (imap-mailbox-put 'list nil mailbox)))
1397     (when (imap-ok-p
1398            (imap-send-command-wait
1399             (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1400                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1401                     "%\"")))
1402       (let (out)
1403         (imap-mailbox-map-1 (lambda (mailbox)
1404                               (when (imap-mailbox-get-1 'list mailbox)
1405                                 (push (imap-utf7-decode mailbox) out))))
1406         (nreverse out)))))
1407
1408 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1409   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1410 Returns non-nil if successful."
1411   (with-current-buffer (or buffer (current-buffer))
1412     (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1413                                                (imap-utf7-encode mailbox)
1414                                                "\"")))))
1415
1416 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1417   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1418 Returns non-nil if successful."
1419   (with-current-buffer (or buffer (current-buffer))
1420     (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1421                                                (imap-utf7-encode mailbox)
1422                                                "\"")))))
1423
1424 (defun imap-mailbox-status (mailbox items &optional buffer)
1425   "Get status items ITEM in MAILBOX from server in BUFFER.
1426 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1427 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1428 or 'unseen.  If ITEMS is a list of symbols, a list of values is
1429 returned, if ITEMS is a symbol only its value is returned."
1430   (with-current-buffer (or buffer (current-buffer))
1431     (when (imap-ok-p
1432            (imap-send-command-wait (list "STATUS \""
1433                                          (imap-utf7-encode mailbox)
1434                                          "\" "
1435                                          (upcase
1436                                           (format "%s"
1437                                                   (if (listp items)
1438                                                       items
1439                                                     (list items)))))))
1440       (if (listp items)
1441           (mapcar (lambda (item)
1442                     (imap-mailbox-get item mailbox))
1443                   items)
1444         (imap-mailbox-get items mailbox)))))
1445
1446 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1447   "Send status item request ITEM on MAILBOX to server in BUFFER.
1448 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1449 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1450 or 'unseen.  The IMAP command tag is returned."
1451   (with-current-buffer (or buffer (current-buffer))
1452     (imap-send-command (list "STATUS \""
1453                              (imap-utf7-encode mailbox)
1454                              "\" "
1455                              (format "%s"
1456                                      (if (listp items)
1457                                          items
1458                                        (list items)))))))
1459
1460 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1461   "Get ACL on mailbox from server in BUFFER."
1462   (let ((mailbox (imap-utf7-encode mailbox)))
1463     (with-current-buffer (or buffer (current-buffer))
1464       (when (imap-ok-p
1465              (imap-send-command-wait (list "GETACL \""
1466                                            (or mailbox imap-current-mailbox)
1467                                            "\"")))
1468         (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1469
1470 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1471   "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1472   (let ((mailbox (imap-utf7-encode mailbox)))
1473     (with-current-buffer (or buffer (current-buffer))
1474       (imap-ok-p
1475        (imap-send-command-wait (list "SETACL \""
1476                                      (or mailbox imap-current-mailbox)
1477                                      "\" "
1478                                      identifier
1479                                      " "
1480                                      rights))))))
1481
1482 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1483   "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1484   (let ((mailbox (imap-utf7-encode mailbox)))
1485     (with-current-buffer (or buffer (current-buffer))
1486       (imap-ok-p
1487        (imap-send-command-wait (list "DELETEACL \""
1488                                      (or mailbox imap-current-mailbox)
1489                                      "\" "
1490                                      identifier))))))
1491
1492 \f
1493 ;; Message functions:
1494
1495 (defun imap-current-message (&optional buffer)
1496   (with-current-buffer (or buffer (current-buffer))
1497     imap-current-message))
1498
1499 (defun imap-list-to-message-set (list)
1500   (mapconcat (lambda (item)
1501                (number-to-string item))
1502              (if (listp list)
1503                  list
1504                (list list))
1505              ","))
1506
1507 (defun imap-range-to-message-set (range)
1508   (mapconcat
1509    (lambda (item)
1510      (if (consp item)
1511          (format "%d:%d"
1512                  (car item) (cdr item))
1513        (format "%d" item)))
1514    (if (and (listp range) (not (listp (cdr range))))
1515        (list range) ;; make (1 . 2) into ((1 . 2))
1516      range)
1517    ","))
1518
1519 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1520   (with-current-buffer (or buffer (current-buffer))
1521     (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1522                                (if (listp uids)
1523                                    (imap-list-to-message-set uids)
1524                                  uids)
1525                                props))))
1526
1527 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1528   "Fetch properties PROPS from message set UIDS from server in BUFFER.
1529 UIDS can be a string, number or a list of numbers.  If RECEIVE
1530 is non-nil return theese properties."
1531   (with-current-buffer (or buffer (current-buffer))
1532     (when (imap-ok-p (imap-send-command-wait
1533                       (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1534                               (if (listp uids)
1535                                   (imap-list-to-message-set uids)
1536                                 uids)
1537                               props)))
1538       (if (or (null receive) (stringp uids))
1539           t
1540         (if (listp uids)
1541             (mapcar (lambda (uid)
1542                       (if (listp receive)
1543                           (mapcar (lambda (prop)
1544                                     (imap-message-get uid prop))
1545                                   receive)
1546                         (imap-message-get uid receive)))
1547                     uids)
1548           (imap-message-get uids receive))))))
1549
1550 (defun imap-message-put (uid propname value &optional buffer)
1551   (with-current-buffer (or buffer (current-buffer))
1552     (if imap-message-data
1553         (put (intern (number-to-string uid) imap-message-data)
1554              propname value)
1555       (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1556              uid propname value (current-buffer)))
1557     t))
1558
1559 (defun imap-message-get (uid propname &optional buffer)
1560   (with-current-buffer (or buffer (current-buffer))
1561     (get (intern-soft (number-to-string uid) imap-message-data)
1562          propname)))
1563
1564 (defun imap-message-map (func propname &optional buffer)
1565   "Map a function across each mailbox in `imap-message-data', returning a list."
1566   (with-current-buffer (or buffer (current-buffer))
1567     (let (result)
1568       (mapatoms
1569        (lambda (s)
1570          (push (funcall func (get s 'UID) (get s propname)) result))
1571        imap-message-data)
1572       result)))
1573
1574 (defmacro imap-message-envelope-date (uid &optional buffer)
1575   `(with-current-buffer (or ,buffer (current-buffer))
1576      (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1577
1578 (defmacro imap-message-envelope-subject (uid &optional buffer)
1579   `(with-current-buffer (or ,buffer (current-buffer))
1580      (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1581
1582 (defmacro imap-message-envelope-from (uid &optional buffer)
1583   `(with-current-buffer (or ,buffer (current-buffer))
1584      (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1585
1586 (defmacro imap-message-envelope-sender (uid &optional buffer)
1587   `(with-current-buffer (or ,buffer (current-buffer))
1588      (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1589
1590 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1591   `(with-current-buffer (or ,buffer (current-buffer))
1592      (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1593
1594 (defmacro imap-message-envelope-to (uid &optional buffer)
1595   `(with-current-buffer (or ,buffer (current-buffer))
1596      (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1597
1598 (defmacro imap-message-envelope-cc (uid &optional buffer)
1599   `(with-current-buffer (or ,buffer (current-buffer))
1600      (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1601
1602 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1603   `(with-current-buffer (or ,buffer (current-buffer))
1604      (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1605
1606 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1607   `(with-current-buffer (or ,buffer (current-buffer))
1608      (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1609
1610 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1611   `(with-current-buffer (or ,buffer (current-buffer))
1612      (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1613
1614 (defmacro imap-message-body (uid &optional buffer)
1615   `(with-current-buffer (or ,buffer (current-buffer))
1616      (imap-message-get ,uid 'BODY)))
1617
1618 (defun imap-search (predicate &optional buffer)
1619   (with-current-buffer (or buffer (current-buffer))
1620     (imap-mailbox-put 'search 'dummy)
1621     (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1622       (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1623           (progn
1624             (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1625             nil)
1626         (imap-mailbox-get-1 'search imap-current-mailbox)))))
1627
1628 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1629   "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1630   (with-current-buffer (or buffer (current-buffer))
1631     (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1632         (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1633
1634 (defun imap-message-flags-set (articles flags &optional silent buffer)
1635   (when (and articles flags)
1636     (with-current-buffer (or buffer (current-buffer))
1637       (imap-ok-p (imap-send-command-wait
1638                   (concat "UID STORE " articles
1639                           " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1640
1641 (defun imap-message-flags-del (articles flags &optional silent buffer)
1642   (when (and articles flags)
1643     (with-current-buffer (or buffer (current-buffer))
1644       (imap-ok-p (imap-send-command-wait
1645                   (concat "UID STORE " articles
1646                           " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1647
1648 (defun imap-message-flags-add (articles flags &optional silent buffer)
1649   (when (and articles flags)
1650     (with-current-buffer (or buffer (current-buffer))
1651       (imap-ok-p (imap-send-command-wait
1652                   (concat "UID STORE " articles
1653                           " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1654
1655 (defun imap-message-copyuid-1 (mailbox)
1656   (if (imap-capability 'UIDPLUS)
1657       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1658             (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1659     (let ((old-mailbox imap-current-mailbox)
1660           (state imap-state)
1661           (imap-message-data (make-vector 2 0)))
1662       (when (imap-mailbox-examine-1 mailbox)
1663         (prog1
1664             (and (imap-fetch "*" "UID")
1665                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1666                        (apply 'max (imap-message-map
1667                                     (lambda (uid prop) uid) 'UID))))
1668           (if old-mailbox
1669               (imap-mailbox-select old-mailbox (eq state 'examine))
1670             (imap-mailbox-unselect)))))))
1671
1672 (defun imap-message-copyuid (mailbox &optional buffer)
1673   (with-current-buffer (or buffer (current-buffer))
1674     (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1675
1676 (defun imap-message-copy (articles mailbox
1677                                    &optional dont-create no-copyuid buffer)
1678   "Copy ARTICLES (a string message set) to MAILBOX on server in
1679 BUFFER, creating mailbox if it doesn't exist.  If dont-create is
1680 non-nil, it will not create a mailbox.  On success, return a list with
1681 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1682 first element, rest of list contain the saved articles' UIDs."
1683   (when articles
1684     (with-current-buffer (or buffer (current-buffer))
1685       (let ((mailbox (imap-utf7-encode mailbox)))
1686         (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1687                   (imap-current-target-mailbox mailbox))
1688               (if (imap-ok-p (imap-send-command-wait cmd))
1689                   t
1690                 (when (and (not dont-create)
1691                            ;; removed because of buggy Oracle server
1692                            ;; that doesn't send TRYCREATE tags (which
1693                            ;; is a MUST according to specifications):
1694                            ;;(imap-mailbox-get-1 'trycreate mailbox)
1695                            (imap-mailbox-create-1 mailbox))
1696                   (imap-ok-p (imap-send-command-wait cmd)))))
1697             (or no-copyuid
1698                 (imap-message-copyuid-1 mailbox)))))))
1699
1700 (defun imap-message-appenduid-1 (mailbox)
1701   (if (imap-capability 'UIDPLUS)
1702       (imap-mailbox-get-1 'appenduid mailbox)
1703     (let ((old-mailbox imap-current-mailbox)
1704           (state imap-state)
1705           (imap-message-data (make-vector 2 0)))
1706       (when (imap-mailbox-examine-1 mailbox)
1707         (prog1
1708             (and (imap-fetch "*" "UID")
1709                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1710                        (apply 'max (imap-message-map
1711                                     (lambda (uid prop) uid) 'UID))))
1712           (if old-mailbox
1713               (imap-mailbox-select old-mailbox (eq state 'examine))
1714             (imap-mailbox-unselect)))))))
1715
1716 (defun imap-message-appenduid (mailbox &optional buffer)
1717   (with-current-buffer (or buffer (current-buffer))
1718     (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1719
1720 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1721   "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1722 FLAGS and DATE-TIME is currently not used.  Return a cons holding
1723 uidvalidity of MAILBOX and UID the newly created article got, or nil
1724 on failure."
1725   (let ((mailbox (imap-utf7-encode mailbox)))
1726     (with-current-buffer (or buffer (current-buffer))
1727       (and (let ((imap-current-target-mailbox mailbox))
1728              (imap-ok-p
1729               (imap-send-command-wait
1730                (list "APPEND \"" mailbox "\" "  article))))
1731            (imap-message-appenduid-1 mailbox)))))
1732
1733 (defun imap-body-lines (body)
1734   "Return number of lines in article by looking at the mime bodystructure BODY."
1735   (if (listp body)
1736       (if (stringp (car body))
1737           (cond ((and (string= (upcase (car body)) "TEXT")
1738                       (numberp (nth 7 body)))
1739                  (nth 7 body))
1740                 ((and (string= (upcase (car body)) "MESSAGE")
1741                       (numberp (nth 9 body)))
1742                  (nth 9 body))
1743                 (t 0))
1744         (apply '+ (mapcar 'imap-body-lines body)))
1745     0))
1746
1747 (defun imap-envelope-from (from)
1748   "Return a from string line."
1749   (and from
1750        (concat (aref from 0)
1751                (if (aref from 0) " <")
1752                (aref from 2)
1753                "@"
1754                (aref from 3)
1755                (if (aref from 0) ">"))))
1756
1757 \f
1758 ;; Internal functions.
1759
1760 (defun imap-add-callback (tag func)
1761   (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1762
1763 (defun imap-send-command-1 (cmdstr)
1764   (setq cmdstr (concat cmdstr imap-client-eol))
1765   (and imap-log
1766        (with-current-buffer (get-buffer-create imap-log-buffer)
1767          (imap-disable-multibyte)
1768          (buffer-disable-undo)
1769          (goto-char (point-max))
1770          (insert cmdstr)))
1771   (process-send-string imap-process cmdstr))
1772
1773 (defun imap-send-command (command &optional buffer)
1774   (with-current-buffer (or buffer (current-buffer))
1775     (if (not (listp command)) (setq command (list command)))
1776     (let ((tag (setq imap-tag (1+ imap-tag)))
1777           cmd cmdstr)
1778       (setq cmdstr (concat (number-to-string imap-tag) " "))
1779       (while (setq cmd (pop command))
1780         (cond ((stringp cmd)
1781                (setq cmdstr (concat cmdstr cmd)))
1782               ((bufferp cmd)
1783                (let ((eol imap-client-eol)
1784                      (calcfirst imap-calculate-literal-size-first)
1785                      size)
1786                  (with-current-buffer cmd
1787                    (if calcfirst
1788                        (setq size (buffer-size)))
1789                    (when (not (equal eol "\r\n"))
1790                      ;; XXX modifies buffer!
1791                      (goto-char (point-min))
1792                      (while (search-forward "\r\n" nil t)
1793                        (replace-match eol)))
1794                    (if (not calcfirst)
1795                        (setq size (buffer-size))))
1796                  (setq cmdstr
1797                        (concat cmdstr (format "{%d}" size))))
1798                (unwind-protect
1799                    (progn
1800                      (imap-send-command-1 cmdstr)
1801                      (setq cmdstr nil)
1802                      (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1803                          (setq command nil) ;; abort command if no cont-req
1804                        (let ((process imap-process)
1805                              (stream imap-stream)
1806                              (eol imap-client-eol))
1807                          (with-current-buffer cmd
1808                            (and imap-log
1809                                 (with-current-buffer (get-buffer-create
1810                                                       imap-log-buffer)
1811                                   (imap-disable-multibyte)
1812                                   (buffer-disable-undo)
1813                                   (goto-char (point-max))
1814                                   (insert-buffer-substring cmd)))
1815                            (process-send-region process (point-min)
1816                                                 (point-max)))
1817                          (process-send-string process imap-client-eol))))
1818                  (setq imap-continuation nil)))
1819               ((functionp cmd)
1820                (imap-send-command-1 cmdstr)
1821                (setq cmdstr nil)
1822                (unwind-protect
1823                    (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1824                        (setq command nil) ;; abort command if no cont-req
1825                      (setq command (cons (funcall cmd imap-continuation)
1826                                          command)))
1827                  (setq imap-continuation nil)))
1828               (t
1829                (error "Unknown command type"))))
1830       (if cmdstr
1831           (imap-send-command-1 cmdstr))
1832       tag)))
1833
1834 (defun imap-wait-for-tag (tag &optional buffer)
1835   (with-current-buffer (or buffer (current-buffer))
1836     (let (imap-have-messaged)
1837       (while (and (null imap-continuation)
1838                   (memq (process-status imap-process) '(open run))
1839                   (< imap-reached-tag tag))
1840         (let ((len (/ (point-max) 1024))
1841               message-log-max)
1842           (unless (< len 10)
1843             (setq imap-have-messaged t)
1844             (message "imap read: %dk" len))
1845           (accept-process-output imap-process
1846                                  (truncate imap-read-timeout)
1847                                  (truncate (* (- imap-read-timeout
1848                                                  (truncate imap-read-timeout))
1849                                               1000)))))
1850       ;; A process can die _before_ we have processed everything it
1851       ;; has to say.  Moreover, this can happen in between the call to
1852       ;; accept-process-output and the call to process-status in an
1853       ;; iteration of the loop above.
1854       (when (and (null imap-continuation)
1855                  (< imap-reached-tag tag))
1856         (accept-process-output imap-process 0 0))
1857       (when imap-have-messaged
1858         (message ""))
1859       (and (memq (process-status imap-process) '(open run))
1860            (or (assq tag imap-failed-tags)
1861                (if imap-continuation
1862                    'INCOMPLETE
1863                  'OK))))))
1864
1865 (defun imap-sentinel (process string)
1866   (delete-process process))
1867
1868 (defun imap-find-next-line ()
1869   "Return point at end of current line, taking into account literals.
1870 Return nil if no complete line has arrived."
1871   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1872                                    imap-server-eol)
1873                            nil t)
1874     (if (match-string 1)
1875         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1876             nil
1877           (goto-char (+ (point) (string-to-number (match-string 1))))
1878           (imap-find-next-line))
1879       (point))))
1880
1881 (defun imap-arrival-filter (proc string)
1882   "IMAP process filter."
1883   ;; Sometimes, we are called even though the process has died.
1884   ;; Better abstain from doing stuff in that case.
1885   (when (buffer-name (process-buffer proc))
1886     (with-current-buffer (process-buffer proc)
1887       (goto-char (point-max))
1888       (insert string)
1889       (and imap-log
1890            (with-current-buffer (get-buffer-create imap-log-buffer)
1891              (imap-disable-multibyte)
1892              (buffer-disable-undo)
1893              (goto-char (point-max))
1894              (insert string)))
1895       (let (end)
1896         (goto-char (point-min))
1897         (while (setq end (imap-find-next-line))
1898           (save-restriction
1899             (narrow-to-region (point-min) end)
1900             (delete-backward-char (length imap-server-eol))
1901             (goto-char (point-min))
1902             (unwind-protect
1903                 (cond ((eq imap-state 'initial)
1904                        (imap-parse-greeting))
1905                       ((or (eq imap-state 'auth)
1906                            (eq imap-state 'nonauth)
1907                            (eq imap-state 'selected)
1908                            (eq imap-state 'examine))
1909                        (imap-parse-response))
1910                       (t
1911                        (message "Unknown state %s in arrival filter"
1912                                 imap-state)))
1913               (delete-region (point-min) (point-max)))))))))
1914
1915 \f
1916 ;; Imap parser.
1917
1918 (defsubst imap-forward ()
1919   (or (eobp) (forward-char)))
1920
1921 ;;   number          = 1*DIGIT
1922 ;;                       ; Unsigned 32-bit integer
1923 ;;                       ; (0 <= n < 4,294,967,296)
1924
1925 (defsubst imap-parse-number ()
1926   (when (looking-at "[0-9]+")
1927     (prog1
1928         (string-to-number (match-string 0))
1929       (goto-char (match-end 0)))))
1930
1931 ;;   literal         = "{" number "}" CRLF *CHAR8
1932 ;;                       ; Number represents the number of CHAR8s
1933
1934 (defsubst imap-parse-literal ()
1935   (when (looking-at "{\\([0-9]+\\)}\r\n")
1936     (let ((pos (match-end 0))
1937           (len (string-to-number (match-string 1))))
1938       (if (< (point-max) (+ pos len))
1939           nil
1940         (goto-char (+ pos len))
1941         (buffer-substring pos (+ pos len))))))
1942
1943 ;;   string          = quoted / literal
1944 ;;
1945 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
1946 ;;
1947 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
1948 ;;                     "\" quoted-specials
1949 ;;
1950 ;;   quoted-specials = DQUOTE / "\"
1951 ;;
1952 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
1953
1954 (defsubst imap-parse-string ()
1955   (cond ((eq (char-after) ?\")
1956          (forward-char 1)
1957          (let ((p (point)) (name ""))
1958            (skip-chars-forward "^\"\\\\")
1959            (setq name (buffer-substring p (point)))
1960            (while (eq (char-after) ?\\)
1961              (setq p (1+ (point)))
1962              (forward-char 2)
1963              (skip-chars-forward "^\"\\\\")
1964              (setq name (concat name (buffer-substring p (point)))))
1965            (forward-char 1)
1966            name))
1967         ((eq (char-after) ?{)
1968          (imap-parse-literal))))
1969
1970 ;;   nil             = "NIL"
1971
1972 (defsubst imap-parse-nil ()
1973   (if (looking-at "NIL")
1974       (goto-char (match-end 0))))
1975
1976 ;;   nstring         = string / nil
1977
1978 (defsubst imap-parse-nstring ()
1979   (or (imap-parse-string)
1980       (and (imap-parse-nil)
1981            nil)))
1982
1983 ;;   astring         = atom / string
1984 ;;
1985 ;;   atom            = 1*ATOM-CHAR
1986 ;;
1987 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
1988 ;;
1989 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
1990 ;;                     quoted-specials
1991 ;;
1992 ;;   list-wildcards  = "%" / "*"
1993 ;;
1994 ;;   quoted-specials = DQUOTE / "\"
1995
1996 (defsubst imap-parse-astring ()
1997   (or (imap-parse-string)
1998       (buffer-substring (point)
1999                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2000                             (goto-char (1- (match-end 0)))
2001                           (end-of-line)
2002                           (point)))))
2003
2004 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
2005 ;;                      addr-host ")"
2006 ;;
2007 ;;   addr-adl        = nstring
2008 ;;                       ; Holds route from [RFC-822] route-addr if
2009 ;;                       ; non-nil
2010 ;;
2011 ;;   addr-host       = nstring
2012 ;;                       ; nil indicates [RFC-822] group syntax.
2013 ;;                       ; Otherwise, holds [RFC-822] domain name
2014 ;;
2015 ;;   addr-mailbox    = nstring
2016 ;;                       ; nil indicates end of [RFC-822] group; if
2017 ;;                       ; non-nil and addr-host is nil, holds
2018 ;;                       ; [RFC-822] group name.
2019 ;;                       ; Otherwise, holds [RFC-822] local-part
2020 ;;                       ; after removing [RFC-822] quoting
2021 ;;
2022 ;;   addr-name       = nstring
2023 ;;                       ; If non-nil, holds phrase from [RFC-822]
2024 ;;                       ; mailbox after removing [RFC-822] quoting
2025 ;;
2026
2027 (defsubst imap-parse-address ()
2028   (let (address)
2029     (when (eq (char-after) ?\()
2030       (imap-forward)
2031       (setq address (vector (prog1 (imap-parse-nstring)
2032                               (imap-forward))
2033                             (prog1 (imap-parse-nstring)
2034                               (imap-forward))
2035                             (prog1 (imap-parse-nstring)
2036                               (imap-forward))
2037                             (imap-parse-nstring)))
2038       (when (eq (char-after) ?\))
2039         (imap-forward)
2040         address))))
2041
2042 ;;   address-list    = "(" 1*address ")" / nil
2043 ;;
2044 ;;   nil             = "NIL"
2045
2046 (defsubst imap-parse-address-list ()
2047   (if (eq (char-after) ?\()
2048       (let (address addresses)
2049         (imap-forward)
2050         (while (and (not (eq (char-after) ?\)))
2051                     ;; next line for MS Exchange bug
2052                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
2053                     (setq address (imap-parse-address)))
2054           (setq addresses (cons address addresses)))
2055         (when (eq (char-after) ?\))
2056           (imap-forward)
2057           (nreverse addresses)))
2058     (assert (imap-parse-nil) t "In imap-parse-address-list")))
2059
2060 ;;   mailbox         = "INBOX" / astring
2061 ;;                       ; INBOX is case-insensitive.  All case variants of
2062 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2063 ;;                       ; not as an astring.  An astring which consists of
2064 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
2065 ;;                       ; is considered to be INBOX and not an astring.
2066 ;;                       ;  Refer to section 5.1 for further
2067 ;;                       ; semantic details of mailbox names.
2068
2069 (defsubst imap-parse-mailbox ()
2070   (let ((mailbox (imap-parse-astring)))
2071     (if (string-equal "INBOX" (upcase mailbox))
2072         "INBOX"
2073       mailbox)))
2074
2075 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2076 ;;
2077 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
2078 ;;                       ; Authentication condition
2079 ;;
2080 ;;   resp-cond-bye   = "BYE" SP resp-text
2081
2082 (defun imap-parse-greeting ()
2083   "Parse a IMAP greeting."
2084   (cond ((looking-at "\\* OK ")
2085          (setq imap-state 'nonauth))
2086         ((looking-at "\\* PREAUTH ")
2087          (setq imap-state 'auth))
2088         ((looking-at "\\* BYE ")
2089          (setq imap-state 'closed))))
2090
2091 ;;   response        = *(continue-req / response-data) response-done
2092 ;;
2093 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
2094 ;;
2095 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
2096 ;;                     mailbox-data / message-data / capability-data) CRLF
2097 ;;
2098 ;;   response-done   = response-tagged / response-fatal
2099 ;;
2100 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
2101 ;;                       ; Server closes connection immediately
2102 ;;
2103 ;;   response-tagged = tag SP resp-cond-state CRLF
2104 ;;
2105 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2106 ;;                       ; Status condition
2107 ;;
2108 ;;   resp-cond-bye   = "BYE" SP resp-text
2109 ;;
2110 ;;   mailbox-data    =  "FLAGS" SP flag-list /
2111 ;;                      "LIST" SP mailbox-list /
2112 ;;                      "LSUB" SP mailbox-list /
2113 ;;                      "SEARCH" *(SP nz-number) /
2114 ;;                      "STATUS" SP mailbox SP "("
2115 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
2116 ;;                      number SP "EXISTS" /
2117 ;;                      number SP "RECENT"
2118 ;;
2119 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2120 ;;
2121 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2122 ;;                     *(SP capability)
2123 ;;                       ; IMAP4rev1 servers which offer RFC 1730
2124 ;;                       ; compatibility MUST list "IMAP4" as the first
2125 ;;                       ; capability.
2126
2127 (defun imap-parse-response ()
2128   "Parse a IMAP command response."
2129   (let (token)
2130     (case (setq token (read (current-buffer)))
2131       (+ (setq imap-continuation
2132                (or (buffer-substring (min (point-max) (1+ (point)))
2133                                      (point-max))
2134                    t)))
2135       (* (case (prog1 (setq token (read (current-buffer)))
2136                  (imap-forward))
2137            (OK         (imap-parse-resp-text))
2138            (NO         (imap-parse-resp-text))
2139            (BAD        (imap-parse-resp-text))
2140            (BYE        (imap-parse-resp-text))
2141            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
2142            (LIST       (imap-parse-data-list 'list))
2143            (LSUB       (imap-parse-data-list 'lsub))
2144            (SEARCH     (imap-mailbox-put
2145                         'search
2146                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2147            (STATUS     (imap-parse-status))
2148            (CAPABILITY (setq imap-capability
2149                                (read (concat "(" (upcase (buffer-substring
2150                                                           (point) (point-max)))
2151                                              ")"))))
2152            (ID         (setq imap-id (read (buffer-substring (point)
2153                                                              (point-max)))))
2154            (ACL        (imap-parse-acl))
2155            (t       (case (prog1 (read (current-buffer))
2156                             (imap-forward))
2157                       (EXISTS  (imap-mailbox-put 'exists token))
2158                       (RECENT  (imap-mailbox-put 'recent token))
2159                       (EXPUNGE t)
2160                       (FETCH   (imap-parse-fetch token))
2161                       (t       (message "Garbage: %s" (buffer-string)))))))
2162       (t (let (status)
2163            (if (not (integerp token))
2164                (message "Garbage: %s" (buffer-string))
2165              (case (prog1 (setq status (read (current-buffer)))
2166                      (imap-forward))
2167                (OK  (progn
2168                       (setq imap-reached-tag (max imap-reached-tag token))
2169                       (imap-parse-resp-text)))
2170                (NO  (progn
2171                       (setq imap-reached-tag (max imap-reached-tag token))
2172                       (save-excursion
2173                         (imap-parse-resp-text))
2174                       (let (code text)
2175                         (when (eq (char-after) ?\[)
2176                           (setq code (buffer-substring (point)
2177                                                        (search-forward "]")))
2178                           (imap-forward))
2179                         (setq text (buffer-substring (point) (point-max)))
2180                         (push (list token status code text)
2181                               imap-failed-tags))))
2182                (BAD (progn
2183                       (setq imap-reached-tag (max imap-reached-tag token))
2184                       (save-excursion
2185                         (imap-parse-resp-text))
2186                       (let (code text)
2187                         (when (eq (char-after) ?\[)
2188                           (setq code (buffer-substring (point)
2189                                                        (search-forward "]")))
2190                           (imap-forward))
2191                         (setq text (buffer-substring (point) (point-max)))
2192                         (push (list token status code text) imap-failed-tags)
2193                         (error "Internal error, tag %s status %s code %s text %s"
2194                                token status code text))))
2195                (t   (message "Garbage: %s" (buffer-string))))
2196              (when (assq token imap-callbacks)
2197                (funcall (cdr (assq token imap-callbacks)) token status)
2198                (setq imap-callbacks
2199                      (imap-remassoc token imap-callbacks)))))))))
2200
2201 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2202 ;;
2203 ;;   text            = 1*TEXT-CHAR
2204 ;;
2205 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2206
2207 (defun imap-parse-resp-text ()
2208   (imap-parse-resp-text-code))
2209
2210 ;;   resp-text-code  = "ALERT" /
2211 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2212 ;;                     "NEWNAME" SP string SP string /
2213 ;;                     "PARSE" /
2214 ;;                     "PERMANENTFLAGS" SP "("
2215 ;;                               [flag-perm *(SP flag-perm)] ")" /
2216 ;;                     "READ-ONLY" /
2217 ;;                     "READ-WRITE" /
2218 ;;                     "TRYCREATE" /
2219 ;;                     "UIDNEXT" SP nz-number /
2220 ;;                     "UIDVALIDITY" SP nz-number /
2221 ;;                     "UNSEEN" SP nz-number /
2222 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2223 ;;
2224 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2225 ;;
2226 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2227 ;;
2228 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2229 ;;                        (set "," set)
2230 ;;                          ; Identifies a set of messages.  For message
2231 ;;                          ; sequence numbers, these are consecutive
2232 ;;                          ; numbers from 1 to the number of messages in
2233 ;;                          ; the mailbox
2234 ;;                          ; Comma delimits individual numbers, colon
2235 ;;                          ; delimits between two numbers inclusive.
2236 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2237 ;;                          ; 14,15 for a mailbox with 15 messages.
2238 ;;
2239 ;;   sequence-num    = nz-number / "*"
2240 ;;                          ; * is the largest number in use.  For message
2241 ;;                          ; sequence numbers, it is the number of messages
2242 ;;                          ; in the mailbox.  For unique identifiers, it is
2243 ;;                          ; the unique identifier of the last message in
2244 ;;                          ; the mailbox.
2245 ;;
2246 ;;   flag-perm       = flag / "\*"
2247 ;;
2248 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2249 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2250 ;;                       ; Does not include "\Recent"
2251 ;;
2252 ;;   flag-extension  = "\" atom
2253 ;;                       ; Future expansion.  Client implementations
2254 ;;                       ; MUST accept flag-extension flags.  Server
2255 ;;                       ; implementations MUST NOT generate
2256 ;;                       ; flag-extension flags except as defined by
2257 ;;                       ; future standard or standards-track
2258 ;;                       ; revisions of this specification.
2259 ;;
2260 ;;   flag-keyword    = atom
2261 ;;
2262 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2263
2264 (defun imap-parse-resp-text-code ()
2265   ;; xxx next line for stalker communigate pro 3.3.1 bug
2266   (when (looking-at " \\[")
2267     (imap-forward))
2268   (when (eq (char-after) ?\[)
2269     (imap-forward)
2270     (cond ((search-forward "PERMANENTFLAGS " nil t)
2271            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2272           ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2273            (imap-mailbox-put 'uidnext (match-string 1)))
2274           ((search-forward "UNSEEN " nil t)
2275            (imap-mailbox-put 'first-unseen (read (current-buffer))))
2276           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2277            (imap-mailbox-put 'uidvalidity (match-string 1)))
2278           ((search-forward "READ-ONLY" nil t)
2279            (imap-mailbox-put 'read-only t))
2280           ((search-forward "NEWNAME " nil t)
2281            (let (oldname newname)
2282              (setq oldname (imap-parse-string))
2283              (imap-forward)
2284              (setq newname (imap-parse-string))
2285              (imap-mailbox-put 'newname newname oldname)))
2286           ((search-forward "TRYCREATE" nil t)
2287            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2288           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2289            (imap-mailbox-put 'appenduid
2290                              (list (match-string 1)
2291                                    (string-to-number (match-string 2)))
2292                              imap-current-target-mailbox))
2293           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2294            (imap-mailbox-put 'copyuid (list (match-string 1)
2295                                             (match-string 2)
2296                                             (match-string 3))
2297                              imap-current-target-mailbox))
2298           ((search-forward "ALERT] " nil t)
2299            (message "Imap server %s information: %s" imap-server
2300                     (buffer-substring (point) (point-max)))))))
2301
2302 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2303 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2304 ;;
2305 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2306 ;;                     *(SP mbx-list-oflag) /
2307 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2308 ;;
2309 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2310 ;;                       ; Other flags; multiple possible per LIST response
2311 ;;
2312 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2313 ;;                       ; Selectability flags; only one per LIST response
2314 ;;
2315 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2316 ;;                     "\" quoted-specials
2317 ;;
2318 ;;   quoted-specials = DQUOTE / "\"
2319
2320 (defun imap-parse-data-list (type)
2321   (let (flags delimiter mailbox)
2322     (setq flags (imap-parse-flag-list))
2323     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2324       (setq delimiter (match-string 1))
2325       (goto-char (1+ (match-end 0)))
2326       (when (setq mailbox (imap-parse-mailbox))
2327         (imap-mailbox-put type t mailbox)
2328         (imap-mailbox-put 'list-flags flags mailbox)
2329         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2330
2331 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2332 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2333 ;;                      "INTERNALDATE" SPACE date_time /
2334 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2335 ;;                      "RFC822.SIZE" SPACE number /
2336 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2337 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2338 ;;                      "UID" SPACE uniqueid) ")"
2339 ;;
2340 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2341 ;;                      SPACE time SPACE zone <">
2342 ;;
2343 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2344 ;;                      ["." (section_text / "MIME")])] "]"
2345 ;;
2346 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2347 ;;                      SPACE header_list / "TEXT"
2348 ;;
2349 ;;  header_fld_name ::= astring
2350 ;;
2351 ;;  header_list     ::= "(" 1#header_fld_name ")"
2352
2353 (defsubst imap-parse-header-list ()
2354   (when (eq (char-after) ?\()
2355     (let (strlist)
2356       (while (not (eq (char-after) ?\)))
2357         (imap-forward)
2358         (push (imap-parse-astring) strlist))
2359       (imap-forward)
2360       (nreverse strlist))))
2361
2362 (defsubst imap-parse-fetch-body-section ()
2363   (let ((section
2364          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2365     (if (eq (char-before) ? )
2366         (prog1
2367             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2368           (search-forward "]" nil t))
2369       section)))
2370
2371 (defun imap-parse-fetch (response)
2372   (when (eq (char-after) ?\()
2373     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2374               rfc822size body bodydetail bodystructure flags-empty)
2375       (while (not (eq (char-after) ?\)))
2376         (imap-forward)
2377         (let ((token (read (current-buffer))))
2378           (imap-forward)
2379           (cond ((eq token 'UID)
2380                  (setq uid (condition-case ()
2381                                (read (current-buffer))
2382                              (error))))
2383                 ((eq token 'FLAGS)
2384                  (setq flags (imap-parse-flag-list))
2385                  (if (not flags)
2386                      (setq flags-empty 't)))
2387                 ((eq token 'ENVELOPE)
2388                  (setq envelope (imap-parse-envelope)))
2389                 ((eq token 'INTERNALDATE)
2390                  (setq internaldate (imap-parse-string)))
2391                 ((eq token 'RFC822)
2392                  (setq rfc822 (imap-parse-nstring)))
2393                 ((eq token 'RFC822.HEADER)
2394                  (setq rfc822header (imap-parse-nstring)))
2395                 ((eq token 'RFC822.TEXT)
2396                  (setq rfc822text (imap-parse-nstring)))
2397                 ((eq token 'RFC822.SIZE)
2398                  (setq rfc822size (read (current-buffer))))
2399                 ((eq token 'BODY)
2400                  (if (eq (char-before) ?\[)
2401                      (push (list
2402                             (upcase (imap-parse-fetch-body-section))
2403                             (and (eq (char-after) ?<)
2404                                  (buffer-substring (1+ (point))
2405                                                    (search-forward ">" nil t)))
2406                             (progn (imap-forward)
2407                                    (imap-parse-nstring)))
2408                            bodydetail)
2409                    (setq body (imap-parse-body))))
2410                 ((eq token 'BODYSTRUCTURE)
2411                  (setq bodystructure (imap-parse-body))))))
2412       (when uid
2413         (setq imap-current-message uid)
2414         (imap-message-put uid 'UID uid)
2415         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2416         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2417         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2418         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2419         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2420         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2421         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2422         (and body (imap-message-put uid 'BODY body))
2423         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2424         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2425         (run-hooks 'imap-fetch-data-hook)))))
2426
2427 ;;   mailbox-data    =  ...
2428 ;;                      "STATUS" SP mailbox SP "("
2429 ;;                            [status-att SP number
2430 ;;                            *(SP status-att SP number)] ")"
2431 ;;                      ...
2432 ;;
2433 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2434 ;;                     "UNSEEN"
2435
2436 (defun imap-parse-status ()
2437   (let ((mailbox (imap-parse-mailbox)))
2438     (if (eq (char-after) ? )
2439         (forward-char))
2440     (when (and mailbox (eq (char-after) ?\())
2441       (while (and (not (eq (char-after) ?\)))
2442                   (or (forward-char) t)
2443                   (looking-at "\\([A-Za-z]+\\) "))
2444         (let ((token (match-string 1)))
2445           (goto-char (match-end 0))
2446           (cond ((string= token "MESSAGES")
2447                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2448                 ((string= token "RECENT")
2449                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2450                 ((string= token "UIDNEXT")
2451                  (and (looking-at "[0-9]+")
2452                       (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2453                       (goto-char (match-end 0))))
2454                 ((string= token "UIDVALIDITY")
2455                  (and (looking-at "[0-9]+")
2456                       (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2457                       (goto-char (match-end 0))))
2458                 ((string= token "UNSEEN")
2459                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2460                 (t
2461                  (message "Unknown status data %s in mailbox %s ignored"
2462                           token mailbox)
2463                  (read (current-buffer)))))))))
2464
2465 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2466 ;;                        rights)
2467 ;;
2468 ;;   identifier      ::= astring
2469 ;;
2470 ;;   rights          ::= astring
2471
2472 (defun imap-parse-acl ()
2473   (let ((mailbox (imap-parse-mailbox))
2474         identifier rights acl)
2475     (while (eq (char-after) ?\ )
2476       (imap-forward)
2477       (setq identifier (imap-parse-astring))
2478       (imap-forward)
2479       (setq rights (imap-parse-astring))
2480       (setq acl (append acl (list (cons identifier rights)))))
2481     (imap-mailbox-put 'acl acl mailbox)))
2482
2483 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2484 ;;
2485 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2486 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2487 ;;                       ; Does not include "\Recent"
2488 ;;
2489 ;;   flag-keyword    = atom
2490 ;;
2491 ;;   flag-extension  = "\" atom
2492 ;;                       ; Future expansion.  Client implementations
2493 ;;                       ; MUST accept flag-extension flags.  Server
2494 ;;                       ; implementations MUST NOT generate
2495 ;;                       ; flag-extension flags except as defined by
2496 ;;                       ; future standard or standards-track
2497 ;;                       ; revisions of this specification.
2498
2499 (defun imap-parse-flag-list ()
2500   (let (flag-list start)
2501     (assert (eq (char-after) ?\() nil "In imap-parse-flag-list")
2502     (while (and (not (eq (char-after) ?\)))
2503                 (setq start (progn
2504                               (imap-forward)
2505                               ;; next line for Courier IMAP bug.
2506                               (skip-chars-forward " ")
2507                               (point)))
2508                 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2509       (push (buffer-substring start (point)) flag-list))
2510     (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list")
2511     (imap-forward)
2512     (nreverse flag-list)))
2513
2514 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2515 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2516 ;;                     env-in-reply-to SP env-message-id ")"
2517 ;;
2518 ;;   env-bcc         = "(" 1*address ")" / nil
2519 ;;
2520 ;;   env-cc          = "(" 1*address ")" / nil
2521 ;;
2522 ;;   env-date        = nstring
2523 ;;
2524 ;;   env-from        = "(" 1*address ")" / nil
2525 ;;
2526 ;;   env-in-reply-to = nstring
2527 ;;
2528 ;;   env-message-id  = nstring
2529 ;;
2530 ;;   env-reply-to    = "(" 1*address ")" / nil
2531 ;;
2532 ;;   env-sender      = "(" 1*address ")" / nil
2533 ;;
2534 ;;   env-subject     = nstring
2535 ;;
2536 ;;   env-to          = "(" 1*address ")" / nil
2537
2538 (defun imap-parse-envelope ()
2539   (when (eq (char-after) ?\()
2540     (imap-forward)
2541     (vector (prog1 (imap-parse-nstring) ;; date
2542               (imap-forward))
2543             (prog1 (imap-parse-nstring) ;; subject
2544               (imap-forward))
2545             (prog1 (imap-parse-address-list) ;; from
2546               (imap-forward))
2547             (prog1 (imap-parse-address-list) ;; sender
2548               (imap-forward))
2549             (prog1 (imap-parse-address-list) ;; reply-to
2550               (imap-forward))
2551             (prog1 (imap-parse-address-list) ;; to
2552               (imap-forward))
2553             (prog1 (imap-parse-address-list) ;; cc
2554               (imap-forward))
2555             (prog1 (imap-parse-address-list) ;; bcc
2556               (imap-forward))
2557             (prog1 (imap-parse-nstring) ;; in-reply-to
2558               (imap-forward))
2559             (prog1 (imap-parse-nstring) ;; message-id
2560               (imap-forward)))))
2561
2562 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2563
2564 (defsubst imap-parse-string-list ()
2565   (cond ((eq (char-after) ?\() ;; body-fld-param
2566          (let (strlist str)
2567            (imap-forward)
2568            (while (setq str (imap-parse-string))
2569              (push str strlist)
2570              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2571              ;; between body-fld-param's sometimes
2572              (or (eq (char-after) ?\")
2573                  (imap-forward)))
2574            (nreverse strlist)))
2575         ((imap-parse-nil)
2576          nil)))
2577
2578 ;;   body-extension  = nstring / number /
2579 ;;                      "(" body-extension *(SP body-extension) ")"
2580 ;;                       ; Future expansion.  Client implementations
2581 ;;                       ; MUST accept body-extension fields.  Server
2582 ;;                       ; implementations MUST NOT generate
2583 ;;                       ; body-extension fields except as defined by
2584 ;;                       ; future standard or standards-track
2585 ;;                       ; revisions of this specification.
2586
2587 (defun imap-parse-body-extension ()
2588   (if (eq (char-after) ?\()
2589       (let (b-e)
2590         (imap-forward)
2591         (push (imap-parse-body-extension) b-e)
2592         (while (eq (char-after) ?\ )
2593           (imap-forward)
2594           (push (imap-parse-body-extension) b-e))
2595         (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2596         (imap-forward)
2597         (nreverse b-e))
2598     (or (imap-parse-number)
2599         (imap-parse-nstring))))
2600
2601 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2602 ;;                     *(SP body-extension)]]
2603 ;;                       ; MUST NOT be returned on non-extensible
2604 ;;                       ; "BODY" fetch
2605 ;;
2606 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2607 ;;                     *(SP body-extension)]]
2608 ;;                       ; MUST NOT be returned on non-extensible
2609 ;;                       ; "BODY" fetch
2610
2611 (defsubst imap-parse-body-ext ()
2612   (let (ext)
2613     (when (eq (char-after) ?\ ) ;; body-fld-dsp
2614       (imap-forward)
2615       (let (dsp)
2616         (if (eq (char-after) ?\()
2617             (progn
2618               (imap-forward)
2619               (push (imap-parse-string) dsp)
2620               (imap-forward)
2621               (push (imap-parse-string-list) dsp)
2622               (imap-forward))
2623           (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2624         (push (nreverse dsp) ext))
2625       (when (eq (char-after) ?\ ) ;; body-fld-lang
2626         (imap-forward)
2627         (if (eq (char-after) ?\()
2628             (push (imap-parse-string-list) ext)
2629           (push (imap-parse-nstring) ext))
2630         (while (eq (char-after) ?\ ) ;; body-extension
2631           (imap-forward)
2632           (setq ext (append (imap-parse-body-extension) ext)))))
2633     ext))
2634
2635 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2636 ;;
2637 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2638 ;;                     *(SP body-extension)]]
2639 ;;                       ; MUST NOT be returned on non-extensible
2640 ;;                       ; "BODY" fetch
2641 ;;
2642 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2643 ;;                     *(SP body-extension)]]
2644 ;;                       ; MUST NOT be returned on non-extensible
2645 ;;                       ; "BODY" fetch
2646 ;;
2647 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2648 ;;                     body-fld-enc SP body-fld-octets
2649 ;;
2650 ;;   body-fld-desc   = nstring
2651 ;;
2652 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2653 ;;
2654 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2655 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2656 ;;
2657 ;;   body-fld-id     = nstring
2658 ;;
2659 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2660 ;;
2661 ;;   body-fld-lines  = number
2662 ;;
2663 ;;   body-fld-md5    = nstring
2664 ;;
2665 ;;   body-fld-octets = number
2666 ;;
2667 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2668 ;;
2669 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2670 ;;                     [SP body-ext-1part]
2671 ;;
2672 ;;   body-type-basic = media-basic SP body-fields
2673 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2674 ;;
2675 ;;   body-type-msg   = media-message SP body-fields SP envelope
2676 ;;                     SP body SP body-fld-lines
2677 ;;
2678 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2679 ;;
2680 ;;   body-type-mpart = 1*body SP media-subtype
2681 ;;                     [SP body-ext-mpart]
2682 ;;
2683 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2684 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2685 ;;                       ; Defined in [MIME-IMT]
2686 ;;
2687 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2688 ;;                      ; Defined in [MIME-IMT]
2689 ;;
2690 ;;   media-subtype   = string
2691 ;;                       ; Defined in [MIME-IMT]
2692 ;;
2693 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2694 ;;                       ; Defined in [MIME-IMT]
2695
2696 (defun imap-parse-body ()
2697   (let (body)
2698     (when (eq (char-after) ?\()
2699       (imap-forward)
2700       (if (eq (char-after) ?\()
2701           (let (subbody)
2702             (while (and (eq (char-after) ?\()
2703                         (setq subbody (imap-parse-body)))
2704              ;; buggy stalker communigate pro 3.0 insert a SPC between
2705               ;; parts in multiparts
2706               (when (and (eq (char-after) ?\ )
2707                          (eq (char-after (1+ (point))) ?\())
2708                 (imap-forward))
2709               (push subbody body))
2710             (imap-forward)
2711             (push (imap-parse-string) body) ;; media-subtype
2712             (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2713               (imap-forward)
2714               (if (eq (char-after) ?\() ;; body-fld-param
2715                   (push (imap-parse-string-list) body)
2716                 (push (and (imap-parse-nil) nil) body))
2717               (setq body
2718                     (append (imap-parse-body-ext) body))) ;; body-ext-...
2719             (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2720             (imap-forward)
2721             (nreverse body))
2722
2723         (push (imap-parse-string) body) ;; media-type
2724         (imap-forward)
2725         (push (imap-parse-string) body) ;; media-subtype
2726         (imap-forward)
2727         ;; next line for Sun SIMS bug
2728         (and (eq (char-after) ? ) (imap-forward))
2729         (if (eq (char-after) ?\() ;; body-fld-param
2730             (push (imap-parse-string-list) body)
2731           (push (and (imap-parse-nil) nil) body))
2732         (imap-forward)
2733         (push (imap-parse-nstring) body) ;; body-fld-id
2734         (imap-forward)
2735         (push (imap-parse-nstring) body) ;; body-fld-desc
2736         (imap-forward)
2737         ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2738         ;; nstring and return nil instead of defaulting back to 7BIT
2739         ;; as the standard says.
2740         (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2741         (imap-forward)
2742         (push (imap-parse-number) body) ;; body-fld-octets
2743
2744    ;; ok, we're done parsing the required parts, what comes now is one
2745         ;; of three things:
2746         ;;
2747         ;; envelope       (then we're parsing body-type-msg)
2748         ;; body-fld-lines (then we're parsing body-type-text)
2749         ;; body-ext-1part (then we're parsing body-type-basic)
2750         ;;
2751   ;; the problem is that the two first are in turn optionally followed
2752 ;; by the third.  So we parse the first two here (if there are any)...
2753
2754         (when (eq (char-after) ?\ )
2755           (imap-forward)
2756           (let (lines)
2757             (cond ((eq (char-after) ?\() ;; body-type-msg:
2758                    (push (imap-parse-envelope) body) ;; envelope
2759                    (imap-forward)
2760                    (push (imap-parse-body) body) ;; body
2761                    ;; buggy stalker communigate pro 3.0 doesn't print
2762                    ;; number of lines in message/rfc822 attachment
2763                    (if (eq (char-after) ?\))
2764                        (push 0 body)
2765                      (imap-forward)
2766                      (push (imap-parse-number) body))) ;; body-fld-lines
2767                   ((setq lines (imap-parse-number)) ;; body-type-text:
2768                    (push lines body)) ;; body-fld-lines
2769                   (t
2770                    (backward-char))))) ;; no match...
2771
2772         ;; ...and then parse the third one here...
2773
2774         (when (eq (char-after) ?\ ) ;; body-ext-1part:
2775           (imap-forward)
2776           (push (imap-parse-nstring) body) ;; body-fld-md5
2777           (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2778
2779         (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2780         (imap-forward)
2781         (nreverse body)))))
2782
2783 (when imap-debug                        ; (untrace-all)
2784   (require 'trace)
2785   (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2786   (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2787           '(
2788             imap-utf7-encode
2789             imap-utf7-decode
2790             imap-error-text
2791             imap-kerberos4s-p
2792             imap-kerberos4-open
2793             imap-ssl-p
2794             imap-ssl-open
2795             imap-network-p
2796             imap-network-open
2797             imap-interactive-login
2798             imap-kerberos4a-p
2799             imap-kerberos4-auth
2800             imap-cram-md5-p
2801             imap-cram-md5-auth
2802             imap-login-p
2803             imap-login-auth
2804             imap-anonymous-p
2805             imap-anonymous-auth
2806             imap-open-1
2807             imap-open
2808             imap-opened
2809             imap-authenticate
2810             imap-close
2811             imap-capability
2812             imap-namespace
2813             imap-send-command-wait
2814             imap-mailbox-put
2815             imap-mailbox-get
2816             imap-mailbox-map-1
2817             imap-mailbox-map
2818             imap-current-mailbox
2819             imap-current-mailbox-p-1
2820             imap-current-mailbox-p
2821             imap-mailbox-select-1
2822             imap-mailbox-select
2823             imap-mailbox-examine-1
2824             imap-mailbox-examine
2825             imap-mailbox-unselect
2826             imap-mailbox-expunge
2827             imap-mailbox-close
2828             imap-mailbox-create-1
2829             imap-mailbox-create
2830             imap-mailbox-delete
2831             imap-mailbox-rename
2832             imap-mailbox-lsub
2833             imap-mailbox-list
2834             imap-mailbox-subscribe
2835             imap-mailbox-unsubscribe
2836             imap-mailbox-status
2837             imap-mailbox-acl-get
2838             imap-mailbox-acl-set
2839             imap-mailbox-acl-delete
2840             imap-current-message
2841             imap-list-to-message-set
2842             imap-fetch-asynch
2843             imap-fetch
2844             imap-message-put
2845             imap-message-get
2846             imap-message-map
2847             imap-search
2848             imap-message-flag-permanent-p
2849             imap-message-flags-set
2850             imap-message-flags-del
2851             imap-message-flags-add
2852             imap-message-copyuid-1
2853             imap-message-copyuid
2854             imap-message-copy
2855             imap-message-appenduid-1
2856             imap-message-appenduid
2857             imap-message-append
2858             imap-body-lines
2859             imap-envelope-from
2860             imap-send-command-1
2861             imap-send-command
2862             imap-wait-for-tag
2863             imap-sentinel
2864             imap-find-next-line
2865             imap-arrival-filter
2866             imap-parse-greeting
2867             imap-parse-response
2868             imap-parse-resp-text
2869             imap-parse-resp-text-code
2870             imap-parse-data-list
2871             imap-parse-fetch
2872             imap-parse-status
2873             imap-parse-acl
2874             imap-parse-flag-list
2875             imap-parse-envelope
2876             imap-parse-body-extension
2877             imap-parse-body
2878             )))
2879
2880 (provide 'imap)
2881
2882 ;;; imap.el ends here