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