Importing Gnus v5.8.3.
[elisp/gnus.git-] / lisp / imap.el
1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998,1999 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;; Keywords: mail
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; imap.el is a elisp library providing an interface for talking to
27 ;; IMAP servers.
28 ;;
29 ;; imap.el is roughly divided in two parts, one that parses IMAP
30 ;; responses from the server and storing data into buffer-local
31 ;; variables, and one for utility functions which send commands to
32 ;; server, waits for an answer, and return information.  The latter
33 ;; part is layered on top of the previous.
34 ;;
35 ;; The imap.el API consist of the following functions, other functions
36 ;; in this file should not be called directly and the result of doing
37 ;; so are at best undefined.
38 ;;
39 ;; Global commands:
40 ;;
41 ;; imap-open,       imap-opened,    imap-authenticate, imap-close,
42 ;; imap-capability, imap-namespace, imap-error-text
43 ;;
44 ;; Mailbox commands:
45 ;;
46 ;; imap-mailbox-get,       imap-mailbox-map,         imap-current-mailbox, 
47 ;; imap-current-mailbox-p, imap-search,              imap-mailbox-select,
48 ;; imap-mailbox-examine,   imap-mailbox-unselect,    imap-mailbox-expunge
49 ;; imap-mailbox-close,     imap-mailbox-create,      imap-mailbox-delete
50 ;; imap-mailbox-rename,    imap-mailbox-lsub,        imap-mailbox-list
51 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
52 ;; imap-mailbox-acl-get,   imap-mailbox-acl-set,     imap-mailbox-acl-delete
53 ;;
54 ;; Message commands:
55 ;;
56 ;; imap-fetch-asynch,                 imap-fetch,
57 ;; imap-current-message,              imap-list-to-message-set,
58 ;; imap-message-get,                  imap-message-map
59 ;; imap-message-envelope-date,        imap-message-envelope-subject, 
60 ;; imap-message-envelope-from,        imap-message-envelope-sender,
61 ;; imap-message-envelope-reply-to,    imap-message-envelope-to,
62 ;; imap-message-envelope-cc,          imap-message-envelope-bcc
63 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
64 ;; imap-message-body,                 imap-message-flag-permanent-p
65 ;; imap-message-flags-set,            imap-message-flags-del
66 ;; imap-message-flags-add,            imap-message-copyuid
67 ;; imap-message-copy,                 imap-message-appenduid
68 ;; imap-message-append,               imap-envelope-from
69 ;; imap-body-lines
70 ;;
71 ;; It is my hope that theese commands should be pretty self
72 ;; explanatory for someone that know IMAP.  All functions have
73 ;; additional documentation on how to invoke them.
74 ;;
75 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
76 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
77 ;; (NAMESPACE), RFC2359 (UIDPLUS), and the kerberos V4 part of RFC1731
78 ;; (with use of external program `imtest').  It also take advantage
79 ;; the UNSELECT extension in Cyrus IMAPD.
80 ;;
81 ;; Without the work of John McClary Prevost and Jim Radford this library
82 ;; would not have seen the light of day.  Many thanks.
83 ;;
84 ;; This is a transcript of short interactive session for demonstration
85 ;; purposes.
86 ;;
87 ;; (imap-open "my.mail.server")
88 ;; => " *imap* my.mail.server:0"
89 ;;
90 ;; The rest are invoked with current buffer as the buffer returned by
91 ;; `imap-open'.  It is possible to do all without this, but it would
92 ;; look ugly here since `buffer' is always the last argument for all
93 ;; imap.el API functions.
94 ;;
95 ;; (imap-authenticate "myusername" "mypassword")
96 ;; => auth
97 ;;
98 ;; (imap-mailbox-lsub "*")
99 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
100 ;;
101 ;; (imap-mailbox-list "INBOX.n%")
102 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
103 ;;
104 ;; (imap-mailbox-select "INBOX.nnimap")
105 ;; => "INBOX.nnimap"
106 ;;
107 ;; (imap-mailbox-get 'exists)
108 ;; => 166
109 ;;
110 ;; (imap-mailbox-get 'uidvalidity)
111 ;; => "908992622"
112 ;;
113 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
114 ;; => (235 236)
115 ;;
116 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
117 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
118 ;;
119 ;; Todo:
120 ;; 
121 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
122 ;; o Don't use `read' at all (important places already fixed)
123 ;; o Accept list of articles instead of message set string in most
124 ;;   imap-message-* functions.
125 ;; o Cyrus IMAPd 1.6.x `imtest' support in the imtest wrapper
126 ;;
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 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   (cond ((eq (char-after) ?\")
1454          (forward-char 1)
1455          (let ((p (point)) (name ""))
1456            (skip-chars-forward "^\"\\\\")
1457            (setq name (buffer-substring p (point)))
1458            (while (eq (char-after) ?\\)
1459              (setq p (1+ (point)))
1460              (forward-char 2)
1461              (skip-chars-forward "^\"\\\\")
1462              (setq name (concat name (buffer-substring p (point)))))
1463            (forward-char 1)
1464            name))
1465         ((eq (char-after) ?{)
1466          (imap-parse-literal))))
1467
1468 ;;   nil             = "NIL"
1469
1470 (defsubst imap-parse-nil ()
1471   (if (looking-at "NIL")
1472       (goto-char (match-end 0))))
1473
1474 ;;   nstring         = string / nil
1475
1476 (defsubst imap-parse-nstring ()
1477   (or (imap-parse-string)
1478       (and (imap-parse-nil)
1479            nil)))
1480
1481 ;;   astring         = atom / string
1482 ;;
1483 ;;   atom            = 1*ATOM-CHAR
1484 ;;
1485 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
1486 ;;
1487 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
1488 ;;                     quoted-specials
1489 ;;
1490 ;;   list-wildcards  = "%" / "*"
1491 ;;
1492 ;;   quoted-specials = DQUOTE / "\"
1493
1494 (defsubst imap-parse-astring ()
1495   (or (imap-parse-string)
1496       (buffer-substring (point) 
1497                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1498                             (goto-char (1- (match-end 0)))
1499                           (end-of-line)
1500                           (point)))))
1501
1502 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
1503 ;;                      addr-host ")"
1504 ;;
1505 ;;   addr-adl        = nstring
1506 ;;                       ; Holds route from [RFC-822] route-addr if
1507 ;;                       ; non-NIL
1508 ;;
1509 ;;   addr-host       = nstring
1510 ;;                       ; NIL indicates [RFC-822] group syntax.
1511 ;;                       ; Otherwise, holds [RFC-822] domain name
1512 ;;
1513 ;;   addr-mailbox    = nstring
1514 ;;                       ; NIL indicates end of [RFC-822] group; if
1515 ;;                       ; non-NIL and addr-host is NIL, holds
1516 ;;                       ; [RFC-822] group name.
1517 ;;                       ; Otherwise, holds [RFC-822] local-part
1518 ;;                       ; after removing [RFC-822] quoting
1519 ;;
1520 ;;   addr-name       = nstring
1521 ;;                       ; If non-NIL, holds phrase from [RFC-822]
1522 ;;                       ; mailbox after removing [RFC-822] quoting
1523 ;;
1524
1525 (defsubst imap-parse-address ()
1526   (let (address)
1527     (when (eq (char-after) ?\()
1528       (imap-forward)
1529       (setq address (vector (prog1 (imap-parse-nstring)
1530                               (imap-forward))
1531                             (prog1 (imap-parse-nstring)
1532                               (imap-forward))
1533                             (prog1 (imap-parse-nstring)
1534                               (imap-forward))
1535                             (imap-parse-nstring)))
1536       (when (eq (char-after) ?\))
1537         (imap-forward)
1538         address))))
1539
1540 ;;   address-list    = "(" 1*address ")" / nil
1541 ;;
1542 ;;   nil             = "NIL"
1543
1544 (defsubst imap-parse-address-list ()
1545   (if (eq (char-after) ?\()
1546       (let (address addresses)
1547         (imap-forward)
1548         (while (and (not (eq (char-after) ?\)))
1549                     ;; next line for MS Exchange bug
1550                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
1551                     (setq address (imap-parse-address)))
1552           (setq addresses (cons address addresses)))
1553         (when (eq (char-after) ?\))
1554           (imap-forward)
1555           (nreverse addresses)))
1556     (assert (imap-parse-nil))))
1557
1558 ;;   mailbox         = "INBOX" / astring
1559 ;;                       ; INBOX is case-insensitive.  All case variants of
1560 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1561 ;;                       ; not as an astring.  An astring which consists of
1562 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
1563 ;;                       ; is considered to be INBOX and not an astring.
1564 ;;                       ;  Refer to section 5.1 for further
1565 ;;                       ; semantic details of mailbox names.
1566
1567 (defsubst imap-parse-mailbox ()
1568   (let ((mailbox (imap-parse-astring)))
1569     (if (string-equal "INBOX" (upcase mailbox))
1570         "INBOX"
1571       mailbox)))
1572
1573 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1574 ;;
1575 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
1576 ;;                       ; Authentication condition
1577 ;;
1578 ;;   resp-cond-bye   = "BYE" SP resp-text
1579
1580 (defun imap-parse-greeting ()
1581   "Parse a IMAP greeting."
1582   (cond ((looking-at "\\* OK ")
1583          (setq imap-state 'nonauth))
1584         ((looking-at "\\* PREAUTH ")
1585          (setq imap-state 'auth))
1586         ((looking-at "\\* BYE ")
1587          (setq imap-state 'closed))))
1588
1589 ;;   response        = *(continue-req / response-data) response-done
1590 ;;
1591 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
1592 ;;
1593 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
1594 ;;                     mailbox-data / message-data / capability-data) CRLF
1595 ;;
1596 ;;   response-done   = response-tagged / response-fatal
1597 ;;
1598 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
1599 ;;                       ; Server closes connection immediately
1600 ;;
1601 ;;   response-tagged = tag SP resp-cond-state CRLF
1602 ;;
1603 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1604 ;;                       ; Status condition
1605 ;;
1606 ;;   resp-cond-bye   = "BYE" SP resp-text
1607 ;;
1608 ;;   mailbox-data    =  "FLAGS" SP flag-list /
1609 ;;                      "LIST" SP mailbox-list /
1610 ;;                      "LSUB" SP mailbox-list /
1611 ;;                      "SEARCH" *(SP nz-number) /
1612 ;;                      "STATUS" SP mailbox SP "("
1613 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
1614 ;;                      number SP "EXISTS" /
1615 ;;                      number SP "RECENT"
1616 ;;
1617 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1618 ;;
1619 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1620 ;;                     *(SP capability)
1621 ;;                       ; IMAP4rev1 servers which offer RFC 1730
1622 ;;                       ; compatibility MUST list "IMAP4" as the first
1623 ;;                       ; capability.
1624
1625 (defun imap-parse-response ()
1626   "Parse a IMAP command response."
1627   (let (token)
1628     (case (setq token (read (current-buffer)))
1629       (+ (setq imap-continuation
1630                (or (buffer-substring (min (point-max) (1+ (point)))
1631                                      (point-max))
1632                    t)))
1633       (* (case (prog1 (setq token (read (current-buffer)))
1634                  (imap-forward))
1635            (OK         (imap-parse-resp-text))
1636            (NO         (imap-parse-resp-text))
1637            (BAD        (imap-parse-resp-text))
1638            (BYE        (imap-parse-resp-text))
1639            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
1640            (LIST       (imap-parse-data-list 'list))
1641            (LSUB       (imap-parse-data-list 'lsub))
1642            (SEARCH     (imap-mailbox-put 
1643                         'search 
1644                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1645            (STATUS     (imap-parse-status))
1646            (CAPABILITY (setq imap-capability 
1647                              (read (concat "(" (upcase (buffer-substring
1648                                                         (point) (point-max)))
1649                                            ")"))))
1650            (ACL        (imap-parse-acl))
1651            (t       (case (prog1 (read (current-buffer))
1652                             (imap-forward))
1653                       (EXISTS  (imap-mailbox-put 'exists token))
1654                       (RECENT  (imap-mailbox-put 'recent token))
1655                       (EXPUNGE t)
1656                       (FETCH   (imap-parse-fetch token))
1657                       (t       (message "Garbage: %s" (buffer-string)))))))
1658       (t (let (status)
1659            (if (not (integerp token))
1660                (message "Garbage: %s" (buffer-string))
1661              (case (prog1 (setq status (read (current-buffer)))
1662                      (imap-forward))
1663                (OK  (progn
1664                       (setq imap-reached-tag (max imap-reached-tag token))
1665                       (imap-parse-resp-text)))
1666                (NO  (progn
1667                       (setq imap-reached-tag (max imap-reached-tag token))
1668                       (save-excursion
1669                         (imap-parse-resp-text))
1670                       (let (code text)
1671                         (when (eq (char-after) ?\[)
1672                           (setq code (buffer-substring (point)
1673                                                        (search-forward "]")))
1674                           (imap-forward))
1675                         (setq text (buffer-substring (point) (point-max)))
1676                         (push (list token status code text) 
1677                               imap-failed-tags))))
1678                (BAD (progn
1679                       (setq imap-reached-tag (max imap-reached-tag token))
1680                       (save-excursion
1681                         (imap-parse-resp-text))
1682                       (let (code text)
1683                         (when (eq (char-after) ?\[)
1684                           (setq code (buffer-substring (point)
1685                                                        (search-forward "]")))
1686                           (imap-forward))
1687                         (setq text (buffer-substring (point) (point-max)))
1688                         (push (list token status code text) imap-failed-tags)
1689                         (error "Internal error, tag %s status %s code %s text %s"
1690                                token status code text))))
1691                (t   (message "Garbage: %s" (buffer-string))))))))))
1692
1693 ;;   resp-text       = ["[" resp-text-code "]" SP] text
1694 ;;
1695 ;;   text            = 1*TEXT-CHAR
1696 ;;
1697 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
1698
1699 (defun imap-parse-resp-text ()
1700   (imap-parse-resp-text-code))
1701
1702 ;;   resp-text-code  = "ALERT" /
1703 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
1704 ;;                     "NEWNAME" SP string SP string / 
1705 ;;                     "PARSE" /
1706 ;;                     "PERMANENTFLAGS" SP "(" 
1707 ;;                               [flag-perm *(SP flag-perm)] ")" /
1708 ;;                     "READ-ONLY" / 
1709 ;;                     "READ-WRITE" / 
1710 ;;                     "TRYCREATE" /
1711 ;;                     "UIDNEXT" SP nz-number / 
1712 ;;                     "UIDVALIDITY" SP nz-number /
1713 ;;                     "UNSEEN" SP nz-number /
1714 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
1715 ;;
1716 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
1717 ;;
1718 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
1719 ;;
1720 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
1721 ;;                        (set "," set)
1722 ;;                          ; Identifies a set of messages.  For message
1723 ;;                          ; sequence numbers, these are consecutive
1724 ;;                          ; numbers from 1 to the number of messages in
1725 ;;                          ; the mailbox
1726 ;;                          ; Comma delimits individual numbers, colon
1727 ;;                          ; delimits between two numbers inclusive.
1728 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
1729 ;;                          ; 14,15 for a mailbox with 15 messages.
1730 ;; 
1731 ;;   sequence-num    = nz-number / "*"
1732 ;;                          ; * is the largest number in use.  For message
1733 ;;                          ; sequence numbers, it is the number of messages
1734 ;;                          ; in the mailbox.  For unique identifiers, it is
1735 ;;                          ; the unique identifier of the last message in
1736 ;;                          ; the mailbox.
1737 ;;
1738 ;;   flag-perm       = flag / "\*"
1739 ;;
1740 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
1741 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
1742 ;;                       ; Does not include "\Recent"
1743 ;;
1744 ;;   flag-extension  = "\" atom
1745 ;;                       ; Future expansion.  Client implementations
1746 ;;                       ; MUST accept flag-extension flags.  Server
1747 ;;                       ; implementations MUST NOT generate
1748 ;;                       ; flag-extension flags except as defined by
1749 ;;                       ; future standard or standards-track
1750 ;;                       ; revisions of this specification.
1751 ;;
1752 ;;   flag-keyword    = atom
1753 ;;
1754 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
1755
1756 (defun imap-parse-resp-text-code ()
1757   (when (eq (char-after) ?\[)
1758     (imap-forward)
1759     (cond ((search-forward "PERMANENTFLAGS " nil t)
1760            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
1761           ((search-forward "UIDNEXT " nil t)
1762            (imap-mailbox-put 'uidnext (read (current-buffer))))
1763           ((search-forward "UNSEEN " nil t)
1764            (imap-mailbox-put 'unseen (read (current-buffer))))
1765           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
1766            (imap-mailbox-put 'uidvalidity (match-string 1)))
1767           ((search-forward "READ-ONLY" nil t)
1768            (imap-mailbox-put 'read-only t))
1769           ((search-forward "NEWNAME " nil t)
1770            (let (oldname newname)
1771              (setq oldname (imap-parse-string))
1772              (imap-forward)
1773              (setq newname (imap-parse-string))
1774              (imap-mailbox-put 'newname newname oldname)))
1775           ((search-forward "TRYCREATE" nil t)
1776            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
1777           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
1778            (imap-mailbox-put 'appenduid
1779                              (list (match-string 1)
1780                                    (string-to-number (match-string 2)))
1781                              imap-current-target-mailbox))
1782           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
1783            (imap-mailbox-put 'copyuid (list (match-string 1)
1784                                             (match-string 2)
1785                                             (match-string 3))
1786                              imap-current-target-mailbox))
1787           ((search-forward "ALERT] " nil t)
1788            (message "Imap server %s information: %s" imap-server
1789                     (buffer-substring (point) (point-max)))))))
1790
1791 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
1792 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
1793 ;;
1794 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
1795 ;;                     *(SP mbx-list-oflag) /
1796 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
1797 ;;
1798 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
1799 ;;                       ; Other flags; multiple possible per LIST response
1800 ;;
1801 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
1802 ;;                       ; Selectability flags; only one per LIST response
1803 ;;
1804 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
1805 ;;                     "\" quoted-specials
1806 ;;
1807 ;;   quoted-specials = DQUOTE / "\"
1808
1809 (defun imap-parse-data-list (type)
1810   (let (flags delimiter mailbox)
1811     (setq flags (imap-parse-flag-list))
1812     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
1813       (setq delimiter (match-string 1))
1814       (goto-char (1+ (match-end 0)))
1815       (when (setq mailbox (imap-parse-mailbox))
1816         (imap-mailbox-put type t mailbox)
1817         (imap-mailbox-put 'list-flags flags mailbox)
1818         (imap-mailbox-put 'delimiter delimiter mailbox)))))
1819
1820 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
1821 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
1822 ;;                      "INTERNALDATE" SPACE date_time /
1823 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
1824 ;;                      "RFC822.SIZE" SPACE number /
1825 ;;                      "BODY" ["STRUCTURE"] SPACE body /
1826 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
1827 ;;                      "UID" SPACE uniqueid) ")"
1828 ;;  
1829 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
1830 ;;                      SPACE time SPACE zone <">
1831 ;;  
1832 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
1833 ;;                      ["." (section_text / "MIME")])] "]"
1834 ;;  
1835 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
1836 ;;                      SPACE header_list / "TEXT"
1837 ;;  
1838 ;;  header_fld_name ::= astring
1839 ;;  
1840 ;;  header_list     ::= "(" 1#header_fld_name ")"
1841
1842 (defsubst imap-parse-header-list ()
1843   (when (eq (char-after) ?\()
1844     (let (strlist)
1845       (while (not (eq (char-after) ?\)))
1846         (imap-forward)
1847         (push (imap-parse-astring) strlist))
1848       (imap-forward)
1849       (nreverse strlist))))
1850
1851 (defsubst imap-parse-fetch-body-section ()
1852   (let ((section 
1853          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
1854     (if (eq (char-before) ? )
1855         (prog1
1856             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
1857           (search-forward "]" nil t))
1858       section)))
1859
1860 (defun imap-parse-fetch (response)
1861   (when (eq (char-after) ?\()
1862     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text 
1863               rfc822size body bodydetail bodystructure)
1864       (while (not (eq (char-after) ?\)))
1865         (imap-forward)
1866         (let ((token (read (current-buffer))))
1867           (imap-forward)
1868           (cond ((eq token 'UID)
1869                  (setq uid (ignore-errors (read (current-buffer)))))
1870                 ((eq token 'FLAGS)
1871                  (setq flags (imap-parse-flag-list)))
1872                 ((eq token 'ENVELOPE)
1873                  (setq envelope (imap-parse-envelope)))
1874                 ((eq token 'INTERNALDATE)
1875                  (setq internaldate (imap-parse-string)))
1876                 ((eq token 'RFC822)
1877                  (setq rfc822 (imap-parse-nstring)))
1878                 ((eq token 'RFC822.HEADER)
1879                  (setq rfc822header (imap-parse-nstring)))
1880                 ((eq token 'RFC822.TEXT)
1881                  (setq rfc822text (imap-parse-nstring)))
1882                 ((eq token 'RFC822.SIZE)
1883                  (setq rfc822size (read (current-buffer))))
1884                 ((eq token 'BODY)
1885                  (if (eq (char-before) ?\[)
1886                      (push (list
1887                             (upcase (imap-parse-fetch-body-section))
1888                             (and (eq (char-after) ?<)
1889                                  (buffer-substring (1+ (point))
1890                                                    (search-forward ">" nil t)))
1891                             (progn (imap-forward)
1892                                    (imap-parse-nstring)))
1893                            bodydetail)
1894                    (setq body (imap-parse-body))))
1895                 ((eq token 'BODYSTRUCTURE)
1896                  (setq bodystructure (imap-parse-body))))))
1897       (when uid
1898         (setq imap-current-message uid)
1899         (imap-message-put uid 'UID uid)
1900         (and flags (imap-message-put uid 'FLAGS flags))
1901         (and envelope (imap-message-put uid 'ENVELOPE envelope))
1902         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
1903         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
1904         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
1905         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
1906         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
1907         (and body (imap-message-put uid 'BODY body))
1908         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
1909         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
1910         (run-hooks 'imap-fetch-data-hook)))))
1911
1912 ;;   mailbox-data    =  ...
1913 ;;                      "STATUS" SP mailbox SP "("
1914 ;;                            [status-att SP number 
1915 ;;                            *(SP status-att SP number)] ")"
1916 ;;                      ...
1917 ;;
1918 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
1919 ;;                     "UNSEEN"
1920
1921 (defun imap-parse-status ()
1922   (let ((mailbox (imap-parse-mailbox)))
1923     (when (and mailbox (search-forward "(" nil t))
1924       (while (not (eq (char-after) ?\)))
1925         (let ((token (read (current-buffer))))
1926           (cond ((eq token 'MESSAGES)
1927                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
1928                 ((eq token 'RECENT)
1929                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
1930                 ((eq token 'UIDNEXT)
1931                  (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
1932                 ((eq token 'UIDVALIDITY)
1933                  (and (looking-at " \\([0-9]+\\)")
1934                       (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
1935                       (goto-char (match-end 1))))
1936                 ((eq token 'UNSEEN)
1937                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
1938                 (t
1939                  (message "Unknown status data %s in mailbox %s ignored" 
1940                           token mailbox))))))))
1941
1942 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
1943 ;;                        rights)
1944 ;;
1945 ;;   identifier      ::= astring
1946 ;;
1947 ;;   rights          ::= astring
1948
1949 (defun imap-parse-acl ()
1950   (let ((mailbox (imap-parse-mailbox))
1951         identifier rights acl)
1952     (while (eq (char-after) ?\ )
1953       (imap-forward)
1954       (setq identifier (imap-parse-astring))
1955       (imap-forward)
1956       (setq rights (imap-parse-astring))
1957       (setq acl (append acl (list (cons identifier rights)))))
1958     (imap-mailbox-put 'acl acl mailbox)))
1959
1960 ;;   flag-list       = "(" [flag *(SP flag)] ")"
1961 ;;
1962 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
1963 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
1964 ;;                       ; Does not include "\Recent"
1965 ;;
1966 ;;   flag-keyword    = atom
1967 ;;
1968 ;;   flag-extension  = "\" atom
1969 ;;                       ; Future expansion.  Client implementations
1970 ;;                       ; MUST accept flag-extension flags.  Server
1971 ;;                       ; implementations MUST NOT generate
1972 ;;                       ; flag-extension flags except as defined by
1973 ;;                       ; future standard or standards-track
1974 ;;                       ; revisions of this specification.
1975
1976 (defun imap-parse-flag-list ()
1977   (let ((str (buffer-substring (point) (search-forward ")" nil t)))
1978         pos)
1979     (while (setq pos (string-match "\\\\" str (and pos (+ 2 pos))))
1980       (setq str (replace-match "\\\\" nil t str)))
1981     (mapcar 'symbol-name (read str))))
1982
1983 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
1984 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
1985 ;;                     env-in-reply-to SP env-message-id ")"
1986 ;;
1987 ;;   env-bcc         = "(" 1*address ")" / nil
1988 ;;
1989 ;;   env-cc          = "(" 1*address ")" / nil
1990 ;;
1991 ;;   env-date        = nstring
1992 ;;
1993 ;;   env-from        = "(" 1*address ")" / nil
1994 ;;
1995 ;;   env-in-reply-to = nstring
1996 ;;
1997 ;;   env-message-id  = nstring
1998 ;;
1999 ;;   env-reply-to    = "(" 1*address ")" / nil
2000 ;;
2001 ;;   env-sender      = "(" 1*address ")" / nil
2002 ;;
2003 ;;   env-subject     = nstring
2004 ;;
2005 ;;   env-to          = "(" 1*address ")" / nil
2006
2007 (defun imap-parse-envelope ()
2008   (when (eq (char-after) ?\()
2009     (imap-forward)
2010     (vector (prog1 (imap-parse-nstring);; date
2011               (imap-forward))
2012             (prog1 (imap-parse-nstring);; subject
2013               (imap-forward))
2014             (prog1 (imap-parse-address-list);; from
2015               (imap-forward))
2016             (prog1 (imap-parse-address-list);; sender
2017               (imap-forward))
2018             (prog1 (imap-parse-address-list);; reply-to
2019               (imap-forward))
2020             (prog1 (imap-parse-address-list);; to
2021               (imap-forward))
2022             (prog1 (imap-parse-address-list);; cc
2023               (imap-forward))
2024             (prog1 (imap-parse-address-list);; bcc
2025               (imap-forward))
2026             (prog1 (imap-parse-nstring);; in-reply-to
2027               (imap-forward))
2028             (prog1 (imap-parse-nstring);; message-id
2029               (imap-forward)))))
2030
2031 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2032
2033 (defsubst imap-parse-string-list ()
2034   (cond ((eq (char-after) ?\();; body-fld-param
2035          (let (strlist str)
2036            (imap-forward)
2037            (while (setq str (imap-parse-string))
2038              (push str strlist)
2039              (imap-forward))
2040            (nreverse strlist)))
2041         ((imap-parse-nil)
2042          nil)))
2043
2044 ;;   body-extension  = nstring / number /
2045 ;;                      "(" body-extension *(SP body-extension) ")"
2046 ;;                       ; Future expansion.  Client implementations
2047 ;;                       ; MUST accept body-extension fields.  Server
2048 ;;                       ; implementations MUST NOT generate
2049 ;;                       ; body-extension fields except as defined by
2050 ;;                       ; future standard or standards-track
2051 ;;                       ; revisions of this specification.
2052
2053 (defun imap-parse-body-extension ()
2054   (if (eq (char-after) ?\()
2055       (let (b-e)
2056         (imap-forward)
2057         (push (imap-parse-body-extension) b-e)
2058         (while (eq (char-after) ?\ )
2059           (imap-forward)
2060           (push (imap-parse-body-extension) b-e))
2061         (assert (eq (char-after) ?\)))
2062         (imap-forward)
2063         (nreverse b-e))
2064     (or (imap-parse-number)
2065         (imap-parse-nstring))))
2066
2067 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2068 ;;                     *(SP body-extension)]]
2069 ;;                       ; MUST NOT be returned on non-extensible
2070 ;;                       ; "BODY" fetch
2071 ;;
2072 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2073 ;;                     *(SP body-extension)]]
2074 ;;                       ; MUST NOT be returned on non-extensible
2075 ;;                       ; "BODY" fetch
2076
2077 (defsubst imap-parse-body-ext ()
2078   (let (ext)
2079     (when (eq (char-after) ?\ );; body-fld-dsp
2080       (imap-forward)
2081       (let (dsp)
2082         (if (eq (char-after) ?\()
2083             (progn
2084               (imap-forward)
2085               (push (imap-parse-string) dsp)
2086               (imap-forward)
2087               (push (imap-parse-string-list) dsp)
2088               (imap-forward))
2089           (assert (imap-parse-nil)))
2090         (push (nreverse dsp) ext))
2091       (when (eq (char-after) ?\ );; body-fld-lang
2092         (imap-forward)
2093         (if (eq (char-after) ?\()
2094             (push (imap-parse-string-list) ext)
2095           (push (imap-parse-nstring) ext))
2096         (while (eq (char-after) ?\ );; body-extension
2097           (imap-forward)
2098           (setq ext (append (imap-parse-body-extension) ext)))))
2099     ext))
2100
2101 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2102 ;;
2103 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2104 ;;                     *(SP body-extension)]]
2105 ;;                       ; MUST NOT be returned on non-extensible
2106 ;;                       ; "BODY" fetch
2107 ;;
2108 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2109 ;;                     *(SP body-extension)]]
2110 ;;                       ; MUST NOT be returned on non-extensible
2111 ;;                       ; "BODY" fetch
2112 ;;
2113 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2114 ;;                     body-fld-enc SP body-fld-octets
2115 ;;
2116 ;;   body-fld-desc   = nstring
2117 ;;
2118 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2119 ;;
2120 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2121 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2122 ;;
2123 ;;   body-fld-id     = nstring
2124 ;;
2125 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2126 ;;
2127 ;;   body-fld-lines  = number
2128 ;;
2129 ;;   body-fld-md5    = nstring
2130 ;;
2131 ;;   body-fld-octets = number
2132 ;;
2133 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2134 ;;
2135 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2136 ;;                     [SP body-ext-1part]
2137 ;;
2138 ;;   body-type-basic = media-basic SP body-fields
2139 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2140 ;;
2141 ;;   body-type-msg   = media-message SP body-fields SP envelope
2142 ;;                     SP body SP body-fld-lines
2143 ;;
2144 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2145 ;;
2146 ;;   body-type-mpart = 1*body SP media-subtype
2147 ;;                     [SP body-ext-mpart]
2148 ;;
2149 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2150 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2151 ;;                       ; Defined in [MIME-IMT]
2152 ;;
2153 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2154 ;;                      ; Defined in [MIME-IMT]
2155 ;;
2156 ;;   media-subtype   = string
2157 ;;                       ; Defined in [MIME-IMT]
2158 ;;
2159 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2160 ;;                       ; Defined in [MIME-IMT]
2161
2162 (defun imap-parse-body ()
2163   (let (body)
2164     (when (eq (char-after) ?\()
2165       (imap-forward)
2166       (if (eq (char-after) ?\()
2167           (let (subbody)
2168             (while (and (eq (char-after) ?\()
2169                         (setq subbody (imap-parse-body)))
2170               (push subbody body))
2171             (imap-forward)
2172             (push (imap-parse-string) body);; media-subtype
2173             (when (eq (char-after) ?\ );; body-ext-mpart:
2174               (imap-forward)
2175               (if (eq (char-after) ?\();; body-fld-param
2176                   (push (imap-parse-string-list) body)
2177                 (push (and (imap-parse-nil) nil) body))
2178               (setq body
2179                     (append (imap-parse-body-ext) body)));; body-ext-...
2180             (assert (eq (char-after) ?\)))
2181             (imap-forward)
2182             (nreverse body))
2183
2184         (push (imap-parse-string) body);; media-type
2185         (imap-forward)
2186         (push (imap-parse-string) body);; media-subtype
2187         (imap-forward)
2188         ;; next line for Sun SIMS bug
2189         (and (eq (char-after) ? ) (imap-forward))
2190         (if (eq (char-after) ?\();; body-fld-param
2191             (push (imap-parse-string-list) body)
2192           (push (and (imap-parse-nil) nil) body))
2193         (imap-forward)
2194         (push (imap-parse-nstring) body);; body-fld-id
2195         (imap-forward)
2196         (push (imap-parse-nstring) body);; body-fld-desc
2197         (imap-forward)
2198         (push (imap-parse-string) body);; body-fld-enc
2199         (imap-forward)
2200         (push (imap-parse-number) body);; body-fld-octets
2201
2202         ;; ok, we're done parsing the required parts, what comes now is one
2203         ;; of three things:
2204         ;;
2205         ;; envelope       (then we're parsing body-type-msg)
2206         ;; body-fld-lines (then we're parsing body-type-text)
2207         ;; body-ext-1part (then we're parsing body-type-basic)
2208         ;;
2209         ;; the problem is that the two first are in turn optionally followed
2210         ;; by the third.  So we parse the first two here (if there are any)...
2211
2212         (when (eq (char-after) ?\ )
2213           (imap-forward)
2214           (let (lines)
2215             (cond ((eq (char-after) ?\();; body-type-msg:
2216                    (push (imap-parse-envelope) body);; envelope
2217                    (imap-forward)
2218                    (push (imap-parse-body) body);; body
2219                    (imap-forward)
2220                    (push (imap-parse-number) body));; body-fld-lines
2221                   ((setq lines (imap-parse-number));; body-type-text:
2222                    (push lines body));; body-fld-lines
2223                   (t
2224                    (backward-char)))));; no match...
2225
2226         ;; ...and then parse the third one here...
2227
2228         (when (eq (char-after) ?\ );; body-ext-1part:
2229           (imap-forward)
2230           (push (imap-parse-nstring) body);; body-fld-md5
2231           (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2232     
2233         (assert (eq (char-after) ?\)))
2234         (imap-forward)
2235         (nreverse body)))))
2236
2237 (when imap-debug                        ; (untrace-all)
2238   (require 'trace)
2239   (buffer-disable-undo (get-buffer-create imap-debug))
2240   (mapcar (lambda (f) (trace-function-background f imap-debug)) 
2241           '(
2242             imap-read-passwd
2243             imap-utf7-encode
2244             imap-utf7-decode
2245             imap-error-text
2246             imap-kerberos4s-p
2247             imap-kerberos4-open
2248             imap-ssl-p
2249             imap-ssl-open
2250             imap-network-p
2251             imap-network-open
2252             imap-interactive-login
2253             imap-kerberos4a-p
2254             imap-kerberos4-auth
2255             imap-cram-md5-p
2256             imap-cram-md5-auth
2257             imap-login-p
2258             imap-login-auth
2259             imap-anonymous-p
2260             imap-anonymous-auth
2261             imap-open-1
2262             imap-open
2263             imap-opened
2264             imap-authenticate
2265             imap-close
2266             imap-capability
2267             imap-namespace
2268             imap-send-command-wait
2269             imap-mailbox-put
2270             imap-mailbox-get
2271             imap-mailbox-map-1
2272             imap-mailbox-map
2273             imap-current-mailbox
2274             imap-current-mailbox-p-1
2275             imap-current-mailbox-p
2276             imap-mailbox-select-1
2277             imap-mailbox-select
2278             imap-mailbox-examine
2279             imap-mailbox-unselect
2280             imap-mailbox-expunge
2281             imap-mailbox-close
2282             imap-mailbox-create-1
2283             imap-mailbox-create
2284             imap-mailbox-delete
2285             imap-mailbox-rename
2286             imap-mailbox-lsub
2287             imap-mailbox-list
2288             imap-mailbox-subscribe
2289             imap-mailbox-unsubscribe
2290             imap-mailbox-status
2291             imap-mailbox-acl-get
2292             imap-mailbox-acl-set
2293             imap-mailbox-acl-delete
2294             imap-current-message
2295             imap-list-to-message-set
2296             imap-fetch-asynch
2297             imap-fetch
2298             imap-message-put
2299             imap-message-get
2300             imap-message-map
2301             imap-search
2302             imap-message-flag-permanent-p
2303             imap-message-flags-set
2304             imap-message-flags-del
2305             imap-message-flags-add
2306             imap-message-copyuid-1
2307             imap-message-copyuid
2308             imap-message-copy
2309             imap-message-appenduid-1
2310             imap-message-appenduid
2311             imap-message-append
2312             imap-body-lines
2313             imap-envelope-from
2314             imap-send-command-1
2315             imap-send-command
2316             imap-wait-for-tag
2317             imap-sentinel
2318             imap-find-next-line
2319             imap-arrival-filter
2320             imap-parse-greeting
2321             imap-parse-response
2322             imap-parse-resp-text
2323             imap-parse-resp-text-code
2324             imap-parse-data-list
2325             imap-parse-fetch
2326             imap-parse-status
2327             imap-parse-acl
2328             imap-parse-flag-list
2329             imap-parse-envelope
2330             imap-parse-body-extension
2331             imap-parse-body
2332             )))
2333         
2334 (provide 'imap)
2335
2336 ;;; imap.el ends here