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