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