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