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