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