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