Synch with Oort Gnus.
[elisp/gnus.git-] / 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= (cdr (assq 'format cont))
437                                             "flowed"))
438                                (setq use-hard-newlines
439                                      (text-property-any
440                                       (point-min) (point-max) 'hard 't)))
441                       (fill-flowed-encode)
442                       ;; Indicate that `mml-insert-mime-headers' should
443                       ;; insert a "; format=flowed" string unless the
444                       ;; user has already specified it.
445                       (setq flowed (null (assq 'format cont)))))
446                   (setq coded (buffer-string)))
447                 (mml-insert-mime-headers cont type charset encoding flowed)
448                 (insert "\n")
449                 (insert coded))
450             (mm-with-unibyte-buffer
451               (cond
452                ((cdr (assq 'buffer cont))
453                 (insert-buffer-substring (cdr (assq 'buffer cont))))
454                ((and (setq filename (cdr (assq 'filename cont)))
455                      (not (equal (cdr (assq 'nofile cont)) "yes")))
456                 (let ((coding-system-for-read mm-binary-coding-system))
457                   (mm-insert-file-contents filename nil nil nil nil t)))
458                (t
459                 (insert (cdr (assq 'contents cont)))))
460               (setq encoding (mm-encode-buffer type)
461                     coded (mm-string-as-multibyte (buffer-string))))
462             (mml-insert-mime-headers cont type charset encoding nil)
463             (insert "\n")
464             (mm-with-unibyte-current-buffer
465               (insert coded)))))
466        ((eq (car cont) 'external)
467         (insert "Content-Type: message/external-body")
468         (let ((parameters (mml-parameter-string
469                            cont '(expiration size permission)))
470               (name (cdr (assq 'name cont)))
471               (url (cdr (assq 'url cont))))
472           (when name
473             (setq name (mml-parse-file-name name))
474             (if (stringp name)
475                 (mml-insert-parameter
476                  (mail-header-encode-parameter "name" name)
477                  "access-type=local-file")
478               (mml-insert-parameter
479                (mail-header-encode-parameter
480                 "name" (file-name-nondirectory (nth 2 name)))
481                (mail-header-encode-parameter "site" (nth 1 name))
482                (mail-header-encode-parameter
483                 "directory" (file-name-directory (nth 2 name))))
484               (mml-insert-parameter
485                (concat "access-type="
486                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
487                            "anon-ftp"
488                          "ftp")))))
489           (when url
490             (mml-insert-parameter
491              (mail-header-encode-parameter "url" url)
492              "access-type=url"))
493           (when parameters
494             (mml-insert-parameter-string
495              cont '(expiration size permission))))
496         (insert "\n\n")
497         (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
498         (insert "Content-ID: " (message-make-message-id) "\n")
499         (insert "Content-Transfer-Encoding: "
500                 (or (cdr (assq 'encoding cont)) "binary"))
501         (insert "\n\n")
502         (insert (or (cdr (assq 'contents cont))))
503         (insert "\n"))
504        ((eq (car cont) 'multipart)
505         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
506                (mml-generate-default-type (if (equal type "digest")
507                                               "message/rfc822"
508                                             "text/plain"))
509                (handler (assoc type mml-generate-multipart-alist)))
510           (if handler
511               (funcall (cdr handler) cont)
512             ;; No specific handler.  Use default one.
513             (let ((mml-boundary (mml-compute-boundary cont)))
514               (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
515                               type mml-boundary))
516               (let ((cont cont) part)
517                 (while (setq part (pop cont))
518                   ;; Skip `multipart' and attributes.
519                   (when (and (consp part) (consp (cdr part)))
520                     (insert "\n--" mml-boundary "\n")
521                     (mml-generate-mime-1 part))))
522               (insert "\n--" mml-boundary "--\n")))))
523        (t
524         (error "Invalid element: %S" cont)))
525       (let ((item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
526             sender recipients)
527         (when item
528           (if (setq sender (cdr (assq 'sender cont)))
529               (message-options-set 'message-sender sender))
530           (if (setq recipients (cdr (assq 'recipients cont)))
531               (message-options-set 'message-recipients recipients))
532           (funcall (nth 1 item) cont)))
533       (let ((item (assoc (cdr (assq 'encrypt cont)) mml-encrypt-alist))
534             sender recipients)
535         (when item
536           (if (setq sender (cdr (assq 'sender cont)))
537               (message-options-set 'message-sender sender))
538           (if (setq recipients (cdr (assq 'recipients cont)))
539               (message-options-set 'message-recipients recipients))
540           (funcall (nth 1 item) cont))))))
541
542 (defun mml-compute-boundary (cont)
543   "Return a unique boundary that does not exist in CONT."
544   (let ((mml-boundary (funcall mml-boundary-function
545                                (incf mml-multipart-number))))
546     ;; This function tries again and again until it has found
547     ;; a unique boundary.
548     (while (not (catch 'not-unique
549                   (mml-compute-boundary-1 cont))))
550     mml-boundary))
551
552 (defun mml-compute-boundary-1 (cont)
553   (let (filename)
554     (cond
555      ((eq (car cont) 'part)
556       (with-temp-buffer
557         (cond
558          ((cdr (assq 'buffer cont))
559           (insert-buffer-substring (cdr (assq 'buffer cont))))
560          ((and (setq filename (cdr (assq 'filename cont)))
561                (not (equal (cdr (assq 'nofile cont)) "yes")))
562           (mm-insert-file-contents filename))
563          (t
564           (insert (cdr (assq 'contents cont)))))
565         (goto-char (point-min))
566         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
567                                  nil t)
568           (setq mml-boundary (funcall mml-boundary-function
569                                       (incf mml-multipart-number)))
570           (throw 'not-unique nil))))
571      ((eq (car cont) 'multipart)
572       (mapcar 'mml-compute-boundary-1 (cddr cont))))
573     t))
574
575 (defun mml-make-boundary (number)
576   (concat (make-string (% number 60) ?=)
577           (if (> number 17)
578               (format "%x" number)
579             "")
580           mml-base-boundary))
581
582 (defun mml-insert-mime-headers (cont type charset encoding flowed)
583   (let (parameters disposition description)
584     (setq parameters
585           (mml-parameter-string
586            cont mml-content-type-parameters))
587     (when (or charset
588               parameters
589               flowed
590               (not (equal type mml-generate-default-type)))
591       (when (consp charset)
592         (error
593          "Can't encode a part with several charsets."))
594       (insert "Content-Type: " type)
595       (when charset
596         (insert "; " (mail-header-encode-parameter
597                       "charset" (symbol-name charset))))
598       (when flowed
599         (insert "; format=flowed"))
600       (when parameters
601         (mml-insert-parameter-string
602          cont mml-content-type-parameters))
603       (insert "\n"))
604     (setq parameters
605           (mml-parameter-string
606            cont mml-content-disposition-parameters))
607     (when (or (setq disposition (cdr (assq 'disposition cont)))
608               parameters)
609       (insert "Content-Disposition: " (or disposition "inline"))
610       (when parameters
611         (mml-insert-parameter-string
612          cont mml-content-disposition-parameters))
613       (insert "\n"))
614     (unless (eq encoding '7bit)
615       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
616     (when (setq description (cdr (assq 'description cont)))
617       (insert "Content-Description: "
618               (mail-encode-encoded-word-string description) "\n"))))
619
620 (defun mml-parameter-string (cont types)
621   (let ((string "")
622         value type)
623     (while (setq type (pop types))
624       (when (setq value (cdr (assq type cont)))
625         ;; Strip directory component from the filename parameter.
626         (when (eq type 'filename)
627           (setq value (file-name-nondirectory value)))
628         (setq string (concat string "; "
629                              (mail-header-encode-parameter
630                               (symbol-name type) value)))))
631     (when (not (zerop (length string)))
632       string)))
633
634 (defun mml-insert-parameter-string (cont types)
635   (let (value type)
636     (while (setq type (pop types))
637       (when (setq value (cdr (assq type cont)))
638         ;; Strip directory component from the filename parameter.
639         (when (eq type 'filename)
640           (setq value (file-name-nondirectory value)))
641         (mml-insert-parameter
642          (mail-header-encode-parameter
643           (symbol-name type) value))))))
644
645 (eval-when-compile
646   (defvar ange-ftp-name-format)
647   (defvar efs-path-regexp))
648 (defun mml-parse-file-name (path)
649   (if (if (boundp 'efs-path-regexp)
650           (string-match efs-path-regexp path)
651         (if (boundp 'ange-ftp-name-format)
652             (string-match (car ange-ftp-name-format) path)))
653       (list (match-string 1 path) (match-string 2 path)
654             (substring path (1+ (match-end 2))))
655     path))
656
657 (defun mml-insert-buffer (buffer)
658   "Insert BUFFER at point and quote any MML markup."
659   (save-restriction
660     (narrow-to-region (point) (point))
661     (insert-buffer-substring buffer)
662     (mml-quote-region (point-min) (point-max))
663     (goto-char (point-max))))
664
665 ;;;
666 ;;; Transforming MIME to MML
667 ;;;
668
669 (defun mime-to-mml (&optional handles)
670   "Translate the current buffer (which should be a message) into MML.
671 If HANDLES is non-nil, use it instead reparsing the buffer."
672   ;; First decode the head.
673   (save-restriction
674     (message-narrow-to-head)
675     (mail-decode-encoded-word-region (point-min) (point-max)))
676   (unless handles
677     (setq handles (mm-dissect-buffer t)))
678   (goto-char (point-min))
679   (search-forward "\n\n" nil t)
680   (delete-region (point) (point-max))
681   (if (stringp (car handles))
682       (mml-insert-mime handles)
683     (mml-insert-mime handles t))
684   (mm-destroy-parts handles)
685   (save-restriction
686     (message-narrow-to-head)
687     ;; Remove them, they are confusing.
688     (message-remove-header "Content-Type")
689     (message-remove-header "MIME-Version")
690     (message-remove-header "Content-Disposition")
691     (message-remove-header "Content-Transfer-Encoding")))
692
693 (defun mml-to-mime ()
694   "Translate the current buffer from MML to MIME."
695   (message-encode-message-body)
696   (save-restriction
697     (message-narrow-to-headers-or-head)
698     ;; Skip past any From_ headers.
699     (while (looking-at "From ")
700       (forward-line 1))
701     (let ((mail-parse-charset message-default-charset))
702       (mail-encode-encoded-word-buffer))))
703
704 (defun mml-insert-mime (handle &optional no-markup)
705   (let (textp buffer mmlp)
706     ;; Determine type and stuff.
707     (unless (stringp (car handle))
708       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
709         (save-excursion
710           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
711           (mm-insert-part handle)
712           (if (setq mmlp (equal (mm-handle-media-type handle)
713                                 "message/rfc822"))
714               (mime-to-mml)))))
715     (if mmlp
716         (mml-insert-mml-markup handle nil t t)
717       (unless (and no-markup
718                    (equal (mm-handle-media-type handle) "text/plain"))
719         (mml-insert-mml-markup handle buffer textp)))
720     (cond
721      (mmlp
722       (insert-buffer buffer)
723       (goto-char (point-max))
724       (insert "<#/mml>\n"))
725      ((stringp (car handle))
726       (mapcar 'mml-insert-mime (cdr handle))
727       (insert "<#/multipart>\n"))
728      (textp
729       (let ((charset (mail-content-type-get
730                       (mm-handle-type handle) 'charset)))
731         (if (eq charset 'gnus-decoded)
732             (mm-insert-part handle)
733           (insert (mm-decode-string (mm-get-part handle) charset))))
734       (goto-char (point-max)))
735      (t
736       (insert "<#/part>\n")))))
737
738 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
739   "Take a MIME handle and insert an MML tag."
740   (if (stringp (car handle))
741       (insert "<#multipart type=" (mm-handle-media-subtype handle)
742               ">\n")
743     (if mmlp
744         (insert "<#mml type=" (mm-handle-media-type handle))
745       (insert "<#part type=" (mm-handle-media-type handle)))
746     (dolist (elem (append (cdr (mm-handle-type handle))
747                           (cdr (mm-handle-disposition handle))))
748       (unless (symbolp (cdr elem))
749         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
750     (when (mm-handle-disposition handle)
751       (insert " disposition=" (car (mm-handle-disposition handle))))
752     (when buffer
753       (insert " buffer=\"" (buffer-name buffer) "\""))
754     (when nofile
755       (insert " nofile=yes"))
756     (when (mm-handle-description handle)
757       (insert " description=\"" (mm-handle-description handle) "\""))
758     (insert ">\n")))
759
760 (defun mml-insert-parameter (&rest parameters)
761   "Insert PARAMETERS in a nice way."
762   (dolist (param parameters)
763     (insert ";")
764     (let ((point (point)))
765       (insert " " param)
766       (when (> (current-column) 71)
767         (goto-char point)
768         (insert "\n ")
769         (end-of-line)))))
770
771 ;;;
772 ;;; Mode for inserting and editing MML forms
773 ;;;
774
775 (defvar mml-mode-map
776   (let ((sign (make-sparse-keymap))
777         (encrypt (make-sparse-keymap))
778         (map (make-sparse-keymap))
779         (main (make-sparse-keymap)))
780     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
781     (define-key sign "o" 'mml-secure-message-sign-pgp)
782     (define-key sign "s" 'mml-secure-message-sign-smime)
783     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
784     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
785     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
786     (define-key map "f" 'mml-attach-file)
787     (define-key map "b" 'mml-attach-buffer)
788     (define-key map "e" 'mml-attach-external)
789     (define-key map "q" 'mml-quote-region)
790     (define-key map "m" 'mml-insert-multipart)
791     (define-key map "p" 'mml-insert-part)
792     (define-key map "v" 'mml-validate)
793     (define-key map "P" 'mml-preview)
794     (define-key map "s" sign)
795     (define-key map "c" encrypt)
796     ;;(define-key map "n" 'mml-narrow-to-part)
797     ;; `M-m' conflicts with `back-to-indentation'.
798     ;; (define-key main "\M-m" map)
799     (define-key main "\C-c\C-m" map)
800     main))
801
802 (easy-menu-define
803  mml-menu mml-mode-map ""
804  `("Attachments"
805    ["Attach File" mml-attach-file
806     ,@(if (featurep 'xemacs) '(t)
807         '(:help "Attach a file at point"))]
808    ["Attach Buffer" mml-attach-buffer t]
809    ["Attach External" mml-attach-external t]
810    ["Insert Part" mml-insert-part t]
811    ["Insert Multipart" mml-insert-multipart t]
812    ["PGP/MIME Sign" mml-secure-message-sign-pgpmime t]
813    ["PGP/MIME Encrypt" mml-secure-message-encrypt-pgpmime t]
814    ["PGP Sign" mml-secure-message-sign-pgp t]
815    ["PGP Encrypt" mml-secure-message-encrypt-pgp t]
816    ["S/MIME Sign" mml-secure-message-sign-smime t]
817    ["S/MIME Encrypt" mml-secure-message-encrypt-smime t]
818    ;;["Narrow" mml-narrow-to-part t]
819    ["Quote MML" mml-quote-region t]
820    ["Validate MML" mml-validate t]
821    ["Preview" mml-preview t]))
822
823 (defvar mml-mode nil
824   "Minor mode for editing MML.")
825
826 (defun mml-mode (&optional arg)
827   "Minor mode for editing MML.
828 MML is the MIME Meta Language, a minor mode for composing MIME articles.
829 See Info node `(emacs-mime)Composing'.
830
831 \\{mml-mode-map}"
832   (interactive "P")
833   (when (set (make-local-variable 'mml-mode)
834              (if (null arg) (not mml-mode)
835                (> (prefix-numeric-value arg) 0)))
836     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
837     (easy-menu-add mml-menu mml-mode-map)
838     (run-hooks 'mml-mode-hook)))
839
840 ;;;
841 ;;; Helper functions for reading MIME stuff from the minibuffer and
842 ;;; inserting stuff to the buffer.
843 ;;;
844
845 (defun mml-minibuffer-read-file (prompt)
846   (let ((file (read-file-name prompt nil nil t)))
847     ;; Prevent some common errors.  This is inspired by similar code in
848     ;; VM.
849     (when (file-directory-p file)
850       (error "%s is a directory, cannot attach" file))
851     (unless (file-exists-p file)
852       (error "No such file: %s" file))
853     (unless (file-readable-p file)
854       (error "Permission denied: %s" file))
855     file))
856
857 (defun mml-minibuffer-read-type (name &optional default)
858   (mailcap-parse-mimetypes)
859   (let* ((default (or default
860                       (mm-default-file-encoding name)
861                       ;; Perhaps here we should check what the file
862                       ;; looks like, and offer text/plain if it looks
863                       ;; like text/plain.
864                       "application/octet-stream"))
865          (string (completing-read
866                   (format "Content type (default %s): " default)
867                   (mapcar 'list (mailcap-mime-types)))))
868     (if (not (equal string ""))
869         string
870       default)))
871
872 (defun mml-minibuffer-read-description ()
873   (let ((description (read-string "One line description: ")))
874     (when (string-match "\\`[ \t]*\\'" description)
875       (setq description nil))
876     description))
877
878 (defun mml-quote-region (beg end)
879   "Quote the MML tags in the region."
880   (interactive "r")
881   (save-excursion
882     (save-restriction
883       ;; Temporarily narrow the region to defend from changes
884       ;; invalidating END.
885       (narrow-to-region beg end)
886       (goto-char (point-min))
887       ;; Quote parts.
888       (while (re-search-forward
889               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
890         ;; Insert ! after the #.
891         (goto-char (+ (match-beginning 0) 2))
892         (insert "!")))))
893
894 (defun mml-insert-tag (name &rest plist)
895   "Insert an MML tag described by NAME and PLIST."
896   (when (symbolp name)
897     (setq name (symbol-name name)))
898   (insert "<#" name)
899   (while plist
900     (let ((key (pop plist))
901           (value (pop plist)))
902       (when value
903         ;; Quote VALUE if it contains suspicious characters.
904         (when (string-match "[\"'\\~/*;() \t\n]" value)
905           (setq value (prin1-to-string value)))
906         (insert (format " %s=%s" key value)))))
907   (insert ">\n"))
908
909 (defun mml-insert-empty-tag (name &rest plist)
910   "Insert an empty MML tag described by NAME and PLIST."
911   (when (symbolp name)
912     (setq name (symbol-name name)))
913   (apply #'mml-insert-tag name plist)
914   (insert "<#/" name ">\n"))
915
916 ;;; Attachment functions.
917
918 (defun mml-attach-file (file &optional type description)
919   "Attach a file to the outgoing MIME message.
920 The file is not inserted or encoded until you send the message with
921 `\\[message-send-and-exit]' or `\\[message-send]'.
922
923 FILE is the name of the file to attach.  TYPE is its content-type, a
924 string of the form \"type/subtype\".  DESCRIPTION is a one-line
925 description of the attachment."
926   (interactive
927    (let* ((file (mml-minibuffer-read-file "Attach file: "))
928           (type (mml-minibuffer-read-type file))
929           (description (mml-minibuffer-read-description)))
930      (list file type description)))
931   (mml-insert-empty-tag 'part 'type type 'filename file
932                         'disposition "attachment" 'description description))
933
934 (defun mml-attach-buffer (buffer &optional type description)
935   "Attach a buffer to the outgoing MIME message.
936 See `mml-attach-file' for details of operation."
937   (interactive
938    (let* ((buffer (read-buffer "Attach buffer: "))
939           (type (mml-minibuffer-read-type buffer "text/plain"))
940           (description (mml-minibuffer-read-description)))
941      (list buffer type description)))
942   (mml-insert-empty-tag 'part 'type type 'buffer buffer
943                         'disposition "attachment" 'description description))
944
945 (defun mml-attach-external (file &optional type description)
946   "Attach an external file into the buffer.
947 FILE is an ange-ftp/efs specification of the part location.
948 TYPE is the MIME type to use."
949   (interactive
950    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
951           (type (mml-minibuffer-read-type file))
952           (description (mml-minibuffer-read-description)))
953      (list file type description)))
954   (mml-insert-empty-tag 'external 'type type 'name file
955                         'disposition "attachment" 'description description))
956
957 (defun mml-insert-multipart (&optional type)
958   (interactive (list (completing-read "Multipart type (default mixed): "
959                                       '(("mixed") ("alternative") ("digest") ("parallel")
960                                         ("signed") ("encrypted"))
961                                       nil nil "mixed")))
962   (or type
963       (setq type "mixed"))
964   (mml-insert-empty-tag "multipart" 'type type)
965   (forward-line -1))
966
967 (defun mml-insert-part (&optional type)
968   (interactive
969    (list (mml-minibuffer-read-type "")))
970   (mml-insert-tag 'part 'type type 'disposition "inline")
971   (forward-line -1))
972
973 (defun mml-preview (&optional raw)
974   "Display current buffer with Gnus, in a new buffer.
975 If RAW, don't highlight the article."
976   (interactive "P")
977   (save-excursion
978     (let* ((buf (current-buffer))
979            (message-options message-options)
980            (message-this-is-news (message-news-p))
981            (message-posting-charset (or (gnus-setup-posting-charset
982                                          (save-restriction
983                                            (message-narrow-to-headers-or-head)
984                                            (message-fetch-field "Newsgroups")))
985                                         message-posting-charset)))
986       (message-options-set-recipient)
987       (switch-to-buffer (generate-new-buffer
988                          (concat (if raw "*Raw MIME preview of "
989                                    "*MIME preview of ") (buffer-name))))
990       (erase-buffer)
991       (insert-buffer buf)
992       (if (re-search-forward
993            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
994           (replace-match "\n"))
995       (let ((mail-header-separator ""));; mail-header-separator is removed.
996         (mml-to-mime))
997       (if raw
998           (when (fboundp 'set-buffer-multibyte)
999             (let ((s (buffer-string)))
1000               ;; Insert the content into unibyte buffer.
1001               (erase-buffer)
1002               (mm-disable-multibyte)
1003               (insert s)))
1004         (let ((gnus-newsgroup-charset (car message-posting-charset))
1005               gnus-article-prepare-hook gnus-original-article-buffer)
1006           (run-hooks 'gnus-article-decode-hook)
1007           (let ((gnus-newsgroup-name "dummy"))
1008             (gnus-article-prepare-display))))
1009       ;; Disable article-mode-map.
1010       (use-local-map nil)
1011       (setq buffer-read-only t)
1012       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1013       (goto-char (point-min)))))
1014
1015 (defun mml-validate ()
1016   "Validate the current MML document."
1017   (interactive)
1018   (mml-parse))
1019
1020 (defun mml-tweak-part (cont)
1021   "Tweak a MML part."
1022   (let ((tweak (cdr (assq 'tweak cont)))
1023         func)
1024     (cond
1025      (tweak
1026       (setq func
1027             (or (cdr (assoc tweak mml-tweak-function-alist))
1028                 (intern tweak))))
1029      (mml-tweak-type-alist
1030       (let ((alist mml-tweak-type-alist)
1031             (type (or (cdr (assq 'type cont)) "text/plain")))
1032         (while alist
1033           (if (string-match (caar alist) type)
1034               (setq func (cdar alist)
1035                     alist nil)
1036             (setq alist (cdr alist)))))))
1037     (if func
1038         (funcall func cont)
1039       cont)
1040     (let ((alist mml-tweak-sexp-alist))
1041       (while alist
1042         (if (eval (caar alist))
1043             (funcall (cdar alist) cont))
1044         (setq alist (cdr alist)))))
1045   cont)
1046
1047 (defun mml-tweak-externalize-attachments (cont)
1048   "Tweak attached files as external parts."
1049   (let (filename-cons)
1050     (when (and (eq (car cont) 'part)
1051                (not (cdr (assq 'buffer cont)))
1052                (and (setq filename-cons (assq 'filename cont))
1053                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1054       (setcar cont 'external)
1055       (setcar filename-cons 'name))))
1056
1057 (provide 'mml)
1058
1059 ;;; mml.el ends here