Synch with Gnus.
[elisp/gnus.git-] / lisp / mml.el
1 ;;; mml.el --- A package for parsing and validating MML documents
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 (require 'mm-util)
27 (require 'mm-bodies)
28 (require 'mm-encode)
29 (require 'mm-decode)
30 (require 'mml-sec)
31 (eval-when-compile (require 'cl))
32
33 (eval-and-compile
34   (autoload 'message-make-message-id "message")
35   (autoload 'gnus-setup-posting-charset "gnus-msg")
36   (autoload 'message-fetch-field "message")
37   (autoload 'message-posting-charset "message"))
38
39 (defvar mml-generate-multipart-alist nil
40   "*Alist of multipart generation functions.
41 Each entry has the form (NAME . FUNCTION), where
42 NAME is a string containing the name of the part (without the 
43 leading \"/multipart/\"),
44 FUNCTION is a Lisp function which is called to generate the part.
45
46 The Lisp function has to supply the appropriate MIME headers and the
47 contents of this part.")
48
49 (defvar mml-syntax-table
50   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
51     (modify-syntax-entry ?\\ "/" table)
52     (modify-syntax-entry ?< "(" table)
53     (modify-syntax-entry ?> ")" table)
54     (modify-syntax-entry ?@ "w" table)
55     (modify-syntax-entry ?/ "w" table)
56     (modify-syntax-entry ?= " " table)
57     (modify-syntax-entry ?* " " table)
58     (modify-syntax-entry ?\; " " table)
59     (modify-syntax-entry ?\' " " table)
60     table))
61
62 (defvar mml-boundary-function 'mml-make-boundary
63   "A function called to suggest a boundary.
64 The function may be called several times, and should try to make a new
65 suggestion each time.  The function is called with one parameter,
66 which is a number that says how many times the function has been
67 called for this message.")
68
69 (defvar mml-confirmation-set nil
70   "A list of symbols, each of which disables some warning.
71 `unknown-encoding': always send messages contain characters with
72 unknown encoding; `use-ascii': always use ASCII for those characters
73 with unknown encoding; `multipart': always send messages with more than
74 one charsets.")
75
76 (defvar mml-generate-mime-preprocess-function nil
77   "A function called before generating a mime part.
78 The function is called with one parameter, which is the part to be 
79 generated.")
80
81 (defvar mml-generate-mime-postprocess-function 'mml-postprocess
82   "A function called after generating a mime part.
83 The function is called with one parameter, which is the generated part.")
84
85 (autoload 'mml2015-sign "mml2015")
86 (autoload 'mml2015-encrypt "mml2015")
87 (autoload 'mml-smime-encrypt "mml-smime")
88 (autoload 'mml-smime-sign "mml-smime")
89
90 (defvar mml-postprocess-alist
91   '(("pgp-sign" . mml2015-sign)
92     ("pgp-encrypt" . mml2015-encrypt)
93     ("smime-sign" . mml-smime-sign)
94     ("smime-encrypt" . mml-smime-encrypt))
95   "Alist of postprocess functions.")
96
97 (defvar mml-generate-default-type "text/plain")
98
99 (defvar mml-buffer-list nil)
100
101 (defun mml-generate-new-buffer (name) 
102   (let ((buf (generate-new-buffer name)))
103     (push buf mml-buffer-list)
104     buf))
105
106 (defun mml-destroy-buffers ()
107   (let (kill-buffer-hook)
108     (mapcar 'kill-buffer mml-buffer-list)
109     (setq mml-buffer-list nil)))
110
111 (defun mml-parse ()
112   "Parse the current buffer as an MML document."
113   (goto-char (point-min))
114   (let ((table (syntax-table)))
115     (unwind-protect
116         (progn
117           (set-syntax-table mml-syntax-table)
118           (mml-parse-1))
119       (set-syntax-table table))))
120
121 (defun mml-parse-1 ()
122   "Parse the current buffer as an MML document."
123   (let (struct tag point contents charsets warn use-ascii no-markup-p raw)
124     (while (and (not (eobp))
125                 (not (looking-at "<#/multipart")))
126       (cond
127        ((looking-at "<#multipart")
128         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
129        ((looking-at "<#external")
130         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
131               struct))
132        (t
133         (if (or (looking-at "<#part") (looking-at "<#mml"))
134             (setq tag (mml-read-tag)
135                   no-markup-p nil
136                   warn nil)
137           (setq tag (list 'part '(type . "text/plain"))
138                 no-markup-p t
139                 warn t))
140         (setq raw (cdr (assq 'raw tag))
141               point (point)
142               contents (mml-read-part (eq 'mml (car tag)))
143               charsets (if raw nil 
144                          (mm-find-mime-charset-region point (point))))
145         (when (and (not raw) (memq nil charsets))
146           (if (or (memq 'unknown-encoding mml-confirmation-set)
147                   (y-or-n-p
148                    "Message contains characters with unknown encoding.  Really send?"))
149               (if (setq use-ascii 
150                         (or (memq 'use-ascii mml-confirmation-set)
151                             (y-or-n-p "Use ASCII as charset?")))
152                   (setq charsets (delq nil charsets))
153                 (setq warn nil))
154             (error "Edit your message to remove those characters")))
155         (if (or raw
156                 (eq 'mml (car tag))
157                 (< (length charsets) 2))
158             (if (or (not no-markup-p)
159                     (string-match "[^ \t\r\n]" contents))
160                 ;; Don't create blank parts.
161                 (push (nconc tag (list (cons 'contents contents)))
162                       struct))
163           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
164                           tag point (point) use-ascii)))
165             (when (and warn
166                        (not (memq 'multipart mml-confirmation-set))
167                        (not
168                         (y-or-n-p
169                          (format
170                           "Warning: Your message contains more than %d parts.  Really send? "
171                           (length nstruct)))))
172               (error "Edit your message to use only one charset"))
173             (setq struct (nconc nstruct struct)))))))
174     (unless (eobp)
175       (forward-line 1))
176     (nreverse struct)))
177
178 (defun mml-parse-singlepart-with-multiple-charsets 
179   (orig-tag beg end &optional use-ascii)
180   (save-excursion
181     (save-restriction
182       (narrow-to-region beg end)
183       (goto-char (point-min))
184       (let ((current (or (mm-mime-charset (mm-charset-after))
185                          (and use-ascii 'us-ascii)))
186             charset struct space newline paragraph)
187         (while (not (eobp))
188           (setq charset (mm-mime-charset (mm-charset-after)))
189           (cond
190            ;; The charset remains the same.
191            ((eq charset 'us-ascii))
192            ((or (and use-ascii (not charset))
193                 (eq charset current))
194             (setq space nil
195                   newline nil
196                   paragraph nil))
197            ;; The initial charset was ascii.
198            ((eq current 'us-ascii)
199             (setq current charset
200                   space nil
201                   newline nil
202                   paragraph nil))
203            ;; We have a change in charsets.
204            (t
205             (push (append
206                    orig-tag
207                    (list (cons 'contents
208                                (buffer-substring-no-properties
209                                 beg (or paragraph newline space (point))))))
210                   struct)
211             (setq beg (or paragraph newline space (point))
212                   current charset
213                   space nil
214                   newline nil
215                   paragraph nil)))
216           ;; Compute places where it might be nice to break the part.
217           (cond
218            ((memq (following-char) '(?  ?\t))
219             (setq space (1+ (point))))
220            ((and (eq (following-char) ?\n)
221                  (not (bobp))
222                  (eq (char-after (1- (point))) ?\n))
223             (setq paragraph (point)))
224            ((eq (following-char) ?\n)
225             (setq newline (1+ (point)))))
226           (forward-char 1))
227         ;; Do the final part.
228         (unless (= beg (point))
229           (push (append orig-tag
230                         (list (cons 'contents
231                                     (buffer-substring-no-properties
232                                      beg (point)))))
233                 struct))
234         struct))))
235
236 (defun mml-read-tag ()
237   "Read a tag and return the contents."
238   (let (contents name elem val)
239     (forward-char 2)
240     (setq name (buffer-substring-no-properties
241                 (point) (progn (forward-sexp 1) (point))))
242     (skip-chars-forward " \t\n")
243     (while (not (looking-at ">"))
244       (setq elem (buffer-substring-no-properties
245                   (point) (progn (forward-sexp 1) (point))))
246       (skip-chars-forward "= \t\n")
247       (setq val (buffer-substring-no-properties
248                  (point) (progn (forward-sexp 1) (point))))
249       (when (string-match "^\"\\(.*\\)\"$" val)
250         (setq val (match-string 1 val)))
251       (push (cons (intern elem) val) contents)
252       (skip-chars-forward " \t\n"))
253     (forward-char 1)
254     (skip-chars-forward " \t\n")
255     (cons (intern name) (nreverse contents))))
256
257 (defun mml-read-part (&optional mml)
258   "Return the buffer up till the next part, multipart or closing part or multipart.
259 If MML is non-nil, return the buffer up till the correspondent mml tag."
260   (let ((beg (point)) (count 1))
261     ;; If the tag ended at the end of the line, we go to the next line.
262     (when (looking-at "[ \t]*\n")
263       (forward-line 1))
264     (if mml
265         (progn
266           (while (and (> count 0) (not (eobp)))
267             (if (re-search-forward "<#\\(/\\)?mml." nil t)
268                 (setq count (+ count (if (match-beginning 1) -1 1)))
269               (goto-char (point-max))))
270           (buffer-substring-no-properties beg (if (> count 0) 
271                                                   (point)
272                                                 (match-beginning 0))))
273       (if (re-search-forward
274            "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
275           (prog1
276               (buffer-substring-no-properties beg (match-beginning 0))
277             (if (or (not (match-beginning 1))
278                     (equal (match-string 2) "multipart"))
279                 (goto-char (match-beginning 0))
280               (when (looking-at "[ \t]*\n")
281                 (forward-line 1))))
282         (buffer-substring-no-properties beg (goto-char (point-max)))))))
283
284 (defvar mml-boundary nil)
285 (defvar mml-base-boundary "-=-=")
286 (defvar mml-multipart-number 0)
287
288 (defun mml-generate-mime ()
289   "Generate a MIME message based on the current MML document."
290   (let ((cont (mml-parse))
291         (mml-multipart-number mml-multipart-number))
292     (if (not cont)
293         nil
294       (with-temp-buffer
295         (if (and (consp (car cont))
296                  (= (length cont) 1))
297             (mml-generate-mime-1 (car cont))
298           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
299                                       cont)))
300         (buffer-string)))))
301
302 (defun mml-generate-mime-1 (cont)
303   (save-restriction
304     (narrow-to-region (point) (point))
305     (if mml-generate-mime-preprocess-function
306         (funcall mml-generate-mime-preprocess-function cont))
307     (cond
308      ((or (eq (car cont) 'part) (eq (car cont) 'mml))
309       (let ((raw (cdr (assq 'raw cont)))
310             coded encoding charset filename type)
311         (setq type (or (cdr (assq 'type cont)) "text/plain"))
312         (if (and (not raw)
313                  (member (car (split-string type "/")) '("text" "message")))
314             (with-temp-buffer
315               (cond
316                ((cdr (assq 'buffer cont))
317                 (insert-buffer-substring (cdr (assq 'buffer cont))))
318                ((and (setq filename (cdr (assq 'filename cont)))
319                      (not (equal (cdr (assq 'nofile cont)) "yes")))
320                 (mm-insert-file-contents filename))
321                ((eq 'mml (car cont))
322                 (insert (cdr (assq 'contents cont))))
323                (t
324                 (save-restriction
325                   (narrow-to-region (point) (point))
326                   (insert (cdr (assq 'contents cont)))
327                   ;; Remove quotes from quoted tags.
328                   (goto-char (point-min))
329                   (while (re-search-forward
330                           "<#!+/?\\(part\\|multipart\\|external\\|mml\\)" nil t)
331                     (delete-region (+ (match-beginning 0) 2)
332                                    (+ (match-beginning 0) 3))))))
333               (cond 
334                ((eq (car cont) 'mml)
335                 (let ((mml-boundary (funcall mml-boundary-function
336                                              (incf mml-multipart-number)))
337                       (mml-generate-default-type "text/plain"))
338                   (mml-to-mime))
339                 (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
340                   ;; ignore 0x1b, it is part of iso-2022-jp
341                   (setq encoding (mm-body-7-or-8))))
342                ((string= (car (split-string type "/")) "message")
343                 (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
344                   ;; ignore 0x1b, it is part of iso-2022-jp
345                   (setq encoding (mm-body-7-or-8))))
346                (t 
347                 (setq charset (mm-encode-body))
348                 (setq encoding (mm-body-encoding
349                                 charset (cdr (assq 'encoding cont))))))
350               (setq coded (buffer-string)))
351           (mm-with-unibyte-buffer
352             (cond
353              ((cdr (assq 'buffer cont))
354               (insert-buffer-substring (cdr (assq 'buffer cont))))
355              ((and (setq filename (cdr (assq 'filename cont)))
356                    (not (equal (cdr (assq 'nofile cont)) "yes")))
357               (let ((coding-system-for-read mm-binary-coding-system))
358                 (mm-insert-file-contents filename nil nil nil nil t)))
359              (t
360               (insert (cdr (assq 'contents cont)))))
361             (setq encoding (mm-encode-buffer type)
362                   coded (buffer-string))))
363         (mml-insert-mime-headers cont type charset encoding)
364         (insert "\n")
365         (insert coded)))
366      ((eq (car cont) 'external)
367       (insert "Content-Type: message/external-body")
368       (let ((parameters (mml-parameter-string
369                          cont '(expiration size permission)))
370             (name (cdr (assq 'name cont))))
371         (when name
372           (setq name (mml-parse-file-name name))
373           (if (stringp name)
374               (mml-insert-parameter
375                (mail-header-encode-parameter "name" name)
376                "access-type=local-file")
377             (mml-insert-parameter
378              (mail-header-encode-parameter
379               "name" (file-name-nondirectory (nth 2 name)))
380              (mail-header-encode-parameter "site" (nth 1 name))
381              (mail-header-encode-parameter
382               "directory" (file-name-directory (nth 2 name))))
383             (mml-insert-parameter
384              (concat "access-type="
385                      (if (member (nth 0 name) '("ftp@" "anonymous@"))
386                          "anon-ftp"
387                        "ftp")))))      
388         (when parameters
389           (mml-insert-parameter-string
390            cont '(expiration size permission))))
391       (insert "\n\n")
392       (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
393       (insert "Content-ID: " (message-make-message-id) "\n")
394       (insert "Content-Transfer-Encoding: "
395               (or (cdr (assq 'encoding cont)) "binary"))
396       (insert "\n\n")
397       (insert (or (cdr (assq 'contents cont))))
398       (insert "\n"))
399      ((eq (car cont) 'multipart)
400       (let* ((type (or (cdr (assq 'type cont)) "mixed"))
401              (mml-generate-default-type (if (equal type "digest")
402                                             "message/rfc822"
403                                           "text/plain"))
404              (handler (assoc type mml-generate-multipart-alist)))
405         (if handler
406             (funcall (cdr handler) cont)
407           ;; No specific handler.  Use default one.
408           (let ((mml-boundary (mml-compute-boundary cont)))
409             (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
410                             type mml-boundary))
411             ;; Skip `multipart' and `type' elements.
412             (setq cont (cddr cont))
413             (while cont
414               (insert "\n--" mml-boundary "\n")
415               (mml-generate-mime-1 (pop cont)))
416             (insert "\n--" mml-boundary "--\n")))))
417      (t
418       (error "Invalid element: %S" cont)))
419     (if mml-generate-mime-postprocess-function
420         (funcall mml-generate-mime-postprocess-function cont))
421     (let ((item (assoc (cdr (assq 'sign cont)) mml-sign-alist)))
422       (when item
423         (funcall (nth 1 item) cont)))
424     (let ((item (assoc (cdr (assq 'encrypt cont)) mml-encrypt-alist)))
425       (when item
426         (funcall (nth 1 item) cont)))))
427
428 (defun mml-compute-boundary (cont)
429   "Return a unique boundary that does not exist in CONT."
430   (let ((mml-boundary (funcall mml-boundary-function
431                                (incf mml-multipart-number))))
432     ;; This function tries again and again until it has found
433     ;; a unique boundary.
434     (while (not (catch 'not-unique
435                   (mml-compute-boundary-1 cont))))
436     mml-boundary))
437
438 (defun mml-compute-boundary-1 (cont)
439   (let (filename)
440     (cond
441      ((eq (car cont) 'part)
442       (with-temp-buffer
443         (cond
444          ((cdr (assq 'buffer cont))
445           (insert-buffer-substring (cdr (assq 'buffer cont))))
446          ((and (setq filename (cdr (assq 'filename cont)))
447                (not (equal (cdr (assq 'nofile cont)) "yes")))
448           (mm-insert-file-contents filename))
449          (t
450           (insert (cdr (assq 'contents cont)))))
451         (goto-char (point-min))
452         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
453                                  nil t)
454           (setq mml-boundary (funcall mml-boundary-function
455                                       (incf mml-multipart-number)))
456           (throw 'not-unique nil))))
457      ((eq (car cont) 'multipart)
458       (mapcar 'mml-compute-boundary-1 (cddr cont))))
459     t))
460
461 (defun mml-make-boundary (number)
462   (concat (make-string (% number 60) ?=)
463           (if (> number 17)
464               (format "%x" number)
465             "")
466           mml-base-boundary))
467
468 (defun mml-insert-mime-headers (cont type charset encoding)
469   (let (parameters disposition description)
470     (setq parameters
471           (mml-parameter-string
472            cont '(name access-type expiration size permission)))
473     (when (or charset
474               parameters
475               (not (equal type mml-generate-default-type)))
476       (when (consp charset)
477         (error
478          "Can't encode a part with several charsets."))
479       (insert "Content-Type: " type)
480       (when charset
481         (insert "; " (mail-header-encode-parameter
482                       "charset" (symbol-name charset))))
483       (when parameters
484         (mml-insert-parameter-string
485          cont '(name access-type expiration size permission)))
486       (insert "\n"))
487     (setq parameters
488           (mml-parameter-string
489            cont '(filename creation-date modification-date read-date)))
490     (when (or (setq disposition (cdr (assq 'disposition cont)))
491               parameters)
492       (insert "Content-Disposition: " (or disposition "inline"))
493       (when parameters
494         (mml-insert-parameter-string
495          cont '(filename creation-date modification-date read-date)))
496       (insert "\n"))
497     (unless (eq encoding '7bit)
498       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
499     (when (setq description (cdr (assq 'description cont)))
500       (insert "Content-Description: "
501               (mail-encode-encoded-word-string description) "\n"))))
502
503 (defun mml-parameter-string (cont types)
504   (let ((string "")
505         value type)
506     (while (setq type (pop types))
507       (when (setq value (cdr (assq type cont)))
508         ;; Strip directory component from the filename parameter.
509         (when (eq type 'filename)
510           (setq value (file-name-nondirectory value)))
511         (setq string (concat string "; "
512                              (mail-header-encode-parameter
513                               (symbol-name type) value)))))
514     (when (not (zerop (length string)))
515       string)))
516
517 (defun mml-insert-parameter-string (cont types)
518   (let (value type)
519     (while (setq type (pop types))
520       (when (setq value (cdr (assq type cont)))
521         ;; Strip directory component from the filename parameter.
522         (when (eq type 'filename)
523           (setq value (file-name-nondirectory value)))
524         (mml-insert-parameter
525          (mail-header-encode-parameter
526           (symbol-name type) value))))))
527
528 (defvar ange-ftp-name-format)
529 (defvar efs-path-regexp)
530 (defun mml-parse-file-name (path)
531   (if (if (boundp 'efs-path-regexp)
532           (string-match efs-path-regexp path)
533         (if (boundp 'ange-ftp-name-format)
534             (string-match (car ange-ftp-name-format) path)))
535       (list (match-string 1 path) (match-string 2 path)
536             (substring path (1+ (match-end 2))))
537     path))
538
539 (defun mml-insert-buffer (buffer)
540   "Insert BUFFER at point and quote any MML markup."
541   (save-restriction
542     (narrow-to-region (point) (point))
543     (insert-buffer-substring buffer)
544     (mml-quote-region (point-min) (point-max))
545     (goto-char (point-max))))
546
547 ;;;
548 ;;; Transforming MIME to MML
549 ;;;
550
551 (defun mime-to-mml ()
552   "Translate the current buffer (which should be a message) into MML."
553   ;; First decode the head.
554   (save-restriction
555     (message-narrow-to-head)
556     (mail-decode-encoded-word-region (point-min) (point-max)))
557   (let ((handles (mm-dissect-buffer t)))
558     (goto-char (point-min))
559     (search-forward "\n\n" nil t)
560     (delete-region (point) (point-max))
561     (if (stringp (car handles))
562         (mml-insert-mime handles)
563       (mml-insert-mime handles t))
564     (mm-destroy-parts handles))
565   (save-restriction
566     (message-narrow-to-head)
567     ;; Remove them, they are confusing.
568     (message-remove-header "Content-Type")
569     (message-remove-header "MIME-Version")
570     (message-remove-header "Content-Transfer-Encoding")))
571
572 (defun mml-to-mime ()
573   "Translate the current buffer from MML to MIME."
574   (message-encode-message-body)
575   (save-restriction
576     (message-narrow-to-headers-or-head)
577     (let ((mail-parse-charset message-default-charset))
578       (mail-encode-encoded-word-buffer))))
579
580 (defun mml-insert-mime (handle &optional no-markup)
581   (let (textp buffer mmlp)
582     ;; Determine type and stuff.
583     (unless (stringp (car handle))
584       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
585         (save-excursion
586           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
587           (mm-insert-part handle)
588           (if (setq mmlp (equal (mm-handle-media-type handle) 
589                                 "message/rfc822"))
590               (mime-to-mml)))))
591     (if mmlp
592         (mml-insert-mml-markup handle nil t t)
593       (unless (and no-markup
594                    (equal (mm-handle-media-type handle) "text/plain"))
595         (mml-insert-mml-markup handle buffer textp)))
596     (cond
597      (mmlp 
598       (insert-buffer buffer)
599       (goto-char (point-max))
600       (insert "<#/mml>\n"))
601      ((stringp (car handle))
602       (mapcar 'mml-insert-mime (cdr handle))
603       (insert "<#/multipart>\n"))
604      (textp
605       (let ((text (mm-get-part handle))
606             (charset (mail-content-type-get
607                       (mm-handle-type handle) 'charset)))
608         (insert (mm-decode-string text charset)))
609       (goto-char (point-max)))
610      (t
611       (insert "<#/part>\n")))))
612
613 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
614   "Take a MIME handle and insert an MML tag."
615   (if (stringp (car handle))
616       (insert "<#multipart type=" (mm-handle-media-subtype handle)
617               ">\n")
618     (if mmlp
619         (insert "<#mml type=" (mm-handle-media-type handle))
620       (insert "<#part type=" (mm-handle-media-type handle)))
621     (dolist (elem (append (cdr (mm-handle-type handle))
622                           (cdr (mm-handle-disposition handle))))
623       (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\""))
624     (when (mm-handle-disposition handle)
625       (insert " disposition=" (car (mm-handle-disposition handle))))
626     (when buffer
627       (insert " buffer=\"" (buffer-name buffer) "\""))
628     (when nofile
629       (insert " nofile=yes"))
630     (when (mm-handle-description handle)
631       (insert " description=\"" (mm-handle-description handle) "\""))
632     (insert ">\n")))
633
634 (defun mml-insert-parameter (&rest parameters)
635   "Insert PARAMETERS in a nice way."
636   (dolist (param parameters)
637     (insert ";")
638     (let ((point (point)))
639       (insert " " param)
640       (when (> (current-column) 71)
641         (goto-char point)
642         (insert "\n ")
643         (end-of-line)))))
644
645 ;;;
646 ;;; Mode for inserting and editing MML forms
647 ;;;
648
649 (defvar mml-mode-map
650   (let ((sign (make-sparse-keymap))
651         (encrypt (make-sparse-keymap))
652         (map (make-sparse-keymap))
653         (main (make-sparse-keymap)))
654     (define-key sign "p" 'mml-secure-sign-pgpmime)
655     (define-key sign "s" 'mml-secure-sign-smime)
656     (define-key encrypt "p" 'mml-secure-encrypt-pgpmime)
657     (define-key encrypt "s" 'mml-secure-encrypt-smime)
658     (define-key map "f" 'mml-attach-file)
659     (define-key map "b" 'mml-attach-buffer)
660     (define-key map "e" 'mml-attach-external)
661     (define-key map "q" 'mml-quote-region)
662     (define-key map "m" 'mml-insert-multipart)
663     (define-key map "p" 'mml-insert-part)
664     (define-key map "v" 'mml-validate)
665     (define-key map "P" 'mml-preview)
666     (define-key map "s" sign)
667     (define-key map "c" encrypt)
668     ;;(define-key map "n" 'mml-narrow-to-part)
669     (define-key main "\M-m" map)
670     main))
671
672 (easy-menu-define
673  mml-menu mml-mode-map ""
674  '("MML"
675    ("Attach"
676     ["File" mml-attach-file t]
677     ["Buffer" mml-attach-buffer t]
678     ["External" mml-attach-external t])
679    ("Insert"
680     ["Multipart" mml-insert-multipart t]
681     ["Part" mml-insert-part t])
682    ("Security"
683     ("Sign"
684      ["PGP/MIME" mml-secure-sign-pgpmime t]
685      ["S/MIME" mml-secure-sign-smime t])
686     ("Encrypt"
687      ["PGP/MIME" mml-secure-encrypt-pgpmime t]
688      ["S/MIME" mml-secure-encrypt-smime t]))
689    ;;["Narrow" mml-narrow-to-part t]
690    ["Quote" mml-quote-region t]
691    ["Validate" mml-validate t]
692    ["Preview" mml-preview t]))
693
694 (defvar mml-mode nil
695   "Minor mode for editing MML.")
696
697 (defun mml-mode (&optional arg)
698   "Minor mode for editing MML.
699
700 \\{mml-mode-map}"
701   (interactive "P")
702   (if (not (set (make-local-variable 'mml-mode)
703                 (if (null arg) (not mml-mode)
704                   (> (prefix-numeric-value arg) 0))))
705       nil
706     (set (make-local-variable 'mml-mode) t)
707     (unless (assq 'mml-mode minor-mode-alist)
708       (push `(mml-mode " MML") minor-mode-alist))
709     (unless (assq 'mml-mode minor-mode-map-alist)
710       (push (cons 'mml-mode mml-mode-map)
711             minor-mode-map-alist)))
712   (run-hooks 'mml-mode-hook))
713
714 ;;;
715 ;;; Helper functions for reading MIME stuff from the minibuffer and
716 ;;; inserting stuff to the buffer.
717 ;;;
718
719 (defun mml-minibuffer-read-file (prompt)
720   (let ((file (read-file-name prompt nil nil t)))
721     ;; Prevent some common errors.  This is inspired by similar code in
722     ;; VM.
723     (when (file-directory-p file)
724       (error "%s is a directory, cannot attach" file))
725     (unless (file-exists-p file)
726       (error "No such file: %s" file))
727     (unless (file-readable-p file)
728       (error "Permission denied: %s" file))
729     file))
730
731 (defun mml-minibuffer-read-type (name &optional default)
732   (mailcap-parse-mimetypes)
733   (let* ((default (or default
734                       (mm-default-file-encoding name)
735                       ;; Perhaps here we should check what the file
736                       ;; looks like, and offer text/plain if it looks
737                       ;; like text/plain.
738                       "application/octet-stream"))
739          (string (completing-read
740                   (format "Content type (default %s): " default)
741                   (mapcar 'list (mailcap-mime-types)))))
742     (if (not (equal string ""))
743         string
744       default)))
745
746 (defun mml-minibuffer-read-description ()
747   (let ((description (read-string "One line description: ")))
748     (when (string-match "\\`[ \t]*\\'" description)
749       (setq description nil))
750     description))
751
752 (defun mml-quote-region (beg end)
753   "Quote the MML tags in the region."
754   (interactive "r")
755   (save-excursion
756     (save-restriction
757       ;; Temporarily narrow the region to defend from changes
758       ;; invalidating END.
759       (narrow-to-region beg end)
760       (goto-char (point-min))
761       ;; Quote parts.
762       (while (re-search-forward
763               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
764         ;; Insert ! after the #.
765         (goto-char (+ (match-beginning 0) 2))
766         (insert "!")))))
767
768 (defun mml-insert-tag (name &rest plist)
769   "Insert an MML tag described by NAME and PLIST."
770   (when (symbolp name)
771     (setq name (symbol-name name)))
772   (insert "<#" name)
773   (while plist
774     (let ((key (pop plist))
775           (value (pop plist)))
776       (when value
777         ;; Quote VALUE if it contains suspicious characters.
778         (when (string-match "[\"'\\~/*;() \t\n]" value)
779           (setq value (prin1-to-string value)))
780         (insert (format " %s=%s" key value)))))
781   (insert ">\n"))
782
783 (defun mml-insert-empty-tag (name &rest plist)
784   "Insert an empty MML tag described by NAME and PLIST."
785   (when (symbolp name)
786     (setq name (symbol-name name)))
787   (apply #'mml-insert-tag name plist)
788   (insert "<#/" name ">\n"))
789
790 ;;; Attachment functions.
791
792 (defun mml-attach-file (file &optional type description)
793   "Attach a file to the outgoing MIME message.
794 The file is not inserted or encoded until you send the message with
795 `\\[message-send-and-exit]' or `\\[message-send]'.
796
797 FILE is the name of the file to attach.  TYPE is its content-type, a
798 string of the form \"type/subtype\".  DESCRIPTION is a one-line
799 description of the attachment."
800   (interactive
801    (let* ((file (mml-minibuffer-read-file "Attach file: "))
802           (type (mml-minibuffer-read-type file))
803           (description (mml-minibuffer-read-description)))
804      (list file type description)))
805   (mml-insert-empty-tag 'part 'type type 'filename file
806                         'disposition "attachment" 'description description))
807
808 (defun mml-attach-buffer (buffer &optional type description)
809   "Attach a buffer to the outgoing MIME message.
810 See `mml-attach-file' for details of operation."
811   (interactive
812    (let* ((buffer (read-buffer "Attach buffer: "))
813           (type (mml-minibuffer-read-type buffer "text/plain"))
814           (description (mml-minibuffer-read-description)))
815      (list buffer type description)))
816   (mml-insert-empty-tag 'part 'type type 'buffer buffer
817                         'disposition "attachment" 'description description))
818
819 (defun mml-attach-external (file &optional type description)
820   "Attach an external file into the buffer.
821 FILE is an ange-ftp/efs specification of the part location.
822 TYPE is the MIME type to use."
823   (interactive
824    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
825           (type (mml-minibuffer-read-type file))
826           (description (mml-minibuffer-read-description)))
827      (list file type description)))
828   (mml-insert-empty-tag 'external 'type type 'name file
829                         'disposition "attachment" 'description description))
830
831 (defun mml-insert-multipart (&optional type)
832   (interactive (list (completing-read "Multipart type (default mixed): "
833                                       '(("mixed") ("alternative") ("digest") ("parallel")
834                                         ("signed") ("encrypted"))
835                                       nil nil "mixed")))
836   (or type
837       (setq type "mixed"))
838   (mml-insert-empty-tag "multipart" 'type type)
839   (forward-line -1))
840
841 (defun mml-insert-part (&optional type)
842   (interactive
843    (list (mml-minibuffer-read-type "")))
844   (mml-insert-tag 'part 'type type 'disposition "inline")
845   (forward-line -1))
846
847 (defun mml-preview (&optional raw)
848   "Display current buffer with Gnus, in a new buffer.
849 If RAW, don't highlight the article."
850   (interactive "P")
851   (let ((buf (current-buffer))
852         (message-options message-options)
853         (message-posting-charset (or (gnus-setup-posting-charset 
854                                       (save-restriction
855                                         (message-narrow-to-headers-or-head)
856                                         (message-fetch-field "Newsgroups")))
857                                      message-posting-charset)))
858     (message-options-set-recipient)
859     (switch-to-buffer (generate-new-buffer
860                        (concat (if raw "*Raw MIME preview of "
861                                  "*MIME preview of ") (buffer-name))))
862     (erase-buffer)
863     (insert-buffer buf)
864     (if (re-search-forward
865          (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
866         (replace-match "\n"))
867     (mml-to-mime)
868     (if raw
869         (when (fboundp 'set-buffer-multibyte)
870           (let ((s (buffer-string)))
871             ;; Insert the content into unibyte buffer.
872             (erase-buffer)
873             (mm-disable-multibyte)
874             (insert s)))
875       (let ((gnus-newsgroup-charset (car message-posting-charset)))
876         (run-hooks 'gnus-article-decode-hook)
877         (let ((gnus-newsgroup-name "dummy"))
878           (gnus-article-prepare-display))))
879     (fundamental-mode)
880     (setq buffer-read-only t)
881     (goto-char (point-min))))
882
883 (defun mml-validate ()
884   "Validate the current MML document."
885   (interactive)
886   (mml-parse))
887
888 (defun mml-postprocess (cont)
889   (let ((pp (cdr (or (assq 'postprocess cont)
890                      (assq 'pp cont))))
891         item)
892     (if (and pp (setq item (assoc pp mml-postprocess-alist)))
893         (funcall (cdr item) cont))))
894
895 (provide 'mml)
896
897 ;;; mml.el ends here