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