2757551c63262137796784365d9fcfad92e055b5
[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  '("Mime"
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 PGP/MIME" mml-secure-sign-pgpmime t]
733     ["Sign S/MIME" mml-secure-sign-smime t]
734     ["Encrypt PGP/MIME" mml-secure-encrypt-pgpmime t]
735     ["Encrypt S/MIME" mml-secure-encrypt-smime t])
736    ;;["Narrow" mml-narrow-to-part t]
737    ["Quote" mml-quote-region t]
738    ["Validate" mml-validate t]
739    ["Preview" mml-preview t]))
740
741 (defvar mml-mode nil
742   "Minor mode for editing MML.")
743
744 (defun mml-mode (&optional arg)
745   "Minor mode for editing MML.
746
747 \\{mml-mode-map}"
748   (interactive "P")
749   (when (set (make-local-variable 'mml-mode)
750              (if (null arg) (not mml-mode)
751                (> (prefix-numeric-value arg) 0)))
752     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
753     (easy-menu-add mml-menu mml-mode-map)
754     (run-hooks 'mml-mode-hook)))
755
756 ;;;
757 ;;; Helper functions for reading MIME stuff from the minibuffer and
758 ;;; inserting stuff to the buffer.
759 ;;;
760
761 (defun mml-minibuffer-read-file (prompt)
762   (let ((file (read-file-name prompt nil nil t)))
763     ;; Prevent some common errors.  This is inspired by similar code in
764     ;; VM.
765     (when (file-directory-p file)
766       (error "%s is a directory, cannot attach" file))
767     (unless (file-exists-p file)
768       (error "No such file: %s" file))
769     (unless (file-readable-p file)
770       (error "Permission denied: %s" file))
771     file))
772
773 (defun mml-minibuffer-read-type (name &optional default)
774   (mailcap-parse-mimetypes)
775   (let* ((default (or default
776                       (mm-default-file-encoding name)
777                       ;; Perhaps here we should check what the file
778                       ;; looks like, and offer text/plain if it looks
779                       ;; like text/plain.
780                       "application/octet-stream"))
781          (string (completing-read
782                   (format "Content type (default %s): " default)
783                   (mapcar 'list (mailcap-mime-types)))))
784     (if (not (equal string ""))
785         string
786       default)))
787
788 (defun mml-minibuffer-read-description ()
789   (let ((description (read-string "One line description: ")))
790     (when (string-match "\\`[ \t]*\\'" description)
791       (setq description nil))
792     description))
793
794 (defun mml-quote-region (beg end)
795   "Quote the MML tags in the region."
796   (interactive "r")
797   (save-excursion
798     (save-restriction
799       ;; Temporarily narrow the region to defend from changes
800       ;; invalidating END.
801       (narrow-to-region beg end)
802       (goto-char (point-min))
803       ;; Quote parts.
804       (while (re-search-forward
805               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
806         ;; Insert ! after the #.
807         (goto-char (+ (match-beginning 0) 2))
808         (insert "!")))))
809
810 (defun mml-insert-tag (name &rest plist)
811   "Insert an MML tag described by NAME and PLIST."
812   (when (symbolp name)
813     (setq name (symbol-name name)))
814   (insert "<#" name)
815   (while plist
816     (let ((key (pop plist))
817           (value (pop plist)))
818       (when value
819         ;; Quote VALUE if it contains suspicious characters.
820         (when (string-match "[\"'\\~/*;() \t\n]" value)
821           (setq value (prin1-to-string value)))
822         (insert (format " %s=%s" key value)))))
823   (insert ">\n"))
824
825 (defun mml-insert-empty-tag (name &rest plist)
826   "Insert an empty MML tag described by NAME and PLIST."
827   (when (symbolp name)
828     (setq name (symbol-name name)))
829   (apply #'mml-insert-tag name plist)
830   (insert "<#/" name ">\n"))
831
832 ;;; Attachment functions.
833
834 (defun mml-attach-file (file &optional type description)
835   "Attach a file to the outgoing MIME message.
836 The file is not inserted or encoded until you send the message with
837 `\\[message-send-and-exit]' or `\\[message-send]'.
838
839 FILE is the name of the file to attach.  TYPE is its content-type, a
840 string of the form \"type/subtype\".  DESCRIPTION is a one-line
841 description of the attachment."
842   (interactive
843    (let* ((file (mml-minibuffer-read-file "Attach file: "))
844           (type (mml-minibuffer-read-type file))
845           (description (mml-minibuffer-read-description)))
846      (list file type description)))
847   (mml-insert-empty-tag 'part 'type type 'filename file
848                         'disposition "attachment" 'description description))
849
850 (defun mml-attach-buffer (buffer &optional type description)
851   "Attach a buffer to the outgoing MIME message.
852 See `mml-attach-file' for details of operation."
853   (interactive
854    (let* ((buffer (read-buffer "Attach buffer: "))
855           (type (mml-minibuffer-read-type buffer "text/plain"))
856           (description (mml-minibuffer-read-description)))
857      (list buffer type description)))
858   (mml-insert-empty-tag 'part 'type type 'buffer buffer
859                         'disposition "attachment" 'description description))
860
861 (defun mml-attach-external (file &optional type description)
862   "Attach an external file into the buffer.
863 FILE is an ange-ftp/efs specification of the part location.
864 TYPE is the MIME type to use."
865   (interactive
866    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
867           (type (mml-minibuffer-read-type file))
868           (description (mml-minibuffer-read-description)))
869      (list file type description)))
870   (mml-insert-empty-tag 'external 'type type 'name file
871                         'disposition "attachment" 'description description))
872
873 (defun mml-insert-multipart (&optional type)
874   (interactive (list (completing-read "Multipart type (default mixed): "
875                                       '(("mixed") ("alternative") ("digest") ("parallel")
876                                         ("signed") ("encrypted"))
877                                       nil nil "mixed")))
878   (or type
879       (setq type "mixed"))
880   (mml-insert-empty-tag "multipart" 'type type)
881   (forward-line -1))
882
883 (defun mml-insert-part (&optional type)
884   (interactive
885    (list (mml-minibuffer-read-type "")))
886   (mml-insert-tag 'part 'type type 'disposition "inline")
887   (forward-line -1))
888
889 (defun mml-preview (&optional raw)
890   "Display current buffer with Gnus, in a new buffer.
891 If RAW, don't highlight the article."
892   (interactive "P")
893   (let ((buf (current-buffer))
894         (message-options message-options)
895         (message-posting-charset (or (gnus-setup-posting-charset
896                                       (save-restriction
897                                         (message-narrow-to-headers-or-head)
898                                         (message-fetch-field "Newsgroups")))
899                                      message-posting-charset)))
900     (message-options-set-recipient)
901     (switch-to-buffer (generate-new-buffer
902                        (concat (if raw "*Raw MIME preview of "
903                                  "*MIME preview of ") (buffer-name))))
904     (erase-buffer)
905     (insert-buffer buf)
906     (if (re-search-forward
907          (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
908         (replace-match "\n"))
909     (mml-to-mime)
910     (if raw
911         (when (fboundp 'set-buffer-multibyte)
912           (let ((s (buffer-string)))
913             ;; Insert the content into unibyte buffer.
914             (erase-buffer)
915             (mm-disable-multibyte)
916             (insert s)))
917       (let ((gnus-newsgroup-charset (car message-posting-charset)))
918         (run-hooks 'gnus-article-decode-hook)
919         (let ((gnus-newsgroup-name "dummy"))
920           (gnus-article-prepare-display))))
921     ;; Disable article-mode-map.
922     (use-local-map nil)
923     (setq buffer-read-only t)
924     (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
925     (goto-char (point-min))))
926
927 (defun mml-validate ()
928   "Validate the current MML document."
929   (interactive)
930   (mml-parse))
931
932 (defun mml-tweak-part (cont)
933   "Tweak a MML part."
934   (let ((tweak (cdr (assq 'tweak cont)))
935         func)
936     (cond
937      (tweak
938       (setq func
939             (or (cdr (assoc tweak mml-tweak-function-alist))
940                 (intern tweak))))
941      (mml-tweak-type-alist
942       (let ((alist mml-tweak-type-alist)
943             (type (or (cdr (assq 'type cont)) "text/plain")))
944         (while alist
945           (if (string-match (caar alist) type)
946               (setq func (cdar alist)
947                     alist nil)
948             (setq alist (cdr alist)))))))
949     (if func
950         (funcall func cont)
951       cont)))
952
953 (provide 'mml)
954
955 ;;; mml.el ends here