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