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