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