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