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