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