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