* gnus.el: Fix copyright statements.
[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
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             (when (string= (car (split-string type "/")) "message")
262               ;; message/rfc822 parts have to have their heads encoded.
263               (save-restriction
264                 (message-narrow-to-head)
265                 (let ((rfc2047-header-encoding-alist nil))
266                   (mail-encode-encoded-word-buffer))))
267             (setq charset (mm-encode-body))
268             (setq encoding (mm-body-encoding charset 
269                                              (cdr (assq 'encoding cont))))
270             (setq coded (buffer-string)))
271         (mm-with-unibyte-buffer
272           (cond
273            ((cdr (assq 'buffer cont))
274             (insert-buffer-substring (cdr (assq 'buffer cont))))
275            ((and (setq filename (cdr (assq 'filename cont)))
276                  (not (equal (cdr (assq 'nofile cont)) "yes")))
277             (let ((coding-system-for-read mm-binary-coding-system))
278               (mm-insert-file-contents filename nil nil nil nil t)))
279            (t
280             (insert (cdr (assq 'contents cont)))))
281           (setq encoding (mm-encode-buffer type)
282                 coded (buffer-string))))
283       (mml-insert-mime-headers cont type charset encoding)
284       (insert "\n")
285       (insert coded)))
286    ((eq (car cont) 'external)
287     (insert "Content-Type: message/external-body")
288     (let ((parameters (mml-parameter-string
289                        cont '(expiration size permission)))
290           (name (cdr (assq 'name cont))))
291       (when name
292         (setq name (mml-parse-file-name name))
293         (if (stringp name)
294             (mml-insert-parameter
295              (mail-header-encode-parameter "name" name)
296              "access-type=local-file")
297           (mml-insert-parameter
298            (mail-header-encode-parameter
299             "name" (file-name-nondirectory (nth 2 name)))
300            (mail-header-encode-parameter "site" (nth 1 name))
301            (mail-header-encode-parameter
302             "directory" (file-name-directory (nth 2 name))))
303           (mml-insert-parameter
304            (concat "access-type="
305                    (if (member (nth 0 name) '("ftp@" "anonymous@"))
306                        "anon-ftp"
307                      "ftp")))))      
308       (when parameters
309         (mml-insert-parameter-string
310          cont '(expiration size permission))))
311     (insert "\n\n")
312     (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
313     (insert "Content-ID: " (message-make-message-id) "\n")
314     (insert "Content-Transfer-Encoding: "
315             (or (cdr (assq 'encoding cont)) "binary"))
316     (insert "\n\n")
317     (insert (or (cdr (assq 'contents cont))))
318     (insert "\n"))
319    ((eq (car cont) 'multipart)
320     (let* ((type (or (cdr (assq 'type cont)) "mixed"))
321            (handler (assoc type mml-generate-multipart-alist)))
322       (if handler
323           (funcall (cdr handler) cont)
324         ;; No specific handler.  Use default one.
325         (let ((mml-boundary (mml-compute-boundary cont)))
326           (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
327                           type mml-boundary))
328           (setq cont (cddr cont))
329           (while cont
330             (insert "\n--" mml-boundary "\n")
331             (mml-generate-mime-1 (pop cont)))
332           (insert "\n--" mml-boundary "--\n")))))
333    (t
334     (error "Invalid element: %S" cont))))
335
336 (defun mml-compute-boundary (cont)
337   "Return a unique boundary that does not exist in CONT."
338   (let ((mml-boundary (funcall mml-boundary-function
339                                (incf mml-multipart-number))))
340     ;; This function tries again and again until it has found
341     ;; a unique boundary.
342     (while (not (catch 'not-unique
343                   (mml-compute-boundary-1 cont))))
344     mml-boundary))
345
346 (defun mml-compute-boundary-1 (cont)
347   (let (filename)
348     (cond
349      ((eq (car cont) 'part)
350       (with-temp-buffer
351         (cond
352          ((cdr (assq 'buffer cont))
353           (insert-buffer-substring (cdr (assq 'buffer cont))))
354          ((and (setq filename (cdr (assq 'filename cont)))
355                (not (equal (cdr (assq 'nofile cont)) "yes")))
356           (mm-insert-file-contents filename))
357          (t
358           (insert (cdr (assq 'contents cont)))))
359         (goto-char (point-min))
360         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
361                                  nil t)
362           (setq mml-boundary (funcall mml-boundary-function
363                                       (incf mml-multipart-number)))
364           (throw 'not-unique nil))))
365      ((eq (car cont) 'multipart)
366       (mapcar 'mml-compute-boundary-1 (cddr cont))))
367     t))
368
369 (defun mml-make-boundary (number)
370   (concat (make-string (% number 60) ?=)
371           (if (> number 17)
372               (format "%x" number)
373             "")
374           mml-base-boundary))
375
376 (defun mml-make-string (num string)
377   (let ((out ""))
378     (while (not (zerop (decf num)))
379       (setq out (concat out string)))
380     out))
381
382 (defun mml-insert-mime-headers (cont type charset encoding)
383   (let (parameters disposition description)
384     (setq parameters
385           (mml-parameter-string
386            cont '(name access-type expiration size permission)))
387     (when (or charset
388               parameters
389               (not (equal type "text/plain")))
390       (when (consp charset)
391         (error
392          "Can't encode a part with several charsets."))
393       (insert "Content-Type: " type)
394       (when charset
395         (insert "; " (mail-header-encode-parameter
396                       "charset" (symbol-name charset))))
397       (when parameters
398         (mml-insert-parameter-string
399          cont '(name access-type expiration size permission)))
400       (insert "\n"))
401     (setq parameters
402           (mml-parameter-string
403            cont '(filename creation-date modification-date read-date)))
404     (when (or (setq disposition (cdr (assq 'disposition cont)))
405               parameters)
406       (insert "Content-Disposition: " (or disposition "inline"))
407       (when parameters
408         (mml-insert-parameter-string
409          cont '(filename creation-date modification-date read-date)))
410       (insert "\n"))
411     (unless (eq encoding '7bit)
412       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
413     (when (setq description (cdr (assq 'description cont)))
414       (insert "Content-Description: "
415               (mail-encode-encoded-word-string description) "\n"))))
416
417 (defun mml-parameter-string (cont types)
418   (let ((string "")
419         value type)
420     (while (setq type (pop types))
421       (when (setq value (cdr (assq type cont)))
422         ;; Strip directory component from the filename parameter.
423         (when (eq type 'filename)
424           (setq value (file-name-nondirectory value)))
425         (setq string (concat string "; "
426                              (mail-header-encode-parameter
427                               (symbol-name type) value)))))
428     (when (not (zerop (length string)))
429       string)))
430
431 (defun mml-insert-parameter-string (cont types)
432   (let (value type)
433     (while (setq type (pop types))
434       (when (setq value (cdr (assq type cont)))
435         ;; Strip directory component from the filename parameter.
436         (when (eq type 'filename)
437           (setq value (file-name-nondirectory value)))
438         (mml-insert-parameter
439          (mail-header-encode-parameter
440           (symbol-name type) value))))))
441
442 (defvar ange-ftp-path-format)
443 (defvar efs-path-regexp)
444 (defun mml-parse-file-name (path)
445   (if (if (boundp 'efs-path-regexp)
446           (string-match efs-path-regexp path)
447         (if (boundp 'ange-ftp-path-format)
448             (string-match (car ange-ftp-path-format))))
449       (list (match-string 1 path) (match-string 2 path)
450             (substring path (1+ (match-end 2))))
451     path))
452
453 (defun mml-insert-buffer (buffer)
454   "Insert BUFFER at point and quote any MML markup."
455   (save-restriction
456     (narrow-to-region (point) (point))
457     (insert-buffer-substring buffer)
458     (mml-quote-region (point-min) (point-max))
459     (goto-char (point-max))))
460
461 ;;;
462 ;;; Transforming MIME to MML
463 ;;;
464
465 (defun mime-to-mml ()
466   "Translate the current buffer (which should be a message) into MML."
467   ;; First decode the head.
468   (save-restriction
469     (message-narrow-to-head)
470     (mail-decode-encoded-word-region (point-min) (point-max)))
471   (let ((handles (mm-dissect-buffer t)))
472     (goto-char (point-min))
473     (search-forward "\n\n" nil t)
474     (delete-region (point) (point-max))
475     (if (stringp (car handles))
476         (mml-insert-mime handles)
477       (mml-insert-mime handles t))
478     (mm-destroy-parts handles)))
479
480 (defun mml-to-mime ()
481   "Translate the current buffer from MML to MIME."
482   (message-encode-message-body)
483   (save-restriction
484     (message-narrow-to-headers-or-head)
485     (mail-encode-encoded-word-buffer)))
486
487 (defun mml-insert-mime (handle &optional no-markup)
488   (let (textp buffer)
489     ;; Determine type and stuff.
490     (unless (stringp (car handle))
491       (unless (setq textp (equal (mm-handle-media-supertype handle)
492                                  "text"))
493         (save-excursion
494           (set-buffer (setq buffer (generate-new-buffer " *mml*")))
495           (mm-insert-part handle))))
496     (unless no-markup
497       (mml-insert-mml-markup handle buffer textp))
498     (cond
499      ((stringp (car handle))
500       (mapcar 'mml-insert-mime (cdr handle))
501       (insert "<#/multipart>\n"))
502      (textp
503       (let ((text (mm-get-part handle))
504             (charset (mail-content-type-get
505                       (mm-handle-type handle) 'charset)))
506         (insert (mm-decode-string text charset)))
507       (goto-char (point-max)))
508      (t
509       (insert "<#/part>\n")))))
510
511 (defun mml-insert-mml-markup (handle &optional buffer nofile)
512   "Take a MIME handle and insert an MML tag."
513   (if (stringp (car handle))
514       (insert "<#multipart type=" (mm-handle-media-subtype handle)
515               ">\n")
516     (insert "<#part type=" (mm-handle-media-type handle))
517     (dolist (elem (append (cdr (mm-handle-type handle))
518                           (cdr (mm-handle-disposition handle))))
519       (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\""))
520     (when (mm-handle-disposition handle)
521       (insert " disposition=" (car (mm-handle-disposition handle))))
522     (when buffer
523       (insert " buffer=\"" (buffer-name buffer) "\""))
524     (when nofile
525       (insert " nofile=yes"))
526     (when (mm-handle-description handle)
527       (insert " description=\"" (mm-handle-description handle) "\""))
528     (insert ">\n")))
529
530 (defun mml-insert-parameter (&rest parameters)
531   "Insert PARAMETERS in a nice way."
532   (dolist (param parameters)
533     (insert ";")
534     (let ((point (point)))
535       (insert " " param)
536       (when (> (current-column) 71)
537         (goto-char point)
538         (insert "\n ")
539         (end-of-line)))))
540
541 ;;;
542 ;;; Mode for inserting and editing MML forms
543 ;;;
544
545 (defvar mml-mode-map
546   (let ((map (make-sparse-keymap))
547         (main (make-sparse-keymap)))
548     (define-key map "f" 'mml-attach-file)
549     (define-key map "b" 'mml-attach-buffer)
550     (define-key map "e" 'mml-attach-external)
551     (define-key map "q" 'mml-quote-region)
552     (define-key map "m" 'mml-insert-multipart)
553     (define-key map "p" 'mml-insert-part)
554     (define-key map "v" 'mml-validate)
555     (define-key map "P" 'mml-preview)
556     (define-key map "n" 'mml-narrow-to-part)
557     (define-key main "\M-m" map)
558     main))
559
560 (easy-menu-define
561  mml-menu mml-mode-map ""
562  '("MML"
563    ("Attach"
564     ["File" mml-attach-file t]
565     ["Buffer" mml-attach-buffer t]
566     ["External" mml-attach-external t])
567    ("Insert"
568     ["Multipart" mml-insert-multipart t]
569     ["Part" mml-insert-part t])
570    ["Narrow" mml-narrow-to-part t]
571    ["Quote" mml-quote-region t]
572    ["Validate" mml-validate t]
573    ["Preview" mml-preview t]))
574
575 (defvar mml-mode nil
576   "Minor mode for editing MML.")
577
578 (defun mml-mode (&optional arg)
579   "Minor mode for editing MML.
580
581 \\{mml-mode-map}"
582   (interactive "P")
583   (if (not (set (make-local-variable 'mml-mode)
584                 (if (null arg) (not mml-mode)
585                   (> (prefix-numeric-value arg) 0))))
586       nil
587     (set (make-local-variable 'mml-mode) t)
588     (unless (assq 'mml-mode minor-mode-alist)
589       (push `(mml-mode " MML") minor-mode-alist))
590     (unless (assq 'mml-mode minor-mode-map-alist)
591       (push (cons 'mml-mode mml-mode-map)
592             minor-mode-map-alist)))
593   (run-hooks 'mml-mode-hook))
594
595 ;;;
596 ;;; Helper functions for reading MIME stuff from the minibuffer and
597 ;;; inserting stuff to the buffer.
598 ;;;
599
600 (defun mml-minibuffer-read-file (prompt)
601   (let ((file (read-file-name prompt nil nil t)))
602     ;; Prevent some common errors.  This is inspired by similar code in
603     ;; VM.
604     (when (file-directory-p file)
605       (error "%s is a directory, cannot attach" file))
606     (unless (file-exists-p file)
607       (error "No such file: %s" file))
608     (unless (file-readable-p file)
609       (error "Permission denied: %s" file))
610     file))
611
612 (defun mml-minibuffer-read-type (name &optional default)
613   (let* ((default (or default
614                       (mm-default-file-encoding name)
615                       ;; Perhaps here we should check what the file
616                       ;; looks like, and offer text/plain if it looks
617                       ;; like text/plain.
618                       "application/octet-stream"))
619          (string (completing-read
620                   (format "Content type (default %s): " default)
621                   (mapcar
622                    'list
623                    (mm-delete-duplicates
624                     (nconc
625                      (mapcar (lambda (m) (cdr m))
626                              mailcap-mime-extensions)
627                      (apply
628                       'nconc
629                       (mapcar
630                        (lambda (l)
631                          (delq nil
632                                (mapcar
633                                 (lambda (m)
634                                   (let ((type (cdr (assq 'type (cdr m)))))
635                                     (if (equal (cadr (split-string type "/"))
636                                                "*")
637                                         nil
638                                       type)))
639                                 (cdr l))))
640                        mailcap-mime-data))))))))
641     (if (not (equal string ""))
642         string
643       default)))
644
645 (defun mml-minibuffer-read-description ()
646   (let ((description (read-string "One line description: ")))
647     (when (string-match "\\`[ \t]*\\'" description)
648       (setq description nil))
649     description))
650
651 (defun mml-quote-region (beg end)
652   "Quote the MML tags in the region."
653   (interactive "r")
654   (save-excursion
655     (save-restriction
656       ;; Temporarily narrow the region to defend from changes
657       ;; invalidating END.
658       (narrow-to-region beg end)
659       (goto-char (point-min))
660       ;; Quote parts.
661       (while (re-search-forward
662               "<#/?!*\\(multipart\\|part\\|external\\)" nil t)
663         ;; Insert ! after the #.
664         (goto-char (+ (match-beginning 0) 2))
665         (insert "!")))))
666
667 (defun mml-insert-tag (name &rest plist)
668   "Insert an MML tag described by NAME and PLIST."
669   (when (symbolp name)
670     (setq name (symbol-name name)))
671   (insert "<#" name)
672   (while plist
673     (let ((key (pop plist))
674           (value (pop plist)))
675       (when value
676         ;; Quote VALUE if it contains suspicious characters.
677         (when (string-match "[\"\\~/* \t\n]" value)
678           (setq value (prin1-to-string value)))
679         (insert (format " %s=%s" key value)))))
680   (insert ">\n"))
681
682 (defun mml-insert-empty-tag (name &rest plist)
683   "Insert an empty MML tag described by NAME and PLIST."
684   (when (symbolp name)
685     (setq name (symbol-name name)))
686   (apply #'mml-insert-tag name plist)
687   (insert "<#/" name ">\n"))
688
689 ;;; Attachment functions.
690
691 (defun mml-attach-file (file &optional type description)
692   "Attach a file to the outgoing MIME message.
693 The file is not inserted or encoded until you send the message with
694 `\\[message-send-and-exit]' or `\\[message-send]'.
695
696 FILE is the name of the file to attach.  TYPE is its content-type, a
697 string of the form \"type/subtype\".  DESCRIPTION is a one-line
698 description of the attachment."
699   (interactive
700    (let* ((file (mml-minibuffer-read-file "Attach file: "))
701           (type (mml-minibuffer-read-type file))
702           (description (mml-minibuffer-read-description)))
703      (list file type description)))
704   (mml-insert-empty-tag 'part 'type type 'filename file
705                         'disposition "attachment" 'description description))
706
707 (defun mml-attach-buffer (buffer &optional type description)
708   "Attach a buffer to the outgoing MIME message.
709 See `mml-attach-file' for details of operation."
710   (interactive
711    (let* ((buffer (read-buffer "Attach buffer: "))
712           (type (mml-minibuffer-read-type buffer "text/plain"))
713           (description (mml-minibuffer-read-description)))
714      (list buffer type description)))
715   (mml-insert-empty-tag 'part 'type type 'buffer buffer
716                         'disposition "attachment" 'description description))
717
718 (defun mml-attach-external (file &optional type description)
719   "Attach an external file into the buffer.
720 FILE is an ange-ftp/efs specification of the part location.
721 TYPE is the MIME type to use."
722   (interactive
723    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
724           (type (mml-minibuffer-read-type file))
725           (description (mml-minibuffer-read-description)))
726      (list file type description)))
727   (mml-insert-empty-tag 'external 'type type 'name file
728                         'disposition "attachment" 'description description))
729
730 (defun mml-insert-multipart (&optional type)
731   (interactive (list (completing-read "Multipart type (default mixed): "
732                                       '(("mixed") ("alternative") ("digest") ("parallel")
733                                         ("signed") ("encrypted"))
734                                       nil nil "mixed")))
735   (or type
736       (setq type "mixed"))
737   (mml-insert-empty-tag "multipart" 'type type)
738   (forward-line -1))
739
740 (defun mml-insert-part (&optional type)
741   (interactive
742    (list (mml-minibuffer-read-type "")))
743   (mml-insert-tag 'part 'type type 'disposition "inline")
744   (forward-line -1))
745
746 (defun mml-preview (&optional raw)
747   "Display current buffer with Gnus, in a new buffer.
748 If RAW, don't highlight the article."
749   (interactive "P")
750   (let ((buf (current-buffer)))
751     (switch-to-buffer (get-buffer-create 
752                        (concat (if raw "*Raw MIME preview of "
753                                  "*MIME preview of ") (buffer-name))))
754     (erase-buffer)
755     (insert-buffer buf)
756     (if (re-search-forward
757          (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
758         (replace-match "\n"))
759     (mml-to-mime)
760     (unless raw
761       (run-hooks 'gnus-article-decode-hook)
762       (let ((gnus-newsgroup-name "dummy"))
763         (gnus-article-prepare-display)))
764     (fundamental-mode)
765     (setq buffer-read-only t)
766     (goto-char (point-min))))
767
768 (defun mml-validate ()
769   "Validate the current MML document."
770   (interactive)
771   (mml-parse))
772
773 (provide 'mml)
774
775 ;;; mml.el ends here