(mml-mode): Silence the byte compiler.
[gnus] / lisp / mml.el
1 ;;; mml.el --- A package for parsing and validating MML documents
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'mm-util)
29 (require 'mm-bodies)
30 (require 'mm-encode)
31 (require 'mm-decode)
32 (require 'mml-sec)
33 (eval-when-compile (require 'cl))
34
35 (eval-and-compile
36   (autoload 'message-make-message-id "message")
37   (autoload 'gnus-setup-posting-charset "gnus-msg")
38   (autoload 'gnus-make-local-hook "gnus-util")
39   (autoload 'message-fetch-field "message")
40   (autoload 'message-mark-active-p "message")
41   (autoload 'fill-flowed-encode "flow-fill")
42   (autoload 'message-posting-charset "message"))
43
44 (eval-when-compile
45   (autoload 'dnd-get-local-file-name "dnd"))
46
47 (defcustom mml-content-type-parameters
48   '(name access-type expiration size permission format)
49   "*A list of acceptable parameters in MML tag.
50 These parameters are generated in Content-Type header if exists."
51   :version "22.1"
52   :type '(repeat (symbol :tag "Parameter"))
53   :group 'message)
54
55 (defcustom mml-content-disposition-parameters
56   '(filename creation-date modification-date read-date)
57   "*A list of acceptable parameters in MML tag.
58 These parameters are generated in Content-Disposition header if exists."
59   :version "22.1"
60   :type '(repeat (symbol :tag "Parameter"))
61   :group 'message)
62
63 (defcustom mml-insert-mime-headers-always nil
64   "If non-nil, always put Content-Type: text/plain at top of empty parts.
65 It is necessary to work against a bug in certain clients."
66   :version "22.1"
67   :type 'boolean
68   :group 'message)
69
70 (defvar mml-tweak-type-alist nil
71   "A list of (TYPE . FUNCTION) for tweaking MML parts.
72 TYPE is a string containing a regexp to match the MIME type.  FUNCTION
73 is a Lisp function which is called with the MML handle to tweak the
74 part.  This variable is used only when no TWEAK parameter exists in
75 the MML handle.")
76
77 (defvar mml-tweak-function-alist nil
78   "A list of (NAME . FUNCTION) for tweaking MML parts.
79 NAME is a string containing the name of the TWEAK parameter in the MML
80 handle.  FUNCTION is a Lisp function which is called with the MML
81 handle to tweak the part.")
82
83 (defvar mml-tweak-sexp-alist
84   '((mml-externalize-attachments . mml-tweak-externalize-attachments))
85   "A list of (SEXP . FUNCTION) for tweaking MML parts.
86 SEXP is an s-expression.  If the evaluation of SEXP is non-nil, FUNCTION
87 is called.  FUNCTION is a Lisp function which is called with the MML
88 handle to tweak the part.")
89
90 (defvar mml-externalize-attachments nil
91   "*If non-nil, local-file attachments are generated as external parts.")
92
93 (defvar mml-generate-multipart-alist nil
94   "*Alist of multipart generation functions.
95 Each entry has the form (NAME . FUNCTION), where
96 NAME is a string containing the name of the part (without the
97 leading \"/multipart/\"),
98 FUNCTION is a Lisp function which is called to generate the part.
99
100 The Lisp function has to supply the appropriate MIME headers and the
101 contents of this part.")
102
103 (defvar mml-syntax-table
104   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
105     (modify-syntax-entry ?\\ "/" table)
106     (modify-syntax-entry ?< "(" table)
107     (modify-syntax-entry ?> ")" table)
108     (modify-syntax-entry ?@ "w" table)
109     (modify-syntax-entry ?/ "w" table)
110     (modify-syntax-entry ?= " " table)
111     (modify-syntax-entry ?* " " table)
112     (modify-syntax-entry ?\; " " table)
113     (modify-syntax-entry ?\' " " table)
114     table))
115
116 (defvar mml-boundary-function 'mml-make-boundary
117   "A function called to suggest a boundary.
118 The function may be called several times, and should try to make a new
119 suggestion each time.  The function is called with one parameter,
120 which is a number that says how many times the function has been
121 called for this message.")
122
123 (defvar mml-confirmation-set nil
124   "A list of symbols, each of which disables some warning.
125 `unknown-encoding': always send messages contain characters with
126 unknown encoding; `use-ascii': always use ASCII for those characters
127 with unknown encoding; `multipart': always send messages with more than
128 one charsets.")
129
130 (defvar mml-generate-default-type "text/plain"
131   "Content type by which the Content-Type header can be omitted.
132 The Content-Type header will not be put in the MIME part if the type
133 equals the value and there's no parameter (e.g. charset, format, etc.)
134 and `mml-insert-mime-headers-always' is nil.  The value will be bound
135 to \"message/rfc822\" when encoding an article to be forwarded as a MIME
136 part.  This is for the internal use, you should never modify the value.")
137
138 (defvar mml-buffer-list nil)
139
140 (defun mml-generate-new-buffer (name)
141   (let ((buf (generate-new-buffer name)))
142     (push buf mml-buffer-list)
143     buf))
144
145 (defun mml-destroy-buffers ()
146   (let (kill-buffer-hook)
147     (mapc 'kill-buffer mml-buffer-list)
148     (setq mml-buffer-list nil)))
149
150 (defun mml-parse ()
151   "Parse the current buffer as an MML document."
152   (save-excursion
153     (goto-char (point-min))
154     (with-syntax-table mml-syntax-table
155       (mml-parse-1))))
156
157 (defun mml-parse-1 ()
158   "Parse the current buffer as an MML document."
159   (let (struct tag point contents charsets warn use-ascii no-markup-p raw)
160     (while (and (not (eobp))
161                 (not (looking-at "<#/multipart")))
162       (cond
163        ((looking-at "<#secure")
164         ;; The secure part is essentially a meta-meta tag, which
165         ;; expands to either a part tag if there are no other parts in
166         ;; the document or a multipart tag if there are other parts
167         ;; included in the message
168         (let* (secure-mode
169                (taginfo (mml-read-tag))
170                (keyfile (cdr (assq 'keyfile taginfo)))
171                (certfile (cdr (assq 'certfile taginfo)))
172                (recipients (cdr (assq 'recipients taginfo)))
173                (sender (cdr (assq 'sender taginfo)))
174                (location (cdr (assq 'tag-location taginfo)))
175                (mode (cdr (assq 'mode taginfo)))
176                (method (cdr (assq 'method taginfo)))
177                tags)
178           (save-excursion
179             (if (re-search-forward
180                  "<#/?\\(multipart\\|part\\|external\\|mml\\)." nil t)
181                 (setq secure-mode "multipart")
182               (setq secure-mode "part")))
183           (save-excursion
184             (goto-char location)
185             (re-search-forward "<#secure[^\n]*>\n"))
186           (delete-region (match-beginning 0) (match-end 0))
187           (cond ((string= mode "sign")
188                  (setq tags (list "sign" method)))
189                 ((string= mode "encrypt")
190                  (setq tags (list "encrypt" method)))
191                 ((string= mode "signencrypt")
192                  (setq tags (list "sign" method "encrypt" method))))
193           (eval `(mml-insert-tag ,secure-mode
194                                  ,@tags
195                                  ,(if keyfile "keyfile")
196                                  ,keyfile
197                                  ,(if certfile "certfile")
198                                  ,certfile
199                                  ,(if recipients "recipients")
200                                  ,recipients
201                                  ,(if sender "sender")
202                                  ,sender))
203           ;; restart the parse
204           (goto-char location)))
205        ((looking-at "<#multipart")
206         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
207        ((looking-at "<#external")
208         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
209               struct))
210        (t
211         (if (or (looking-at "<#part") (looking-at "<#mml"))
212             (setq tag (mml-read-tag)
213                   no-markup-p nil
214                   warn nil)
215           (setq tag (list 'part '(type . "text/plain"))
216                 no-markup-p t
217                 warn t))
218         (setq raw (cdr (assq 'raw tag))
219               point (point)
220               contents (mml-read-part (eq 'mml (car tag)))
221               charsets (cond
222                         (raw nil)
223                         ((assq 'charset tag)
224                          (list
225                           (intern (downcase (cdr (assq 'charset tag))))))
226                         (t
227                          (mm-find-mime-charset-region point (point)
228                                                       mm-hack-charsets))))
229         (when (and (not raw) (memq nil charsets))
230           (if (or (memq 'unknown-encoding mml-confirmation-set)
231                   (message-options-get 'unknown-encoding)
232                   (and (y-or-n-p "\
233 Message contains characters with unknown encoding.  Really send? ")
234                        (message-options-set 'unknown-encoding t)))
235               (if (setq use-ascii
236                         (or (memq 'use-ascii mml-confirmation-set)
237                             (message-options-get 'use-ascii)
238                             (and (y-or-n-p "Use ASCII as charset? ")
239                                  (message-options-set 'use-ascii t))))
240                   (setq charsets (delq nil charsets))
241                 (setq warn nil))
242             (error "Edit your message to remove those characters")))
243         (if (or raw
244                 (eq 'mml (car tag))
245                 (< (length charsets) 2))
246             (if (or (not no-markup-p)
247                     (string-match "[^ \t\r\n]" contents))
248                 ;; Don't create blank parts.
249                 (push (nconc tag (list (cons 'contents contents)))
250                       struct))
251           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
252                           tag point (point) use-ascii)))
253             (when (and warn
254                        (not (memq 'multipart mml-confirmation-set))
255                        (not (message-options-get 'multipart))
256                        (not (and (y-or-n-p (format "\
257 A message part needs to be split into %d charset parts.  Really send? "
258                                                    (length nstruct)))
259                                  (message-options-set 'multipart t))))
260               (error "Edit your message to use only one charset"))
261             (setq struct (nconc nstruct struct)))))))
262     (unless (eobp)
263       (forward-line 1))
264     (nreverse struct)))
265
266 (defun mml-parse-singlepart-with-multiple-charsets
267   (orig-tag beg end &optional use-ascii)
268   (save-excursion
269     (save-restriction
270       (narrow-to-region beg end)
271       (goto-char (point-min))
272       (let ((current (or (mm-mime-charset (mm-charset-after))
273                          (and use-ascii 'us-ascii)))
274             charset struct space newline paragraph)
275         (while (not (eobp))
276           (setq charset (mm-mime-charset (mm-charset-after)))
277           (cond
278            ;; The charset remains the same.
279            ((eq charset 'us-ascii))
280            ((or (and use-ascii (not charset))
281                 (eq charset current))
282             (setq space nil
283                   newline nil
284                   paragraph nil))
285            ;; The initial charset was ascii.
286            ((eq current 'us-ascii)
287             (setq current charset
288                   space nil
289                   newline nil
290                   paragraph nil))
291            ;; We have a change in charsets.
292            (t
293             (push (append
294                    orig-tag
295                    (list (cons 'contents
296                                (buffer-substring-no-properties
297                                 beg (or paragraph newline space (point))))))
298                   struct)
299             (setq beg (or paragraph newline space (point))
300                   current charset
301                   space nil
302                   newline nil
303                   paragraph nil)))
304           ;; Compute places where it might be nice to break the part.
305           (cond
306            ((memq (following-char) '(?  ?\t))
307             (setq space (1+ (point))))
308            ((and (eq (following-char) ?\n)
309                  (not (bobp))
310                  (eq (char-after (1- (point))) ?\n))
311             (setq paragraph (point)))
312            ((eq (following-char) ?\n)
313             (setq newline (1+ (point)))))
314           (forward-char 1))
315         ;; Do the final part.
316         (unless (= beg (point))
317           (push (append orig-tag
318                         (list (cons 'contents
319                                     (buffer-substring-no-properties
320                                      beg (point)))))
321                 struct))
322         struct))))
323
324 (defun mml-read-tag ()
325   "Read a tag and return the contents."
326   (let ((orig-point (point))
327         contents name elem val)
328     (forward-char 2)
329     (setq name (buffer-substring-no-properties
330                 (point) (progn (forward-sexp 1) (point))))
331     (skip-chars-forward " \t\n")
332     (while (not (looking-at ">[ \t]*\n?"))
333       (setq elem (buffer-substring-no-properties
334                   (point) (progn (forward-sexp 1) (point))))
335       (skip-chars-forward "= \t\n")
336       (setq val (buffer-substring-no-properties
337                  (point) (progn (forward-sexp 1) (point))))
338       (when (string-match "^\"\\(.*\\)\"$" val)
339         (setq val (match-string 1 val)))
340       (push (cons (intern elem) val) contents)
341       (skip-chars-forward " \t\n"))
342     (goto-char (match-end 0))
343     ;; Don't skip the leading space.
344     ;;(skip-chars-forward " \t\n")
345     ;; Put the tag location into the returned contents
346     (setq contents (append (list (cons 'tag-location orig-point)) contents))
347     (cons (intern name) (nreverse contents))))
348
349 (defun mml-buffer-substring-no-properties-except-hard-newlines (start end)
350   (let ((str (buffer-substring-no-properties start end))
351         (bufstart start) tmp)
352     (while (setq tmp (text-property-any start end 'hard 't))
353       (set-text-properties (- tmp bufstart) (- tmp bufstart -1)
354                            '(hard t) str)
355       (setq start (1+ tmp)))
356     str))
357
358 (defun mml-read-part (&optional mml)
359   "Return the buffer up till the next part, multipart or closing part or multipart.
360 If MML is non-nil, return the buffer up till the correspondent mml tag."
361   (let ((beg (point)) (count 1))
362     ;; If the tag ended at the end of the line, we go to the next line.
363     (when (looking-at "[ \t]*\n")
364       (forward-line 1))
365     (if mml
366         (progn
367           (while (and (> count 0) (not (eobp)))
368             (if (re-search-forward "<#\\(/\\)?mml." nil t)
369                 (setq count (+ count (if (match-beginning 1) -1 1)))
370               (goto-char (point-max))))
371           (mml-buffer-substring-no-properties-except-hard-newlines
372            beg (if (> count 0)
373                    (point)
374                  (match-beginning 0))))
375       (if (re-search-forward
376            "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
377           (prog1
378               (mml-buffer-substring-no-properties-except-hard-newlines
379                beg (match-beginning 0))
380             (if (or (not (match-beginning 1))
381                     (equal (match-string 2) "multipart"))
382                 (goto-char (match-beginning 0))
383               (when (looking-at "[ \t]*\n")
384                 (forward-line 1))))
385         (mml-buffer-substring-no-properties-except-hard-newlines
386          beg (goto-char (point-max)))))))
387
388 (defvar mml-boundary nil)
389 (defvar mml-base-boundary "-=-=")
390 (defvar mml-multipart-number 0)
391
392 (defun mml-generate-mime ()
393   "Generate a MIME message based on the current MML document."
394   (let ((cont (mml-parse))
395         (mml-multipart-number mml-multipart-number))
396     (if (not cont)
397         nil
398       (with-temp-buffer
399         (if (and (consp (car cont))
400                  (= (length cont) 1))
401             (mml-generate-mime-1 (car cont))
402           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
403                                       cont)))
404         (buffer-string)))))
405
406 (defun mml-generate-mime-1 (cont)
407   (let ((mm-use-ultra-safe-encoding
408          (or mm-use-ultra-safe-encoding (assq 'sign cont))))
409     (save-restriction
410       (narrow-to-region (point) (point))
411       (mml-tweak-part cont)
412       (cond
413        ((or (eq (car cont) 'part) (eq (car cont) 'mml))
414         (let* ((raw (cdr (assq 'raw cont)))
415                (filename (cdr (assq 'filename cont)))
416                (type (or (cdr (assq 'type cont))
417                          (if filename
418                              (or (mm-default-file-encoding filename)
419                                  "application/octet-stream")
420                            "text/plain")))
421                (charset (cdr (assq 'charset cont)))
422                (coding (mm-charset-to-coding-system charset))
423                encoding flowed coded)
424           (cond ((eq coding 'ascii)
425                  (setq charset nil
426                        coding nil))
427                 (charset
428                  (setq charset (intern (downcase charset)))))
429           (if (and (not raw)
430                    (member (car (split-string type "/")) '("text" "message")))
431               (progn
432                 (with-temp-buffer
433                   (cond
434                    ((cdr (assq 'buffer cont))
435                     (insert-buffer-substring (cdr (assq 'buffer cont))))
436                    ((and filename
437                          (not (equal (cdr (assq 'nofile cont)) "yes")))
438                     (let ((coding-system-for-read coding))
439                       (mm-insert-file-contents filename)))
440                    ((eq 'mml (car cont))
441                     (insert (cdr (assq 'contents cont))))
442                    (t
443                     (save-restriction
444                       (narrow-to-region (point) (point))
445                       (insert (cdr (assq 'contents cont)))
446                       ;; Remove quotes from quoted tags.
447                       (goto-char (point-min))
448                       (while (re-search-forward
449                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\)"
450                               nil t)
451                         (delete-region (+ (match-beginning 0) 2)
452                                        (+ (match-beginning 0) 3))))))
453                   (cond
454                    ((eq (car cont) 'mml)
455                     (let ((mml-boundary (mml-compute-boundary cont))
456                           ;; It is necessary for the case where this
457                           ;; function is called recursively since
458                           ;; `m-g-d-t' will be bound to "message/rfc822"
459                           ;; when encoding an article to be forwarded.
460                           (mml-generate-default-type "text/plain"))
461                       (mml-to-mime))
462                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
463                       ;; ignore 0x1b, it is part of iso-2022-jp
464                       (setq encoding (mm-body-7-or-8))))
465                    ((string= (car (split-string type "/")) "message")
466                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
467                       ;; ignore 0x1b, it is part of iso-2022-jp
468                       (setq encoding (mm-body-7-or-8))))
469                    (t
470                     ;; Only perform format=flowed filling on text/plain
471                     ;; parts where there either isn't a format parameter
472                     ;; in the mml tag or it says "flowed" and there
473                     ;; actually are hard newlines in the text.
474                     (let (use-hard-newlines)
475                       (when (and (string= type "text/plain")
476                                  (not (string= (cdr (assq 'sign cont)) "pgp"))
477                                  (or (null (assq 'format cont))
478                                      (string= (cdr (assq 'format cont))
479                                               "flowed"))
480                                  (setq use-hard-newlines
481                                        (text-property-any
482                                         (point-min) (point-max) 'hard 't)))
483                         (fill-flowed-encode)
484                         ;; Indicate that `mml-insert-mime-headers' should
485                         ;; insert a "; format=flowed" string unless the
486                         ;; user has already specified it.
487                         (setq flowed (null (assq 'format cont)))))
488                     (setq charset (mm-encode-body charset))
489                     (setq encoding (mm-body-encoding
490                                     charset (cdr (assq 'encoding cont))))))
491                   (setq coded (buffer-string)))
492                 (mml-insert-mime-headers cont type charset encoding flowed)
493                 (insert "\n")
494                 (insert coded))
495             (mm-with-unibyte-buffer
496               (cond
497                ((cdr (assq 'buffer cont))
498                 (insert (with-current-buffer (cdr (assq 'buffer cont))
499                           (mm-with-unibyte-current-buffer
500                             (buffer-string)))))
501                ((and filename
502                      (not (equal (cdr (assq 'nofile cont)) "yes")))
503                 (let ((coding-system-for-read mm-binary-coding-system))
504                   (mm-insert-file-contents filename nil nil nil nil t))
505                 (unless charset
506                   (setq charset (mm-coding-system-to-mime-charset
507                                  (mm-find-buffer-file-coding-system
508                                   filename)))))
509                (t
510                 (insert (cdr (assq 'contents cont)))))
511               (setq encoding (mm-encode-buffer type)
512                     coded (mm-string-as-multibyte (buffer-string))))
513             (mml-insert-mime-headers cont type charset encoding nil)
514             (insert "\n")
515             (mm-with-unibyte-current-buffer
516               (insert coded)))))
517        ((eq (car cont) 'external)
518         (insert "Content-Type: message/external-body")
519         (let ((parameters (mml-parameter-string
520                            cont '(expiration size permission)))
521               (name (cdr (assq 'name cont)))
522               (url (cdr (assq 'url cont))))
523           (when name
524             (setq name (mml-parse-file-name name))
525             (if (stringp name)
526                 (mml-insert-parameter
527                  (mail-header-encode-parameter "name" name)
528                  "access-type=local-file")
529               (mml-insert-parameter
530                (mail-header-encode-parameter
531                 "name" (file-name-nondirectory (nth 2 name)))
532                (mail-header-encode-parameter "site" (nth 1 name))
533                (mail-header-encode-parameter
534                 "directory" (file-name-directory (nth 2 name))))
535               (mml-insert-parameter
536                (concat "access-type="
537                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
538                            "anon-ftp"
539                          "ftp")))))
540           (when url
541             (mml-insert-parameter
542              (mail-header-encode-parameter "url" url)
543              "access-type=url"))
544           (when parameters
545             (mml-insert-parameter-string
546              cont '(expiration size permission)))
547           (insert "\n\n")
548           (insert "Content-Type: "
549                   (or (cdr (assq 'type cont))
550                       (if name
551                           (or (mm-default-file-encoding name)
552                               "application/octet-stream")
553                         "text/plain"))
554                   "\n")
555           (insert "Content-ID: " (message-make-message-id) "\n")
556           (insert "Content-Transfer-Encoding: "
557                   (or (cdr (assq 'encoding cont)) "binary"))
558           (insert "\n\n")
559           (insert (or (cdr (assq 'contents cont))))
560           (insert "\n")))
561        ((eq (car cont) 'multipart)
562         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
563                (mml-generate-default-type (if (equal type "digest")
564                                               "message/rfc822"
565                                             "text/plain"))
566                (handler (assoc type mml-generate-multipart-alist)))
567           (if handler
568               (funcall (cdr handler) cont)
569             ;; No specific handler.  Use default one.
570             (let ((mml-boundary (mml-compute-boundary cont)))
571               (insert (format "Content-Type: multipart/%s; boundary=\"%s\""
572                               type mml-boundary)
573                       (if (cdr (assq 'start cont))
574                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
575                         "\n"))
576               (let ((cont cont) part)
577                 (while (setq part (pop cont))
578                   ;; Skip `multipart' and attributes.
579                   (when (and (consp part) (consp (cdr part)))
580                     (insert "\n--" mml-boundary "\n")
581                     (mml-generate-mime-1 part))))
582               (insert "\n--" mml-boundary "--\n")))))
583        (t
584         (error "Invalid element: %S" cont)))
585       ;; handle sign & encrypt tags in a semi-smart way.
586       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
587             (encrypt-item (assoc (cdr (assq 'encrypt cont))
588                                  mml-encrypt-alist))
589             sender recipients)
590         (when (or sign-item encrypt-item)
591           (when (setq sender (cdr (assq 'sender cont)))
592             (message-options-set 'mml-sender sender)
593             (message-options-set 'message-sender sender))
594           (if (setq recipients (cdr (assq 'recipients cont)))
595               (message-options-set 'message-recipients recipients))
596           (let ((style (mml-signencrypt-style
597                         (first (or sign-item encrypt-item)))))
598             ;; check if: we're both signing & encrypting, both methods
599             ;; are the same (why would they be different?!), and that
600             ;; the signencrypt style allows for combined operation.
601             (if (and sign-item encrypt-item (equal (first sign-item)
602                                                    (first encrypt-item))
603                      (equal style 'combined))
604                 (funcall (nth 1 encrypt-item) cont t)
605               ;; otherwise, revert to the old behavior.
606               (when sign-item
607                 (funcall (nth 1 sign-item) cont))
608               (when encrypt-item
609                 (funcall (nth 1 encrypt-item) cont)))))))))
610
611 (defun mml-compute-boundary (cont)
612   "Return a unique boundary that does not exist in CONT."
613   (let ((mml-boundary (funcall mml-boundary-function
614                                (incf mml-multipart-number))))
615     ;; This function tries again and again until it has found
616     ;; a unique boundary.
617     (while (not (catch 'not-unique
618                   (mml-compute-boundary-1 cont))))
619     mml-boundary))
620
621 (defun mml-compute-boundary-1 (cont)
622   (let (filename)
623     (cond
624      ((eq (car cont) 'part)
625       (with-temp-buffer
626         (cond
627          ((cdr (assq 'buffer cont))
628           (insert-buffer-substring (cdr (assq 'buffer cont))))
629          ((and (setq filename (cdr (assq 'filename cont)))
630                (not (equal (cdr (assq 'nofile cont)) "yes")))
631           (mm-insert-file-contents filename nil nil nil nil t))
632          (t
633           (insert (cdr (assq 'contents cont)))))
634         (goto-char (point-min))
635         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
636                                  nil t)
637           (setq mml-boundary (funcall mml-boundary-function
638                                       (incf mml-multipart-number)))
639           (throw 'not-unique nil))))
640      ((eq (car cont) 'multipart)
641       (mapc 'mml-compute-boundary-1 (cddr cont))))
642     t))
643
644 (defun mml-make-boundary (number)
645   (concat (make-string (% number 60) ?=)
646           (if (> number 17)
647               (format "%x" number)
648             "")
649           mml-base-boundary))
650
651 (defun mml-insert-mime-headers (cont type charset encoding flowed)
652   (let (parameters id disposition description)
653     (setq parameters
654           (mml-parameter-string
655            cont mml-content-type-parameters))
656     (when (or charset
657               parameters
658               flowed
659               (not (equal type mml-generate-default-type))
660               mml-insert-mime-headers-always)
661       (when (consp charset)
662         (error
663          "Can't encode a part with several charsets"))
664       (insert "Content-Type: " type)
665       (when charset
666         (insert "; " (mail-header-encode-parameter
667                       "charset" (symbol-name charset))))
668       (when flowed
669         (insert "; format=flowed"))
670       (when parameters
671         (mml-insert-parameter-string
672          cont mml-content-type-parameters))
673       (insert "\n"))
674     (when (setq id (cdr (assq 'id cont)))
675       (insert "Content-ID: " id "\n"))
676     (setq parameters
677           (mml-parameter-string
678            cont mml-content-disposition-parameters))
679     (when (or (setq disposition (cdr (assq 'disposition cont)))
680               parameters)
681       (insert "Content-Disposition: " (or disposition "inline"))
682       (when parameters
683         (mml-insert-parameter-string
684          cont mml-content-disposition-parameters))
685       (insert "\n"))
686     (unless (eq encoding '7bit)
687       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
688     (when (setq description (cdr (assq 'description cont)))
689       (insert "Content-Description: "
690               (mail-encode-encoded-word-string description) "\n"))))
691
692 (defun mml-parameter-string (cont types)
693   (let ((string "")
694         value type)
695     (while (setq type (pop types))
696       (when (setq value (cdr (assq type cont)))
697         ;; Strip directory component from the filename parameter.
698         (when (eq type 'filename)
699           (setq value (file-name-nondirectory value)))
700         (setq string (concat string "; "
701                              (mail-header-encode-parameter
702                               (symbol-name type) value)))))
703     (when (not (zerop (length string)))
704       string)))
705
706 (defun mml-insert-parameter-string (cont types)
707   (let (value type)
708     (while (setq type (pop types))
709       (when (setq value (cdr (assq type cont)))
710         ;; Strip directory component from the filename parameter.
711         (when (eq type 'filename)
712           (setq value (file-name-nondirectory value)))
713         (mml-insert-parameter
714          (mail-header-encode-parameter
715           (symbol-name type) value))))))
716
717 (eval-when-compile
718   (defvar ange-ftp-name-format)
719   (defvar efs-path-regexp))
720 (defun mml-parse-file-name (path)
721   (if (if (boundp 'efs-path-regexp)
722           (string-match efs-path-regexp path)
723         (if (boundp 'ange-ftp-name-format)
724             (string-match (car ange-ftp-name-format) path)))
725       (list (match-string 1 path) (match-string 2 path)
726             (substring path (1+ (match-end 2))))
727     path))
728
729 (defun mml-insert-buffer (buffer)
730   "Insert BUFFER at point and quote any MML markup."
731   (save-restriction
732     (narrow-to-region (point) (point))
733     (insert-buffer-substring buffer)
734     (mml-quote-region (point-min) (point-max))
735     (goto-char (point-max))))
736
737 ;;;
738 ;;; Transforming MIME to MML
739 ;;;
740
741 (defun mime-to-mml (&optional handles)
742   "Translate the current buffer (which should be a message) into MML.
743 If HANDLES is non-nil, use it instead reparsing the buffer."
744   ;; First decode the head.
745   (save-restriction
746     (message-narrow-to-head)
747     (let ((rfc2047-quote-decoded-words-containing-tspecials t))
748       (mail-decode-encoded-word-region (point-min) (point-max))))
749   (unless handles
750     (setq handles (mm-dissect-buffer t)))
751   (goto-char (point-min))
752   (search-forward "\n\n" nil t)
753   (delete-region (point) (point-max))
754   (if (stringp (car handles))
755       (mml-insert-mime handles)
756     (mml-insert-mime handles t))
757   (mm-destroy-parts handles)
758   (save-restriction
759     (message-narrow-to-head)
760     ;; Remove them, they are confusing.
761     (message-remove-header "Content-Type")
762     (message-remove-header "MIME-Version")
763     (message-remove-header "Content-Disposition")
764     (message-remove-header "Content-Transfer-Encoding")))
765
766 (defun mml-to-mime ()
767   "Translate the current buffer from MML to MIME."
768   (message-encode-message-body)
769   (save-restriction
770     (message-narrow-to-headers-or-head)
771     ;; Skip past any From_ headers.
772     (while (looking-at "From ")
773       (forward-line 1))
774     (let ((mail-parse-charset message-default-charset))
775       (mail-encode-encoded-word-buffer))))
776
777 (defun mml-insert-mime (handle &optional no-markup)
778   (let (textp buffer mmlp)
779     ;; Determine type and stuff.
780     (unless (stringp (car handle))
781       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
782         (save-excursion
783           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
784           (mm-insert-part handle)
785           (if (setq mmlp (equal (mm-handle-media-type handle)
786                                 "message/rfc822"))
787               (mime-to-mml)))))
788     (if mmlp
789         (mml-insert-mml-markup handle nil t t)
790       (unless (and no-markup
791                    (equal (mm-handle-media-type handle) "text/plain"))
792         (mml-insert-mml-markup handle buffer textp)))
793     (cond
794      (mmlp
795       (insert-buffer-substring buffer)
796       (goto-char (point-max))
797       (insert "<#/mml>\n"))
798      ((stringp (car handle))
799       (mapcar 'mml-insert-mime (cdr handle))
800       (insert "<#/multipart>\n"))
801      (textp
802       (let ((charset (mail-content-type-get
803                       (mm-handle-type handle) 'charset))
804             (start (point)))
805         (if (eq charset 'gnus-decoded)
806             (mm-insert-part handle)
807           (insert (mm-decode-string (mm-get-part handle) charset)))
808         (mml-quote-region start (point)))
809       (goto-char (point-max)))
810      (t
811       (insert "<#/part>\n")))))
812
813 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
814   "Take a MIME handle and insert an MML tag."
815   (if (stringp (car handle))
816       (progn
817         (insert "<#multipart type=" (mm-handle-media-subtype handle))
818         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
819           (when start
820             (insert " start=\"" start "\"")))
821         (insert ">\n"))
822     (if mmlp
823         (insert "<#mml type=" (mm-handle-media-type handle))
824       (insert "<#part type=" (mm-handle-media-type handle)))
825     (dolist (elem (append (cdr (mm-handle-type handle))
826                           (cdr (mm-handle-disposition handle))))
827       (unless (symbolp (cdr elem))
828         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
829     (when (mm-handle-id handle)
830       (insert " id=\"" (mm-handle-id handle) "\""))
831     (when (mm-handle-disposition handle)
832       (insert " disposition=" (car (mm-handle-disposition handle))))
833     (when buffer
834       (insert " buffer=\"" (buffer-name buffer) "\""))
835     (when nofile
836       (insert " nofile=yes"))
837     (when (mm-handle-description handle)
838       (insert " description=\"" (mm-handle-description handle) "\""))
839     (insert ">\n")))
840
841 (defun mml-insert-parameter (&rest parameters)
842   "Insert PARAMETERS in a nice way."
843   (dolist (param parameters)
844     (insert ";")
845     (let ((point (point)))
846       (insert " " param)
847       (when (> (current-column) 71)
848         (goto-char point)
849         (insert "\n")
850         (end-of-line)))))
851
852 ;;;
853 ;;; Mode for inserting and editing MML forms
854 ;;;
855
856 (defvar mml-mode-map
857   (let ((sign (make-sparse-keymap))
858         (encrypt (make-sparse-keymap))
859         (signpart (make-sparse-keymap))
860         (encryptpart (make-sparse-keymap))
861         (map (make-sparse-keymap))
862         (main (make-sparse-keymap)))
863     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
864     (define-key sign "o" 'mml-secure-message-sign-pgp)
865     (define-key sign "s" 'mml-secure-message-sign-smime)
866     (define-key signpart "p" 'mml-secure-sign-pgpmime)
867     (define-key signpart "o" 'mml-secure-sign-pgp)
868     (define-key signpart "s" 'mml-secure-sign-smime)
869     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
870     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
871     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
872     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
873     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
874     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
875     (define-key map "\C-n" 'mml-unsecure-message)
876     (define-key map "f" 'mml-attach-file)
877     (define-key map "b" 'mml-attach-buffer)
878     (define-key map "e" 'mml-attach-external)
879     (define-key map "q" 'mml-quote-region)
880     (define-key map "m" 'mml-insert-multipart)
881     (define-key map "p" 'mml-insert-part)
882     (define-key map "v" 'mml-validate)
883     (define-key map "P" 'mml-preview)
884     (define-key map "s" sign)
885     (define-key map "S" signpart)
886     (define-key map "c" encrypt)
887     (define-key map "C" encryptpart)
888     ;;(define-key map "n" 'mml-narrow-to-part)
889     ;; `M-m' conflicts with `back-to-indentation'.
890     ;; (define-key main "\M-m" map)
891     (define-key main "\C-c\C-m" map)
892     main))
893
894 (easy-menu-define
895   mml-menu mml-mode-map ""
896   `("Attachments"
897     ["Attach File..." mml-attach-file
898      ,@(if (featurep 'xemacs) '(t)
899          '(:help "Attach a file at point"))]
900     ["Attach Buffer..." mml-attach-buffer t]
901     ["Attach External..." mml-attach-external t]
902     ["Insert Part..." mml-insert-part t]
903     ["Insert Multipart..." mml-insert-multipart t]
904     ["PGP/MIME Sign" mml-secure-message-sign-pgpmime t]
905     ["PGP/MIME Encrypt" mml-secure-message-encrypt-pgpmime t]
906     ["PGP Sign" mml-secure-message-sign-pgp t]
907     ["PGP Encrypt" mml-secure-message-encrypt-pgp t]
908     ["S/MIME Sign" mml-secure-message-sign-smime t]
909     ["S/MIME Encrypt" mml-secure-message-encrypt-smime t]
910     ("Secure MIME part"
911      ["PGP/MIME Sign Part" mml-secure-sign-pgpmime t]
912      ["PGP/MIME Encrypt Part" mml-secure-encrypt-pgpmime t]
913      ["PGP Sign Part" mml-secure-sign-pgp t]
914      ["PGP Encrypt Part" mml-secure-encrypt-pgp t]
915      ["S/MIME Sign Part" mml-secure-sign-smime t]
916      ["S/MIME Encrypt Part" mml-secure-encrypt-smime t])
917     ["Encrypt/Sign off" mml-unsecure-message t]
918     ;;["Narrow" mml-narrow-to-part t]
919     ["Quote MML" mml-quote-region
920      :active (message-mark-active-p)
921      ,@(if (featurep 'xemacs) nil
922          '(:help "Quote MML tags in region"))]
923     ["Validate MML" mml-validate t]
924     ["Preview" mml-preview t]))
925
926 (defvar mml-mode nil
927   "Minor mode for editing MML.")
928
929 (defun mml-mode (&optional arg)
930   "Minor mode for editing MML.
931 MML is the MIME Meta Language, a minor mode for composing MIME articles.
932 See Info node `(emacs-mime)Composing'.
933
934 \\{mml-mode-map}"
935   (interactive "P")
936   (when (set (make-local-variable 'mml-mode)
937              (if (null arg) (not mml-mode)
938                (> (prefix-numeric-value arg) 0)))
939     (add-minor-mode 'mml-mode " MML" mml-mode-map)
940     (easy-menu-add mml-menu mml-mode-map)
941     (when (boundp 'dnd-protocol-alist)
942       (set (make-local-variable 'dnd-protocol-alist)
943            (append mml-dnd-protocol-alist
944                    (symbol-value 'dnd-protocol-alist))))
945     (run-hooks 'mml-mode-hook)))
946
947 ;;;
948 ;;; Helper functions for reading MIME stuff from the minibuffer and
949 ;;; inserting stuff to the buffer.
950 ;;;
951
952 (defun mml-minibuffer-read-file (prompt)
953   (let* ((completion-ignored-extensions nil)
954          (file (read-file-name prompt nil nil t)))
955     ;; Prevent some common errors.  This is inspired by similar code in
956     ;; VM.
957     (when (file-directory-p file)
958       (error "%s is a directory, cannot attach" file))
959     (unless (file-exists-p file)
960       (error "No such file: %s" file))
961     (unless (file-readable-p file)
962       (error "Permission denied: %s" file))
963     file))
964
965 (defun mml-minibuffer-read-type (name &optional default)
966   (mailcap-parse-mimetypes)
967   (let* ((default (or default
968                       (mm-default-file-encoding name)
969                       ;; Perhaps here we should check what the file
970                       ;; looks like, and offer text/plain if it looks
971                       ;; like text/plain.
972                       "application/octet-stream"))
973          (string (completing-read
974                   (format "Content type (default %s): " default)
975                   (mapcar 'list (mailcap-mime-types)))))
976     (if (not (equal string ""))
977         string
978       default)))
979
980 (defun mml-minibuffer-read-description ()
981   (let ((description (read-string "One line description: ")))
982     (when (string-match "\\`[ \t]*\\'" description)
983       (setq description nil))
984     description))
985
986 (defun mml-minibuffer-read-disposition (type &optional default)
987   (unless default (setq default
988                         (if (and (string-match "\\`text/" type)
989                                  (not (string-match "\\`text/rtf\\'" type)))
990                             "inline"
991                           "attachment")))
992   (let ((disposition (completing-read
993                       (format "Disposition (default %s): " default)
994                       '(("attachment") ("inline") (""))
995                       nil t nil nil default)))
996     (if (not (equal disposition ""))
997         disposition
998       default)))
999
1000 (defun mml-quote-region (beg end)
1001   "Quote the MML tags in the region."
1002   (interactive "r")
1003   (save-excursion
1004     (save-restriction
1005       ;; Temporarily narrow the region to defend from changes
1006       ;; invalidating END.
1007       (narrow-to-region beg end)
1008       (goto-char (point-min))
1009       ;; Quote parts.
1010       (while (re-search-forward
1011               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
1012         ;; Insert ! after the #.
1013         (goto-char (+ (match-beginning 0) 2))
1014         (insert "!")))))
1015
1016 (defun mml-insert-tag (name &rest plist)
1017   "Insert an MML tag described by NAME and PLIST."
1018   (when (symbolp name)
1019     (setq name (symbol-name name)))
1020   (insert "<#" name)
1021   (while plist
1022     (let ((key (pop plist))
1023           (value (pop plist)))
1024       (when value
1025         ;; Quote VALUE if it contains suspicious characters.
1026         (when (string-match "[\"'\\~/*;() \t\n]" value)
1027           (setq value (with-output-to-string
1028                         (let (print-escape-nonascii)
1029                           (prin1 value)))))
1030         (insert (format " %s=%s" key value)))))
1031   (insert ">\n"))
1032
1033 (defun mml-insert-empty-tag (name &rest plist)
1034   "Insert an empty MML tag described by NAME and PLIST."
1035   (when (symbolp name)
1036     (setq name (symbol-name name)))
1037   (apply #'mml-insert-tag name plist)
1038   (insert "<#/" name ">\n"))
1039
1040 ;;; Attachment functions.
1041
1042 (defcustom mml-dnd-protocol-alist
1043   '(("^file:///" . mml-dnd-attach-file)
1044     ("^file://"  . dnd-open-file)
1045     ("^file:"    . mml-dnd-attach-file))
1046   "The functions to call when a drop in `mml-mode' is made.
1047 See `dnd-protocol-alist' for more information.  When nil, behave
1048 as in other buffers."
1049   :type '(choice (repeat (cons (regexp) (function)))
1050                  (const :tag "Behave as in other buffers" nil))
1051   :version "23.0" ;; No Gnus
1052   :group 'message)
1053
1054 (defcustom mml-dnd-attach-options nil
1055   "Which options should be queried when attaching a file via drag and drop.
1056
1057 If it is a list, valid members are `type', `description' and
1058 `disposition'.  `disposition' implies `type'.  If it is nil,
1059 don't ask for options.  If it is t, ask the user whether or not
1060 to specify options."
1061   :type '(choice
1062           (const :tag "Non" nil)
1063           (const :tag "Query" t)
1064           (list :value (type description disposition)
1065            (set :inline t
1066                 (const type)
1067                 (const description)
1068                 (const disposition))))
1069   :version "23.0" ;; No Gnus
1070   :group 'message)
1071
1072 (defun mml-attach-file (file &optional type description disposition)
1073   "Attach a file to the outgoing MIME message.
1074 The file is not inserted or encoded until you send the message with
1075 `\\[message-send-and-exit]' or `\\[message-send]'.
1076
1077 FILE is the name of the file to attach.  TYPE is its content-type, a
1078 string of the form \"type/subtype\".  DESCRIPTION is a one-line
1079 description of the attachment."
1080   (interactive
1081    (let* ((file (mml-minibuffer-read-file "Attach file: "))
1082           (type (mml-minibuffer-read-type file))
1083           (description (mml-minibuffer-read-description))
1084           (disposition (mml-minibuffer-read-disposition type)))
1085      (list file type description disposition)))
1086   (mml-insert-empty-tag 'part
1087                         'type type
1088                         'filename file
1089                         'disposition (or disposition "attachment")
1090                         'description description))
1091
1092 (defun mml-dnd-attach-file (uri action)
1093   "Attach a drag and drop file.
1094
1095 Ask for type, description or disposition according to
1096 `mml-dnd-attach-options'."
1097   (let ((file (dnd-get-local-file-name uri t)))
1098     (when (and file (file-regular-p file))
1099       (let ((mml-dnd-attach-options mml-dnd-attach-options)
1100             type description disposition)
1101         (setq mml-dnd-attach-options
1102               (when (and (eq mml-dnd-attach-options t)
1103                          (not
1104                           (y-or-n-p
1105                            "Use default type, disposition and description? ")))
1106                 '(type description disposition)))
1107         (when (or (memq 'type mml-dnd-attach-options)
1108                   (memq 'disposition mml-dnd-attach-options))
1109           (setq type (mml-minibuffer-read-type file)))
1110         (when (memq 'description mml-dnd-attach-options)
1111           (setq description (mml-minibuffer-read-description)))
1112         (when (memq 'disposition mml-dnd-attach-options)
1113           (setq disposition (mml-minibuffer-read-disposition type)))
1114         (mml-attach-file file type description disposition)))))
1115
1116 (defun mml-attach-buffer (buffer &optional type description)
1117   "Attach a buffer to the outgoing MIME message.
1118 See `mml-attach-file' for details of operation."
1119   (interactive
1120    (let* ((buffer (read-buffer "Attach buffer: "))
1121           (type (mml-minibuffer-read-type buffer "text/plain"))
1122           (description (mml-minibuffer-read-description)))
1123      (list buffer type description)))
1124   (mml-insert-empty-tag 'part 'type type 'buffer buffer
1125                         'disposition "attachment" 'description description))
1126
1127 (defun mml-attach-external (file &optional type description)
1128   "Attach an external file into the buffer.
1129 FILE is an ange-ftp/efs specification of the part location.
1130 TYPE is the MIME type to use."
1131   (interactive
1132    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1133           (type (mml-minibuffer-read-type file))
1134           (description (mml-minibuffer-read-description)))
1135      (list file type description)))
1136   (mml-insert-empty-tag 'external 'type type 'name file
1137                         'disposition "attachment" 'description description))
1138
1139 (defun mml-insert-multipart (&optional type)
1140   (interactive (list (completing-read "Multipart type (default mixed): "
1141                                       '(("mixed") ("alternative") ("digest") ("parallel")
1142                                         ("signed") ("encrypted"))
1143                                       nil nil "mixed")))
1144   (or type
1145       (setq type "mixed"))
1146   (mml-insert-empty-tag "multipart" 'type type)
1147   (forward-line -1))
1148
1149 (defun mml-insert-part (&optional type)
1150   (interactive
1151    (list (mml-minibuffer-read-type "")))
1152   (mml-insert-tag 'part 'type type 'disposition "inline")
1153   (forward-line -1))
1154
1155 (defun mml-preview-insert-mail-followup-to ()
1156   "Insert a Mail-Followup-To header before previewing an article.
1157 Should be adopted if code in `message-send-mail' is changed."
1158   (when (and (message-mail-p)
1159              (message-subscribed-p)
1160              (not (mail-fetch-field "mail-followup-to"))
1161              (message-make-mail-followup-to))
1162     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1163     (insert (message-make-mail-followup-to))))
1164
1165 (defvar mml-preview-buffer nil)
1166
1167 (defun mml-preview (&optional raw)
1168   "Display current buffer with Gnus, in a new buffer.
1169 If RAW, don't highlight the article."
1170   (interactive "P")
1171   (setq mml-preview-buffer (generate-new-buffer
1172                             (concat (if raw "*Raw MIME preview of "
1173                                       "*MIME preview of ") (buffer-name))))
1174   (save-excursion
1175     (let* ((buf (current-buffer))
1176            (message-options message-options)
1177            (message-this-is-mail (message-mail-p))
1178            (message-this-is-news (message-news-p))
1179            (message-posting-charset (or (gnus-setup-posting-charset
1180                                          (save-restriction
1181                                            (message-narrow-to-headers-or-head)
1182                                            (message-fetch-field "Newsgroups")))
1183                                         message-posting-charset)))
1184       (message-options-set-recipient)
1185       (when (boundp 'gnus-buffers)
1186         (push mml-preview-buffer gnus-buffers))
1187       (save-restriction
1188         (widen)
1189         (set-buffer mml-preview-buffer)
1190         (erase-buffer)
1191         (insert-buffer-substring buf))
1192       (mml-preview-insert-mail-followup-to)
1193       (let ((message-deletable-headers (if (message-news-p)
1194                                            nil
1195                                          message-deletable-headers)))
1196         (message-generate-headers
1197          (copy-sequence (if (message-news-p)
1198                             message-required-news-headers
1199                           message-required-mail-headers))))
1200       (if (re-search-forward
1201            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1202           (replace-match "\n"))
1203       (let ((mail-header-separator ""));; mail-header-separator is removed.
1204         (message-sort-headers)
1205         (mml-to-mime))
1206       (if raw
1207           (when (fboundp 'set-buffer-multibyte)
1208             (let ((s (buffer-string)))
1209               ;; Insert the content into unibyte buffer.
1210               (erase-buffer)
1211               (mm-disable-multibyte)
1212               (insert s)))
1213         (let ((gnus-newsgroup-charset (car message-posting-charset))
1214               gnus-article-prepare-hook gnus-original-article-buffer)
1215           (run-hooks 'gnus-article-decode-hook)
1216           (let ((gnus-newsgroup-name "dummy")
1217                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1218                                         (gnus-make-hashtable 5))))
1219             (gnus-article-prepare-display))))
1220       ;; Disable article-mode-map.
1221       (use-local-map nil)
1222       (gnus-make-local-hook 'kill-buffer-hook)
1223       (add-hook 'kill-buffer-hook
1224                 (lambda ()
1225                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1226       (setq buffer-read-only t)
1227       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1228       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1229       (local-set-key "\r"
1230                      (lambda ()
1231                        (interactive)
1232                        (widget-button-press (point))))
1233       (local-set-key gnus-mouse-2
1234                      (lambda (event)
1235                        (interactive "@e")
1236                        (widget-button-press (widget-event-point event) event)))
1237       (goto-char (point-min))))
1238   (if (and (boundp 'gnus-buffer-configuration)
1239            (assq 'mml-preview gnus-buffer-configuration))
1240       (let ((gnus-message-buffer (current-buffer)))
1241         (gnus-configure-windows 'mml-preview))
1242     (pop-to-buffer mml-preview-buffer)))
1243
1244 (defun mml-validate ()
1245   "Validate the current MML document."
1246   (interactive)
1247   (mml-parse))
1248
1249 (defun mml-tweak-part (cont)
1250   "Tweak a MML part."
1251   (let ((tweak (cdr (assq 'tweak cont)))
1252         func)
1253     (cond
1254      (tweak
1255       (setq func
1256             (or (cdr (assoc tweak mml-tweak-function-alist))
1257                 (intern tweak))))
1258      (mml-tweak-type-alist
1259       (let ((alist mml-tweak-type-alist)
1260             (type (or (cdr (assq 'type cont)) "text/plain")))
1261         (while alist
1262           (if (string-match (caar alist) type)
1263               (setq func (cdar alist)
1264                     alist nil)
1265             (setq alist (cdr alist)))))))
1266     (if func
1267         (funcall func cont)
1268       cont)
1269     (let ((alist mml-tweak-sexp-alist))
1270       (while alist
1271         (if (eval (caar alist))
1272             (funcall (cdar alist) cont))
1273         (setq alist (cdr alist)))))
1274   cont)
1275
1276 (defun mml-tweak-externalize-attachments (cont)
1277   "Tweak attached files as external parts."
1278   (let (filename-cons)
1279     (when (and (eq (car cont) 'part)
1280                (not (cdr (assq 'buffer cont)))
1281                (and (setq filename-cons (assq 'filename cont))
1282                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1283       (setcar cont 'external)
1284       (setcar filename-cons 'name))))
1285
1286 (provide 'mml)
1287
1288 ;;; arch-tag: 583c96cf-1ffe-451b-a5e5-4733ae9ddd12
1289 ;;; mml.el ends here