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