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