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