459173238a4a983f254f97f46bed8563cf30fd64
[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, 2006 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 'message-info "message")
42   (autoload 'fill-flowed-encode "flow-fill")
43   (autoload 'message-posting-charset "message")
44   (autoload 'dnd-get-local-file-name "dnd"))
45
46 (defvar gnus-article-mime-handles)
47 (defvar gnus-mouse-2)
48 (defvar gnus-newsrc-hashtb)
49 (defvar message-default-charset)
50 (defvar message-deletable-headers)
51 (defvar message-options)
52 (defvar message-posting-charset)
53 (defvar message-required-mail-headers)
54 (defvar message-required-news-headers)
55 (defvar dnd-protocol-alist)
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                 (let ((contents (cdr (assq 'contents cont))))
521                   (if (if (featurep 'xemacs)
522                           (string-match "[^\000-\377]" contents)
523                         (mm-multibyte-string-p contents))
524                       (progn
525                         (mm-enable-multibyte)
526                         (insert contents)
527                         (setq charset (mm-encode-body charset)))
528                     (insert contents)))))
529               (setq encoding (mm-encode-buffer type)
530                     coded (mm-string-as-multibyte (buffer-string))))
531             (mml-insert-mime-headers cont type charset encoding nil)
532             (insert "\n")
533             (mm-with-unibyte-current-buffer
534               (insert coded)))))
535        ((eq (car cont) 'external)
536         (insert "Content-Type: message/external-body")
537         (let ((parameters (mml-parameter-string
538                            cont '(expiration size permission)))
539               (name (cdr (assq 'name cont)))
540               (url (cdr (assq 'url cont))))
541           (when name
542             (setq name (mml-parse-file-name name))
543             (if (stringp name)
544                 (mml-insert-parameter
545                  (mail-header-encode-parameter "name" name)
546                  "access-type=local-file")
547               (mml-insert-parameter
548                (mail-header-encode-parameter
549                 "name" (file-name-nondirectory (nth 2 name)))
550                (mail-header-encode-parameter "site" (nth 1 name))
551                (mail-header-encode-parameter
552                 "directory" (file-name-directory (nth 2 name))))
553               (mml-insert-parameter
554                (concat "access-type="
555                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
556                            "anon-ftp"
557                          "ftp")))))
558           (when url
559             (mml-insert-parameter
560              (mail-header-encode-parameter "url" url)
561              "access-type=url"))
562           (when parameters
563             (mml-insert-parameter-string
564              cont '(expiration size permission)))
565           (insert "\n\n")
566           (insert "Content-Type: "
567                   (or (cdr (assq 'type cont))
568                       (if name
569                           (or (mm-default-file-encoding name)
570                               "application/octet-stream")
571                         "text/plain"))
572                   "\n")
573           (insert "Content-ID: " (message-make-message-id) "\n")
574           (insert "Content-Transfer-Encoding: "
575                   (or (cdr (assq 'encoding cont)) "binary"))
576           (insert "\n\n")
577           (insert (or (cdr (assq 'contents cont))))
578           (insert "\n")))
579        ((eq (car cont) 'multipart)
580         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
581                (mml-generate-default-type (if (equal type "digest")
582                                               "message/rfc822"
583                                             "text/plain"))
584                (handler (assoc type mml-generate-multipart-alist)))
585           (if handler
586               (funcall (cdr handler) cont)
587             ;; No specific handler.  Use default one.
588             (let ((mml-boundary (mml-compute-boundary cont)))
589               (insert (format "Content-Type: multipart/%s; boundary=\"%s\""
590                               type mml-boundary)
591                       (if (cdr (assq 'start cont))
592                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
593                         "\n"))
594               (let ((cont cont) part)
595                 (while (setq part (pop cont))
596                   ;; Skip `multipart' and attributes.
597                   (when (and (consp part) (consp (cdr part)))
598                     (insert "\n--" mml-boundary "\n")
599                     (mml-generate-mime-1 part)
600                     (goto-char (point-max)))))
601               (insert "\n--" mml-boundary "--\n")))))
602        (t
603         (error "Invalid element: %S" cont)))
604       ;; handle sign & encrypt tags in a semi-smart way.
605       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
606             (encrypt-item (assoc (cdr (assq 'encrypt cont))
607                                  mml-encrypt-alist))
608             sender recipients)
609         (when (or sign-item encrypt-item)
610           (when (setq sender (cdr (assq 'sender cont)))
611             (message-options-set 'mml-sender sender)
612             (message-options-set 'message-sender sender))
613           (if (setq recipients (cdr (assq 'recipients cont)))
614               (message-options-set 'message-recipients recipients))
615           (let ((style (mml-signencrypt-style
616                         (first (or sign-item encrypt-item)))))
617             ;; check if: we're both signing & encrypting, both methods
618             ;; are the same (why would they be different?!), and that
619             ;; the signencrypt style allows for combined operation.
620             (if (and sign-item encrypt-item (equal (first sign-item)
621                                                    (first encrypt-item))
622                      (equal style 'combined))
623                 (funcall (nth 1 encrypt-item) cont t)
624               ;; otherwise, revert to the old behavior.
625               (when sign-item
626                 (funcall (nth 1 sign-item) cont))
627               (when encrypt-item
628                 (funcall (nth 1 encrypt-item) cont)))))))))
629
630 (defun mml-compute-boundary (cont)
631   "Return a unique boundary that does not exist in CONT."
632   (let ((mml-boundary (funcall mml-boundary-function
633                                (incf mml-multipart-number))))
634     ;; This function tries again and again until it has found
635     ;; a unique boundary.
636     (while (not (catch 'not-unique
637                   (mml-compute-boundary-1 cont))))
638     mml-boundary))
639
640 (defun mml-compute-boundary-1 (cont)
641   (let (filename)
642     (cond
643      ((eq (car cont) 'part)
644       (with-temp-buffer
645         (cond
646          ((cdr (assq 'buffer cont))
647           (insert-buffer-substring (cdr (assq 'buffer cont))))
648          ((and (setq filename (cdr (assq 'filename cont)))
649                (not (equal (cdr (assq 'nofile cont)) "yes")))
650           (mm-insert-file-contents filename nil nil nil nil t))
651          (t
652           (insert (cdr (assq 'contents cont)))))
653         (goto-char (point-min))
654         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
655                                  nil t)
656           (setq mml-boundary (funcall mml-boundary-function
657                                       (incf mml-multipart-number)))
658           (throw 'not-unique nil))))
659      ((eq (car cont) 'multipart)
660       (mapc 'mml-compute-boundary-1 (cddr cont))))
661     t))
662
663 (defun mml-make-boundary (number)
664   (concat (make-string (% number 60) ?=)
665           (if (> number 17)
666               (format "%x" number)
667             "")
668           mml-base-boundary))
669
670 (defun mml-insert-mime-headers (cont type charset encoding flowed)
671   (let (parameters id disposition description)
672     (setq parameters
673           (mml-parameter-string
674            cont mml-content-type-parameters))
675     (when (or charset
676               parameters
677               flowed
678               (not (equal type mml-generate-default-type))
679               mml-insert-mime-headers-always)
680       (when (consp charset)
681         (error
682          "Can't encode a part with several charsets"))
683       (insert "Content-Type: " type)
684       (when charset
685         (mml-insert-parameter
686          (mail-header-encode-parameter "charset" (symbol-name charset))))
687       (when flowed
688         (mml-insert-parameter "format=flowed"))
689       (when parameters
690         (mml-insert-parameter-string
691          cont mml-content-type-parameters))
692       (insert "\n"))
693     (when (setq id (cdr (assq 'id cont)))
694       (insert "Content-ID: " id "\n"))
695     (setq parameters
696           (mml-parameter-string
697            cont mml-content-disposition-parameters))
698     (when (or (setq disposition (cdr (assq 'disposition cont)))
699               parameters)
700       (insert "Content-Disposition: " (or disposition "inline"))
701       (when parameters
702         (mml-insert-parameter-string
703          cont mml-content-disposition-parameters))
704       (insert "\n"))
705     (unless (eq encoding '7bit)
706       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
707     (when (setq description (cdr (assq 'description cont)))
708       (insert "Content-Description: ")
709       (setq description (prog1
710                             (point)
711                           (insert description "\n")))
712       (mail-encode-encoded-word-region description (point)))))
713
714 (defun mml-parameter-string (cont types)
715   (let ((string "")
716         value type)
717     (while (setq type (pop types))
718       (when (setq value (cdr (assq type cont)))
719         ;; Strip directory component from the filename parameter.
720         (when (eq type 'filename)
721           (setq value (file-name-nondirectory value)))
722         (setq string (concat string "; "
723                              (mail-header-encode-parameter
724                               (symbol-name type) value)))))
725     (when (not (zerop (length string)))
726       string)))
727
728 (defun mml-insert-parameter-string (cont types)
729   (let (value type)
730     (while (setq type (pop types))
731       (when (setq value (cdr (assq type cont)))
732         ;; Strip directory component from the filename parameter.
733         (when (eq type 'filename)
734           (setq value (file-name-nondirectory value)))
735         (mml-insert-parameter
736          (mail-header-encode-parameter
737           (symbol-name type) value))))))
738
739 (eval-when-compile
740   (defvar ange-ftp-name-format)
741   (defvar efs-path-regexp))
742 (defun mml-parse-file-name (path)
743   (if (if (boundp 'efs-path-regexp)
744           (string-match efs-path-regexp path)
745         (if (boundp 'ange-ftp-name-format)
746             (string-match (car ange-ftp-name-format) path)))
747       (list (match-string 1 path) (match-string 2 path)
748             (substring path (1+ (match-end 2))))
749     path))
750
751 (defun mml-insert-buffer (buffer)
752   "Insert BUFFER at point and quote any MML markup."
753   (save-restriction
754     (narrow-to-region (point) (point))
755     (insert-buffer-substring buffer)
756     (mml-quote-region (point-min) (point-max))
757     (goto-char (point-max))))
758
759 ;;;
760 ;;; Transforming MIME to MML
761 ;;;
762
763 (defun mime-to-mml (&optional handles)
764   "Translate the current buffer (which should be a message) into MML.
765 If HANDLES is non-nil, use it instead reparsing the buffer."
766   ;; First decode the head.
767   (save-restriction
768     (message-narrow-to-head)
769     (let ((rfc2047-quote-decoded-words-containing-tspecials t))
770       (mail-decode-encoded-word-region (point-min) (point-max))))
771   (unless handles
772     (setq handles (mm-dissect-buffer t)))
773   (goto-char (point-min))
774   (search-forward "\n\n" nil t)
775   (delete-region (point) (point-max))
776   (if (stringp (car handles))
777       (mml-insert-mime handles)
778     (mml-insert-mime handles t))
779   (mm-destroy-parts handles)
780   (save-restriction
781     (message-narrow-to-head)
782     ;; Remove them, they are confusing.
783     (message-remove-header "Content-Type")
784     (message-remove-header "MIME-Version")
785     (message-remove-header "Content-Disposition")
786     (message-remove-header "Content-Transfer-Encoding")))
787
788 (defun mml-to-mime ()
789   "Translate the current buffer from MML to MIME."
790   (message-encode-message-body)
791   (save-restriction
792     (message-narrow-to-headers-or-head)
793     ;; Skip past any From_ headers.
794     (while (looking-at "From ")
795       (forward-line 1))
796     (let ((mail-parse-charset message-default-charset))
797       (mail-encode-encoded-word-buffer))))
798
799 (defun mml-insert-mime (handle &optional no-markup)
800   (let (textp buffer mmlp)
801     ;; Determine type and stuff.
802     (unless (stringp (car handle))
803       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
804         (save-excursion
805           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
806           (mm-insert-part handle 'no-cache)
807           (if (setq mmlp (equal (mm-handle-media-type handle)
808                                 "message/rfc822"))
809               (mime-to-mml)))))
810     (if mmlp
811         (mml-insert-mml-markup handle nil t t)
812       (unless (and no-markup
813                    (equal (mm-handle-media-type handle) "text/plain"))
814         (mml-insert-mml-markup handle buffer textp)))
815     (cond
816      (mmlp
817       (insert-buffer-substring buffer)
818       (goto-char (point-max))
819       (insert "<#/mml>\n"))
820      ((stringp (car handle))
821       (mapcar 'mml-insert-mime (cdr handle))
822       (insert "<#/multipart>\n"))
823      (textp
824       (let ((charset (mail-content-type-get
825                       (mm-handle-type handle) 'charset))
826             (start (point)))
827         (if (eq charset 'gnus-decoded)
828             (mm-insert-part handle)
829           (insert (mm-decode-string (mm-get-part handle) charset)))
830         (mml-quote-region start (point)))
831       (goto-char (point-max)))
832      (t
833       (insert "<#/part>\n")))))
834
835 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
836   "Take a MIME handle and insert an MML tag."
837   (if (stringp (car handle))
838       (progn
839         (insert "<#multipart type=" (mm-handle-media-subtype handle))
840         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
841           (when start
842             (insert " start=\"" start "\"")))
843         (insert ">\n"))
844     (if mmlp
845         (insert "<#mml type=" (mm-handle-media-type handle))
846       (insert "<#part type=" (mm-handle-media-type handle)))
847     (dolist (elem (append (cdr (mm-handle-type handle))
848                           (cdr (mm-handle-disposition handle))))
849       (unless (symbolp (cdr elem))
850         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
851     (when (mm-handle-id handle)
852       (insert " id=\"" (mm-handle-id handle) "\""))
853     (when (mm-handle-disposition handle)
854       (insert " disposition=" (car (mm-handle-disposition handle))))
855     (when buffer
856       (insert " buffer=\"" (buffer-name buffer) "\""))
857     (when nofile
858       (insert " nofile=yes"))
859     (when (mm-handle-description handle)
860       (insert " description=\"" (mm-handle-description handle) "\""))
861     (insert ">\n")))
862
863 (defun mml-insert-parameter (&rest parameters)
864   "Insert PARAMETERS in a nice way."
865   (let (start end)
866     (dolist (param parameters)
867       (insert ";")
868       (setq start (point))
869       (insert " " param)
870       (setq end (point))
871       (goto-char start)
872       (end-of-line)
873       (if (> (current-column) 76)
874           (progn
875             (goto-char start)
876             (insert "\n")
877             (goto-char (1+ end)))
878         (goto-char end)))))
879
880 ;;;
881 ;;; Mode for inserting and editing MML forms
882 ;;;
883
884 (defvar mml-mode-map
885   (let ((sign (make-sparse-keymap))
886         (encrypt (make-sparse-keymap))
887         (signpart (make-sparse-keymap))
888         (encryptpart (make-sparse-keymap))
889         (map (make-sparse-keymap))
890         (main (make-sparse-keymap)))
891     (define-key map "\C-s" 'mml-secure-message-sign)
892     (define-key map "\C-c" 'mml-secure-message-encrypt)
893     (define-key map "\C-e" 'mml-secure-message-sign-encrypt)
894     (define-key map "\C-p\C-s" 'mml-secure-sign)
895     (define-key map "\C-p\C-c" 'mml-secure-encrypt)
896     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
897     (define-key sign "o" 'mml-secure-message-sign-pgp)
898     (define-key sign "s" 'mml-secure-message-sign-smime)
899     (define-key signpart "p" 'mml-secure-sign-pgpmime)
900     (define-key signpart "o" 'mml-secure-sign-pgp)
901     (define-key signpart "s" 'mml-secure-sign-smime)
902     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
903     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
904     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
905     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
906     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
907     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
908     (define-key map "\C-n" 'mml-unsecure-message)
909     (define-key map "f" 'mml-attach-file)
910     (define-key map "b" 'mml-attach-buffer)
911     (define-key map "e" 'mml-attach-external)
912     (define-key map "q" 'mml-quote-region)
913     (define-key map "m" 'mml-insert-multipart)
914     (define-key map "p" 'mml-insert-part)
915     (define-key map "v" 'mml-validate)
916     (define-key map "P" 'mml-preview)
917     (define-key map "s" sign)
918     (define-key map "S" signpart)
919     (define-key map "c" encrypt)
920     (define-key map "C" encryptpart)
921     ;;(define-key map "n" 'mml-narrow-to-part)
922     ;; `M-m' conflicts with `back-to-indentation'.
923     ;; (define-key main "\M-m" map)
924     (define-key main "\C-c\C-m" map)
925     main))
926
927 (easy-menu-define
928   mml-menu mml-mode-map ""
929   `("Attachments"
930     ["Attach File..." mml-attach-file
931      ,@(if (featurep 'xemacs) '(t)
932          '(:help "Attach a file at point"))]
933     ["Attach Buffer..." mml-attach-buffer
934      ,@(if (featurep 'xemacs) '(t)
935          '(:help "Attach a buffer to the outgoing MIME message"))]
936     ["Attach External..." mml-attach-external
937      ,@(if (featurep 'xemacs) '(t)
938          '(:help "Attach reference to file"))]
939     ;;
940     ("Change Security Method"
941      ["PGP/MIME"
942       (lambda () (interactive) (setq mml-secure-method "pgpmime"))
943       ,@(if (featurep 'xemacs) nil
944           '(:help "Set Security Method to PGP/MIME"))
945       :style radio
946       :selected (equal mml-secure-method "pgpmime") ]
947      ["S/MIME"
948       (lambda () (interactive) (setq mml-secure-method "smime"))
949       ,@(if (featurep 'xemacs) nil
950           '(:help "Set Security Method to S/MIME"))
951       :style radio
952       :selected (equal mml-secure-method "smime") ]
953      ["Inline PGP"
954       (lambda () (interactive) (setq mml-secure-method "pgp"))
955       ,@(if (featurep 'xemacs) nil
956           '(:help "Set Security Method to inline PGP"))
957       :style radio
958       :selected (equal mml-secure-method "pgp") ] )
959     ;;
960     ["Sign Message" mml-secure-message-sign t]
961     ["Encrypt Message" mml-secure-message-encrypt t]
962     ["Sign and Encrypt Message" mml-secure-message-sign-encrypt t]
963     ["Encrypt/Sign off" mml-unsecure-message
964      ,@(if (featurep 'xemacs) '(t)
965          '(:help "Don't Encrypt/Sign Message"))]
966     ;; Maybe we could remove these, because people who write MML most probably
967     ;; don't use the menu:
968     ["Insert Part..." mml-insert-part
969      :active (message-in-body-p)]
970     ["Insert Multipart..." mml-insert-multipart
971      :active (message-in-body-p)]
972     ;;
973     ;; Do we have separate encrypt and encrypt/sign commands for parts?
974     ["Sign Part" mml-secure-sign t]
975     ["Encrypt Part" mml-secure-encrypt t]
976     ;;["Narrow" mml-narrow-to-part t]
977     ["Quote MML in region" mml-quote-region
978      :active (message-mark-active-p)
979      ,@(if (featurep 'xemacs) nil
980          '(:help "Quote MML tags in region"))]
981     ["Validate MML" mml-validate t]
982     ["Preview" mml-preview t]
983     "----"
984     ["Emacs MIME manual" (lambda () (interactive) (message-info 4))
985      ,@(if (featurep 'xemacs) '(t)
986          '(:help "Display the Emacs MIME manual"))]
987     ["PGG manual" (lambda () (interactive) (message-info 16))
988      ,@(if (featurep 'xemacs) '(t)
989          '(:help "Display the PGG manual"))]))
990
991 (defvar mml-mode nil
992   "Minor mode for editing MML.")
993
994 (defun mml-mode (&optional arg)
995   "Minor mode for editing MML.
996 MML is the MIME Meta Language, a minor mode for composing MIME articles.
997 See Info node `(emacs-mime)Composing'.
998
999 \\{mml-mode-map}"
1000   (interactive "P")
1001   (when (set (make-local-variable 'mml-mode)
1002              (if (null arg) (not mml-mode)
1003                (> (prefix-numeric-value arg) 0)))
1004     (add-minor-mode 'mml-mode " MML" mml-mode-map)
1005     (easy-menu-add mml-menu mml-mode-map)
1006     (when (boundp 'dnd-protocol-alist)
1007       (set (make-local-variable 'dnd-protocol-alist)
1008            (append mml-dnd-protocol-alist dnd-protocol-alist)))
1009     (run-hooks 'mml-mode-hook)))
1010
1011 ;;;
1012 ;;; Helper functions for reading MIME stuff from the minibuffer and
1013 ;;; inserting stuff to the buffer.
1014 ;;;
1015
1016 (defcustom mml-default-directory mm-default-directory
1017   "The default directory where mml will find files.
1018 If not set, `default-directory' will be used."
1019   :type '(choice directory (const :tag "Default" nil))
1020   :version "23.0" ;; No Gnus
1021   :group 'message)
1022
1023 (defun mml-minibuffer-read-file (prompt)
1024   (let* ((completion-ignored-extensions nil)
1025          (file (read-file-name prompt
1026                                (or mml-default-directory default-directory)
1027                                nil t)))
1028     ;; Prevent some common errors.  This is inspired by similar code in
1029     ;; VM.
1030     (when (file-directory-p file)
1031       (error "%s is a directory, cannot attach" file))
1032     (unless (file-exists-p file)
1033       (error "No such file: %s" file))
1034     (unless (file-readable-p file)
1035       (error "Permission denied: %s" file))
1036     file))
1037
1038 (defun mml-minibuffer-read-type (name &optional default)
1039   (mailcap-parse-mimetypes)
1040   (let* ((default (or default
1041                       (mm-default-file-encoding name)
1042                       ;; Perhaps here we should check what the file
1043                       ;; looks like, and offer text/plain if it looks
1044                       ;; like text/plain.
1045                       "application/octet-stream"))
1046          (string (completing-read
1047                   (format "Content type (default %s): " default)
1048                   (mapcar 'list (mailcap-mime-types)))))
1049     (if (not (equal string ""))
1050         string
1051       default)))
1052
1053 (defun mml-minibuffer-read-description ()
1054   (let ((description (read-string "One line description: ")))
1055     (when (string-match "\\`[ \t]*\\'" description)
1056       (setq description nil))
1057     description))
1058
1059 (defun mml-minibuffer-read-disposition (type &optional default)
1060   (unless default (setq default
1061                         (if (and (string-match "\\`text/" type)
1062                                  (not (string-match "\\`text/rtf\\'" type)))
1063                             "inline"
1064                           "attachment")))
1065   (let ((disposition (completing-read
1066                       (format "Disposition (default %s): " default)
1067                       '(("attachment") ("inline") (""))
1068                       nil t nil nil default)))
1069     (if (not (equal disposition ""))
1070         disposition
1071       default)))
1072
1073 (defun mml-quote-region (beg end)
1074   "Quote the MML tags in the region."
1075   (interactive "r")
1076   (save-excursion
1077     (save-restriction
1078       ;; Temporarily narrow the region to defend from changes
1079       ;; invalidating END.
1080       (narrow-to-region beg end)
1081       (goto-char (point-min))
1082       ;; Quote parts.
1083       (while (re-search-forward
1084               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
1085         ;; Insert ! after the #.
1086         (goto-char (+ (match-beginning 0) 2))
1087         (insert "!")))))
1088
1089 (defun mml-insert-tag (name &rest plist)
1090   "Insert an MML tag described by NAME and PLIST."
1091   (when (symbolp name)
1092     (setq name (symbol-name name)))
1093   (insert "<#" name)
1094   (while plist
1095     (let ((key (pop plist))
1096           (value (pop plist)))
1097       (when value
1098         ;; Quote VALUE if it contains suspicious characters.
1099         (when (string-match "[\"'\\~/*;() \t\n]" value)
1100           (setq value (with-output-to-string
1101                         (let (print-escape-nonascii)
1102                           (prin1 value)))))
1103         (insert (format " %s=%s" key value)))))
1104   (insert ">\n"))
1105
1106 (defun mml-insert-empty-tag (name &rest plist)
1107   "Insert an empty MML tag described by NAME and PLIST."
1108   (when (symbolp name)
1109     (setq name (symbol-name name)))
1110   (apply #'mml-insert-tag name plist)
1111   (insert "<#/" name ">\n"))
1112
1113 ;;; Attachment functions.
1114
1115 (defcustom mml-dnd-protocol-alist
1116   '(("^file:///" . mml-dnd-attach-file)
1117     ("^file://"  . dnd-open-file)
1118     ("^file:"    . mml-dnd-attach-file))
1119   "The functions to call when a drop in `mml-mode' is made.
1120 See `dnd-protocol-alist' for more information.  When nil, behave
1121 as in other buffers."
1122   :type '(choice (repeat (cons (regexp) (function)))
1123                  (const :tag "Behave as in other buffers" nil))
1124   :version "23.0" ;; No Gnus
1125   :group 'message)
1126
1127 (defcustom mml-dnd-attach-options nil
1128   "Which options should be queried when attaching a file via drag and drop.
1129
1130 If it is a list, valid members are `type', `description' and
1131 `disposition'.  `disposition' implies `type'.  If it is nil,
1132 don't ask for options.  If it is t, ask the user whether or not
1133 to specify options."
1134   :type '(choice
1135           (const :tag "Non" nil)
1136           (const :tag "Query" t)
1137           (list :value (type description disposition)
1138            (set :inline t
1139                 (const type)
1140                 (const description)
1141                 (const disposition))))
1142   :version "23.0" ;; No Gnus
1143   :group 'message)
1144
1145 (defun mml-attach-file (file &optional type description disposition)
1146   "Attach a file to the outgoing MIME message.
1147 The file is not inserted or encoded until you send the message with
1148 `\\[message-send-and-exit]' or `\\[message-send]'.
1149
1150 FILE is the name of the file to attach.  TYPE is its
1151 content-type, a string of the form \"type/subtype\".  DESCRIPTION
1152 is a one-line description of the attachment.  The DISPOSITION
1153 specifies how the attachment is intended to be displayed.  It can
1154 be either \"inline\" (displayed automatically within the message
1155 body) or \"attachment\" (separate from the body)."
1156   (interactive
1157    (let* ((file (mml-minibuffer-read-file "Attach file: "))
1158           (type (mml-minibuffer-read-type file))
1159           (description (mml-minibuffer-read-description))
1160           (disposition (mml-minibuffer-read-disposition type)))
1161      (list file type description disposition)))
1162   (save-excursion
1163     (unless (message-in-body-p) (goto-char (point-max)))
1164     (mml-insert-empty-tag 'part
1165                           'type type
1166                           'filename file
1167                           'disposition (or disposition "attachment")
1168                           'description description)))
1169
1170 (defun mml-dnd-attach-file (uri action)
1171   "Attach a drag and drop file.
1172
1173 Ask for type, description or disposition according to
1174 `mml-dnd-attach-options'."
1175   (let ((file (dnd-get-local-file-name uri t)))
1176     (when (and file (file-regular-p file))
1177       (let ((mml-dnd-attach-options mml-dnd-attach-options)
1178             type description disposition)
1179         (setq mml-dnd-attach-options
1180               (when (and (eq mml-dnd-attach-options t)
1181                          (not
1182                           (y-or-n-p
1183                            "Use default type, disposition and description? ")))
1184                 '(type description disposition)))
1185         (when (or (memq 'type mml-dnd-attach-options)
1186                   (memq 'disposition mml-dnd-attach-options))
1187           (setq type (mml-minibuffer-read-type file)))
1188         (when (memq 'description mml-dnd-attach-options)
1189           (setq description (mml-minibuffer-read-description)))
1190         (when (memq 'disposition mml-dnd-attach-options)
1191           (setq disposition (mml-minibuffer-read-disposition type)))
1192         (mml-attach-file file type description disposition)))))
1193
1194 (defun mml-attach-buffer (buffer &optional type description)
1195   "Attach a buffer to the outgoing MIME message.
1196 See `mml-attach-file' for details of operation."
1197   (interactive
1198    (let* ((buffer (read-buffer "Attach buffer: "))
1199           (type (mml-minibuffer-read-type buffer "text/plain"))
1200           (description (mml-minibuffer-read-description)))
1201      (list buffer type description)))
1202   (save-excursion
1203     (unless (message-in-body-p) (goto-char (point-max)))
1204     (mml-insert-empty-tag 'part 'type type 'buffer buffer
1205                           'disposition "attachment"
1206                           'description description)))
1207
1208 (defun mml-attach-external (file &optional type description)
1209   "Attach an external file into the buffer.
1210 FILE is an ange-ftp/efs specification of the part location.
1211 TYPE is the MIME type to use."
1212   (interactive
1213    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1214           (type (mml-minibuffer-read-type file))
1215           (description (mml-minibuffer-read-description)))
1216      (list file type description)))
1217   (save-excursion
1218     (unless (message-in-body-p) (goto-char (point-max)))
1219     (mml-insert-empty-tag 'external 'type type 'name file
1220                           'disposition "attachment" 'description description)))
1221
1222 (defun mml-insert-multipart (&optional type)
1223   (interactive (list (completing-read "Multipart type (default mixed): "
1224                                       '(("mixed") ("alternative") ("digest") ("parallel")
1225                                         ("signed") ("encrypted"))
1226                                       nil nil "mixed")))
1227   (or type
1228       (setq type "mixed"))
1229   (mml-insert-empty-tag "multipart" 'type type)
1230   (forward-line -1))
1231
1232 (defun mml-insert-part (&optional type)
1233   (interactive
1234    (list (mml-minibuffer-read-type "")))
1235   (mml-insert-tag 'part 'type type 'disposition "inline")
1236   (forward-line -1))
1237
1238 (defun mml-preview-insert-mail-followup-to ()
1239   "Insert a Mail-Followup-To header before previewing an article.
1240 Should be adopted if code in `message-send-mail' is changed."
1241   (when (and (message-mail-p)
1242              (message-subscribed-p)
1243              (not (mail-fetch-field "mail-followup-to"))
1244              (message-make-mail-followup-to))
1245     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1246     (insert (message-make-mail-followup-to))))
1247
1248 (defvar mml-preview-buffer nil)
1249
1250 (defun mml-preview (&optional raw)
1251   "Display current buffer with Gnus, in a new buffer.
1252 If RAW, display a raw encoded MIME message.
1253
1254 The window layout for the preview buffer is controled by the variables
1255 `special-display-buffer-names', `special-display-regexps', or
1256 `gnus-buffer-configuration' (the first match made will be used),
1257 or the `pop-to-buffer' function."
1258   (interactive "P")
1259   (setq mml-preview-buffer (generate-new-buffer
1260                             (concat (if raw "*Raw MIME preview of "
1261                                       "*MIME preview of ") (buffer-name))))
1262   (save-excursion
1263     (let* ((buf (current-buffer))
1264            (message-options message-options)
1265            (message-this-is-mail (message-mail-p))
1266            (message-this-is-news (message-news-p))
1267            (message-posting-charset (or (gnus-setup-posting-charset
1268                                          (save-restriction
1269                                            (message-narrow-to-headers-or-head)
1270                                            (message-fetch-field "Newsgroups")))
1271                                         message-posting-charset)))
1272       (message-options-set-recipient)
1273       (when (boundp 'gnus-buffers)
1274         (push mml-preview-buffer gnus-buffers))
1275       (save-restriction
1276         (widen)
1277         (set-buffer mml-preview-buffer)
1278         (erase-buffer)
1279         (insert-buffer-substring buf))
1280       (mml-preview-insert-mail-followup-to)
1281       (let ((message-deletable-headers (if (message-news-p)
1282                                            nil
1283                                          message-deletable-headers)))
1284         (message-generate-headers
1285          (copy-sequence (if (message-news-p)
1286                             message-required-news-headers
1287                           message-required-mail-headers))))
1288       (if (re-search-forward
1289            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1290           (replace-match "\n"))
1291       (let ((mail-header-separator ""));; mail-header-separator is removed.
1292         (message-sort-headers)
1293         (mml-to-mime))
1294       (if raw
1295           (when (fboundp 'set-buffer-multibyte)
1296             (let ((s (buffer-string)))
1297               ;; Insert the content into unibyte buffer.
1298               (erase-buffer)
1299               (mm-disable-multibyte)
1300               (insert s)))
1301         (let ((gnus-newsgroup-charset (car message-posting-charset))
1302               gnus-article-prepare-hook gnus-original-article-buffer)
1303           (run-hooks 'gnus-article-decode-hook)
1304           (let ((gnus-newsgroup-name "dummy")
1305                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1306                                         (gnus-make-hashtable 5))))
1307             (gnus-article-prepare-display))))
1308       ;; Disable article-mode-map.
1309       (use-local-map nil)
1310       (gnus-make-local-hook 'kill-buffer-hook)
1311       (add-hook 'kill-buffer-hook
1312                 (lambda ()
1313                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1314       (setq buffer-read-only t)
1315       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1316       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1317       (local-set-key "\r"
1318                      (lambda ()
1319                        (interactive)
1320                        (widget-button-press (point))))
1321       (local-set-key gnus-mouse-2
1322                      (lambda (event)
1323                        (interactive "@e")
1324                        (widget-button-press (widget-event-point event) event)))
1325       ;; FIXME: Buffer is in article mode, but most tool bar commands won't
1326       ;; work.  Maybe only keep the following icons: search, print, quit
1327       (goto-char (point-min))))
1328   (if (and (not (mm-special-display-p (buffer-name mml-preview-buffer)))
1329            (boundp 'gnus-buffer-configuration)
1330            (assq 'mml-preview gnus-buffer-configuration))
1331       (let ((gnus-message-buffer (current-buffer)))
1332         (gnus-configure-windows 'mml-preview))
1333     (pop-to-buffer mml-preview-buffer)))
1334
1335 (defun mml-validate ()
1336   "Validate the current MML document."
1337   (interactive)
1338   (mml-parse))
1339
1340 (defun mml-tweak-part (cont)
1341   "Tweak a MML part."
1342   (let ((tweak (cdr (assq 'tweak cont)))
1343         func)
1344     (cond
1345      (tweak
1346       (setq func
1347             (or (cdr (assoc tweak mml-tweak-function-alist))
1348                 (intern tweak))))
1349      (mml-tweak-type-alist
1350       (let ((alist mml-tweak-type-alist)
1351             (type (or (cdr (assq 'type cont)) "text/plain")))
1352         (while alist
1353           (if (string-match (caar alist) type)
1354               (setq func (cdar alist)
1355                     alist nil)
1356             (setq alist (cdr alist)))))))
1357     (if func
1358         (funcall func cont)
1359       cont)
1360     (let ((alist mml-tweak-sexp-alist))
1361       (while alist
1362         (if (eval (caar alist))
1363             (funcall (cdar alist) cont))
1364         (setq alist (cdr alist)))))
1365   cont)
1366
1367 (defun mml-tweak-externalize-attachments (cont)
1368   "Tweak attached files as external parts."
1369   (let (filename-cons)
1370     (when (and (eq (car cont) 'part)
1371                (not (cdr (assq 'buffer cont)))
1372                (and (setq filename-cons (assq 'filename cont))
1373                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1374       (setcar cont 'external)
1375       (setcar filename-cons 'name))))
1376
1377 (provide 'mml)
1378
1379 ;;; arch-tag: 583c96cf-1ffe-451b-a5e5-4733ae9ddd12
1380 ;;; mml.el ends here