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