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