1 ;;; mml.el --- A package for parsing and validating MML documents
2 ;; Copyright (C) 1998,99 Free Software Foundation, Inc.
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; This file is part of GNU Emacs.
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)
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.
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.
32 (autoload 'message-make-message-id "message"))
34 (defvar mml-generate-multipart-alist
36 "*Alist of multipart generation functions.
38 Each entry has the form (NAME . FUNCTION), where
39 NAME: is a string containing the name of the part (without the
40 leading \"/multipart/\"),
41 FUNCTION: is a Lisp function which is called to generate the part.
43 The Lisp function has to supply the appropriate MIME headers and the
44 contents of this part.")
46 (defvar mml-syntax-table
47 (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
48 (modify-syntax-entry ?\\ "/" table)
49 (modify-syntax-entry ?< "(" table)
50 (modify-syntax-entry ?> ")" table)
51 (modify-syntax-entry ?@ "w" table)
52 (modify-syntax-entry ?/ "w" table)
53 (modify-syntax-entry ?= " " table)
54 (modify-syntax-entry ?* " " table)
55 (modify-syntax-entry ?\; " " table)
56 (modify-syntax-entry ?\' " " table)
59 (defvar mml-boundary-function 'mml-make-boundary
60 "A function called to suggest a boundary.
61 The function may be called several times, and should try to make a new
62 suggestion each time. The function is called with one parameter,
63 which is a number that says how many times the function has been
64 called for this message.")
66 (defvar mml-confirmation-set nil
67 "A list of symbols, each of which disables some warning.
68 `unknown-encoding': always send messages contain characters with
69 unknown encoding; `use-ascii': always use ASCII for those characters
70 with unknown encoding; `multipart': always send messages with more than
74 "Parse the current buffer as an MML document."
75 (goto-char (point-min))
76 (let ((table (syntax-table)))
79 (set-syntax-table mml-syntax-table)
81 (set-syntax-table table))))
84 "Parse the current buffer as an MML document."
85 (let (struct tag point contents charsets warn use-ascii)
86 (while (and (not (eobp))
87 (not (looking-at "<#/multipart")))
89 ((looking-at "<#multipart")
90 (push (nconc (mml-read-tag) (mml-parse-1)) struct))
91 ((looking-at "<#external")
92 (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
95 (if (looking-at "<#part")
96 (setq tag (mml-read-tag))
97 (setq tag (list 'part '(type . "text/plain"))
100 contents (mml-read-part)
101 charsets (mm-find-mime-charset-region point (point)))
102 (when (memq nil charsets)
103 (if (or (memq 'unknown-encoding mml-confirmation-set)
105 "Warning: You message contains characters with unknown encoding. Really send?"))
107 (or (memq 'use-ascii mml-confirmation-set)
108 (y-or-n-p "Use ASCII as charset?")))
109 (setq charsets (delq nil charsets))
111 (error "Edit your message to remove those characters")))
112 (if (< (length charsets) 2)
113 (push (nconc tag (list (cons 'contents contents)))
115 (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
116 tag point (point) use-ascii)))
118 (not (memq 'multipart mml-confirmation-set))
122 "Warning: Your message contains %d parts. Really send? "
124 (error "Edit your message to use only one charset"))
125 (setq struct (nconc nstruct struct)))))))
130 (defun mml-parse-singlepart-with-multiple-charsets
131 (orig-tag beg end &optional use-ascii)
133 (narrow-to-region beg end)
134 (goto-char (point-min))
135 (let ((current (or (mm-mime-charset (mm-charset-after))
136 (and use-ascii 'us-ascii)))
137 charset struct space newline paragraph)
140 ;; The charset remains the same.
141 ((or (eq (setq charset (mm-mime-charset (mm-charset-after)))
143 (and use-ascii (not charset))
144 (eq charset current)))
145 ;; The initial charset was ascii.
146 ((eq current 'us-ascii)
147 (setq current charset
151 ;; We have a change in charsets.
155 (list (cons 'contents
156 (buffer-substring-no-properties
157 beg (or paragraph newline space (point))))))
159 (setq beg (or paragraph newline space (point))
164 ;; Compute places where it might be nice to break the part.
166 ((memq (following-char) '(? ?\t))
167 (setq space (1+ (point))))
168 ((eq (following-char) ?\n)
169 (setq newline (1+ (point))))
170 ((and (eq (following-char) ?\n)
172 (eq (char-after (1- (point))) ?\n))
173 (setq paragraph (point))))
175 ;; Do the final part.
176 (unless (= beg (point))
177 (push (append orig-tag
178 (list (cons 'contents
179 (buffer-substring-no-properties
184 (defun mml-read-tag ()
185 "Read a tag and return the contents."
186 (let (contents name elem val)
188 (setq name (buffer-substring-no-properties
189 (point) (progn (forward-sexp 1) (point))))
190 (skip-chars-forward " \t\n")
191 (while (not (looking-at ">"))
192 (setq elem (buffer-substring-no-properties
193 (point) (progn (forward-sexp 1) (point))))
194 (skip-chars-forward "= \t\n")
195 (setq val (buffer-substring-no-properties
196 (point) (progn (forward-sexp 1) (point))))
197 (when (string-match "^\"\\(.*\\)\"$" val)
198 (setq val (match-string 1 val)))
199 (push (cons (intern elem) val) contents)
200 (skip-chars-forward " \t\n"))
202 (skip-chars-forward " \t\n")
203 (cons (intern name) (nreverse contents))))
205 (defun mml-read-part ()
206 "Return the buffer up till the next part, multipart or closing part or multipart."
208 ;; If the tag ended at the end of the line, we go to the next line.
209 (when (looking-at "[ \t]*\n")
211 (if (re-search-forward
212 "<#\\(/\\)?\\(multipart\\|part\\|external\\)." nil t)
214 (buffer-substring-no-properties beg (match-beginning 0))
215 (if (or (not (match-beginning 1))
216 (equal (match-string 2) "multipart"))
217 (goto-char (match-beginning 0))
218 (when (looking-at "[ \t]*\n")
220 (buffer-substring-no-properties beg (goto-char (point-max))))))
222 (defvar mml-boundary nil)
223 (defvar mml-base-boundary "-=-=")
224 (defvar mml-multipart-number 0)
226 (defun mml-generate-mime ()
227 "Generate a MIME message based on the current MML document."
228 (let ((cont (mml-parse))
229 (mml-multipart-number 0))
233 (if (and (consp (car cont))
235 (mml-generate-mime-1 (car cont))
236 (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
240 (defun mml-generate-mime-1 (cont)
242 ((eq (car cont) 'part)
243 (let (coded encoding charset filename type)
244 (setq type (or (cdr (assq 'type cont)) "text/plain"))
245 (if (member (car (split-string type "/")) '("text" "message"))
248 ((cdr (assq 'buffer cont))
249 (insert-buffer-substring (cdr (assq 'buffer cont))))
250 ((and (setq filename (cdr (assq 'filename cont)))
251 (not (equal (cdr (assq 'nofile cont)) "yes")))
252 (mm-insert-file-contents filename))
255 (narrow-to-region (point) (point))
256 (insert (cdr (assq 'contents cont)))
257 ;; Remove quotes from quoted tags.
258 (goto-char (point-min))
259 (while (re-search-forward
260 "<#!+/?\\(part\\|multipart\\|external\\)" nil t)
261 (delete-region (+ (match-beginning 0) 2)
262 (+ (match-beginning 0) 3))))))
263 (setq charset (mm-encode-body))
264 (setq encoding (mm-body-encoding charset
265 (cdr (assq 'encoding cont))))
266 (setq coded (buffer-string)))
267 (mm-with-unibyte-buffer
269 ((cdr (assq 'buffer cont))
270 (insert-buffer-substring (cdr (assq 'buffer cont))))
271 ((and (setq filename (cdr (assq 'filename cont)))
272 (not (equal (cdr (assq 'nofile cont)) "yes")))
273 (let ((coding-system-for-read mm-binary-coding-system))
274 (mm-insert-file-contents filename nil nil nil nil t)))
276 (insert (cdr (assq 'contents cont)))))
277 (setq encoding (mm-encode-buffer type)
278 coded (buffer-string))))
279 (mml-insert-mime-headers cont type charset encoding)
282 ((eq (car cont) 'external)
283 (insert "Content-Type: message/external-body")
284 (let ((parameters (mml-parameter-string
285 cont '(expiration size permission)))
286 (name (cdr (assq 'name cont))))
288 (setq name (mml-parse-file-name name))
290 (mml-insert-parameter
291 (mail-header-encode-parameter "name" name)
292 "access-type=local-file")
293 (mml-insert-parameter
294 (mail-header-encode-parameter
295 "name" (file-name-nondirectory (nth 2 name)))
296 (mail-header-encode-parameter "site" (nth 1 name))
297 (mail-header-encode-parameter
298 "directory" (file-name-directory (nth 2 name))))
299 (mml-insert-parameter
300 (concat "access-type="
301 (if (member (nth 0 name) '("ftp@" "anonymous@"))
305 (mml-insert-parameter-string
306 cont '(expiration size permission))))
308 (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
309 (insert "Content-ID: " (message-make-message-id) "\n")
310 (insert "Content-Transfer-Encoding: "
311 (or (cdr (assq 'encoding cont)) "binary"))
313 (insert (or (cdr (assq 'contents cont))))
315 ((eq (car cont) 'multipart)
316 (let* ((type (or (cdr (assq 'type cont)) "mixed"))
317 (handler (assoc type mml-generate-multipart-alist)))
319 (funcall (cdr handler) cont)
320 ;; No specific handler. Use default one.
321 (let ((mml-boundary (mml-compute-boundary cont)))
322 (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
324 (setq cont (cddr cont))
326 (insert "\n--" mml-boundary "\n")
327 (mml-generate-mime-1 (pop cont)))
328 (insert "\n--" mml-boundary "--\n")))))
330 (error "Invalid element: %S" cont))))
332 (defun mml-compute-boundary (cont)
333 "Return a unique boundary that does not exist in CONT."
334 (let ((mml-boundary (funcall mml-boundary-function
335 (incf mml-multipart-number))))
336 ;; This function tries again and again until it has found
337 ;; a unique boundary.
338 (while (not (catch 'not-unique
339 (mml-compute-boundary-1 cont))))
342 (defun mml-compute-boundary-1 (cont)
345 ((eq (car cont) 'part)
348 ((cdr (assq 'buffer cont))
349 (insert-buffer-substring (cdr (assq 'buffer cont))))
350 ((and (setq filename (cdr (assq 'filename cont)))
351 (not (equal (cdr (assq 'nofile cont)) "yes")))
352 (mm-insert-file-contents filename))
354 (insert (cdr (assq 'contents cont)))))
355 (goto-char (point-min))
356 (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
358 (setq mml-boundary (funcall mml-boundary-function
359 (incf mml-multipart-number)))
360 (throw 'not-unique nil))))
361 ((eq (car cont) 'multipart)
362 (mapcar 'mml-compute-boundary-1 (cddr cont))))
365 (defun mml-make-boundary (number)
366 (concat (make-string (% number 60) ?=)
372 (defun mml-make-string (num string)
374 (while (not (zerop (decf num)))
375 (setq out (concat out string)))
378 (defun mml-insert-mime-headers (cont type charset encoding)
379 (let (parameters disposition description)
381 (mml-parameter-string
382 cont '(name access-type expiration size permission)))
385 (not (equal type "text/plain")))
386 (when (consp charset)
388 "Can't encode a part with several charsets."))
389 (insert "Content-Type: " type)
391 (insert "; " (mail-header-encode-parameter
392 "charset" (symbol-name charset))))
394 (mml-insert-parameter-string
395 cont '(name access-type expiration size permission)))
398 (mml-parameter-string
399 cont '(filename creation-date modification-date read-date)))
400 (when (or (setq disposition (cdr (assq 'disposition cont)))
402 (insert "Content-Disposition: " (or disposition "inline"))
404 (mml-insert-parameter-string
405 cont '(filename creation-date modification-date read-date)))
407 (unless (eq encoding '7bit)
408 (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
409 (when (setq description (cdr (assq 'description cont)))
410 (insert "Content-Description: "
411 (mail-encode-encoded-word-string description) "\n"))))
413 (defun mml-parameter-string (cont types)
416 (while (setq type (pop types))
417 (when (setq value (cdr (assq type cont)))
418 ;; Strip directory component from the filename parameter.
419 (when (eq type 'filename)
420 (setq value (file-name-nondirectory value)))
421 (setq string (concat string "; "
422 (mail-header-encode-parameter
423 (symbol-name type) value)))))
424 (when (not (zerop (length string)))
427 (defun mml-insert-parameter-string (cont types)
429 (while (setq type (pop types))
430 (when (setq value (cdr (assq type cont)))
431 ;; Strip directory component from the filename parameter.
432 (when (eq type 'filename)
433 (setq value (file-name-nondirectory value)))
434 (mml-insert-parameter
435 (mail-header-encode-parameter
436 (symbol-name type) value))))))
438 (defvar ange-ftp-path-format)
439 (defvar efs-path-regexp)
440 (defun mml-parse-file-name (path)
441 (if (if (boundp 'efs-path-regexp)
442 (string-match efs-path-regexp path)
443 (if (boundp 'ange-ftp-path-format)
444 (string-match (car ange-ftp-path-format))))
445 (list (match-string 1 path) (match-string 2 path)
446 (substring path (1+ (match-end 2))))
449 (defun mml-insert-buffer (buffer)
450 "Insert BUFFER at point and quote any MML markup."
452 (narrow-to-region (point) (point))
453 (insert-buffer-substring buffer)
454 (mml-quote-region (point-min) (point-max))
455 (goto-char (point-max))))
458 ;;; Transforming MIME to MML
461 (defun mime-to-mml ()
462 "Translate the current buffer (which should be a message) into MML."
463 ;; First decode the head.
465 (message-narrow-to-head)
466 (mail-decode-encoded-word-region (point-min) (point-max)))
467 (let ((handles (mm-dissect-buffer t)))
468 (goto-char (point-min))
469 (search-forward "\n\n" nil t)
470 (delete-region (point) (point-max))
471 (if (stringp (car handles))
472 (mml-insert-mime handles)
473 (mml-insert-mime handles t))
474 (mm-destroy-parts handles)))
476 (defun mml-to-mime ()
477 "Translate the current buffer from MML to MIME."
478 (message-encode-message-body)
480 (message-narrow-to-headers-or-head)
481 (mail-encode-encoded-word-buffer)))
483 (defun mml-insert-mime (handle &optional no-markup)
485 ;; Determine type and stuff.
486 (unless (stringp (car handle))
487 (unless (setq textp (equal (mm-handle-media-supertype handle)
490 (set-buffer (setq buffer (generate-new-buffer " *mml*")))
491 (mm-insert-part handle))))
493 (mml-insert-mml-markup handle buffer textp))
495 ((stringp (car handle))
496 (mapcar 'mml-insert-mime (cdr handle))
497 (insert "<#/multipart>\n"))
499 (let ((text (mm-get-part handle))
500 (charset (mail-content-type-get
501 (mm-handle-type handle) 'charset)))
502 (insert (mm-decode-string text charset)))
503 (goto-char (point-max)))
505 (insert "<#/part>\n")))))
507 (defun mml-insert-mml-markup (handle &optional buffer nofile)
508 "Take a MIME handle and insert an MML tag."
509 (if (stringp (car handle))
510 (insert "<#multipart type=" (mm-handle-media-subtype handle)
512 (insert "<#part type=" (mm-handle-media-type handle))
513 (dolist (elem (append (cdr (mm-handle-type handle))
514 (cdr (mm-handle-disposition handle))))
515 (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\""))
516 (when (mm-handle-disposition handle)
517 (insert " disposition=" (car (mm-handle-disposition handle))))
519 (insert " buffer=\"" (buffer-name buffer) "\""))
521 (insert " nofile=yes"))
522 (when (mm-handle-description handle)
523 (insert " description=\"" (mm-handle-description handle) "\""))
526 (defun mml-insert-parameter (&rest parameters)
527 "Insert PARAMETERS in a nice way."
528 (dolist (param parameters)
530 (let ((point (point)))
532 (when (> (current-column) 71)
538 ;;; Mode for inserting and editing MML forms
542 (let ((map (make-sparse-keymap))
543 (main (make-sparse-keymap)))
544 (define-key map "f" 'mml-attach-file)
545 (define-key map "b" 'mml-attach-buffer)
546 (define-key map "e" 'mml-attach-external)
547 (define-key map "q" 'mml-quote-region)
548 (define-key map "m" 'mml-insert-multipart)
549 (define-key map "p" 'mml-insert-part)
550 (define-key map "v" 'mml-validate)
551 (define-key map "P" 'mml-preview)
552 (define-key map "n" 'mml-narrow-to-part)
553 (define-key main "\M-m" map)
557 mml-menu mml-mode-map ""
560 ["File" mml-attach-file t]
561 ["Buffer" mml-attach-buffer t]
562 ["External" mml-attach-external t])
564 ["Multipart" mml-insert-multipart t]
565 ["Part" mml-insert-part t])
566 ["Narrow" mml-narrow-to-part t]
567 ["Quote" mml-quote-region t]
568 ["Validate" mml-validate t]
569 ["Preview" mml-preview t]))
572 "Minor mode for editing MML.")
574 (defun mml-mode (&optional arg)
575 "Minor mode for editing MML.
579 (if (not (set (make-local-variable 'mml-mode)
580 (if (null arg) (not mml-mode)
581 (> (prefix-numeric-value arg) 0))))
583 (set (make-local-variable 'mml-mode) t)
584 (unless (assq 'mml-mode minor-mode-alist)
585 (push `(mml-mode " MML") minor-mode-alist))
586 (unless (assq 'mml-mode minor-mode-map-alist)
587 (push (cons 'mml-mode mml-mode-map)
588 minor-mode-map-alist)))
589 (run-hooks 'mml-mode-hook))
592 ;;; Helper functions for reading MIME stuff from the minibuffer and
593 ;;; inserting stuff to the buffer.
596 (defun mml-minibuffer-read-file (prompt)
597 (let ((file (read-file-name prompt nil nil t)))
598 ;; Prevent some common errors. This is inspired by similar code in
600 (when (file-directory-p file)
601 (error "%s is a directory, cannot attach" file))
602 (unless (file-exists-p file)
603 (error "No such file: %s" file))
604 (unless (file-readable-p file)
605 (error "Permission denied: %s" file))
608 (defun mml-minibuffer-read-type (name &optional default)
609 (let* ((default (or default
610 (mm-default-file-encoding name)
611 ;; Perhaps here we should check what the file
612 ;; looks like, and offer text/plain if it looks
614 "application/octet-stream"))
615 (string (completing-read
616 (format "Content type (default %s): " default)
619 (mm-delete-duplicates
621 (mapcar (lambda (m) (cdr m))
622 mailcap-mime-extensions)
630 (let ((type (cdr (assq 'type (cdr m)))))
631 (if (equal (cadr (split-string type "/"))
636 mailcap-mime-data))))))))
637 (if (not (equal string ""))
641 (defun mml-minibuffer-read-description ()
642 (let ((description (read-string "One line description: ")))
643 (when (string-match "\\`[ \t]*\\'" description)
644 (setq description nil))
647 (defun mml-quote-region (beg end)
648 "Quote the MML tags in the region."
652 ;; Temporarily narrow the region to defend from changes
654 (narrow-to-region beg end)
655 (goto-char (point-min))
657 (while (re-search-forward
658 "<#/?!*\\(multipart\\|part\\|external\\)" nil t)
659 ;; Insert ! after the #.
660 (goto-char (+ (match-beginning 0) 2))
663 (defun mml-insert-tag (name &rest plist)
664 "Insert an MML tag described by NAME and PLIST."
666 (setq name (symbol-name name)))
669 (let ((key (pop plist))
672 ;; Quote VALUE if it contains suspicious characters.
673 (when (string-match "[\"\\~/* \t\n]" value)
674 (setq value (prin1-to-string value)))
675 (insert (format " %s=%s" key value)))))
678 (defun mml-insert-empty-tag (name &rest plist)
679 "Insert an empty MML tag described by NAME and PLIST."
681 (setq name (symbol-name name)))
682 (apply #'mml-insert-tag name plist)
683 (insert "<#/" name ">\n"))
685 ;;; Attachment functions.
687 (defun mml-attach-file (file &optional type description)
688 "Attach a file to the outgoing MIME message.
689 The file is not inserted or encoded until you send the message with
690 `\\[message-send-and-exit]' or `\\[message-send]'.
692 FILE is the name of the file to attach. TYPE is its content-type, a
693 string of the form \"type/subtype\". DESCRIPTION is a one-line
694 description of the attachment."
696 (let* ((file (mml-minibuffer-read-file "Attach file: "))
697 (type (mml-minibuffer-read-type file))
698 (description (mml-minibuffer-read-description)))
699 (list file type description)))
700 (mml-insert-empty-tag 'part 'type type 'filename file
701 'disposition "attachment" 'description description))
703 (defun mml-attach-buffer (buffer &optional type description)
704 "Attach a buffer to the outgoing MIME message.
705 See `mml-attach-file' for details of operation."
707 (let* ((buffer (read-buffer "Attach buffer: "))
708 (type (mml-minibuffer-read-type buffer "text/plain"))
709 (description (mml-minibuffer-read-description)))
710 (list buffer type description)))
711 (mml-insert-empty-tag 'part 'type type 'buffer buffer
712 'disposition "attachment" 'description description))
714 (defun mml-attach-external (file &optional type description)
715 "Attach an external file into the buffer.
716 FILE is an ange-ftp/efs specification of the part location.
717 TYPE is the MIME type to use."
719 (let* ((file (mml-minibuffer-read-file "Attach external file: "))
720 (type (mml-minibuffer-read-type file))
721 (description (mml-minibuffer-read-description)))
722 (list file type description)))
723 (mml-insert-empty-tag 'external 'type type 'name file
724 'disposition "attachment" 'description description))
726 (defun mml-insert-multipart (&optional type)
727 (interactive (list (completing-read "Multipart type (default mixed): "
728 '(("mixed") ("alternative") ("digest") ("parallel")
729 ("signed") ("encrypted"))
733 (mml-insert-empty-tag "multipart" 'type type)
736 (defun mml-insert-part (&optional type)
738 (list (mml-minibuffer-read-type "")))
739 (mml-insert-tag 'part 'type type 'disposition "inline")
742 (defun mml-preview (&optional raw)
743 "Display current buffer with Gnus, in a new buffer.
744 If RAW, don't highlight the article."
746 (let ((buf (current-buffer)))
747 (switch-to-buffer (get-buffer-create
748 (concat (if raw "*Raw MIME preview of "
749 "*MIME preview of ") (buffer-name))))
752 (if (re-search-forward
753 (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
754 (replace-match "\n"))
757 (run-hooks 'gnus-article-decode-hook)
758 (let ((gnus-newsgroup-name "dummy"))
759 (gnus-article-prepare-display)))
761 (setq buffer-read-only t)
762 (goto-char (point-min))))
764 (defun mml-validate ()
765 "Validate the current MML document."