(gnus-uu-digest-mail-forward): Fix comment.
[gnus] / lisp / imap.el
1 ;;; imap.el --- imap library
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005 Free Software Foundation, Inc.
5
6 ;; Author: Simon Josefsson <jas@pdc.kth.se>
7 ;; Keywords: mail
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;; imap.el is a elisp library providing an interface for talking to
29 ;; IMAP servers.
30 ;;
31 ;; imap.el is roughly divided in two parts, one that parses IMAP
32 ;; responses from the server and storing data into buffer-local
33 ;; variables, and one for utility functions which send commands to
34 ;; server, waits for an answer, and return information.  The latter
35 ;; part is layered on top of the previous.
36 ;;
37 ;; The imap.el API consist of the following functions, other functions
38 ;; in this file should not be called directly and the result of doing
39 ;; so are at best undefined.
40 ;;
41 ;; Global commands:
42 ;;
43 ;; imap-open,       imap-opened,    imap-authenticate, imap-close,
44 ;; imap-capability, imap-namespace, imap-error-text
45 ;;
46 ;; Mailbox commands:
47 ;;
48 ;; imap-mailbox-get,       imap-mailbox-map,         imap-current-mailbox,
49 ;; imap-current-mailbox-p, imap-search,              imap-mailbox-select,
50 ;; imap-mailbox-examine,   imap-mailbox-unselect,    imap-mailbox-expunge
51 ;; imap-mailbox-close,     imap-mailbox-create,      imap-mailbox-delete
52 ;; imap-mailbox-rename,    imap-mailbox-lsub,        imap-mailbox-list
53 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
54 ;; imap-mailbox-acl-get,   imap-mailbox-acl-set,     imap-mailbox-acl-delete
55 ;;
56 ;; Message commands:
57 ;;
58 ;; imap-fetch-asynch,                 imap-fetch,
59 ;; imap-current-message,              imap-list-to-message-set,
60 ;; imap-message-get,                  imap-message-map
61 ;; imap-message-envelope-date,        imap-message-envelope-subject,
62 ;; imap-message-envelope-from,        imap-message-envelope-sender,
63 ;; imap-message-envelope-reply-to,    imap-message-envelope-to,
64 ;; imap-message-envelope-cc,          imap-message-envelope-bcc
65 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
66 ;; imap-message-body,                 imap-message-flag-permanent-p
67 ;; imap-message-flags-set,            imap-message-flags-del
68 ;; imap-message-flags-add,            imap-message-copyuid
69 ;; imap-message-copy,                 imap-message-appenduid
70 ;; imap-message-append,               imap-envelope-from
71 ;; imap-body-lines
72 ;;
73 ;; It is my hope that these commands should be pretty self
74 ;; explanatory for someone that know IMAP.  All functions have
75 ;; additional documentation on how to invoke them.
76 ;;
77 ;; imap.el support RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1), implemented
78 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
79 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
80 ;; LOGINDISABLED) (with use of external library starttls.el and
81 ;; program starttls), and the GSSAPI / kerberos V4 sections of RFC1731
82 ;; (with use of external program `imtest'), RFC2971 (ID).  It also
83 ;; take advantage the UNSELECT extension in Cyrus IMAPD.
84 ;;
85 ;; Without the work of John McClary Prevost and Jim Radford this library
86 ;; would not have seen the light of day.  Many thanks.
87 ;;
88 ;; This is a transcript of short interactive session for demonstration
89 ;; purposes.
90 ;;
91 ;; (imap-open "my.mail.server")
92 ;; => " *imap* my.mail.server:0"
93 ;;
94 ;; The rest are invoked with current buffer as the buffer returned by
95 ;; `imap-open'.  It is possible to do all without this, but it would
96 ;; look ugly here since `buffer' is always the last argument for all
97 ;; imap.el API functions.
98 ;;
99 ;; (imap-authenticate "myusername" "mypassword")
100 ;; => auth
101 ;;
102 ;; (imap-mailbox-lsub "*")
103 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;;
105 ;; (imap-mailbox-list "INBOX.n%")
106 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;;
108 ;; (imap-mailbox-select "INBOX.nnimap")
109 ;; => "INBOX.nnimap"
110 ;;
111 ;; (imap-mailbox-get 'exists)
112 ;; => 166
113 ;;
114 ;; (imap-mailbox-get 'uidvalidity)
115 ;; => "908992622"
116 ;;
117 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
118 ;; => (235 236)
119 ;;
120 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
121 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
122 ;;
123 ;; Todo:
124 ;;
125 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
126 ;; o Don't use `read' at all (important places already fixed)
127 ;; o Accept list of articles instead of message set string in most
128 ;;   imap-message-* functions.
129 ;; o Send strings as literal if they contain, e.g., ".
130 ;;
131 ;; Revision history:
132 ;;
133 ;;  - 19991218 added starttls/digest-md5 patch,
134 ;;             by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
135 ;;             NB! you need SLIM for starttls.el and digest-md5.el
136 ;;  - 19991023 commited to pgnus
137 ;;
138
139 ;;; Code:
140
141 (eval-when-compile (require 'cl))
142 (eval-and-compile
143   (autoload 'starttls-open-stream "starttls")
144   (autoload 'starttls-negotiate "starttls")
145   (autoload 'sasl-find-mechanism "sasl")
146   (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147   (autoload 'digest-md5-digest-response "digest-md5")
148   (autoload 'digest-md5-digest-uri "digest-md5")
149   (autoload 'digest-md5-challenge "digest-md5")
150   (autoload 'rfc2104-hash "rfc2104")
151   (autoload 'utf7-encode "utf7")
152   (autoload 'utf7-decode "utf7")
153   (autoload 'format-spec "format-spec")
154   (autoload 'format-spec-make "format-spec")
155   (autoload 'open-tls-stream "tls"))
156
157 ;; User variables.
158
159 (defgroup imap nil
160   "Low-level IMAP issues."
161   :version "21.1"
162   :group 'mail)
163
164 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
165                                     "imtest -kp %s %p")
166   "List of strings containing commands for Kerberos 4 authentication.
167 %s is replaced with server hostname, %p with port to connect to, and
168 %l with the value of `imap-default-user'.  The program should accept
169 IMAP commands on stdin and return responses to stdout.  Each entry in
170 the list is tried until a successful connection is made."
171   :group 'imap
172   :type '(repeat string))
173
174 (defcustom imap-gssapi-program (list
175                                 (concat "gsasl %s %p "
176                                         "--mechanism GSSAPI "
177                                         "--authentication-id %l")
178                                 "imtest -m gssapi -u %l -p %p %s")
179   "List of strings containing commands for GSSAPI (krb5) authentication.
180 %s is replaced with server hostname, %p with port to connect to, and
181 %l with the value of `imap-default-user'.  The program should accept
182 IMAP commands on stdin and return responses to stdout.  Each entry in
183 the list is tried until a successful connection is made."
184   :group 'imap
185   :type '(repeat string))
186
187 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
188                               "openssl s_client -quiet -ssl2 -connect %s:%p"
189                               "s_client -quiet -ssl3 -connect %s:%p"
190                               "s_client -quiet -ssl2 -connect %s:%p")
191   "A string, or list of strings, containing commands for SSL connections.
192 Within a string, %s is replaced with the server address and %p with
193 port number on server.  The program should accept IMAP commands on
194 stdin and return responses to stdout.  Each entry in the list is tried
195 until a successful connection is made."
196   :group 'imap
197   :type '(choice string
198                  (repeat string)))
199
200 (defcustom imap-shell-program '("ssh %s imapd"
201                                 "rsh %s imapd"
202                                 "ssh %g ssh %s imapd"
203                                 "rsh %g rsh %s imapd")
204   "A list of strings, containing commands for IMAP connection.
205 Within a string, %s is replaced with the server address, %p with port
206 number on server, %g with `imap-shell-host', and %l with
207 `imap-default-user'.  The program should read IMAP commands from stdin
208 and write IMAP response to stdout. Each entry in the list is tried
209 until a successful connection is made."
210   :group 'imap
211   :type '(repeat string))
212
213 (defcustom imap-process-connection-type nil
214   "*Value for `process-connection-type' to use for Kerberos4, GSSAPI and SSL.
215 The `process-connection-type' variable control type of device
216 used to communicate with subprocesses.  Values are nil to use a
217 pipe, or t or `pty' to use a pty.  The value has no effect if the
218 system has no ptys or if all ptys are busy: then a pipe is used
219 in any case.  The value takes effect when a IMAP server is
220 opened, changing it after that has no effect."
221   :version "22.1"
222   :group 'imap
223   :type 'boolean)
224
225 (defcustom imap-use-utf7 t
226   "If non-nil, do utf7 encoding/decoding of mailbox names.
227 Since the UTF7 decoding currently only decodes into ISO-8859-1
228 characters, you may disable this decoding if you need to access UTF7
229 encoded mailboxes which doesn't translate into ISO-8859-1."
230   :group 'imap
231   :type 'boolean)
232
233 (defcustom imap-log nil
234   "If non-nil, a imap session trace is placed in *imap-log* buffer.
235 Note that username, passwords and other privacy sensitive
236 information (such as e-mail) may be stored in the *imap-log*
237 buffer.  It is not written to disk, however.  Do not enable this
238 variable unless you are comfortable with that."
239   :group 'imap
240   :type 'boolean)
241
242 (defcustom imap-debug nil
243   "If non-nil, random debug spews are placed in *imap-debug* buffer.
244 Note that username, passwords and other privacy sensitive
245 information (such as e-mail) may be stored in the *imap-debug*
246 buffer.  It is not written to disk, however.  Do not enable this
247 variable unless you are comfortable with that."
248   :group 'imap
249   :type 'boolean)
250
251 (defcustom imap-shell-host "gateway"
252   "Hostname of rlogin proxy."
253   :group 'imap
254   :type 'string)
255
256 (defcustom imap-default-user (user-login-name)
257   "Default username to use."
258   :group 'imap
259   :type 'string)
260
261 (defcustom imap-read-timeout (if (string-match
262                                   "windows-nt\\|os/2\\|emx\\|cygwin"
263                                   (symbol-name system-type))
264                                  1.0
265                                0.1)
266   "*How long to wait between checking for the end of output.
267 Shorter values mean quicker response, but is more CPU intensive."
268   :type 'number
269   :group 'imap)
270
271 (defcustom imap-store-password nil
272   "If non-nil, store session password without promting."
273   :group 'imap
274   :type 'boolean)
275
276 ;; Various variables.
277
278 (defvar imap-fetch-data-hook nil
279   "Hooks called after receiving each FETCH response.")
280
281 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
282   "Priority of streams to consider when opening connection to server.")
283
284 (defvar imap-stream-alist
285   '((gssapi    imap-gssapi-stream-p    imap-gssapi-open)
286     (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
287     (tls       imap-tls-p              imap-tls-open)
288     (ssl       imap-ssl-p              imap-ssl-open)
289     (network   imap-network-p          imap-network-open)
290     (shell     imap-shell-p            imap-shell-open)
291     (starttls  imap-starttls-p         imap-starttls-open))
292   "Definition of network streams.
293
294 \(NAME CHECK OPEN)
295
296 NAME names the stream, CHECK is a function returning non-nil if the
297 server support the stream and OPEN is a function for opening the
298 stream.")
299
300 (defvar imap-authenticators '(gssapi
301                               kerberos4
302                               digest-md5
303                               cram-md5
304                               ;;sasl
305                               login
306                               anonymous)
307   "Priority of authenticators to consider when authenticating to server.")
308
309 (defvar imap-authenticator-alist
310   '((gssapi     imap-gssapi-auth-p    imap-gssapi-auth)
311     (kerberos4  imap-kerberos4-auth-p imap-kerberos4-auth)
312     (sasl       imap-sasl-auth-p      imap-sasl-auth)
313     (cram-md5   imap-cram-md5-p       imap-cram-md5-auth)
314     (login      imap-login-p          imap-login-auth)
315     (anonymous  imap-anonymous-p      imap-anonymous-auth)
316     (digest-md5 imap-digest-md5-p     imap-digest-md5-auth))
317   "Definition of authenticators.
318
319 \(NAME CHECK AUTHENTICATE)
320
321 NAME names the authenticator.  CHECK is a function returning non-nil if
322 the server support the authenticator and AUTHENTICATE is a function
323 for doing the actual authentication.")
324
325 (defvar imap-error nil
326   "Error codes from the last command.")
327
328 ;; Internal constants.  Change these and die.
329
330 (defconst imap-default-port 143)
331 (defconst imap-default-ssl-port 993)
332 (defconst imap-default-tls-port 993)
333 (defconst imap-default-stream 'network)
334 (defconst imap-coding-system-for-read 'binary)
335 (defconst imap-coding-system-for-write 'binary)
336 (defconst imap-local-variables '(imap-server
337                                  imap-port
338                                  imap-client-eol
339                                  imap-server-eol
340                                  imap-auth
341                                  imap-stream
342                                  imap-username
343                                  imap-password
344                                  imap-current-mailbox
345                                  imap-current-target-mailbox
346                                  imap-message-data
347                                  imap-capability
348                                  imap-id
349                                  imap-namespace
350                                  imap-state
351                                  imap-reached-tag
352                                  imap-failed-tags
353                                  imap-tag
354                                  imap-process
355                                  imap-calculate-literal-size-first
356                                  imap-mailbox-data))
357 (defconst imap-log-buffer "*imap-log*")
358 (defconst imap-debug-buffer "*imap-debug*")
359
360 ;; Internal variables.
361
362 (defvar imap-stream nil)
363 (defvar imap-auth nil)
364 (defvar imap-server nil)
365 (defvar imap-port nil)
366 (defvar imap-username nil)
367 (defvar imap-password nil)
368 (defvar imap-calculate-literal-size-first nil)
369 (defvar imap-state 'closed
370   "IMAP state.
371 Valid states are `closed', `initial', `nonauth', `auth', `selected'
372 and `examine'.")
373
374 (defvar imap-server-eol "\r\n"
375   "The EOL string sent from the server.")
376
377 (defvar imap-client-eol "\r\n"
378   "The EOL string we send to the server.")
379
380 (defvar imap-current-mailbox nil
381   "Current mailbox name.")
382
383 (defvar imap-current-target-mailbox nil
384   "Current target mailbox for COPY and APPEND commands.")
385
386 (defvar imap-mailbox-data nil
387   "Obarray with mailbox data.")
388
389 (defvar imap-mailbox-prime 997
390   "Length of imap-mailbox-data.")
391
392 (defvar imap-current-message nil
393   "Current message number.")
394
395 (defvar imap-message-data nil
396   "Obarray with message data.")
397
398 (defvar imap-message-prime 997
399   "Length of imap-message-data.")
400
401 (defvar imap-capability nil
402   "Capability for server.")
403
404 (defvar imap-id nil
405   "Identity of server.
406 See RFC 2971.")
407
408 (defvar imap-namespace nil
409   "Namespace for current server.")
410
411 (defvar imap-reached-tag 0
412   "Lower limit on command tags that have been parsed.")
413
414 (defvar imap-failed-tags nil
415   "Alist of tags that failed.
416 Each element is a list with four elements; tag (a integer), response
417 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
418 human readable response text (a string).")
419
420 (defvar imap-tag 0
421   "Command tag number.")
422
423 (defvar imap-process nil
424   "Process.")
425
426 (defvar imap-continuation nil
427   "Non-nil indicates that the server emitted a continuation request.
428 The actual value is really the text on the continuation line.")
429
430 (defvar imap-callbacks nil
431   "List of response tags and callbacks, on the form `(number . function)'.
432 The function should take two arguments, the first the IMAP tag and the
433 second the status (OK, NO, BAD etc) of the command.")
434
435 \f
436 ;; Utility functions:
437
438 (defun imap-remassoc (key alist)
439   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
440 The modified LIST is returned.  If the first member
441 of LIST has a car that is `equal' to KEY, there is no way to remove it
442 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
443 sure of changing the value of `foo'."
444   (when alist
445     (if (equal key (caar alist))
446         (cdr alist)
447       (setcdr alist (imap-remassoc key (cdr alist)))
448       alist)))
449
450 (defsubst imap-disable-multibyte ()
451   "Enable multibyte in the current buffer."
452   (when (fboundp 'set-buffer-multibyte)
453     (set-buffer-multibyte nil)))
454
455 (defsubst imap-utf7-encode (string)
456   (if imap-use-utf7
457       (and string
458            (condition-case ()
459                (utf7-encode string t)
460              (error (message
461                      "imap: Could not UTF7 encode `%s', using it unencoded..."
462                      string)
463                     string)))
464     string))
465
466 (defsubst imap-utf7-decode (string)
467   (if imap-use-utf7
468       (and string
469            (condition-case ()
470                (utf7-decode string t)
471              (error (message
472                      "imap: Could not UTF7 decode `%s', using it undecoded..."
473                      string)
474                     string)))
475     string))
476
477 (defsubst imap-ok-p (status)
478   (if (eq status 'OK)
479       t
480     (setq imap-error status)
481     nil))
482
483 (defun imap-error-text (&optional buffer)
484   (with-current-buffer (or buffer (current-buffer))
485     (nth 3 (car imap-failed-tags))))
486
487 \f
488 ;; Server functions; stream stuff:
489
490 (defun imap-kerberos4-stream-p (buffer)
491   (imap-capability 'AUTH=KERBEROS_V4 buffer))
492
493 (defun imap-kerberos4-open (name buffer server port)
494   (let ((cmds imap-kerberos4-program)
495         cmd done)
496     (while (and (not done) (setq cmd (pop cmds)))
497       (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
498       (erase-buffer)
499       (let* ((port (or port imap-default-port))
500              (coding-system-for-read imap-coding-system-for-read)
501              (coding-system-for-write imap-coding-system-for-write)
502              (process-connection-type imap-process-connection-type)
503              (process (start-process
504                        name buffer shell-file-name shell-command-switch
505                        (format-spec
506                         cmd
507                         (format-spec-make
508                          ?s server
509                          ?p (number-to-string port)
510                          ?l imap-default-user))))
511              response)
512         (when process
513           (with-current-buffer buffer
514             (setq imap-client-eol "\n"
515                   imap-calculate-literal-size-first t)
516             (while (and (memq (process-status process) '(open run))
517                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
518                         (goto-char (point-min))
519                         ;; Athena IMTEST can output SSL verify errors
520                         (or (while (looking-at "^verify error:num=")
521                               (forward-line))
522                             t)
523                         (or (while (looking-at "^TLS connection established")
524                               (forward-line))
525                             t)
526                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
527                         (or (while (looking-at "^C:")
528                               (forward-line))
529                             t)
530                         ;; cyrus 1.6 imtest print "S: " before server greeting
531                         (or (not (looking-at "S: "))
532                             (forward-char 3)
533                             t)
534                         (not (and (imap-parse-greeting)
535                                   ;; success in imtest < 1.6:
536                                   (or (re-search-forward
537                                        "^__\\(.*\\)__\n" nil t)
538                                       ;; success in imtest 1.6:
539                                       (re-search-forward
540                                        "^\\(Authenticat.*\\)" nil t))
541                                   (setq response (match-string 1)))))
542               (accept-process-output process 1)
543               (sit-for 1))
544             (and imap-log
545                  (with-current-buffer (get-buffer-create imap-log-buffer)
546                    (imap-disable-multibyte)
547                    (buffer-disable-undo)
548                    (goto-char (point-max))
549                    (insert-buffer-substring buffer)))
550             (erase-buffer)
551             (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
552                      (if response (concat "done, " response) "failed"))
553             (if (and response (let ((case-fold-search nil))
554                                 (not (string-match "failed" response))))
555                 (setq done process)
556               (if (memq (process-status process) '(open run))
557                   (imap-send-command "LOGOUT"))
558               (delete-process process)
559               nil)))))
560     done))
561
562 (defun imap-gssapi-stream-p (buffer)
563   (imap-capability 'AUTH=GSSAPI buffer))
564
565 (defun imap-gssapi-open (name buffer server port)
566   (let ((cmds imap-gssapi-program)
567         cmd done)
568     (while (and (not done) (setq cmd (pop cmds)))
569       (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
570       (erase-buffer)
571       (let* ((port (or port imap-default-port))
572              (coding-system-for-read imap-coding-system-for-read)
573              (coding-system-for-write imap-coding-system-for-write)
574              (process-connection-type imap-process-connection-type)
575              (process (start-process
576                        name buffer shell-file-name shell-command-switch
577                        (format-spec
578                         cmd
579                         (format-spec-make
580                          ?s server
581                          ?p (number-to-string port)
582                          ?l imap-default-user))))
583              response)
584         (when process
585           (with-current-buffer buffer
586             (setq imap-client-eol "\n"
587                   imap-calculate-literal-size-first t)
588             (while (and (memq (process-status process) '(open run))
589                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
590                         (goto-char (point-min))
591                         ;; Athena IMTEST can output SSL verify errors
592                         (or (while (looking-at "^verify error:num=")
593                               (forward-line))
594                             t)
595                         (or (while (looking-at "^TLS connection established")
596                               (forward-line))
597                             t)
598                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
599                         (or (while (looking-at "^C:")
600                               (forward-line))
601                             t)
602                         ;; cyrus 1.6 imtest print "S: " before server greeting
603                         (or (not (looking-at "S: "))
604                             (forward-char 3)
605                             t)
606                         ;; GNU SASL may print 'Trying ...' first.
607                         (or (not (looking-at "Trying "))
608                             (forward-line)
609                             t)
610                         (not (and (imap-parse-greeting)
611                                   ;; success in imtest 1.6:
612                                   (re-search-forward
613                                    (concat "^\\(\\(Authenticat.*\\)\\|\\("
614                                            "Client authentication "
615                                            "finished.*\\)\\)")
616                                    nil t)
617                                   (setq response (match-string 1)))))
618               (accept-process-output process 1)
619               (sit-for 1))
620             (and imap-log
621                  (with-current-buffer (get-buffer-create imap-log-buffer)
622                    (imap-disable-multibyte)
623                    (buffer-disable-undo)
624                    (goto-char (point-max))
625                    (insert-buffer-substring buffer)))
626             (erase-buffer)
627             (message "GSSAPI IMAP connection: %s" (or response "failed"))
628             (if (and response (let ((case-fold-search nil))
629                                 (not (string-match "failed" response))))
630                 (setq done process)
631               (if (memq (process-status process) '(open run))
632                   (imap-send-command "LOGOUT"))
633               (delete-process process)
634               nil)))))
635     done))
636
637 (defun imap-ssl-p (buffer)
638   nil)
639
640 (defun imap-ssl-open (name buffer server port)
641   "Open a SSL connection to server."
642   (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
643                 (list imap-ssl-program)))
644         cmd done)
645     (while (and (not done) (setq cmd (pop cmds)))
646       (message "imap: Opening SSL connection with `%s'..." cmd)
647       (erase-buffer)
648       (let* ((port (or port imap-default-ssl-port))
649              (coding-system-for-read imap-coding-system-for-read)
650              (coding-system-for-write imap-coding-system-for-write)
651              (process-connection-type imap-process-connection-type)
652              (set-process-query-on-exit-flag
653               (if (fboundp 'set-process-query-on-exit-flag)
654                   'set-process-query-on-exit-flag
655                 'process-kill-without-query))
656              process)
657         (when (progn
658                 (setq process (start-process
659                                name buffer shell-file-name
660                                shell-command-switch
661                                (format-spec cmd
662                                             (format-spec-make
663                                              ?s server
664                                              ?p (number-to-string port)))))
665                 (funcall set-process-query-on-exit-flag process nil)
666                 process)
667           (with-current-buffer buffer
668             (goto-char (point-min))
669             (while (and (memq (process-status process) '(open run))
670                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
671                         (goto-char (point-max))
672                         (forward-line -1)
673                         (not (imap-parse-greeting)))
674               (accept-process-output process 1)
675               (sit-for 1))
676             (and imap-log
677                  (with-current-buffer (get-buffer-create imap-log-buffer)
678                    (imap-disable-multibyte)
679                    (buffer-disable-undo)
680                    (goto-char (point-max))
681                    (insert-buffer-substring buffer)))
682             (erase-buffer)
683             (when (memq (process-status process) '(open run))
684               (setq done process))))))
685     (if done
686         (progn
687           (message "imap: Opening SSL connection with `%s'...done" cmd)
688           done)
689       (message "imap: Opening SSL connection with `%s'...failed" cmd)
690       nil)))
691
692 (defun imap-tls-p (buffer)
693   nil)
694
695 (defun imap-tls-open (name buffer server port)
696   (let* ((port (or port imap-default-tls-port))
697          (coding-system-for-read imap-coding-system-for-read)
698          (coding-system-for-write imap-coding-system-for-write)
699          (process (open-tls-stream name buffer server port)))
700     (when process
701       (while (and (memq (process-status process) '(open run))
702                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
703                   (goto-char (point-max))
704                   (forward-line -1)
705                   (not (imap-parse-greeting)))
706         (accept-process-output process 1)
707         (sit-for 1))
708       (and imap-log
709            (with-current-buffer (get-buffer-create imap-log-buffer)
710              (imap-disable-multibyte)
711              (buffer-disable-undo)
712              (goto-char (point-max))
713              (insert-buffer-substring buffer)))
714       (when (memq (process-status process) '(open run))
715         process))))
716
717 (defun imap-network-p (buffer)
718   t)
719
720 (defun imap-network-open (name buffer server port)
721   (let* ((port (or port imap-default-port))
722          (coding-system-for-read imap-coding-system-for-read)
723          (coding-system-for-write imap-coding-system-for-write)
724          (process (open-network-stream name buffer server port)))
725     (when process
726       (while (and (memq (process-status process) '(open run))
727                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
728                   (goto-char (point-min))
729                   (not (imap-parse-greeting)))
730         (accept-process-output process 1)
731         (sit-for 1))
732       (and imap-log
733            (with-current-buffer (get-buffer-create imap-log-buffer)
734              (imap-disable-multibyte)
735              (buffer-disable-undo)
736              (goto-char (point-max))
737              (insert-buffer-substring buffer)))
738       (when (memq (process-status process) '(open run))
739         process))))
740
741 (defun imap-shell-p (buffer)
742   nil)
743
744 (defun imap-shell-open (name buffer server port)
745   (let ((cmds (if (listp imap-shell-program) imap-shell-program
746                 (list imap-shell-program)))
747         cmd done)
748     (while (and (not done) (setq cmd (pop cmds)))
749       (message "imap: Opening IMAP connection with `%s'..." cmd)
750       (setq imap-client-eol "\n")
751       (let* ((port (or port imap-default-port))
752              (coding-system-for-read imap-coding-system-for-read)
753              (coding-system-for-write imap-coding-system-for-write)
754              (process (start-process
755                        name buffer shell-file-name shell-command-switch
756                        (format-spec
757                         cmd
758                         (format-spec-make
759                          ?s server
760                          ?g imap-shell-host
761                          ?p (number-to-string port)
762                          ?l imap-default-user)))))
763         (when process
764           (while (and (memq (process-status process) '(open run))
765                       (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
766                       (goto-char (point-max))
767                       (forward-line -1)
768                       (not (imap-parse-greeting)))
769             (accept-process-output process 1)
770             (sit-for 1))
771           (and imap-log
772                (with-current-buffer (get-buffer-create imap-log-buffer)
773                  (imap-disable-multibyte)
774                  (buffer-disable-undo)
775                  (goto-char (point-max))
776                  (insert-buffer-substring buffer)))
777           (erase-buffer)
778           (when (memq (process-status process) '(open run))
779             (setq done process)))))
780     (if done
781         (progn
782           (message "imap: Opening IMAP connection with `%s'...done" cmd)
783           done)
784       (message "imap: Opening IMAP connection with `%s'...failed" cmd)
785       nil)))
786
787 (defun imap-starttls-p (buffer)
788   (imap-capability 'STARTTLS buffer))
789
790 (defun imap-starttls-open (name buffer server port)
791   (let* ((port (or port imap-default-port))
792          (coding-system-for-read imap-coding-system-for-read)
793          (coding-system-for-write imap-coding-system-for-write)
794          (process (starttls-open-stream name buffer server port))
795          done tls-info)
796     (message "imap: Connecting with STARTTLS...")
797     (when process
798       (while (and (memq (process-status process) '(open run))
799                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
800                   (goto-char (point-max))
801                   (forward-line -1)
802                   (not (imap-parse-greeting)))
803         (accept-process-output process 1)
804         (sit-for 1))
805       (imap-send-command "STARTTLS")
806       (while (and (memq (process-status process) '(open run))
807                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
808                   (goto-char (point-max))
809                   (forward-line -1)
810                   (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
811         (accept-process-output process 1)
812         (sit-for 1))
813       (and imap-log
814            (with-current-buffer (get-buffer-create imap-log-buffer)
815              (buffer-disable-undo)
816              (goto-char (point-max))
817              (insert-buffer-substring buffer)))
818       (when (and (setq tls-info (starttls-negotiate process))
819                  (memq (process-status process) '(open run)))
820         (setq done process)))
821     (if (stringp tls-info)
822         (message "imap: STARTTLS info: %s" tls-info))
823     (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
824     done))
825
826 ;; Server functions; authenticator stuff:
827
828 (defun imap-interactive-login (buffer loginfunc)
829   "Login to server in BUFFER.
830 LOGINFUNC is passed a username and a password, it should return t if
831 it where successful authenticating itself to the server, nil otherwise.
832 Returns t if login was successful, nil otherwise."
833   (with-current-buffer buffer
834     (make-local-variable 'imap-username)
835     (make-local-variable 'imap-password)
836     (let (user passwd ret)
837       ;;      (condition-case ()
838       (while (or (not user) (not passwd))
839         (setq user (or imap-username
840                        (read-from-minibuffer
841                         (concat "IMAP username for " imap-server
842                                 " (using stream `" (symbol-name imap-stream)
843                                 "'): ")
844                         (or user imap-default-user))))
845         (setq passwd (or imap-password
846                          (read-passwd
847                           (concat "IMAP password for " user "@"
848                                   imap-server " (using authenticator `"
849                                   (symbol-name imap-auth) "'): "))))
850         (when (and user passwd)
851           (if (funcall loginfunc user passwd)
852               (progn
853                 (setq ret t
854                       imap-username user)
855                 (when (and (not imap-password)
856                            (or imap-store-password
857                                (y-or-n-p "Store password for this session? ")))
858                   (setq imap-password passwd)))
859             (message "Login failed...")
860             (setq passwd nil)
861             (setq imap-password nil)
862             (sit-for 1))))
863       ;;        (quit (with-current-buffer buffer
864       ;;                (setq user nil
865       ;;                      passwd nil)))
866       ;;        (error (with-current-buffer buffer
867       ;;                 (setq user nil
868       ;;                       passwd nil))))
869       ret)))
870
871 (defun imap-gssapi-auth-p (buffer)
872   (eq imap-stream 'gssapi))
873
874 (defun imap-gssapi-auth (buffer)
875   (message "imap: Authenticating using GSSAPI...%s"
876            (if (eq imap-stream 'gssapi) "done" "failed"))
877   (eq imap-stream 'gssapi))
878
879 (defun imap-kerberos4-auth-p (buffer)
880   (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
881        (eq imap-stream 'kerberos4)))
882
883 (defun imap-kerberos4-auth (buffer)
884   (message "imap: Authenticating using Kerberos 4...%s"
885            (if (eq imap-stream 'kerberos4) "done" "failed"))
886   (eq imap-stream 'kerberos4))
887
888 (defun imap-cram-md5-p (buffer)
889   (imap-capability 'AUTH=CRAM-MD5 buffer))
890
891 (defun imap-cram-md5-auth (buffer)
892   "Login to server using the AUTH CRAM-MD5 method."
893   (message "imap: Authenticating using CRAM-MD5...")
894   (let ((done (imap-interactive-login
895                buffer
896                (lambda (user passwd)
897                  (imap-ok-p
898                   (imap-send-command-wait
899                    (list
900                     "AUTHENTICATE CRAM-MD5"
901                     (lambda (challenge)
902                       (let* ((decoded (base64-decode-string challenge))
903                              (hash (rfc2104-hash 'md5 64 16 passwd decoded))
904                              (response (concat user " " hash))
905                              (encoded (base64-encode-string response)))
906                         encoded)))))))))
907     (if done
908         (message "imap: Authenticating using CRAM-MD5...done")
909       (message "imap: Authenticating using CRAM-MD5...failed"))))
910
911 (defun imap-login-p (buffer)
912   (and (not (imap-capability 'LOGINDISABLED buffer))
913        (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
914
915 (defun imap-login-auth (buffer)
916   "Login to server using the LOGIN command."
917   (message "imap: Plaintext authentication...")
918   (imap-interactive-login buffer
919                           (lambda (user passwd)
920                             (imap-ok-p (imap-send-command-wait
921                                         (concat "LOGIN \"" user "\" \""
922                                                 passwd "\""))))))
923
924 (defun imap-anonymous-p (buffer)
925   t)
926
927 (defun imap-anonymous-auth (buffer)
928   (message "imap: Logging in anonymously...")
929   (with-current-buffer buffer
930     (imap-ok-p (imap-send-command-wait
931                 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
932                                                      (system-name)) "\"")))))
933
934 ;;; Compiler directives.
935
936 (defvar imap-sasl-client)
937 (defvar imap-sasl-step)
938
939 (defun imap-sasl-make-mechanisms (buffer)
940   (let ((mecs '()))
941     (mapc (lambda (sym)
942             (let ((name (symbol-name sym)))
943               (if (and (> (length name) 5)
944                        (string-equal "AUTH=" (substring name 0 5 )))
945                   (setq mecs (cons (substring name 5) mecs)))))
946           (imap-capability nil buffer))
947     mecs))
948
949 (defun imap-sasl-auth-p (buffer)
950   (and (condition-case ()
951            (require 'sasl)
952          (error nil))
953        (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
954
955 (defun imap-sasl-auth (buffer)
956   "Login to server using the SASL method."
957   (message "imap: Authenticating using SASL...")
958   (with-current-buffer buffer
959     (make-local-variable 'imap-username)
960     (make-local-variable 'imap-sasl-client)
961     (make-local-variable 'imap-sasl-step)
962     (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
963           logged user)
964       (while (not logged)
965         (setq user (or imap-username
966                        (read-from-minibuffer
967                         (concat "IMAP username for " imap-server " using SASL "
968                                 (sasl-mechanism-name mechanism) ": ")
969                         (or user imap-default-user))))
970         (when user
971           (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
972                 imap-sasl-step (sasl-next-step imap-sasl-client nil))
973           (let ((tag (imap-send-command
974                       (if (sasl-step-data imap-sasl-step)
975                           (format "AUTHENTICATE %s %s"
976                                   (sasl-mechanism-name mechanism)
977                                   (sasl-step-data imap-sasl-step))
978                         (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
979                       buffer)))
980             (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
981               (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
982               (setq imap-continuation nil
983                     imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
984               (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
985                                        (base64-encode-string (sasl-step-data imap-sasl-step) t)
986                                      "")))
987             (if (imap-ok-p (imap-wait-for-tag tag))
988                 (setq imap-username user
989                       logged t)
990               (message "Login failed...")
991               (sit-for 1)))))
992       logged)))
993
994 (defun imap-digest-md5-p (buffer)
995   (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
996        (condition-case ()
997            (require 'digest-md5)
998          (error nil))))
999
1000 (defun imap-digest-md5-auth (buffer)
1001   "Login to server using the AUTH DIGEST-MD5 method."
1002   (message "imap: Authenticating using DIGEST-MD5...")
1003   (imap-interactive-login
1004    buffer
1005    (lambda (user passwd)
1006      (let ((tag
1007             (imap-send-command
1008              (list
1009               "AUTHENTICATE DIGEST-MD5"
1010               (lambda (challenge)
1011                 (digest-md5-parse-digest-challenge
1012                  (base64-decode-string challenge))
1013                 (let* ((digest-uri
1014                         (digest-md5-digest-uri
1015                          "imap" (digest-md5-challenge 'realm)))
1016                        (response
1017                         (digest-md5-digest-response
1018                          user passwd digest-uri)))
1019                   (base64-encode-string response 'no-line-break))))
1020              )))
1021        (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1022            nil
1023          (setq imap-continuation nil)
1024          (imap-send-command-1 "")
1025          (imap-ok-p (imap-wait-for-tag tag)))))))
1026
1027 ;; Server functions:
1028
1029 (defun imap-open-1 (buffer)
1030   (with-current-buffer buffer
1031     (erase-buffer)
1032     (setq imap-current-mailbox nil
1033           imap-current-message nil
1034           imap-state 'initial
1035           imap-process (condition-case ()
1036                            (funcall (nth 2 (assq imap-stream
1037                                                  imap-stream-alist))
1038                                     "imap" buffer imap-server imap-port)
1039                          ((error quit) nil)))
1040     (when imap-process
1041       (set-process-filter imap-process 'imap-arrival-filter)
1042       (set-process-sentinel imap-process 'imap-sentinel)
1043       (while (and (eq imap-state 'initial)
1044                   (memq (process-status imap-process) '(open run)))
1045         (message "Waiting for response from %s..." imap-server)
1046         (accept-process-output imap-process 1))
1047       (message "Waiting for response from %s...done" imap-server)
1048       (and (memq (process-status imap-process) '(open run))
1049            imap-process))))
1050
1051 (defun imap-open (server &optional port stream auth buffer)
1052   "Open a IMAP connection to host SERVER at PORT returning a buffer.
1053 If PORT is unspecified, a default value is used (143 except
1054 for SSL which use 993).
1055 STREAM indicates the stream to use, see `imap-streams' for available
1056 streams.  If nil, it choices the best stream the server is capable of.
1057 AUTH indicates authenticator to use, see `imap-authenticators' for
1058 available authenticators.  If nil, it choices the best stream the
1059 server is capable of.
1060 BUFFER can be a buffer or a name of a buffer, which is created if
1061 necessary.  If nil, the buffer name is generated."
1062   (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1063   (with-current-buffer (get-buffer-create buffer)
1064     (if (imap-opened buffer)
1065         (imap-close buffer))
1066     (mapcar 'make-local-variable imap-local-variables)
1067     (imap-disable-multibyte)
1068     (buffer-disable-undo)
1069     (setq imap-server (or server imap-server))
1070     (setq imap-port (or port imap-port))
1071     (setq imap-auth (or auth imap-auth))
1072     (setq imap-stream (or stream imap-stream))
1073     (message "imap: Connecting to %s..." imap-server)
1074     (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1075                 (imap-open-1 buffer)))
1076         (progn
1077           (message "imap: Connecting to %s...failed" imap-server)
1078           nil)
1079       (when (null imap-stream)
1080         ;; Need to choose stream.
1081         (let ((streams imap-streams))
1082           (while (setq stream (pop streams))
1083             ;; OK to use this stream?
1084             (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1085               ;; Stream changed?
1086               (if (not (eq imap-default-stream stream))
1087                   (with-current-buffer (get-buffer-create
1088                                         (generate-new-buffer-name " *temp*"))
1089                     (mapcar 'make-local-variable imap-local-variables)
1090                     (imap-disable-multibyte)
1091                     (buffer-disable-undo)
1092                     (setq imap-server (or server imap-server))
1093                     (setq imap-port (or port imap-port))
1094                     (setq imap-auth (or auth imap-auth))
1095                     (message "imap: Reconnecting with stream `%s'..." stream)
1096                     (if (null (let ((imap-stream stream))
1097                                 (imap-open-1 (current-buffer))))
1098                         (progn
1099                           (kill-buffer (current-buffer))
1100                           (message
1101                            "imap: Reconnecting with stream `%s'...failed"
1102                            stream))
1103                       ;; We're done, kill the first connection
1104                       (imap-close buffer)
1105                       (kill-buffer buffer)
1106                       (rename-buffer buffer)
1107                       (message "imap: Reconnecting with stream `%s'...done"
1108                                stream)
1109                       (setq imap-stream stream)
1110                       (setq imap-capability nil)
1111                       (setq streams nil)))
1112                 ;; We're done
1113                 (message "imap: Connecting to %s...done" imap-server)
1114                 (setq imap-stream stream)
1115                 (setq imap-capability nil)
1116                 (setq streams nil))))))
1117       (when (imap-opened buffer)
1118         (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1119       (when imap-stream
1120         buffer))))
1121
1122 (defun imap-opened (&optional buffer)
1123   "Return non-nil if connection to imap server in BUFFER is open.
1124 If BUFFER is nil then the current buffer is used."
1125   (and (setq buffer (get-buffer (or buffer (current-buffer))))
1126        (buffer-live-p buffer)
1127        (with-current-buffer buffer
1128          (and imap-process
1129               (memq (process-status imap-process) '(open run))))))
1130
1131 (defun imap-authenticate (&optional user passwd buffer)
1132   "Authenticate to server in BUFFER, using current buffer if nil.
1133 It uses the authenticator specified when opening the server.  If the
1134 authenticator requires username/passwords, they are queried from the
1135 user and optionally stored in the buffer.  If USER and/or PASSWD is
1136 specified, the user will not be questioned and the username and/or
1137 password is remembered in the buffer."
1138   (with-current-buffer (or buffer (current-buffer))
1139     (if (not (eq imap-state 'nonauth))
1140         (or (eq imap-state 'auth)
1141             (eq imap-state 'selected)
1142             (eq imap-state 'examine))
1143       (make-local-variable 'imap-username)
1144       (make-local-variable 'imap-password)
1145       (if user (setq imap-username user))
1146       (if passwd (setq imap-password passwd))
1147       (if imap-auth
1148           (and (funcall (nth 2 (assq imap-auth
1149                                      imap-authenticator-alist)) buffer)
1150                (setq imap-state 'auth))
1151         ;; Choose authenticator.
1152         (let ((auths imap-authenticators)
1153               auth)
1154           (while (setq auth (pop auths))
1155             ;; OK to use authenticator?
1156             (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1157               (message "imap: Authenticating to `%s' using `%s'..."
1158                        imap-server auth)
1159               (setq imap-auth auth)
1160               (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1161                   (progn
1162                     (message "imap: Authenticating to `%s' using `%s'...done"
1163                              imap-server auth)
1164                     (setq auths nil))
1165                 (message "imap: Authenticating to `%s' using `%s'...failed"
1166                          imap-server auth)))))
1167         imap-state))))
1168
1169 (defun imap-close (&optional buffer)
1170   "Close connection to server in BUFFER.
1171 If BUFFER is nil, the current buffer is used."
1172   (with-current-buffer (or buffer (current-buffer))
1173     (when (imap-opened)
1174       (condition-case nil
1175           (imap-send-command-wait "LOGOUT")
1176         (quit nil)))
1177     (when (and imap-process
1178                (memq (process-status imap-process) '(open run)))
1179       (delete-process imap-process))
1180     (setq imap-current-mailbox nil
1181           imap-current-message nil
1182           imap-process nil)
1183     (erase-buffer)
1184     t))
1185
1186 (defun imap-capability (&optional identifier buffer)
1187   "Return a list of identifiers which server in BUFFER support.
1188 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1189 If BUFFER is nil, the current buffer is assumed."
1190   (with-current-buffer (or buffer (current-buffer))
1191     (unless imap-capability
1192       (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1193         (setq imap-capability '(IMAP2))))
1194     (if identifier
1195         (memq (intern (upcase (symbol-name identifier))) imap-capability)
1196       imap-capability)))
1197
1198 (defun imap-id (&optional list-of-values buffer)
1199   "Identify client to server in BUFFER, and return server identity.
1200 LIST-OF-VALUES is nil, or a plist with identifier and value
1201 strings to send to the server to identify the client.
1202
1203 Return a list of identifiers which server in BUFFER support, or
1204 nil if it doesn't support ID or returns no information.
1205
1206 If BUFFER is nil, the current buffer is assumed."
1207   (with-current-buffer (or buffer (current-buffer))
1208     (when (and (imap-capability 'ID)
1209                (imap-ok-p (imap-send-command-wait
1210                            (if (null list-of-values)
1211                                "ID NIL"
1212                              (concat "ID (" (mapconcat (lambda (el)
1213                                                          (concat "\"" el "\""))
1214                                                        list-of-values
1215                                                        " ") ")")))))
1216       imap-id)))
1217
1218 (defun imap-namespace (&optional buffer)
1219   "Return a namespace hierarchy at server in BUFFER.
1220 If BUFFER is nil, the current buffer is assumed."
1221   (with-current-buffer (or buffer (current-buffer))
1222     (unless imap-namespace
1223       (when (imap-capability 'NAMESPACE)
1224         (imap-send-command-wait "NAMESPACE")))
1225     imap-namespace))
1226
1227 (defun imap-send-command-wait (command &optional buffer)
1228   (imap-wait-for-tag (imap-send-command command buffer) buffer))
1229
1230 \f
1231 ;; Mailbox functions:
1232
1233 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1234   (with-current-buffer (or buffer (current-buffer))
1235     (if imap-mailbox-data
1236         (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1237              propname value)
1238       (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1239              propname value mailbox (current-buffer)))
1240     t))
1241
1242 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1243   (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1244        propname))
1245
1246 (defun imap-mailbox-get (propname &optional mailbox buffer)
1247   (let ((mailbox (imap-utf7-encode mailbox)))
1248     (with-current-buffer (or buffer (current-buffer))
1249       (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1250
1251 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1252   (with-current-buffer (or buffer (current-buffer))
1253     (let (result)
1254       (mapatoms
1255        (lambda (s)
1256          (push (funcall func (if mailbox-decoder
1257                                  (funcall mailbox-decoder (symbol-name s))
1258                                (symbol-name s))) result))
1259        imap-mailbox-data)
1260       result)))
1261
1262 (defun imap-mailbox-map (func &optional buffer)
1263   "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1264 Function should take a mailbox name (a string) as
1265 the only argument."
1266   (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1267
1268 (defun imap-current-mailbox (&optional buffer)
1269   (with-current-buffer (or buffer (current-buffer))
1270     (imap-utf7-decode imap-current-mailbox)))
1271
1272 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1273   (and (string= mailbox imap-current-mailbox)
1274        (or (and examine
1275                 (eq imap-state 'examine))
1276            (and (not examine)
1277                 (eq imap-state 'selected)))))
1278
1279 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1280   (with-current-buffer (or buffer (current-buffer))
1281     (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1282
1283 (defun imap-mailbox-select-1 (mailbox &optional examine)
1284   "Select MAILBOX on server in BUFFER.
1285 If EXAMINE is non-nil, do a read-only select."
1286   (if (imap-current-mailbox-p-1 mailbox examine)
1287       imap-current-mailbox
1288     (setq imap-current-mailbox mailbox)
1289     (if (imap-ok-p (imap-send-command-wait
1290                     (concat (if examine "EXAMINE" "SELECT") " \""
1291                             mailbox "\"")))
1292         (progn
1293           (setq imap-message-data (make-vector imap-message-prime 0)
1294                 imap-state (if examine 'examine 'selected))
1295           imap-current-mailbox)
1296       ;; Failed SELECT/EXAMINE unselects current mailbox
1297       (setq imap-current-mailbox nil))))
1298
1299 (defun imap-mailbox-select (mailbox &optional examine buffer)
1300   (with-current-buffer (or buffer (current-buffer))
1301     (imap-utf7-decode
1302      (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1303
1304 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1305   (with-current-buffer (or buffer (current-buffer))
1306     (imap-mailbox-select-1 mailbox 'examine)))
1307
1308 (defun imap-mailbox-examine (mailbox &optional buffer)
1309   "Examine MAILBOX on server in BUFFER."
1310   (imap-mailbox-select mailbox 'examine buffer))
1311
1312 (defun imap-mailbox-unselect (&optional buffer)
1313   "Close current folder in BUFFER, without expunging articles."
1314   (with-current-buffer (or buffer (current-buffer))
1315     (when (or (eq imap-state 'auth)
1316               (and (imap-capability 'UNSELECT)
1317                    (imap-ok-p (imap-send-command-wait "UNSELECT")))
1318               (and (imap-ok-p
1319                     (imap-send-command-wait (concat "EXAMINE \""
1320                                                     imap-current-mailbox
1321                                                     "\"")))
1322                    (imap-ok-p (imap-send-command-wait "CLOSE"))))
1323       (setq imap-current-mailbox nil
1324             imap-message-data nil
1325             imap-state 'auth)
1326       t)))
1327
1328 (defun imap-mailbox-expunge (&optional asynch buffer)
1329   "Expunge articles in current folder in BUFFER.
1330 If ASYNCH, do not wait for succesful completion of the command.
1331 If BUFFER is nil the current buffer is assumed."
1332   (with-current-buffer (or buffer (current-buffer))
1333     (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1334       (if asynch
1335           (imap-send-command "EXPUNGE")
1336       (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1337
1338 (defun imap-mailbox-close (&optional asynch buffer)
1339   "Expunge articles and close current folder in BUFFER.
1340 If ASYNCH, do not wait for succesful completion of the command.
1341 If BUFFER is nil the current buffer is assumed."
1342   (with-current-buffer (or buffer (current-buffer))
1343     (when imap-current-mailbox
1344       (if asynch
1345           (imap-add-callback (imap-send-command "CLOSE")
1346                              `(lambda (tag status)
1347                                 (message "IMAP mailbox `%s' closed... %s"
1348                                          imap-current-mailbox status)
1349                                 (when (eq ,imap-current-mailbox
1350                                           imap-current-mailbox)
1351                                   ;; Don't wipe out data if another mailbox
1352                                   ;; was selected...
1353                                   (setq imap-current-mailbox nil
1354                                         imap-message-data nil
1355                                         imap-state 'auth))))
1356         (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1357           (setq imap-current-mailbox nil
1358                 imap-message-data nil
1359                 imap-state 'auth)))
1360       t)))
1361
1362 (defun imap-mailbox-create-1 (mailbox)
1363   (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1364
1365 (defun imap-mailbox-create (mailbox &optional buffer)
1366   "Create MAILBOX on server in BUFFER.
1367 If BUFFER is nil the current buffer is assumed."
1368   (with-current-buffer (or buffer (current-buffer))
1369     (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1370
1371 (defun imap-mailbox-delete (mailbox &optional buffer)
1372   "Delete MAILBOX on server in BUFFER.
1373 If BUFFER is nil the current buffer is assumed."
1374   (let ((mailbox (imap-utf7-encode mailbox)))
1375     (with-current-buffer (or buffer (current-buffer))
1376       (imap-ok-p
1377        (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1378
1379 (defun imap-mailbox-rename (oldname newname &optional buffer)
1380   "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1381 If BUFFER is nil the current buffer is assumed."
1382   (let ((oldname (imap-utf7-encode oldname))
1383         (newname (imap-utf7-encode newname)))
1384     (with-current-buffer (or buffer (current-buffer))
1385       (imap-ok-p
1386        (imap-send-command-wait (list "RENAME \"" oldname "\" "
1387                                      "\"" newname "\""))))))
1388
1389 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1390   "Return a list of subscribed mailboxes on server in BUFFER.
1391 If ROOT is non-nil, only list matching mailboxes.  If ADD-DELIMITER is
1392 non-nil, a hierarchy delimiter is added to root.  REFERENCE is a
1393 implementation-specific string that has to be passed to lsub command."
1394   (with-current-buffer (or buffer (current-buffer))
1395     ;; Make sure we know the hierarchy separator for root's hierarchy
1396     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1397       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1398                                       (imap-utf7-encode root) "\"")))
1399     ;; clear list data (NB not delimiter and other stuff)
1400     (imap-mailbox-map-1 (lambda (mailbox)
1401                           (imap-mailbox-put 'lsub nil mailbox)))
1402     (when (imap-ok-p
1403            (imap-send-command-wait
1404             (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1405                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1406                     "%\"")))
1407       (let (out)
1408         (imap-mailbox-map-1 (lambda (mailbox)
1409                               (when (imap-mailbox-get-1 'lsub mailbox)
1410                                 (push (imap-utf7-decode mailbox) out))))
1411         (nreverse out)))))
1412
1413 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1414   "Return a list of mailboxes matching ROOT on server in BUFFER.
1415 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1416 root.  REFERENCE is a implementation-specific string that has to be
1417 passed to list command."
1418   (with-current-buffer (or buffer (current-buffer))
1419     ;; Make sure we know the hierarchy separator for root's hierarchy
1420     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1421       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1422                                       (imap-utf7-encode root) "\"")))
1423     ;; clear list data (NB not delimiter and other stuff)
1424     (imap-mailbox-map-1 (lambda (mailbox)
1425                           (imap-mailbox-put 'list nil mailbox)))
1426     (when (imap-ok-p
1427            (imap-send-command-wait
1428             (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1429                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1430                     "%\"")))
1431       (let (out)
1432         (imap-mailbox-map-1 (lambda (mailbox)
1433                               (when (imap-mailbox-get-1 'list mailbox)
1434                                 (push (imap-utf7-decode mailbox) out))))
1435         (nreverse out)))))
1436
1437 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1438   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1439 Returns non-nil if successful."
1440   (with-current-buffer (or buffer (current-buffer))
1441     (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1442                                                (imap-utf7-encode mailbox)
1443                                                "\"")))))
1444
1445 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1446   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1447 Returns non-nil if successful."
1448   (with-current-buffer (or buffer (current-buffer))
1449     (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1450                                                (imap-utf7-encode mailbox)
1451                                                "\"")))))
1452
1453 (defun imap-mailbox-status (mailbox items &optional buffer)
1454   "Get status items ITEM in MAILBOX from server in BUFFER.
1455 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1456 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1457 or 'unseen.  If ITEMS is a list of symbols, a list of values is
1458 returned, if ITEMS is a symbol only its value is returned."
1459   (with-current-buffer (or buffer (current-buffer))
1460     (when (imap-ok-p
1461            (imap-send-command-wait (list "STATUS \""
1462                                          (imap-utf7-encode mailbox)
1463                                          "\" "
1464                                          (upcase
1465                                           (format "%s"
1466                                                   (if (listp items)
1467                                                       items
1468                                                     (list items)))))))
1469       (if (listp items)
1470           (mapcar (lambda (item)
1471                     (imap-mailbox-get item mailbox))
1472                   items)
1473         (imap-mailbox-get items mailbox)))))
1474
1475 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1476   "Send status item request ITEM on MAILBOX to server in BUFFER.
1477 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1478 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1479 or 'unseen.  The IMAP command tag is returned."
1480   (with-current-buffer (or buffer (current-buffer))
1481     (imap-send-command (list "STATUS \""
1482                              (imap-utf7-encode mailbox)
1483                              "\" "
1484                              (format "%s"
1485                                      (if (listp items)
1486                                          items
1487                                        (list items)))))))
1488
1489 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1490   "Get ACL on mailbox from server in BUFFER."
1491   (let ((mailbox (imap-utf7-encode mailbox)))
1492     (with-current-buffer (or buffer (current-buffer))
1493       (when (imap-ok-p
1494              (imap-send-command-wait (list "GETACL \""
1495                                            (or mailbox imap-current-mailbox)
1496                                            "\"")))
1497         (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1498
1499 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1500   "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1501   (let ((mailbox (imap-utf7-encode mailbox)))
1502     (with-current-buffer (or buffer (current-buffer))
1503       (imap-ok-p
1504        (imap-send-command-wait (list "SETACL \""
1505                                      (or mailbox imap-current-mailbox)
1506                                      "\" "
1507                                      identifier
1508                                      " "
1509                                      rights))))))
1510
1511 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1512   "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1513   (let ((mailbox (imap-utf7-encode mailbox)))
1514     (with-current-buffer (or buffer (current-buffer))
1515       (imap-ok-p
1516        (imap-send-command-wait (list "DELETEACL \""
1517                                      (or mailbox imap-current-mailbox)
1518                                      "\" "
1519                                      identifier))))))
1520
1521 \f
1522 ;; Message functions:
1523
1524 (defun imap-current-message (&optional buffer)
1525   (with-current-buffer (or buffer (current-buffer))
1526     imap-current-message))
1527
1528 (defun imap-list-to-message-set (list)
1529   (mapconcat (lambda (item)
1530                (number-to-string item))
1531              (if (listp list)
1532                  list
1533                (list list))
1534              ","))
1535
1536 (defun imap-range-to-message-set (range)
1537   (mapconcat
1538    (lambda (item)
1539      (if (consp item)
1540          (format "%d:%d"
1541                  (car item) (cdr item))
1542        (format "%d" item)))
1543    (if (and (listp range) (not (listp (cdr range))))
1544        (list range) ;; make (1 . 2) into ((1 . 2))
1545      range)
1546    ","))
1547
1548 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1549   (with-current-buffer (or buffer (current-buffer))
1550     (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1551                                (if (listp uids)
1552                                    (imap-list-to-message-set uids)
1553                                  uids)
1554                                props))))
1555
1556 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1557   "Fetch properties PROPS from message set UIDS from server in BUFFER.
1558 UIDS can be a string, number or a list of numbers.  If RECEIVE
1559 is non-nil return these properties."
1560   (with-current-buffer (or buffer (current-buffer))
1561     (when (imap-ok-p (imap-send-command-wait
1562                       (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1563                               (if (listp uids)
1564                                   (imap-list-to-message-set uids)
1565                                 uids)
1566                               props)))
1567       (if (or (null receive) (stringp uids))
1568           t
1569         (if (listp uids)
1570             (mapcar (lambda (uid)
1571                       (if (listp receive)
1572                           (mapcar (lambda (prop)
1573                                     (imap-message-get uid prop))
1574                                   receive)
1575                         (imap-message-get uid receive)))
1576                     uids)
1577           (imap-message-get uids receive))))))
1578
1579 (defun imap-message-put (uid propname value &optional buffer)
1580   (with-current-buffer (or buffer (current-buffer))
1581     (if imap-message-data
1582         (put (intern (number-to-string uid) imap-message-data)
1583              propname value)
1584       (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1585              uid propname value (current-buffer)))
1586     t))
1587
1588 (defun imap-message-get (uid propname &optional buffer)
1589   (with-current-buffer (or buffer (current-buffer))
1590     (get (intern-soft (number-to-string uid) imap-message-data)
1591          propname)))
1592
1593 (defun imap-message-map (func propname &optional buffer)
1594   "Map a function across each mailbox in `imap-message-data', returning a list."
1595   (with-current-buffer (or buffer (current-buffer))
1596     (let (result)
1597       (mapatoms
1598        (lambda (s)
1599          (push (funcall func (get s 'UID) (get s propname)) result))
1600        imap-message-data)
1601       result)))
1602
1603 (defmacro imap-message-envelope-date (uid &optional buffer)
1604   `(with-current-buffer (or ,buffer (current-buffer))
1605      (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1606
1607 (defmacro imap-message-envelope-subject (uid &optional buffer)
1608   `(with-current-buffer (or ,buffer (current-buffer))
1609      (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1610
1611 (defmacro imap-message-envelope-from (uid &optional buffer)
1612   `(with-current-buffer (or ,buffer (current-buffer))
1613      (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1614
1615 (defmacro imap-message-envelope-sender (uid &optional buffer)
1616   `(with-current-buffer (or ,buffer (current-buffer))
1617      (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1618
1619 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1620   `(with-current-buffer (or ,buffer (current-buffer))
1621      (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1622
1623 (defmacro imap-message-envelope-to (uid &optional buffer)
1624   `(with-current-buffer (or ,buffer (current-buffer))
1625      (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1626
1627 (defmacro imap-message-envelope-cc (uid &optional buffer)
1628   `(with-current-buffer (or ,buffer (current-buffer))
1629      (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1630
1631 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1632   `(with-current-buffer (or ,buffer (current-buffer))
1633      (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1634
1635 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1636   `(with-current-buffer (or ,buffer (current-buffer))
1637      (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1638
1639 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1640   `(with-current-buffer (or ,buffer (current-buffer))
1641      (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1642
1643 (defmacro imap-message-body (uid &optional buffer)
1644   `(with-current-buffer (or ,buffer (current-buffer))
1645      (imap-message-get ,uid 'BODY)))
1646
1647 (defun imap-search (predicate &optional buffer)
1648   (with-current-buffer (or buffer (current-buffer))
1649     (imap-mailbox-put 'search 'dummy)
1650     (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1651       (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1652           (progn
1653             (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1654             nil)
1655         (imap-mailbox-get-1 'search imap-current-mailbox)))))
1656
1657 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1658   "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1659   (with-current-buffer (or buffer (current-buffer))
1660     (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1661         (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1662
1663 (defun imap-message-flags-set (articles flags &optional silent buffer)
1664   (when (and articles flags)
1665     (with-current-buffer (or buffer (current-buffer))
1666       (imap-ok-p (imap-send-command-wait
1667                   (concat "UID STORE " articles
1668                           " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1669
1670 (defun imap-message-flags-del (articles flags &optional silent buffer)
1671   (when (and articles flags)
1672     (with-current-buffer (or buffer (current-buffer))
1673       (imap-ok-p (imap-send-command-wait
1674                   (concat "UID STORE " articles
1675                           " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1676
1677 (defun imap-message-flags-add (articles flags &optional silent buffer)
1678   (when (and articles flags)
1679     (with-current-buffer (or buffer (current-buffer))
1680       (imap-ok-p (imap-send-command-wait
1681                   (concat "UID STORE " articles
1682                           " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1683
1684 (defun imap-message-copyuid-1 (mailbox)
1685   (if (imap-capability 'UIDPLUS)
1686       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1687             (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1688     (let ((old-mailbox imap-current-mailbox)
1689           (state imap-state)
1690           (imap-message-data (make-vector 2 0)))
1691       (when (imap-mailbox-examine-1 mailbox)
1692         (prog1
1693             (and (imap-fetch "*" "UID")
1694                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1695                        (apply 'max (imap-message-map
1696                                     (lambda (uid prop) uid) 'UID))))
1697           (if old-mailbox
1698               (imap-mailbox-select old-mailbox (eq state 'examine))
1699             (imap-mailbox-unselect)))))))
1700
1701 (defun imap-message-copyuid (mailbox &optional buffer)
1702   (with-current-buffer (or buffer (current-buffer))
1703     (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1704
1705 (defun imap-message-copy (articles mailbox
1706                                    &optional dont-create no-copyuid buffer)
1707   "Copy ARTICLES (a string message set) to MAILBOX on server in
1708 BUFFER, creating mailbox if it doesn't exist.  If dont-create is
1709 non-nil, it will not create a mailbox.  On success, return a list with
1710 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1711 first element, rest of list contain the saved articles' UIDs."
1712   (when articles
1713     (with-current-buffer (or buffer (current-buffer))
1714       (let ((mailbox (imap-utf7-encode mailbox)))
1715         (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1716                   (imap-current-target-mailbox mailbox))
1717               (if (imap-ok-p (imap-send-command-wait cmd))
1718                   t
1719                 (when (and (not dont-create)
1720                            ;; removed because of buggy Oracle server
1721                            ;; that doesn't send TRYCREATE tags (which
1722                            ;; is a MUST according to specifications):
1723                            ;;(imap-mailbox-get-1 'trycreate mailbox)
1724                            (imap-mailbox-create-1 mailbox))
1725                   (imap-ok-p (imap-send-command-wait cmd)))))
1726             (or no-copyuid
1727                 (imap-message-copyuid-1 mailbox)))))))
1728
1729 (defun imap-message-appenduid-1 (mailbox)
1730   (if (imap-capability 'UIDPLUS)
1731       (imap-mailbox-get-1 'appenduid mailbox)
1732     (let ((old-mailbox imap-current-mailbox)
1733           (state imap-state)
1734           (imap-message-data (make-vector 2 0)))
1735       (when (imap-mailbox-examine-1 mailbox)
1736         (prog1
1737             (and (imap-fetch "*" "UID")
1738                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1739                        (apply 'max (imap-message-map
1740                                     (lambda (uid prop) uid) 'UID))))
1741           (if old-mailbox
1742               (imap-mailbox-select old-mailbox (eq state 'examine))
1743             (imap-mailbox-unselect)))))))
1744
1745 (defun imap-message-appenduid (mailbox &optional buffer)
1746   (with-current-buffer (or buffer (current-buffer))
1747     (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1748
1749 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1750   "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1751 FLAGS and DATE-TIME is currently not used.  Return a cons holding
1752 uidvalidity of MAILBOX and UID the newly created article got, or nil
1753 on failure."
1754   (let ((mailbox (imap-utf7-encode mailbox)))
1755     (with-current-buffer (or buffer (current-buffer))
1756       (and (let ((imap-current-target-mailbox mailbox))
1757              (imap-ok-p
1758               (imap-send-command-wait
1759                (list "APPEND \"" mailbox "\" "  article))))
1760            (imap-message-appenduid-1 mailbox)))))
1761
1762 (defun imap-body-lines (body)
1763   "Return number of lines in article by looking at the mime bodystructure BODY."
1764   (if (listp body)
1765       (if (stringp (car body))
1766           (cond ((and (string= (upcase (car body)) "TEXT")
1767                       (numberp (nth 7 body)))
1768                  (nth 7 body))
1769                 ((and (string= (upcase (car body)) "MESSAGE")
1770                       (numberp (nth 9 body)))
1771                  (nth 9 body))
1772                 (t 0))
1773         (apply '+ (mapcar 'imap-body-lines body)))
1774     0))
1775
1776 (defun imap-envelope-from (from)
1777   "Return a from string line."
1778   (and from
1779        (concat (aref from 0)
1780                (if (aref from 0) " <")
1781                (aref from 2)
1782                "@"
1783                (aref from 3)
1784                (if (aref from 0) ">"))))
1785
1786 \f
1787 ;; Internal functions.
1788
1789 (defun imap-add-callback (tag func)
1790   (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1791
1792 (defun imap-send-command-1 (cmdstr)
1793   (setq cmdstr (concat cmdstr imap-client-eol))
1794   (and imap-log
1795        (with-current-buffer (get-buffer-create imap-log-buffer)
1796          (imap-disable-multibyte)
1797          (buffer-disable-undo)
1798          (goto-char (point-max))
1799          (insert cmdstr)))
1800   (process-send-string imap-process cmdstr))
1801
1802 (defun imap-send-command (command &optional buffer)
1803   (with-current-buffer (or buffer (current-buffer))
1804     (if (not (listp command)) (setq command (list command)))
1805     (let ((tag (setq imap-tag (1+ imap-tag)))
1806           cmd cmdstr)
1807       (setq cmdstr (concat (number-to-string imap-tag) " "))
1808       (while (setq cmd (pop command))
1809         (cond ((stringp cmd)
1810                (setq cmdstr (concat cmdstr cmd)))
1811               ((bufferp cmd)
1812                (let ((eol imap-client-eol)
1813                      (calcfirst imap-calculate-literal-size-first)
1814                      size)
1815                  (with-current-buffer cmd
1816                    (if calcfirst
1817                        (setq size (buffer-size)))
1818                    (when (not (equal eol "\r\n"))
1819                      ;; XXX modifies buffer!
1820                      (goto-char (point-min))
1821                      (while (search-forward "\r\n" nil t)
1822                        (replace-match eol)))
1823                    (if (not calcfirst)
1824                        (setq size (buffer-size))))
1825                  (setq cmdstr
1826                        (concat cmdstr (format "{%d}" size))))
1827                (unwind-protect
1828                    (progn
1829                      (imap-send-command-1 cmdstr)
1830                      (setq cmdstr nil)
1831                      (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1832                          (setq command nil) ;; abort command if no cont-req
1833                        (let ((process imap-process)
1834                              (stream imap-stream)
1835                              (eol imap-client-eol))
1836                          (with-current-buffer cmd
1837                            (and imap-log
1838                                 (with-current-buffer (get-buffer-create
1839                                                       imap-log-buffer)
1840                                   (imap-disable-multibyte)
1841                                   (buffer-disable-undo)
1842                                   (goto-char (point-max))
1843                                   (insert-buffer-substring cmd)))
1844                            (process-send-region process (point-min)
1845                                                 (point-max)))
1846                          (process-send-string process imap-client-eol))))
1847                  (setq imap-continuation nil)))
1848               ((functionp cmd)
1849                (imap-send-command-1 cmdstr)
1850                (setq cmdstr nil)
1851                (unwind-protect
1852                    (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1853                        (setq command nil) ;; abort command if no cont-req
1854                      (setq command (cons (funcall cmd imap-continuation)
1855                                          command)))
1856                  (setq imap-continuation nil)))
1857               (t
1858                (error "Unknown command type"))))
1859       (if cmdstr
1860           (imap-send-command-1 cmdstr))
1861       tag)))
1862
1863 (defun imap-wait-for-tag (tag &optional buffer)
1864   (with-current-buffer (or buffer (current-buffer))
1865     (let (imap-have-messaged)
1866       (while (and (null imap-continuation)
1867                   (memq (process-status imap-process) '(open run))
1868                   (< imap-reached-tag tag))
1869         (let ((len (/ (point-max) 1024))
1870               message-log-max)
1871           (unless (< len 10)
1872             (setq imap-have-messaged t)
1873             (message "imap read: %dk" len))
1874           (accept-process-output imap-process
1875                                  (truncate imap-read-timeout)
1876                                  (truncate (* (- imap-read-timeout
1877                                                  (truncate imap-read-timeout))
1878                                               1000)))))
1879       ;; A process can die _before_ we have processed everything it
1880       ;; has to say.  Moreover, this can happen in between the call to
1881       ;; accept-process-output and the call to process-status in an
1882       ;; iteration of the loop above.
1883       (when (and (null imap-continuation)
1884                  (< imap-reached-tag tag))
1885         (accept-process-output imap-process 0 0))
1886       (when imap-have-messaged
1887         (message ""))
1888       (and (memq (process-status imap-process) '(open run))
1889            (or (assq tag imap-failed-tags)
1890                (if imap-continuation
1891                    'INCOMPLETE
1892                  'OK))))))
1893
1894 (defun imap-sentinel (process string)
1895   (delete-process process))
1896
1897 (defun imap-find-next-line ()
1898   "Return point at end of current line, taking into account literals.
1899 Return nil if no complete line has arrived."
1900   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1901                                    imap-server-eol)
1902                            nil t)
1903     (if (match-string 1)
1904         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1905             nil
1906           (goto-char (+ (point) (string-to-number (match-string 1))))
1907           (imap-find-next-line))
1908       (point))))
1909
1910 (defun imap-arrival-filter (proc string)
1911   "IMAP process filter."
1912   ;; Sometimes, we are called even though the process has died.
1913   ;; Better abstain from doing stuff in that case.
1914   (when (buffer-name (process-buffer proc))
1915     (with-current-buffer (process-buffer proc)
1916       (goto-char (point-max))
1917       (insert string)
1918       (and imap-log
1919            (with-current-buffer (get-buffer-create imap-log-buffer)
1920              (imap-disable-multibyte)
1921              (buffer-disable-undo)
1922              (goto-char (point-max))
1923              (insert string)))
1924       (let (end)
1925         (goto-char (point-min))
1926         (while (setq end (imap-find-next-line))
1927           (save-restriction
1928             (narrow-to-region (point-min) end)
1929             (delete-backward-char (length imap-server-eol))
1930             (goto-char (point-min))
1931             (unwind-protect
1932                 (cond ((eq imap-state 'initial)
1933                        (imap-parse-greeting))
1934                       ((or (eq imap-state 'auth)
1935                            (eq imap-state 'nonauth)
1936                            (eq imap-state 'selected)
1937                            (eq imap-state 'examine))
1938                        (imap-parse-response))
1939                       (t
1940                        (message "Unknown state %s in arrival filter"
1941                                 imap-state)))
1942               (delete-region (point-min) (point-max)))))))))
1943
1944 \f
1945 ;; Imap parser.
1946
1947 (defsubst imap-forward ()
1948   (or (eobp) (forward-char)))
1949
1950 ;;   number          = 1*DIGIT
1951 ;;                       ; Unsigned 32-bit integer
1952 ;;                       ; (0 <= n < 4,294,967,296)
1953
1954 (defsubst imap-parse-number ()
1955   (when (looking-at "[0-9]+")
1956     (prog1
1957         (string-to-number (match-string 0))
1958       (goto-char (match-end 0)))))
1959
1960 ;;   literal         = "{" number "}" CRLF *CHAR8
1961 ;;                       ; Number represents the number of CHAR8s
1962
1963 (defsubst imap-parse-literal ()
1964   (when (looking-at "{\\([0-9]+\\)}\r\n")
1965     (let ((pos (match-end 0))
1966           (len (string-to-number (match-string 1))))
1967       (if (< (point-max) (+ pos len))
1968           nil
1969         (goto-char (+ pos len))
1970         (buffer-substring pos (+ pos len))))))
1971
1972 ;;   string          = quoted / literal
1973 ;;
1974 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
1975 ;;
1976 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
1977 ;;                     "\" quoted-specials
1978 ;;
1979 ;;   quoted-specials = DQUOTE / "\"
1980 ;;
1981 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
1982
1983 (defsubst imap-parse-string ()
1984   (cond ((eq (char-after) ?\")
1985          (forward-char 1)
1986          (let ((p (point)) (name ""))
1987            (skip-chars-forward "^\"\\\\")
1988            (setq name (buffer-substring p (point)))
1989            (while (eq (char-after) ?\\)
1990              (setq p (1+ (point)))
1991              (forward-char 2)
1992              (skip-chars-forward "^\"\\\\")
1993              (setq name (concat name (buffer-substring p (point)))))
1994            (forward-char 1)
1995            name))
1996         ((eq (char-after) ?{)
1997          (imap-parse-literal))))
1998
1999 ;;   nil             = "NIL"
2000
2001 (defsubst imap-parse-nil ()
2002   (if (looking-at "NIL")
2003       (goto-char (match-end 0))))
2004
2005 ;;   nstring         = string / nil
2006
2007 (defsubst imap-parse-nstring ()
2008   (or (imap-parse-string)
2009       (and (imap-parse-nil)
2010            nil)))
2011
2012 ;;   astring         = atom / string
2013 ;;
2014 ;;   atom            = 1*ATOM-CHAR
2015 ;;
2016 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
2017 ;;
2018 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
2019 ;;                     quoted-specials
2020 ;;
2021 ;;   list-wildcards  = "%" / "*"
2022 ;;
2023 ;;   quoted-specials = DQUOTE / "\"
2024
2025 (defsubst imap-parse-astring ()
2026   (or (imap-parse-string)
2027       (buffer-substring (point)
2028                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2029                             (goto-char (1- (match-end 0)))
2030                           (end-of-line)
2031                           (point)))))
2032
2033 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
2034 ;;                      addr-host ")"
2035 ;;
2036 ;;   addr-adl        = nstring
2037 ;;                       ; Holds route from [RFC-822] route-addr if
2038 ;;                       ; non-nil
2039 ;;
2040 ;;   addr-host       = nstring
2041 ;;                       ; nil indicates [RFC-822] group syntax.
2042 ;;                       ; Otherwise, holds [RFC-822] domain name
2043 ;;
2044 ;;   addr-mailbox    = nstring
2045 ;;                       ; nil indicates end of [RFC-822] group; if
2046 ;;                       ; non-nil and addr-host is nil, holds
2047 ;;                       ; [RFC-822] group name.
2048 ;;                       ; Otherwise, holds [RFC-822] local-part
2049 ;;                       ; after removing [RFC-822] quoting
2050 ;;
2051 ;;   addr-name       = nstring
2052 ;;                       ; If non-nil, holds phrase from [RFC-822]
2053 ;;                       ; mailbox after removing [RFC-822] quoting
2054 ;;
2055
2056 (defsubst imap-parse-address ()
2057   (let (address)
2058     (when (eq (char-after) ?\()
2059       (imap-forward)
2060       (setq address (vector (prog1 (imap-parse-nstring)
2061                               (imap-forward))
2062                             (prog1 (imap-parse-nstring)
2063                               (imap-forward))
2064                             (prog1 (imap-parse-nstring)
2065                               (imap-forward))
2066                             (imap-parse-nstring)))
2067       (when (eq (char-after) ?\))
2068         (imap-forward)
2069         address))))
2070
2071 ;;   address-list    = "(" 1*address ")" / nil
2072 ;;
2073 ;;   nil             = "NIL"
2074
2075 (defsubst imap-parse-address-list ()
2076   (if (eq (char-after) ?\()
2077       (let (address addresses)
2078         (imap-forward)
2079         (while (and (not (eq (char-after) ?\)))
2080                     ;; next line for MS Exchange bug
2081                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
2082                     (setq address (imap-parse-address)))
2083           (setq addresses (cons address addresses)))
2084         (when (eq (char-after) ?\))
2085           (imap-forward)
2086           (nreverse addresses)))
2087     ;; With assert, the code might not be eval'd.
2088     ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2089     (imap-parse-nil)))
2090
2091 ;;   mailbox         = "INBOX" / astring
2092 ;;                       ; INBOX is case-insensitive.  All case variants of
2093 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2094 ;;                       ; not as an astring.  An astring which consists of
2095 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
2096 ;;                       ; is considered to be INBOX and not an astring.
2097 ;;                       ;  Refer to section 5.1 for further
2098 ;;                       ; semantic details of mailbox names.
2099
2100 (defsubst imap-parse-mailbox ()
2101   (let ((mailbox (imap-parse-astring)))
2102     (if (string-equal "INBOX" (upcase mailbox))
2103         "INBOX"
2104       mailbox)))
2105
2106 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2107 ;;
2108 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
2109 ;;                       ; Authentication condition
2110 ;;
2111 ;;   resp-cond-bye   = "BYE" SP resp-text
2112
2113 (defun imap-parse-greeting ()
2114   "Parse a IMAP greeting."
2115   (cond ((looking-at "\\* OK ")
2116          (setq imap-state 'nonauth))
2117         ((looking-at "\\* PREAUTH ")
2118          (setq imap-state 'auth))
2119         ((looking-at "\\* BYE ")
2120          (setq imap-state 'closed))))
2121
2122 ;;   response        = *(continue-req / response-data) response-done
2123 ;;
2124 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
2125 ;;
2126 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
2127 ;;                     mailbox-data / message-data / capability-data) CRLF
2128 ;;
2129 ;;   response-done   = response-tagged / response-fatal
2130 ;;
2131 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
2132 ;;                       ; Server closes connection immediately
2133 ;;
2134 ;;   response-tagged = tag SP resp-cond-state CRLF
2135 ;;
2136 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2137 ;;                       ; Status condition
2138 ;;
2139 ;;   resp-cond-bye   = "BYE" SP resp-text
2140 ;;
2141 ;;   mailbox-data    =  "FLAGS" SP flag-list /
2142 ;;                      "LIST" SP mailbox-list /
2143 ;;                      "LSUB" SP mailbox-list /
2144 ;;                      "SEARCH" *(SP nz-number) /
2145 ;;                      "STATUS" SP mailbox SP "("
2146 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
2147 ;;                      number SP "EXISTS" /
2148 ;;                      number SP "RECENT"
2149 ;;
2150 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2151 ;;
2152 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2153 ;;                     *(SP capability)
2154 ;;                       ; IMAP4rev1 servers which offer RFC 1730
2155 ;;                       ; compatibility MUST list "IMAP4" as the first
2156 ;;                       ; capability.
2157
2158 (defun imap-parse-response ()
2159   "Parse a IMAP command response."
2160   (let (token)
2161     (case (setq token (read (current-buffer)))
2162       (+ (setq imap-continuation
2163                (or (buffer-substring (min (point-max) (1+ (point)))
2164                                      (point-max))
2165                    t)))
2166       (* (case (prog1 (setq token (read (current-buffer)))
2167                  (imap-forward))
2168            (OK         (imap-parse-resp-text))
2169            (NO         (imap-parse-resp-text))
2170            (BAD        (imap-parse-resp-text))
2171            (BYE        (imap-parse-resp-text))
2172            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
2173            (LIST       (imap-parse-data-list 'list))
2174            (LSUB       (imap-parse-data-list 'lsub))
2175            (SEARCH     (imap-mailbox-put
2176                         'search
2177                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2178            (STATUS     (imap-parse-status))
2179            (CAPABILITY (setq imap-capability
2180                                (read (concat "(" (upcase (buffer-substring
2181                                                           (point) (point-max)))
2182                                              ")"))))
2183            (ID         (setq imap-id (read (buffer-substring (point)
2184                                                              (point-max)))))
2185            (ACL        (imap-parse-acl))
2186            (t       (case (prog1 (read (current-buffer))
2187                             (imap-forward))
2188                       (EXISTS  (imap-mailbox-put 'exists token))
2189                       (RECENT  (imap-mailbox-put 'recent token))
2190                       (EXPUNGE t)
2191                       (FETCH   (imap-parse-fetch token))
2192                       (t       (message "Garbage: %s" (buffer-string)))))))
2193       (t (let (status)
2194            (if (not (integerp token))
2195                (message "Garbage: %s" (buffer-string))
2196              (case (prog1 (setq status (read (current-buffer)))
2197                      (imap-forward))
2198                (OK  (progn
2199                       (setq imap-reached-tag (max imap-reached-tag token))
2200                       (imap-parse-resp-text)))
2201                (NO  (progn
2202                       (setq imap-reached-tag (max imap-reached-tag token))
2203                       (save-excursion
2204                         (imap-parse-resp-text))
2205                       (let (code text)
2206                         (when (eq (char-after) ?\[)
2207                           (setq code (buffer-substring (point)
2208                                                        (search-forward "]")))
2209                           (imap-forward))
2210                         (setq text (buffer-substring (point) (point-max)))
2211                         (push (list token status code text)
2212                               imap-failed-tags))))
2213                (BAD (progn
2214                       (setq imap-reached-tag (max imap-reached-tag token))
2215                       (save-excursion
2216                         (imap-parse-resp-text))
2217                       (let (code text)
2218                         (when (eq (char-after) ?\[)
2219                           (setq code (buffer-substring (point)
2220                                                        (search-forward "]")))
2221                           (imap-forward))
2222                         (setq text (buffer-substring (point) (point-max)))
2223                         (push (list token status code text) imap-failed-tags)
2224                         (error "Internal error, tag %s status %s code %s text %s"
2225                                token status code text))))
2226                (t   (message "Garbage: %s" (buffer-string))))
2227              (when (assq token imap-callbacks)
2228                (funcall (cdr (assq token imap-callbacks)) token status)
2229                (setq imap-callbacks
2230                      (imap-remassoc token imap-callbacks)))))))))
2231
2232 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2233 ;;
2234 ;;   text            = 1*TEXT-CHAR
2235 ;;
2236 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2237
2238 (defun imap-parse-resp-text ()
2239   (imap-parse-resp-text-code))
2240
2241 ;;   resp-text-code  = "ALERT" /
2242 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2243 ;;                     "NEWNAME" SP string SP string /
2244 ;;                     "PARSE" /
2245 ;;                     "PERMANENTFLAGS" SP "("
2246 ;;                               [flag-perm *(SP flag-perm)] ")" /
2247 ;;                     "READ-ONLY" /
2248 ;;                     "READ-WRITE" /
2249 ;;                     "TRYCREATE" /
2250 ;;                     "UIDNEXT" SP nz-number /
2251 ;;                     "UIDVALIDITY" SP nz-number /
2252 ;;                     "UNSEEN" SP nz-number /
2253 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2254 ;;
2255 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2256 ;;
2257 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2258 ;;
2259 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2260 ;;                        (set "," set)
2261 ;;                          ; Identifies a set of messages.  For message
2262 ;;                          ; sequence numbers, these are consecutive
2263 ;;                          ; numbers from 1 to the number of messages in
2264 ;;                          ; the mailbox
2265 ;;                          ; Comma delimits individual numbers, colon
2266 ;;                          ; delimits between two numbers inclusive.
2267 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2268 ;;                          ; 14,15 for a mailbox with 15 messages.
2269 ;;
2270 ;;   sequence-num    = nz-number / "*"
2271 ;;                          ; * is the largest number in use.  For message
2272 ;;                          ; sequence numbers, it is the number of messages
2273 ;;                          ; in the mailbox.  For unique identifiers, it is
2274 ;;                          ; the unique identifier of the last message in
2275 ;;                          ; the mailbox.
2276 ;;
2277 ;;   flag-perm       = flag / "\*"
2278 ;;
2279 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2280 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2281 ;;                       ; Does not include "\Recent"
2282 ;;
2283 ;;   flag-extension  = "\" atom
2284 ;;                       ; Future expansion.  Client implementations
2285 ;;                       ; MUST accept flag-extension flags.  Server
2286 ;;                       ; implementations MUST NOT generate
2287 ;;                       ; flag-extension flags except as defined by
2288 ;;                       ; future standard or standards-track
2289 ;;                       ; revisions of this specification.
2290 ;;
2291 ;;   flag-keyword    = atom
2292 ;;
2293 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2294
2295 (defun imap-parse-resp-text-code ()
2296   ;; xxx next line for stalker communigate pro 3.3.1 bug
2297   (when (looking-at " \\[")
2298     (imap-forward))
2299   (when (eq (char-after) ?\[)
2300     (imap-forward)
2301     (cond ((search-forward "PERMANENTFLAGS " nil t)
2302            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2303           ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2304            (imap-mailbox-put 'uidnext (match-string 1)))
2305           ((search-forward "UNSEEN " nil t)
2306            (imap-mailbox-put 'first-unseen (read (current-buffer))))
2307           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2308            (imap-mailbox-put 'uidvalidity (match-string 1)))
2309           ((search-forward "READ-ONLY" nil t)
2310            (imap-mailbox-put 'read-only t))
2311           ((search-forward "NEWNAME " nil t)
2312            (let (oldname newname)
2313              (setq oldname (imap-parse-string))
2314              (imap-forward)
2315              (setq newname (imap-parse-string))
2316              (imap-mailbox-put 'newname newname oldname)))
2317           ((search-forward "TRYCREATE" nil t)
2318            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2319           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2320            (imap-mailbox-put 'appenduid
2321                              (list (match-string 1)
2322                                    (string-to-number (match-string 2)))
2323                              imap-current-target-mailbox))
2324           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2325            (imap-mailbox-put 'copyuid (list (match-string 1)
2326                                             (match-string 2)
2327                                             (match-string 3))
2328                              imap-current-target-mailbox))
2329           ((search-forward "ALERT] " nil t)
2330            (message "Imap server %s information: %s" imap-server
2331                     (buffer-substring (point) (point-max)))))))
2332
2333 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2334 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2335 ;;
2336 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2337 ;;                     *(SP mbx-list-oflag) /
2338 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2339 ;;
2340 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2341 ;;                       ; Other flags; multiple possible per LIST response
2342 ;;
2343 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2344 ;;                       ; Selectability flags; only one per LIST response
2345 ;;
2346 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2347 ;;                     "\" quoted-specials
2348 ;;
2349 ;;   quoted-specials = DQUOTE / "\"
2350
2351 (defun imap-parse-data-list (type)
2352   (let (flags delimiter mailbox)
2353     (setq flags (imap-parse-flag-list))
2354     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2355       (setq delimiter (match-string 1))
2356       (goto-char (1+ (match-end 0)))
2357       (when (setq mailbox (imap-parse-mailbox))
2358         (imap-mailbox-put type t mailbox)
2359         (imap-mailbox-put 'list-flags flags mailbox)
2360         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2361
2362 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2363 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2364 ;;                      "INTERNALDATE" SPACE date_time /
2365 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2366 ;;                      "RFC822.SIZE" SPACE number /
2367 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2368 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2369 ;;                      "UID" SPACE uniqueid) ")"
2370 ;;
2371 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2372 ;;                      SPACE time SPACE zone <">
2373 ;;
2374 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2375 ;;                      ["." (section_text / "MIME")])] "]"
2376 ;;
2377 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2378 ;;                      SPACE header_list / "TEXT"
2379 ;;
2380 ;;  header_fld_name ::= astring
2381 ;;
2382 ;;  header_list     ::= "(" 1#header_fld_name ")"
2383
2384 (defsubst imap-parse-header-list ()
2385   (when (eq (char-after) ?\()
2386     (let (strlist)
2387       (while (not (eq (char-after) ?\)))
2388         (imap-forward)
2389         (push (imap-parse-astring) strlist))
2390       (imap-forward)
2391       (nreverse strlist))))
2392
2393 (defsubst imap-parse-fetch-body-section ()
2394   (let ((section
2395          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2396     (if (eq (char-before) ? )
2397         (prog1
2398             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2399           (search-forward "]" nil t))
2400       section)))
2401
2402 (defun imap-parse-fetch (response)
2403   (when (eq (char-after) ?\()
2404     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2405               rfc822size body bodydetail bodystructure flags-empty)
2406       (while (not (eq (char-after) ?\)))
2407         (imap-forward)
2408         (let ((token (read (current-buffer))))
2409           (imap-forward)
2410           (cond ((eq token 'UID)
2411                  (setq uid (condition-case ()
2412                                (read (current-buffer))
2413                              (error))))
2414                 ((eq token 'FLAGS)
2415                  (setq flags (imap-parse-flag-list))
2416                  (if (not flags)
2417                      (setq flags-empty 't)))
2418                 ((eq token 'ENVELOPE)
2419                  (setq envelope (imap-parse-envelope)))
2420                 ((eq token 'INTERNALDATE)
2421                  (setq internaldate (imap-parse-string)))
2422                 ((eq token 'RFC822)
2423                  (setq rfc822 (imap-parse-nstring)))
2424                 ((eq token 'RFC822.HEADER)
2425                  (setq rfc822header (imap-parse-nstring)))
2426                 ((eq token 'RFC822.TEXT)
2427                  (setq rfc822text (imap-parse-nstring)))
2428                 ((eq token 'RFC822.SIZE)
2429                  (setq rfc822size (read (current-buffer))))
2430                 ((eq token 'BODY)
2431                  (if (eq (char-before) ?\[)
2432                      (push (list
2433                             (upcase (imap-parse-fetch-body-section))
2434                             (and (eq (char-after) ?<)
2435                                  (buffer-substring (1+ (point))
2436                                                    (search-forward ">" nil t)))
2437                             (progn (imap-forward)
2438                                    (imap-parse-nstring)))
2439                            bodydetail)
2440                    (setq body (imap-parse-body))))
2441                 ((eq token 'BODYSTRUCTURE)
2442                  (setq bodystructure (imap-parse-body))))))
2443       (when uid
2444         (setq imap-current-message uid)
2445         (imap-message-put uid 'UID uid)
2446         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2447         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2448         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2449         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2450         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2451         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2452         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2453         (and body (imap-message-put uid 'BODY body))
2454         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2455         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2456         (run-hooks 'imap-fetch-data-hook)))))
2457
2458 ;;   mailbox-data    =  ...
2459 ;;                      "STATUS" SP mailbox SP "("
2460 ;;                            [status-att SP number
2461 ;;                            *(SP status-att SP number)] ")"
2462 ;;                      ...
2463 ;;
2464 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2465 ;;                     "UNSEEN"
2466
2467 (defun imap-parse-status ()
2468   (let ((mailbox (imap-parse-mailbox)))
2469     (if (eq (char-after) ? )
2470         (forward-char))
2471     (when (and mailbox (eq (char-after) ?\())
2472       (while (and (not (eq (char-after) ?\)))
2473                   (or (forward-char) t)
2474                   (looking-at "\\([A-Za-z]+\\) "))
2475         (let ((token (match-string 1)))
2476           (goto-char (match-end 0))
2477           (cond ((string= token "MESSAGES")
2478                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2479                 ((string= token "RECENT")
2480                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2481                 ((string= token "UIDNEXT")
2482                  (and (looking-at "[0-9]+")
2483                       (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2484                       (goto-char (match-end 0))))
2485                 ((string= token "UIDVALIDITY")
2486                  (and (looking-at "[0-9]+")
2487                       (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2488                       (goto-char (match-end 0))))
2489                 ((string= token "UNSEEN")
2490                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2491                 (t
2492                  (message "Unknown status data %s in mailbox %s ignored"
2493                           token mailbox)
2494                  (read (current-buffer)))))))))
2495
2496 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2497 ;;                        rights)
2498 ;;
2499 ;;   identifier      ::= astring
2500 ;;
2501 ;;   rights          ::= astring
2502
2503 (defun imap-parse-acl ()
2504   (let ((mailbox (imap-parse-mailbox))
2505         identifier rights acl)
2506     (while (eq (char-after) ?\ )
2507       (imap-forward)
2508       (setq identifier (imap-parse-astring))
2509       (imap-forward)
2510       (setq rights (imap-parse-astring))
2511       (setq acl (append acl (list (cons identifier rights)))))
2512     (imap-mailbox-put 'acl acl mailbox)))
2513
2514 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2515 ;;
2516 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2517 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2518 ;;                       ; Does not include "\Recent"
2519 ;;
2520 ;;   flag-keyword    = atom
2521 ;;
2522 ;;   flag-extension  = "\" atom
2523 ;;                       ; Future expansion.  Client implementations
2524 ;;                       ; MUST accept flag-extension flags.  Server
2525 ;;                       ; implementations MUST NOT generate
2526 ;;                       ; flag-extension flags except as defined by
2527 ;;                       ; future standard or standards-track
2528 ;;                       ; revisions of this specification.
2529
2530 (defun imap-parse-flag-list ()
2531   (let (flag-list start)
2532     (assert (eq (char-after) ?\() nil "In imap-parse-flag-list")
2533     (while (and (not (eq (char-after) ?\)))
2534                 (setq start (progn
2535                               (imap-forward)
2536                               ;; next line for Courier IMAP bug.
2537                               (skip-chars-forward " ")
2538                               (point)))
2539                 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2540       (push (buffer-substring start (point)) flag-list))
2541     (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list")
2542     (imap-forward)
2543     (nreverse flag-list)))
2544
2545 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2546 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2547 ;;                     env-in-reply-to SP env-message-id ")"
2548 ;;
2549 ;;   env-bcc         = "(" 1*address ")" / nil
2550 ;;
2551 ;;   env-cc          = "(" 1*address ")" / nil
2552 ;;
2553 ;;   env-date        = nstring
2554 ;;
2555 ;;   env-from        = "(" 1*address ")" / nil
2556 ;;
2557 ;;   env-in-reply-to = nstring
2558 ;;
2559 ;;   env-message-id  = nstring
2560 ;;
2561 ;;   env-reply-to    = "(" 1*address ")" / nil
2562 ;;
2563 ;;   env-sender      = "(" 1*address ")" / nil
2564 ;;
2565 ;;   env-subject     = nstring
2566 ;;
2567 ;;   env-to          = "(" 1*address ")" / nil
2568
2569 (defun imap-parse-envelope ()
2570   (when (eq (char-after) ?\()
2571     (imap-forward)
2572     (vector (prog1 (imap-parse-nstring) ;; date
2573               (imap-forward))
2574             (prog1 (imap-parse-nstring) ;; subject
2575               (imap-forward))
2576             (prog1 (imap-parse-address-list) ;; from
2577               (imap-forward))
2578             (prog1 (imap-parse-address-list) ;; sender
2579               (imap-forward))
2580             (prog1 (imap-parse-address-list) ;; reply-to
2581               (imap-forward))
2582             (prog1 (imap-parse-address-list) ;; to
2583               (imap-forward))
2584             (prog1 (imap-parse-address-list) ;; cc
2585               (imap-forward))
2586             (prog1 (imap-parse-address-list) ;; bcc
2587               (imap-forward))
2588             (prog1 (imap-parse-nstring) ;; in-reply-to
2589               (imap-forward))
2590             (prog1 (imap-parse-nstring) ;; message-id
2591               (imap-forward)))))
2592
2593 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2594
2595 (defsubst imap-parse-string-list ()
2596   (cond ((eq (char-after) ?\() ;; body-fld-param
2597          (let (strlist str)
2598            (imap-forward)
2599            (while (setq str (imap-parse-string))
2600              (push str strlist)
2601              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2602              ;; between body-fld-param's sometimes
2603              (or (eq (char-after) ?\")
2604                  (imap-forward)))
2605            (nreverse strlist)))
2606         ((imap-parse-nil)
2607          nil)))
2608
2609 ;;   body-extension  = nstring / number /
2610 ;;                      "(" body-extension *(SP body-extension) ")"
2611 ;;                       ; Future expansion.  Client implementations
2612 ;;                       ; MUST accept body-extension fields.  Server
2613 ;;                       ; implementations MUST NOT generate
2614 ;;                       ; body-extension fields except as defined by
2615 ;;                       ; future standard or standards-track
2616 ;;                       ; revisions of this specification.
2617
2618 (defun imap-parse-body-extension ()
2619   (if (eq (char-after) ?\()
2620       (let (b-e)
2621         (imap-forward)
2622         (push (imap-parse-body-extension) b-e)
2623         (while (eq (char-after) ?\ )
2624           (imap-forward)
2625           (push (imap-parse-body-extension) b-e))
2626         (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2627         (imap-forward)
2628         (nreverse b-e))
2629     (or (imap-parse-number)
2630         (imap-parse-nstring))))
2631
2632 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2633 ;;                     *(SP body-extension)]]
2634 ;;                       ; MUST NOT be returned on non-extensible
2635 ;;                       ; "BODY" fetch
2636 ;;
2637 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2638 ;;                     *(SP body-extension)]]
2639 ;;                       ; MUST NOT be returned on non-extensible
2640 ;;                       ; "BODY" fetch
2641
2642 (defsubst imap-parse-body-ext ()
2643   (let (ext)
2644     (when (eq (char-after) ?\ ) ;; body-fld-dsp
2645       (imap-forward)
2646       (let (dsp)
2647         (if (eq (char-after) ?\()
2648             (progn
2649               (imap-forward)
2650               (push (imap-parse-string) dsp)
2651               (imap-forward)
2652               (push (imap-parse-string-list) dsp)
2653               (imap-forward))
2654           ;; With assert, the code might not be eval'd.
2655           ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2656           (imap-parse-nil))
2657         (push (nreverse dsp) ext))
2658       (when (eq (char-after) ?\ ) ;; body-fld-lang
2659         (imap-forward)
2660         (if (eq (char-after) ?\()
2661             (push (imap-parse-string-list) ext)
2662           (push (imap-parse-nstring) ext))
2663         (while (eq (char-after) ?\ ) ;; body-extension
2664           (imap-forward)
2665           (setq ext (append (imap-parse-body-extension) ext)))))
2666     ext))
2667
2668 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2669 ;;
2670 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2671 ;;                     *(SP body-extension)]]
2672 ;;                       ; MUST NOT be returned on non-extensible
2673 ;;                       ; "BODY" fetch
2674 ;;
2675 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2676 ;;                     *(SP body-extension)]]
2677 ;;                       ; MUST NOT be returned on non-extensible
2678 ;;                       ; "BODY" fetch
2679 ;;
2680 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2681 ;;                     body-fld-enc SP body-fld-octets
2682 ;;
2683 ;;   body-fld-desc   = nstring
2684 ;;
2685 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2686 ;;
2687 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2688 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2689 ;;
2690 ;;   body-fld-id     = nstring
2691 ;;
2692 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2693 ;;
2694 ;;   body-fld-lines  = number
2695 ;;
2696 ;;   body-fld-md5    = nstring
2697 ;;
2698 ;;   body-fld-octets = number
2699 ;;
2700 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2701 ;;
2702 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2703 ;;                     [SP body-ext-1part]
2704 ;;
2705 ;;   body-type-basic = media-basic SP body-fields
2706 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2707 ;;
2708 ;;   body-type-msg   = media-message SP body-fields SP envelope
2709 ;;                     SP body SP body-fld-lines
2710 ;;
2711 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2712 ;;
2713 ;;   body-type-mpart = 1*body SP media-subtype
2714 ;;                     [SP body-ext-mpart]
2715 ;;
2716 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2717 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2718 ;;                       ; Defined in [MIME-IMT]
2719 ;;
2720 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2721 ;;                      ; Defined in [MIME-IMT]
2722 ;;
2723 ;;   media-subtype   = string
2724 ;;                       ; Defined in [MIME-IMT]
2725 ;;
2726 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2727 ;;                       ; Defined in [MIME-IMT]
2728
2729 (defun imap-parse-body ()
2730   (let (body)
2731     (when (eq (char-after) ?\()
2732       (imap-forward)
2733       (if (eq (char-after) ?\()
2734           (let (subbody)
2735             (while (and (eq (char-after) ?\()
2736                         (setq subbody (imap-parse-body)))
2737              ;; buggy stalker communigate pro 3.0 insert a SPC between
2738               ;; parts in multiparts
2739               (when (and (eq (char-after) ?\ )
2740                          (eq (char-after (1+ (point))) ?\())
2741                 (imap-forward))
2742               (push subbody body))
2743             (imap-forward)
2744             (push (imap-parse-string) body) ;; media-subtype
2745             (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2746               (imap-forward)
2747               (if (eq (char-after) ?\() ;; body-fld-param
2748                   (push (imap-parse-string-list) body)
2749                 (push (and (imap-parse-nil) nil) body))
2750               (setq body
2751                     (append (imap-parse-body-ext) body))) ;; body-ext-...
2752             (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2753             (imap-forward)
2754             (nreverse body))
2755
2756         (push (imap-parse-string) body) ;; media-type
2757         (imap-forward)
2758         (push (imap-parse-string) body) ;; media-subtype
2759         (imap-forward)
2760         ;; next line for Sun SIMS bug
2761         (and (eq (char-after) ? ) (imap-forward))
2762         (if (eq (char-after) ?\() ;; body-fld-param
2763             (push (imap-parse-string-list) body)
2764           (push (and (imap-parse-nil) nil) body))
2765         (imap-forward)
2766         (push (imap-parse-nstring) body) ;; body-fld-id
2767         (imap-forward)
2768         (push (imap-parse-nstring) body) ;; body-fld-desc
2769         (imap-forward)
2770         ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2771         ;; nstring and return nil instead of defaulting back to 7BIT
2772         ;; as the standard says.
2773         (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2774         (imap-forward)
2775         (push (imap-parse-number) body) ;; body-fld-octets
2776
2777    ;; ok, we're done parsing the required parts, what comes now is one
2778         ;; of three things:
2779         ;;
2780         ;; envelope       (then we're parsing body-type-msg)
2781         ;; body-fld-lines (then we're parsing body-type-text)
2782         ;; body-ext-1part (then we're parsing body-type-basic)
2783         ;;
2784   ;; the problem is that the two first are in turn optionally followed
2785 ;; by the third.  So we parse the first two here (if there are any)...
2786
2787         (when (eq (char-after) ?\ )
2788           (imap-forward)
2789           (let (lines)
2790             (cond ((eq (char-after) ?\() ;; body-type-msg:
2791                    (push (imap-parse-envelope) body) ;; envelope
2792                    (imap-forward)
2793                    (push (imap-parse-body) body) ;; body
2794                    ;; buggy stalker communigate pro 3.0 doesn't print
2795                    ;; number of lines in message/rfc822 attachment
2796                    (if (eq (char-after) ?\))
2797                        (push 0 body)
2798                      (imap-forward)
2799                      (push (imap-parse-number) body))) ;; body-fld-lines
2800                   ((setq lines (imap-parse-number)) ;; body-type-text:
2801                    (push lines body)) ;; body-fld-lines
2802                   (t
2803                    (backward-char))))) ;; no match...
2804
2805         ;; ...and then parse the third one here...
2806
2807         (when (eq (char-after) ?\ ) ;; body-ext-1part:
2808           (imap-forward)
2809           (push (imap-parse-nstring) body) ;; body-fld-md5
2810           (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2811
2812         (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2813         (imap-forward)
2814         (nreverse body)))))
2815
2816 (when imap-debug                        ; (untrace-all)
2817   (require 'trace)
2818   (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2819   (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2820           '(
2821             imap-utf7-encode
2822             imap-utf7-decode
2823             imap-error-text
2824             imap-kerberos4s-p
2825             imap-kerberos4-open
2826             imap-ssl-p
2827             imap-ssl-open
2828             imap-network-p
2829             imap-network-open
2830             imap-interactive-login
2831             imap-kerberos4a-p
2832             imap-kerberos4-auth
2833             imap-cram-md5-p
2834             imap-cram-md5-auth
2835             imap-login-p
2836             imap-login-auth
2837             imap-anonymous-p
2838             imap-anonymous-auth
2839             imap-open-1
2840             imap-open
2841             imap-opened
2842             imap-authenticate
2843             imap-close
2844             imap-capability
2845             imap-namespace
2846             imap-send-command-wait
2847             imap-mailbox-put
2848             imap-mailbox-get
2849             imap-mailbox-map-1
2850             imap-mailbox-map
2851             imap-current-mailbox
2852             imap-current-mailbox-p-1
2853             imap-current-mailbox-p
2854             imap-mailbox-select-1
2855             imap-mailbox-select
2856             imap-mailbox-examine-1
2857             imap-mailbox-examine
2858             imap-mailbox-unselect
2859             imap-mailbox-expunge
2860             imap-mailbox-close
2861             imap-mailbox-create-1
2862             imap-mailbox-create
2863             imap-mailbox-delete
2864             imap-mailbox-rename
2865             imap-mailbox-lsub
2866             imap-mailbox-list
2867             imap-mailbox-subscribe
2868             imap-mailbox-unsubscribe
2869             imap-mailbox-status
2870             imap-mailbox-acl-get
2871             imap-mailbox-acl-set
2872             imap-mailbox-acl-delete
2873             imap-current-message
2874             imap-list-to-message-set
2875             imap-fetch-asynch
2876             imap-fetch
2877             imap-message-put
2878             imap-message-get
2879             imap-message-map
2880             imap-search
2881             imap-message-flag-permanent-p
2882             imap-message-flags-set
2883             imap-message-flags-del
2884             imap-message-flags-add
2885             imap-message-copyuid-1
2886             imap-message-copyuid
2887             imap-message-copy
2888             imap-message-appenduid-1
2889             imap-message-appenduid
2890             imap-message-append
2891             imap-body-lines
2892             imap-envelope-from
2893             imap-send-command-1
2894             imap-send-command
2895             imap-wait-for-tag
2896             imap-sentinel
2897             imap-find-next-line
2898             imap-arrival-filter
2899             imap-parse-greeting
2900             imap-parse-response
2901             imap-parse-resp-text
2902             imap-parse-resp-text-code
2903             imap-parse-data-list
2904             imap-parse-fetch
2905             imap-parse-status
2906             imap-parse-acl
2907             imap-parse-flag-list
2908             imap-parse-envelope
2909             imap-parse-body-extension
2910             imap-parse-body
2911             )))
2912
2913 (provide 'imap)
2914
2915 ;;; arch-tag: 27369ed6-33e4-482f-96f1-8bb906ba70f7
2916 ;;; imap.el ends here