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