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