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