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