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