2002-01-01 Steve Youngs <youngs@xemacs.org>
[gnus] / 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               (progn
338                 (with-temp-buffer
339                   (setq charset (mm-charset-to-coding-system
340                                  (cdr (assq 'charset cont))))
341                   (when (eq charset 'ascii)
342                     (setq charset nil))
343                   (cond
344                    ((cdr (assq 'buffer cont))
345                     (insert-buffer-substring (cdr (assq 'buffer cont))))
346                    ((and (setq filename (cdr (assq 'filename cont)))
347                          (not (equal (cdr (assq 'nofile cont)) "yes")))
348                     (let ((coding-system-for-read charset))
349                       (mm-insert-file-contents filename)))
350                    ((eq 'mml (car cont))
351                     (insert (cdr (assq 'contents cont))))
352                    (t
353                     (save-restriction
354                       (narrow-to-region (point) (point))
355                       (insert (cdr (assq 'contents cont)))
356                       ;; Remove quotes from quoted tags.
357                       (goto-char (point-min))
358                       (while (re-search-forward
359                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\)"
360                               nil t)
361                         (delete-region (+ (match-beginning 0) 2)
362                                        (+ (match-beginning 0) 3))))))
363                   (cond
364                    ((eq (car cont) 'mml)
365                     (let ((mml-boundary (funcall mml-boundary-function
366                                                  (incf mml-multipart-number)))
367                           (mml-generate-default-type "text/plain"))
368                       (mml-to-mime))
369                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
370                       ;; ignore 0x1b, it is part of iso-2022-jp
371                       (setq encoding (mm-body-7-or-8))))
372                    ((string= (car (split-string type "/")) "message")
373                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
374                       ;; ignore 0x1b, it is part of iso-2022-jp
375                       (setq encoding (mm-body-7-or-8))))
376                    (t
377                     (setq charset (mm-encode-body charset))
378                     (setq encoding (mm-body-encoding
379                                     charset (cdr (assq 'encoding cont))))))
380                   (setq coded (buffer-string)))
381                 (mml-insert-mime-headers cont type charset encoding)
382                 (insert "\n")
383                 (insert coded))
384             (mm-with-unibyte-buffer
385               (cond
386                ((cdr (assq 'buffer cont))
387                 (insert-buffer-substring (cdr (assq 'buffer cont))))
388                ((and (setq filename (cdr (assq 'filename cont)))
389                      (not (equal (cdr (assq 'nofile cont)) "yes")))
390                 (let ((coding-system-for-read mm-binary-coding-system))
391                   (mm-insert-file-contents filename nil nil nil nil t)))
392                (t
393                 (insert (cdr (assq 'contents cont)))))
394               (setq encoding (mm-encode-buffer type)
395                     coded (mm-string-as-multibyte (buffer-string))))
396             (mml-insert-mime-headers cont type charset encoding)
397             (insert "\n")
398             (mm-with-unibyte-current-buffer
399               (insert coded)))))
400        ((eq (car cont) 'external)
401         (insert "Content-Type: message/external-body")
402         (let ((parameters (mml-parameter-string
403                            cont '(expiration size permission)))
404               (name (cdr (assq 'name cont)))
405               (url (cdr (assq 'url cont))))
406           (when name
407             (setq name (mml-parse-file-name name))
408             (if (stringp name)
409                 (mml-insert-parameter
410                  (mail-header-encode-parameter "name" name)
411                  "access-type=local-file")
412               (mml-insert-parameter
413                (mail-header-encode-parameter
414                 "name" (file-name-nondirectory (nth 2 name)))
415                (mail-header-encode-parameter "site" (nth 1 name))
416                (mail-header-encode-parameter
417                 "directory" (file-name-directory (nth 2 name))))
418               (mml-insert-parameter
419                (concat "access-type="
420                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
421                            "anon-ftp"
422                          "ftp")))))
423           (when url
424             (mml-insert-parameter
425              (mail-header-encode-parameter "url" url)
426              "access-type=url"))
427           (when parameters
428             (mml-insert-parameter-string
429              cont '(expiration size permission))))
430         (insert "\n\n")
431         (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
432         (insert "Content-ID: " (message-make-message-id) "\n")
433         (insert "Content-Transfer-Encoding: "
434                 (or (cdr (assq 'encoding cont)) "binary"))
435         (insert "\n\n")
436         (insert (or (cdr (assq 'contents cont))))
437         (insert "\n"))
438        ((eq (car cont) 'multipart)
439         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
440                (mml-generate-default-type (if (equal type "digest")
441                                               "message/rfc822"
442                                             "text/plain"))
443                (handler (assoc type mml-generate-multipart-alist)))
444           (if handler
445               (funcall (cdr handler) cont)
446             ;; No specific handler.  Use default one.
447             (let ((mml-boundary (mml-compute-boundary cont)))
448               (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
449                               type mml-boundary))
450               (let ((cont cont) part)
451                 (while (setq part (pop cont))
452                   ;; Skip `multipart' and attributes.
453                   (when (and (consp part) (consp (cdr part)))
454                     (insert "\n--" mml-boundary "\n")
455                     (mml-generate-mime-1 part))))
456               (insert "\n--" mml-boundary "--\n")))))
457        (t
458         (error "Invalid element: %S" cont)))
459       (let ((item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
460             sender recipients)
461         (when item
462           (if (setq sender (cdr (assq 'sender cont)))
463               (message-options-set 'message-sender sender))
464           (if (setq recipients (cdr (assq 'recipients cont)))
465               (message-options-set 'message-sender recipients))
466           (funcall (nth 1 item) cont)))
467       (let ((item (assoc (cdr (assq 'encrypt cont)) mml-encrypt-alist))
468             sender recipients)
469         (when item
470           (if (setq sender (cdr (assq 'sender cont)))
471               (message-options-set 'message-sender sender))
472           (if (setq recipients (cdr (assq 'recipients cont)))
473               (message-options-set 'message-sender recipients))
474           (funcall (nth 1 item) cont))))))
475
476 (defun mml-compute-boundary (cont)
477   "Return a unique boundary that does not exist in CONT."
478   (let ((mml-boundary (funcall mml-boundary-function
479                                (incf mml-multipart-number))))
480     ;; This function tries again and again until it has found
481     ;; a unique boundary.
482     (while (not (catch 'not-unique
483                   (mml-compute-boundary-1 cont))))
484     mml-boundary))
485
486 (defun mml-compute-boundary-1 (cont)
487   (let (filename)
488     (cond
489      ((eq (car cont) 'part)
490       (with-temp-buffer
491         (cond
492          ((cdr (assq 'buffer cont))
493           (insert-buffer-substring (cdr (assq 'buffer cont))))
494          ((and (setq filename (cdr (assq 'filename cont)))
495                (not (equal (cdr (assq 'nofile cont)) "yes")))
496           (mm-insert-file-contents filename))
497          (t
498           (insert (cdr (assq 'contents cont)))))
499         (goto-char (point-min))
500         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
501                                  nil t)
502           (setq mml-boundary (funcall mml-boundary-function
503                                       (incf mml-multipart-number)))
504           (throw 'not-unique nil))))
505      ((eq (car cont) 'multipart)
506       (mapcar 'mml-compute-boundary-1 (cddr cont))))
507     t))
508
509 (defun mml-make-boundary (number)
510   (concat (make-string (% number 60) ?=)
511           (if (> number 17)
512               (format "%x" number)
513             "")
514           mml-base-boundary))
515
516 (defun mml-insert-mime-headers (cont type charset encoding)
517   (let (parameters disposition description)
518     (setq parameters
519           (mml-parameter-string
520            cont mml-content-type-parameters))
521     (when (or charset
522               parameters
523               (not (equal type mml-generate-default-type)))
524       (when (consp charset)
525         (error
526          "Can't encode a part with several charsets."))
527       (insert "Content-Type: " type)
528       (when charset
529         (insert "; " (mail-header-encode-parameter
530                       "charset" (symbol-name charset))))
531       (when parameters
532         (mml-insert-parameter-string
533          cont mml-content-type-parameters))
534       (insert "\n"))
535     (setq parameters
536           (mml-parameter-string
537            cont mml-content-disposition-parameters))
538     (when (or (setq disposition (cdr (assq 'disposition cont)))
539               parameters)
540       (insert "Content-Disposition: " (or disposition "inline"))
541       (when parameters
542         (mml-insert-parameter-string
543          cont mml-content-disposition-parameters))
544       (insert "\n"))
545     (unless (eq encoding '7bit)
546       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
547     (when (setq description (cdr (assq 'description cont)))
548       (insert "Content-Description: "
549               (mail-encode-encoded-word-string description) "\n"))))
550
551 (defun mml-parameter-string (cont types)
552   (let ((string "")
553         value type)
554     (while (setq type (pop types))
555       (when (setq value (cdr (assq type cont)))
556         ;; Strip directory component from the filename parameter.
557         (when (eq type 'filename)
558           (setq value (file-name-nondirectory value)))
559         (setq string (concat string "; "
560                              (mail-header-encode-parameter
561                               (symbol-name type) value)))))
562     (when (not (zerop (length string)))
563       string)))
564
565 (defun mml-insert-parameter-string (cont types)
566   (let (value type)
567     (while (setq type (pop types))
568       (when (setq value (cdr (assq type cont)))
569         ;; Strip directory component from the filename parameter.
570         (when (eq type 'filename)
571           (setq value (file-name-nondirectory value)))
572         (mml-insert-parameter
573          (mail-header-encode-parameter
574           (symbol-name type) value))))))
575
576 (eval-when-compile
577   (defvar ange-ftp-name-format)
578   (defvar efs-path-regexp))
579 (defun mml-parse-file-name (path)
580   (if (if (boundp 'efs-path-regexp)
581           (string-match efs-path-regexp path)
582         (if (boundp 'ange-ftp-name-format)
583             (string-match (car ange-ftp-name-format) path)))
584       (list (match-string 1 path) (match-string 2 path)
585             (substring path (1+ (match-end 2))))
586     path))
587
588 (defun mml-insert-buffer (buffer)
589   "Insert BUFFER at point and quote any MML markup."
590   (save-restriction
591     (narrow-to-region (point) (point))
592     (insert-buffer-substring buffer)
593     (mml-quote-region (point-min) (point-max))
594     (goto-char (point-max))))
595
596 ;;;
597 ;;; Transforming MIME to MML
598 ;;;
599
600 (defun mime-to-mml (&optional handles)
601   "Translate the current buffer (which should be a message) into MML.
602 If HANDLES is non-nil, use it instead reparsing the buffer."
603   ;; First decode the head.
604   (save-restriction
605     (message-narrow-to-head)
606     (mail-decode-encoded-word-region (point-min) (point-max)))
607   (unless handles
608     (setq handles (mm-dissect-buffer t)))
609   (goto-char (point-min))
610   (search-forward "\n\n" nil t)
611   (delete-region (point) (point-max))
612   (if (stringp (car handles))
613       (mml-insert-mime handles)
614     (mml-insert-mime handles t))
615   (mm-destroy-parts handles)
616   (save-restriction
617     (message-narrow-to-head)
618     ;; Remove them, they are confusing.
619     (message-remove-header "Content-Type")
620     (message-remove-header "MIME-Version")
621     (message-remove-header "Content-Disposition")
622     (message-remove-header "Content-Transfer-Encoding")))
623
624 (defun mml-to-mime ()
625   "Translate the current buffer from MML to MIME."
626   (message-encode-message-body)
627   (save-restriction
628     (message-narrow-to-headers-or-head)
629     (let ((mail-parse-charset message-default-charset))
630       (mail-encode-encoded-word-buffer))))
631
632 (defun mml-insert-mime (handle &optional no-markup)
633   (let (textp buffer mmlp)
634     ;; Determine type and stuff.
635     (unless (stringp (car handle))
636       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
637         (save-excursion
638           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
639           (mm-insert-part handle)
640           (if (setq mmlp (equal (mm-handle-media-type handle)
641                                 "message/rfc822"))
642               (mime-to-mml)))))
643     (if mmlp
644         (mml-insert-mml-markup handle nil t t)
645       (unless (and no-markup
646                    (equal (mm-handle-media-type handle) "text/plain"))
647         (mml-insert-mml-markup handle buffer textp)))
648     (cond
649      (mmlp
650       (insert-buffer buffer)
651       (goto-char (point-max))
652       (insert "<#/mml>\n"))
653      ((stringp (car handle))
654       (mapcar 'mml-insert-mime (cdr handle))
655       (insert "<#/multipart>\n"))
656      (textp
657       (let ((charset (mail-content-type-get
658                       (mm-handle-type handle) 'charset)))
659         (if (eq charset 'gnus-decoded)
660             (mm-insert-part handle)
661           (insert (mm-decode-string (mm-get-part handle) charset))))
662       (goto-char (point-max)))
663      (t
664       (insert "<#/part>\n")))))
665
666 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
667   "Take a MIME handle and insert an MML tag."
668   (if (stringp (car handle))
669       (insert "<#multipart type=" (mm-handle-media-subtype handle)
670               ">\n")
671     (if mmlp
672         (insert "<#mml type=" (mm-handle-media-type handle))
673       (insert "<#part type=" (mm-handle-media-type handle)))
674     (dolist (elem (append (cdr (mm-handle-type handle))
675                           (cdr (mm-handle-disposition handle))))
676       (unless (symbolp (cdr elem))
677         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
678     (when (mm-handle-disposition handle)
679       (insert " disposition=" (car (mm-handle-disposition handle))))
680     (when buffer
681       (insert " buffer=\"" (buffer-name buffer) "\""))
682     (when nofile
683       (insert " nofile=yes"))
684     (when (mm-handle-description handle)
685       (insert " description=\"" (mm-handle-description handle) "\""))
686     (insert ">\n")))
687
688 (defun mml-insert-parameter (&rest parameters)
689   "Insert PARAMETERS in a nice way."
690   (dolist (param parameters)
691     (insert ";")
692     (let ((point (point)))
693       (insert " " param)
694       (when (> (current-column) 71)
695         (goto-char point)
696         (insert "\n ")
697         (end-of-line)))))
698
699 ;;;
700 ;;; Mode for inserting and editing MML forms
701 ;;;
702
703 (defvar mml-mode-map
704   (let ((sign (make-sparse-keymap))
705         (encrypt (make-sparse-keymap))
706         (map (make-sparse-keymap))
707         (main (make-sparse-keymap)))
708     (define-key sign "p" 'mml-secure-sign-pgpmime)
709     (define-key sign "o" 'mml-secure-sign-pgp)
710     (define-key sign "s" 'mml-secure-sign-smime)
711     (define-key encrypt "p" 'mml-secure-encrypt-pgpmime)
712     (define-key encrypt "o" 'mml-secure-encrypt-pgp)
713     (define-key encrypt "s" 'mml-secure-encrypt-smime)
714     (define-key map "f" 'mml-attach-file)
715     (define-key map "b" 'mml-attach-buffer)
716     (define-key map "e" 'mml-attach-external)
717     (define-key map "q" 'mml-quote-region)
718     (define-key map "m" 'mml-insert-multipart)
719     (define-key map "p" 'mml-insert-part)
720     (define-key map "v" 'mml-validate)
721     (define-key map "P" 'mml-preview)
722     (define-key map "s" sign)
723     (define-key map "c" encrypt)
724     ;;(define-key map "n" 'mml-narrow-to-part)
725     ;; `M-m' conflicts with `back-to-indentation'.
726     ;; (define-key main "\M-m" map)
727     (define-key main "\C-c\C-m" map)
728     main))
729
730 (easy-menu-define
731   mml-menu mml-mode-map ""
732   `("Attachments"
733     ["Attach File" mml-attach-file
734      ,@(if (featurep 'xemacs) '(t)
735          '(:help "Attach a file at point"))]
736     ["Attach Buffer" mml-attach-buffer t]
737     ["Attach External" mml-attach-external t]
738     ["Insert Part" mml-insert-part t]
739     ["Insert Multipart" mml-insert-multipart t]
740     ["PGP/MIME Sign" mml-secure-sign-pgpmime t]
741     ["PGP/MIME Encrypt" mml-secure-encrypt-pgpmime t]
742     ["PGP Sign" mml-secure-sign-pgp t]
743     ["PGP Encrypt" mml-secure-encrypt-pgp t]
744     ["S/MIME Sign" mml-secure-sign-smime t]
745     ["S/MIME Encrypt" mml-secure-encrypt-smime t]
746     ;;["Narrow" mml-narrow-to-part t]
747     ["Quote MML" mml-quote-region t]
748     ["Validate MML" mml-validate t]
749     ["Preview" mml-preview t]))
750
751 (defvar mml-mode nil
752   "Minor mode for editing MML.")
753
754 (defun mml-mode (&optional arg)
755   "Minor mode for editing MML.
756 MML is the MIME Meta Language, a minor mode for composing MIME articles.
757 See Info node `(emacs-mime)Composing'.
758
759 \\{mml-mode-map}"
760   (interactive "P")
761   (when (set (make-local-variable 'mml-mode)
762              (if (null arg) (not mml-mode)
763                (> (prefix-numeric-value arg) 0)))
764     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
765     (easy-menu-add mml-menu mml-mode-map)
766     (run-hooks 'mml-mode-hook)))
767
768 ;;;
769 ;;; Helper functions for reading MIME stuff from the minibuffer and
770 ;;; inserting stuff to the buffer.
771 ;;;
772
773 (defun mml-minibuffer-read-file (prompt)
774   (let ((file (read-file-name prompt nil nil t)))
775    ;; Prevent some common errors.  This is inspired by similar code in
776     ;; VM.
777     (when (file-directory-p file)
778       (error "%s is a directory, cannot attach" file))
779     (unless (file-exists-p file)
780       (error "No such file: %s" file))
781     (unless (file-readable-p file)
782       (error "Permission denied: %s" file))
783     file))
784
785 (defun mml-minibuffer-read-type (name &optional default)
786   (mailcap-parse-mimetypes)
787   (let* ((default (or default
788                       (mm-default-file-encoding name)
789                       ;; Perhaps here we should check what the file
790                       ;; looks like, and offer text/plain if it looks
791                       ;; like text/plain.
792                       "application/octet-stream"))
793          (string (completing-read
794                   (format "Content type (default %s): " default)
795                   (mapcar 'list (mailcap-mime-types)))))
796     (if (not (equal string ""))
797         string
798       default)))
799
800 (defun mml-minibuffer-read-description ()
801   (let ((description (read-string "One line description: ")))
802     (when (string-match "\\`[ \t]*\\'" description)
803       (setq description nil))
804     description))
805
806 (defun mml-quote-region (beg end)
807   "Quote the MML tags in the region."
808   (interactive "r")
809   (save-excursion
810     (save-restriction
811       ;; Temporarily narrow the region to defend from changes
812       ;; invalidating END.
813       (narrow-to-region beg end)
814       (goto-char (point-min))
815       ;; Quote parts.
816       (while (re-search-forward
817               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
818         ;; Insert ! after the #.
819         (goto-char (+ (match-beginning 0) 2))
820         (insert "!")))))
821
822 (defun mml-insert-tag (name &rest plist)
823   "Insert an MML tag described by NAME and PLIST."
824   (when (symbolp name)
825     (setq name (symbol-name name)))
826   (insert "<#" name)
827   (while plist
828     (let ((key (pop plist))
829           (value (pop plist)))
830       (when value
831         ;; Quote VALUE if it contains suspicious characters.
832         (when (string-match "[\"'\\~/*;() \t\n]" value)
833           (setq value (prin1-to-string value)))
834         (insert (format " %s=%s" key value)))))
835   (insert ">\n"))
836
837 (defun mml-insert-empty-tag (name &rest plist)
838   "Insert an empty MML tag described by NAME and PLIST."
839   (when (symbolp name)
840     (setq name (symbol-name name)))
841   (apply #'mml-insert-tag name plist)
842   (insert "<#/" name ">\n"))
843
844 ;;; Attachment functions.
845
846 (defun mml-attach-file (file &optional type description)
847   "Attach a file to the outgoing MIME message.
848 The file is not inserted or encoded until you send the message with
849 `\\[message-send-and-exit]' or `\\[message-send]'.
850
851 FILE is the name of the file to attach.  TYPE is its content-type, a
852 string of the form \"type/subtype\".  DESCRIPTION is a one-line
853 description of the attachment."
854   (interactive
855    (let* ((file (mml-minibuffer-read-file "Attach file: "))
856           (type (mml-minibuffer-read-type file))
857           (description (mml-minibuffer-read-description)))
858      (list file type description)))
859   (mml-insert-empty-tag 'part 'type type 'filename file
860                         'disposition "attachment" 'description description))
861
862 (defun mml-attach-buffer (buffer &optional type description)
863   "Attach a buffer to the outgoing MIME message.
864 See `mml-attach-file' for details of operation."
865   (interactive
866    (let* ((buffer (read-buffer "Attach buffer: "))
867           (type (mml-minibuffer-read-type buffer "text/plain"))
868           (description (mml-minibuffer-read-description)))
869      (list buffer type description)))
870   (mml-insert-empty-tag 'part 'type type 'buffer buffer
871                         'disposition "attachment" 'description description))
872
873 (defun mml-attach-external (file &optional type description)
874   "Attach an external file into the buffer.
875 FILE is an ange-ftp/efs specification of the part location.
876 TYPE is the MIME type to use."
877   (interactive
878    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
879           (type (mml-minibuffer-read-type file))
880           (description (mml-minibuffer-read-description)))
881      (list file type description)))
882   (mml-insert-empty-tag 'external 'type type 'name file
883                         'disposition "attachment" 'description description))
884
885 (defun mml-insert-multipart (&optional type)
886   (interactive (list (completing-read "Multipart type (default mixed): "
887                                       '(("mixed") ("alternative") ("digest") ("parallel")
888                                         ("signed") ("encrypted"))
889                                       nil nil "mixed")))
890   (or type
891       (setq type "mixed"))
892   (mml-insert-empty-tag "multipart" 'type type)
893   (forward-line -1))
894
895 (defun mml-insert-part (&optional type)
896   (interactive
897    (list (mml-minibuffer-read-type "")))
898   (mml-insert-tag 'part 'type type 'disposition "inline")
899   (forward-line -1))
900
901 (defun mml-preview (&optional raw)
902   "Display current buffer with Gnus, in a new buffer.
903 If RAW, don't highlight the article."
904   (interactive "P")
905   (let* ((buf (current-buffer))
906          (message-options message-options)
907          (message-this-is-news (message-news-p))
908          (message-posting-charset (or (gnus-setup-posting-charset
909                                        (save-restriction
910                                          (message-narrow-to-headers-or-head)
911                                          (message-fetch-field "Newsgroups")))
912                                       message-posting-charset)))
913     (message-options-set-recipient)
914     (switch-to-buffer (generate-new-buffer
915                        (concat (if raw "*Raw MIME preview of "
916                                  "*MIME preview of ") (buffer-name))))
917     (erase-buffer)
918     (insert-buffer buf)
919     (if (re-search-forward
920          (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
921         (replace-match "\n"))
922     (let ((mail-header-separator "")) ;; mail-header-separator is removed.
923       (mml-to-mime))
924     (if raw
925         (when (fboundp 'set-buffer-multibyte)
926           (let ((s (buffer-string)))
927             ;; Insert the content into unibyte buffer.
928             (erase-buffer)
929             (mm-disable-multibyte)
930             (insert s)))
931       (let ((gnus-newsgroup-charset (car message-posting-charset)))
932         (run-hooks 'gnus-article-decode-hook)
933         (let ((gnus-newsgroup-name "dummy"))
934           (gnus-article-prepare-display))))
935     ;; Disable article-mode-map.
936     (use-local-map nil)
937     (setq buffer-read-only t)
938     (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
939     (goto-char (point-min))))
940
941 (defun mml-validate ()
942   "Validate the current MML document."
943   (interactive)
944   (mml-parse))
945
946 (defun mml-tweak-part (cont)
947   "Tweak a MML part."
948   (let ((tweak (cdr (assq 'tweak cont)))
949         func)
950     (cond
951      (tweak
952       (setq func
953             (or (cdr (assoc tweak mml-tweak-function-alist))
954                 (intern tweak))))
955      (mml-tweak-type-alist
956       (let ((alist mml-tweak-type-alist)
957             (type (or (cdr (assq 'type cont)) "text/plain")))
958         (while alist
959           (if (string-match (caar alist) type)
960               (setq func (cdar alist)
961                     alist nil)
962             (setq alist (cdr alist)))))))
963     (if func
964         (funcall func cont)
965       cont)))
966
967 (provide 'mml)
968
969 ;;; mml.el ends here