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 "\C-n" 'mml-unsecure-message)
787     (define-key map "f" 'mml-attach-file)
788     (define-key map "b" 'mml-attach-buffer)
789     (define-key map "e" 'mml-attach-external)
790     (define-key map "q" 'mml-quote-region)
791     (define-key map "m" 'mml-insert-multipart)
792     (define-key map "p" 'mml-insert-part)
793     (define-key map "v" 'mml-validate)
794     (define-key map "P" 'mml-preview)
795     (define-key map "s" sign)
796     (define-key map "c" encrypt)
797     ;;(define-key map "n" 'mml-narrow-to-part)
798     ;; `M-m' conflicts with `back-to-indentation'.
799     ;; (define-key main "\M-m" map)
800     (define-key main "\C-c\C-m" map)
801     main))
802
803 (easy-menu-define
804  mml-menu mml-mode-map ""
805  `("Attachments"
806    ["Attach File" mml-attach-file
807     ,@(if (featurep 'xemacs) '(t)
808         '(:help "Attach a file at point"))]
809    ["Attach Buffer" mml-attach-buffer t]
810    ["Attach External" mml-attach-external t]
811    ["Insert Part" mml-insert-part t]
812    ["Insert Multipart" mml-insert-multipart t]
813    ["PGP/MIME Sign" mml-secure-message-sign-pgpmime t]
814    ["PGP/MIME Encrypt" mml-secure-message-encrypt-pgpmime t]
815    ["PGP Sign" mml-secure-message-sign-pgp t]
816    ["PGP Encrypt" mml-secure-message-encrypt-pgp t]
817    ["S/MIME Sign" mml-secure-message-sign-smime t]
818    ["S/MIME Encrypt" mml-secure-message-encrypt-smime t]
819    ["Encrypt/Sign off" mml-unsecure-message t]
820    ;;["Narrow" mml-narrow-to-part t]
821    ["Quote MML" mml-quote-region t]
822    ["Validate MML" mml-validate t]
823    ["Preview" mml-preview t]))
824
825 (defvar mml-mode nil
826   "Minor mode for editing MML.")
827
828 (defun mml-mode (&optional arg)
829   "Minor mode for editing MML.
830 MML is the MIME Meta Language, a minor mode for composing MIME articles.
831 See Info node `(emacs-mime)Composing'.
832
833 \\{mml-mode-map}"
834   (interactive "P")
835   (when (set (make-local-variable 'mml-mode)
836              (if (null arg) (not mml-mode)
837                (> (prefix-numeric-value arg) 0)))
838     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
839     (easy-menu-add mml-menu mml-mode-map)
840     (run-hooks 'mml-mode-hook)))
841
842 ;;;
843 ;;; Helper functions for reading MIME stuff from the minibuffer and
844 ;;; inserting stuff to the buffer.
845 ;;;
846
847 (defun mml-minibuffer-read-file (prompt)
848   (let ((file (read-file-name prompt nil nil t)))
849     ;; Prevent some common errors.  This is inspired by similar code in
850     ;; VM.
851     (when (file-directory-p file)
852       (error "%s is a directory, cannot attach" file))
853     (unless (file-exists-p file)
854       (error "No such file: %s" file))
855     (unless (file-readable-p file)
856       (error "Permission denied: %s" file))
857     file))
858
859 (defun mml-minibuffer-read-type (name &optional default)
860   (mailcap-parse-mimetypes)
861   (let* ((default (or default
862                       (mm-default-file-encoding name)
863                       ;; Perhaps here we should check what the file
864                       ;; looks like, and offer text/plain if it looks
865                       ;; like text/plain.
866                       "application/octet-stream"))
867          (string (completing-read
868                   (format "Content type (default %s): " default)
869                   (mapcar 'list (mailcap-mime-types)))))
870     (if (not (equal string ""))
871         string
872       default)))
873
874 (defun mml-minibuffer-read-description ()
875   (let ((description (read-string "One line description: ")))
876     (when (string-match "\\`[ \t]*\\'" description)
877       (setq description nil))
878     description))
879
880 (defun mml-quote-region (beg end)
881   "Quote the MML tags in the region."
882   (interactive "r")
883   (save-excursion
884     (save-restriction
885       ;; Temporarily narrow the region to defend from changes
886       ;; invalidating END.
887       (narrow-to-region beg end)
888       (goto-char (point-min))
889       ;; Quote parts.
890       (while (re-search-forward
891               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
892         ;; Insert ! after the #.
893         (goto-char (+ (match-beginning 0) 2))
894         (insert "!")))))
895
896 (defun mml-insert-tag (name &rest plist)
897   "Insert an MML tag described by NAME and PLIST."
898   (when (symbolp name)
899     (setq name (symbol-name name)))
900   (insert "<#" name)
901   (while plist
902     (let ((key (pop plist))
903           (value (pop plist)))
904       (when value
905         ;; Quote VALUE if it contains suspicious characters.
906         (when (string-match "[\"'\\~/*;() \t\n]" value)
907           (setq value (prin1-to-string value)))
908         (insert (format " %s=%s" key value)))))
909   (insert ">\n"))
910
911 (defun mml-insert-empty-tag (name &rest plist)
912   "Insert an empty MML tag described by NAME and PLIST."
913   (when (symbolp name)
914     (setq name (symbol-name name)))
915   (apply #'mml-insert-tag name plist)
916   (insert "<#/" name ">\n"))
917
918 ;;; Attachment functions.
919
920 (defun mml-attach-file (file &optional type description)
921   "Attach a file to the outgoing MIME message.
922 The file is not inserted or encoded until you send the message with
923 `\\[message-send-and-exit]' or `\\[message-send]'.
924
925 FILE is the name of the file to attach.  TYPE is its content-type, a
926 string of the form \"type/subtype\".  DESCRIPTION is a one-line
927 description of the attachment."
928   (interactive
929    (let* ((file (mml-minibuffer-read-file "Attach file: "))
930           (type (mml-minibuffer-read-type file))
931           (description (mml-minibuffer-read-description)))
932      (list file type description)))
933   (mml-insert-empty-tag 'part 'type type 'filename file
934                         'disposition "attachment" 'description description))
935
936 (defun mml-attach-buffer (buffer &optional type description)
937   "Attach a buffer to the outgoing MIME message.
938 See `mml-attach-file' for details of operation."
939   (interactive
940    (let* ((buffer (read-buffer "Attach buffer: "))
941           (type (mml-minibuffer-read-type buffer "text/plain"))
942           (description (mml-minibuffer-read-description)))
943      (list buffer type description)))
944   (mml-insert-empty-tag 'part 'type type 'buffer buffer
945                         'disposition "attachment" 'description description))
946
947 (defun mml-attach-external (file &optional type description)
948   "Attach an external file into the buffer.
949 FILE is an ange-ftp/efs specification of the part location.
950 TYPE is the MIME type to use."
951   (interactive
952    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
953           (type (mml-minibuffer-read-type file))
954           (description (mml-minibuffer-read-description)))
955      (list file type description)))
956   (mml-insert-empty-tag 'external 'type type 'name file
957                         'disposition "attachment" 'description description))
958
959 (defun mml-insert-multipart (&optional type)
960   (interactive (list (completing-read "Multipart type (default mixed): "
961                                       '(("mixed") ("alternative") ("digest") ("parallel")
962                                         ("signed") ("encrypted"))
963                                       nil nil "mixed")))
964   (or type
965       (setq type "mixed"))
966   (mml-insert-empty-tag "multipart" 'type type)
967   (forward-line -1))
968
969 (defun mml-insert-part (&optional type)
970   (interactive
971    (list (mml-minibuffer-read-type "")))
972   (mml-insert-tag 'part 'type type 'disposition "inline")
973   (forward-line -1))
974
975 (defun mml-preview (&optional raw)
976   "Display current buffer with Gnus, in a new buffer.
977 If RAW, don't highlight the article."
978   (interactive "P")
979   (save-excursion
980     (let* ((buf (current-buffer))
981            (message-options message-options)
982            (message-this-is-news (message-news-p))
983            (message-posting-charset (or (gnus-setup-posting-charset
984                                          (save-restriction
985                                            (message-narrow-to-headers-or-head)
986                                            (message-fetch-field "Newsgroups")))
987                                         message-posting-charset)))
988       (message-options-set-recipient)
989       (switch-to-buffer (generate-new-buffer
990                          (concat (if raw "*Raw MIME preview of "
991                                    "*MIME preview of ") (buffer-name))))
992       (erase-buffer)
993       (insert-buffer buf)
994       (if (re-search-forward
995            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
996           (replace-match "\n"))
997       (let ((mail-header-separator ""));; mail-header-separator is removed.
998         (mml-to-mime))
999       (if raw
1000           (when (fboundp 'set-buffer-multibyte)
1001             (let ((s (buffer-string)))
1002               ;; Insert the content into unibyte buffer.
1003               (erase-buffer)
1004               (mm-disable-multibyte)
1005               (insert s)))
1006         (let ((gnus-newsgroup-charset (car message-posting-charset))
1007               gnus-article-prepare-hook gnus-original-article-buffer)
1008           (run-hooks 'gnus-article-decode-hook)
1009           (let ((gnus-newsgroup-name "dummy"))
1010             (gnus-article-prepare-display))))
1011       ;; Disable article-mode-map.
1012       (use-local-map nil)
1013       (setq buffer-read-only t)
1014       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1015       (goto-char (point-min)))))
1016
1017 (defun mml-validate ()
1018   "Validate the current MML document."
1019   (interactive)
1020   (mml-parse))
1021
1022 (defun mml-tweak-part (cont)
1023   "Tweak a MML part."
1024   (let ((tweak (cdr (assq 'tweak cont)))
1025         func)
1026     (cond
1027      (tweak
1028       (setq func
1029             (or (cdr (assoc tweak mml-tweak-function-alist))
1030                 (intern tweak))))
1031      (mml-tweak-type-alist
1032       (let ((alist mml-tweak-type-alist)
1033             (type (or (cdr (assq 'type cont)) "text/plain")))
1034         (while alist
1035           (if (string-match (caar alist) type)
1036               (setq func (cdar alist)
1037                     alist nil)
1038             (setq alist (cdr alist)))))))
1039     (if func
1040         (funcall func cont)
1041       cont)
1042     (let ((alist mml-tweak-sexp-alist))
1043       (while alist
1044         (if (eval (caar alist))
1045             (funcall (cdar alist) cont))
1046         (setq alist (cdr alist)))))
1047   cont)
1048
1049 (defun mml-tweak-externalize-attachments (cont)
1050   "Tweak attached files as external parts."
1051   (let (filename-cons)
1052     (when (and (eq (car cont) 'part)
1053                (not (cdr (assq 'buffer cont)))
1054                (and (setq filename-cons (assq 'filename cont))
1055                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1056       (setcar cont 'external)
1057       (setcar filename-cons 'name))))
1058
1059 (provide 'mml)
1060
1061 ;;; mml.el ends here