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