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