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