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