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