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