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