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