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