(mml-menu): Add workarounds for XEmacs.
[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.1" ;; 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' will insert an encoded Content-Description
879   ;; header in the message header if the body contains a single part
880   ;; that is specified by a user with a MML tag containing a description
881   ;; token.  So, we encode the message header first to prevent the encoded
882   ;; Content-Description header from being encoded again.
883   (save-restriction
884     (message-narrow-to-headers-or-head)
885     ;; Skip past any From_ headers.
886     (while (looking-at "From ")
887       (forward-line 1))
888     (let ((mail-parse-charset message-default-charset))
889       (mail-encode-encoded-word-buffer)))
890   (message-encode-message-body))
891
892 (defun mml-insert-mime (handle &optional no-markup)
893   (let (textp buffer mmlp)
894     ;; Determine type and stuff.
895     (unless (stringp (car handle))
896       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
897         (save-excursion
898           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
899           (mm-insert-part handle 'no-cache)
900           (if (setq mmlp (equal (mm-handle-media-type handle)
901                                 "message/rfc822"))
902               (mime-to-mml)))))
903     (if mmlp
904         (mml-insert-mml-markup handle nil t t)
905       (unless (and no-markup
906                    (equal (mm-handle-media-type handle) "text/plain"))
907         (mml-insert-mml-markup handle buffer textp)))
908     (cond
909      (mmlp
910       (insert-buffer-substring buffer)
911       (goto-char (point-max))
912       (insert "<#/mml>\n"))
913      ((stringp (car handle))
914       (mapc 'mml-insert-mime (cdr handle))
915       (insert "<#/multipart>\n"))
916      (textp
917       (let ((charset (mail-content-type-get
918                       (mm-handle-type handle) 'charset))
919             (start (point)))
920         (if (eq charset 'gnus-decoded)
921             (mm-insert-part handle)
922           (insert (mm-decode-string (mm-get-part handle) charset)))
923         (mml-quote-region start (point)))
924       (goto-char (point-max)))
925      (t
926       (insert "<#/part>\n")))))
927
928 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
929   "Take a MIME handle and insert an MML tag."
930   (if (stringp (car handle))
931       (progn
932         (insert "<#multipart type=" (mm-handle-media-subtype handle))
933         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
934           (when start
935             (insert " start=\"" start "\"")))
936         (insert ">\n"))
937     (if mmlp
938         (insert "<#mml type=" (mm-handle-media-type handle))
939       (insert "<#part type=" (mm-handle-media-type handle)))
940     (dolist (elem (append (cdr (mm-handle-type handle))
941                           (cdr (mm-handle-disposition handle))))
942       (unless (symbolp (cdr elem))
943         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
944     (when (mm-handle-id handle)
945       (insert " id=\"" (mm-handle-id handle) "\""))
946     (when (mm-handle-disposition handle)
947       (insert " disposition=" (car (mm-handle-disposition handle))))
948     (when buffer
949       (insert " buffer=\"" (buffer-name buffer) "\""))
950     (when nofile
951       (insert " nofile=yes"))
952     (when (mm-handle-description handle)
953       (insert " description=\"" (mm-handle-description handle) "\""))
954     (insert ">\n")))
955
956 (defun mml-insert-parameter (&rest parameters)
957   "Insert PARAMETERS in a nice way."
958   (let (start end)
959     (dolist (param parameters)
960       (insert ";")
961       (setq start (point))
962       (insert " " param)
963       (setq end (point))
964       (goto-char start)
965       (end-of-line)
966       (if (> (current-column) 76)
967           (progn
968             (goto-char start)
969             (insert "\n")
970             (goto-char (1+ end)))
971         (goto-char end)))))
972
973 ;;;
974 ;;; Mode for inserting and editing MML forms
975 ;;;
976
977 (defvar mml-mode-map
978   (let ((sign (make-sparse-keymap))
979         (encrypt (make-sparse-keymap))
980         (signpart (make-sparse-keymap))
981         (encryptpart (make-sparse-keymap))
982         (map (make-sparse-keymap))
983         (main (make-sparse-keymap)))
984     (define-key map "\C-s" 'mml-secure-message-sign)
985     (define-key map "\C-c" 'mml-secure-message-encrypt)
986     (define-key map "\C-e" 'mml-secure-message-sign-encrypt)
987     (define-key map "\C-p\C-s" 'mml-secure-sign)
988     (define-key map "\C-p\C-c" 'mml-secure-encrypt)
989     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
990     (define-key sign "o" 'mml-secure-message-sign-pgp)
991     (define-key sign "s" 'mml-secure-message-sign-smime)
992     (define-key signpart "p" 'mml-secure-sign-pgpmime)
993     (define-key signpart "o" 'mml-secure-sign-pgp)
994     (define-key signpart "s" 'mml-secure-sign-smime)
995     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
996     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
997     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
998     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
999     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
1000     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
1001     (define-key map "\C-n" 'mml-unsecure-message)
1002     (define-key map "f" 'mml-attach-file)
1003     (define-key map "b" 'mml-attach-buffer)
1004     (define-key map "e" 'mml-attach-external)
1005     (define-key map "q" 'mml-quote-region)
1006     (define-key map "m" 'mml-insert-multipart)
1007     (define-key map "p" 'mml-insert-part)
1008     (define-key map "v" 'mml-validate)
1009     (define-key map "P" 'mml-preview)
1010     (define-key map "s" sign)
1011     (define-key map "S" signpart)
1012     (define-key map "c" encrypt)
1013     (define-key map "C" encryptpart)
1014     ;;(define-key map "n" 'mml-narrow-to-part)
1015     ;; `M-m' conflicts with `back-to-indentation'.
1016     ;; (define-key main "\M-m" map)
1017     (define-key main "\C-c\C-m" map)
1018     main))
1019
1020 (easy-menu-define
1021   mml-menu mml-mode-map ""
1022   `("Attachments"
1023     ["Attach File..." mml-attach-file
1024      ,@(if (featurep 'xemacs) '(t)
1025          '(:help "Attach a file at point"))]
1026     ["Attach Buffer..." mml-attach-buffer
1027      ,@(if (featurep 'xemacs) '(t)
1028          '(:help "Attach a buffer to the outgoing message"))]
1029     ["Attach External..." mml-attach-external
1030      ,@(if (featurep 'xemacs) '(t)
1031          '(:help "Attach reference to an external file"))]
1032     ;; FIXME: Is it possible to do this without using
1033     ;; `gnus-gcc-externalize-attachments'?
1034     ["Externalize Attachments"
1035      (lambda ()
1036        (interactive)
1037        (if (not (and (boundp 'gnus-gcc-externalize-attachments)
1038                      (memq gnus-gcc-externalize-attachments
1039                            '(all t nil))))
1040            ;; Stupid workaround for XEmacs not honoring :visible.
1041            (message "Can't handle this value of `gnus-gcc-externalize-attachments'")
1042          (setq gnus-gcc-externalize-attachments
1043                (not gnus-gcc-externalize-attachments))
1044          (message "gnus-gcc-externalize-attachments is `%s'."
1045                   gnus-gcc-externalize-attachments)))
1046      ;; XEmacs barfs on :visible.
1047      ,@(if (featurep 'xemacs) nil
1048          '(:visible (and (boundp 'gnus-gcc-externalize-attachments)
1049                          (memq gnus-gcc-externalize-attachments
1050                                '(all t nil)))))
1051      :style toggle
1052      :selected gnus-gcc-externalize-attachments
1053      ,@(if (featurep 'xemacs) nil
1054          '(:help "Save attachments as external parts in Gcc copies"))]
1055     "----"
1056     ;;
1057     ("Change Security Method"
1058      ["PGP/MIME"
1059       (lambda () (interactive) (setq mml-secure-method "pgpmime"))
1060       ,@(if (featurep 'xemacs) nil
1061           '(:help "Set Security Method to PGP/MIME"))
1062       :style radio
1063       :selected (equal mml-secure-method "pgpmime") ]
1064      ["S/MIME"
1065       (lambda () (interactive) (setq mml-secure-method "smime"))
1066       ,@(if (featurep 'xemacs) nil
1067           '(:help "Set Security Method to S/MIME"))
1068       :style radio
1069       :selected (equal mml-secure-method "smime") ]
1070      ["Inline PGP"
1071       (lambda () (interactive) (setq mml-secure-method "pgp"))
1072       ,@(if (featurep 'xemacs) nil
1073           '(:help "Set Security Method to inline PGP"))
1074       :style radio
1075       :selected (equal mml-secure-method "pgp") ] )
1076     ;;
1077     ["Sign Message" mml-secure-message-sign t]
1078     ["Encrypt Message" mml-secure-message-encrypt t]
1079     ["Sign and Encrypt Message" mml-secure-message-sign-encrypt t]
1080     ["Encrypt/Sign off" mml-unsecure-message
1081      ,@(if (featurep 'xemacs) '(t)
1082          '(:help "Don't Encrypt/Sign Message"))]
1083     ;; Do we have separate encrypt and encrypt/sign commands for parts?
1084     ["Sign Part" mml-secure-sign t]
1085     ["Encrypt Part" mml-secure-encrypt t]
1086     "----"
1087     ;; Maybe we could remove these, because people who write MML most probably
1088     ;; don't use the menu:
1089     ["Insert Part..." mml-insert-part
1090      :active (message-in-body-p)]
1091     ["Insert Multipart..." mml-insert-multipart
1092      :active (message-in-body-p)]
1093     ;;
1094     ;;["Narrow" mml-narrow-to-part t]
1095     ["Quote MML in region" mml-quote-region
1096      :active (message-mark-active-p)
1097      ,@(if (featurep 'xemacs) nil
1098          '(:help "Quote MML tags in region"))]
1099     ["Validate MML" mml-validate t]
1100     ["Preview" mml-preview t]
1101     "----"
1102     ["Emacs MIME manual" (lambda () (interactive) (message-info 4))
1103      ,@(if (featurep 'xemacs) '(t)
1104          '(:help "Display the Emacs MIME manual"))]
1105     ["PGG manual" (lambda () (interactive) (message-info mml2015-use))
1106      ;; XEmacs barfs on :visible.
1107      ,@(if (featurep 'xemacs) nil
1108          '(:visible (equal mml2015-use 'pgg)))
1109      ,@(if (featurep 'xemacs) '(t)
1110          '(:help "Display the PGG manual"))]
1111     ["EasyPG manual" (lambda () (interactive) (message-info mml2015-use))
1112      ;; XEmacs barfs on :visible.
1113      ,@(if (featurep 'xemacs) nil
1114          '(:visible (equal mml2015-use 'epg)))
1115      ,@(if (featurep 'xemacs) '(t)
1116          '(:help "Display the EasyPG manual"))]))
1117
1118 (defvar mml-mode nil
1119   "Minor mode for editing MML.")
1120
1121 (defun mml-mode (&optional arg)
1122   "Minor mode for editing MML.
1123 MML is the MIME Meta Language, a minor mode for composing MIME articles.
1124 See Info node `(emacs-mime)Composing'.
1125
1126 \\{mml-mode-map}"
1127   (interactive "P")
1128   (when (set (make-local-variable 'mml-mode)
1129              (if (null arg) (not mml-mode)
1130                (> (prefix-numeric-value arg) 0)))
1131     (add-minor-mode 'mml-mode " MML" mml-mode-map)
1132     (easy-menu-add mml-menu mml-mode-map)
1133     (when (boundp 'dnd-protocol-alist)
1134       (set (make-local-variable 'dnd-protocol-alist)
1135            (append mml-dnd-protocol-alist dnd-protocol-alist)))
1136     (run-hooks 'mml-mode-hook)))
1137
1138 ;;;
1139 ;;; Helper functions for reading MIME stuff from the minibuffer and
1140 ;;; inserting stuff to the buffer.
1141 ;;;
1142
1143 (defcustom mml-default-directory mm-default-directory
1144   "The default directory where mml will find files.
1145 If not set, `default-directory' will be used."
1146   :type '(choice directory (const :tag "Default" nil))
1147   :version "23.1" ;; No Gnus
1148   :group 'message)
1149
1150 (defun mml-minibuffer-read-file (prompt)
1151   (let* ((completion-ignored-extensions nil)
1152          (file (read-file-name prompt
1153                                (or mml-default-directory default-directory)
1154                                nil t)))
1155     ;; Prevent some common errors.  This is inspired by similar code in
1156     ;; VM.
1157     (when (file-directory-p file)
1158       (error "%s is a directory, cannot attach" file))
1159     (unless (file-exists-p file)
1160       (error "No such file: %s" file))
1161     (unless (file-readable-p file)
1162       (error "Permission denied: %s" file))
1163     file))
1164
1165 (defun mml-minibuffer-read-type (name &optional default)
1166   (mailcap-parse-mimetypes)
1167   (let* ((default (or default
1168                       (mm-default-file-encoding name)
1169                       ;; Perhaps here we should check what the file
1170                       ;; looks like, and offer text/plain if it looks
1171                       ;; like text/plain.
1172                       "application/octet-stream"))
1173          (string (completing-read
1174                   (format "Content type (default %s): " default)
1175                   (mapcar 'list (mailcap-mime-types)))))
1176     (if (not (equal string ""))
1177         string
1178       default)))
1179
1180 (defun mml-minibuffer-read-description ()
1181   (let ((description (read-string "One line description: ")))
1182     (when (string-match "\\`[ \t]*\\'" description)
1183       (setq description nil))
1184     description))
1185
1186 (defun mml-minibuffer-read-disposition (type &optional default filename)
1187   (unless default
1188     (setq default (mml-content-disposition type filename)))
1189   (let ((disposition (completing-read
1190                       (format "Disposition (default %s): " default)
1191                       '(("attachment") ("inline") (""))
1192                       nil t nil nil default)))
1193     (if (not (equal disposition ""))
1194         disposition
1195       default)))
1196
1197 (defun mml-quote-region (beg end)
1198   "Quote the MML tags in the region."
1199   (interactive "r")
1200   (save-excursion
1201     (save-restriction
1202       ;; Temporarily narrow the region to defend from changes
1203       ;; invalidating END.
1204       (narrow-to-region beg end)
1205       (goto-char (point-min))
1206       ;; Quote parts.
1207       (while (re-search-forward
1208               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
1209         ;; Insert ! after the #.
1210         (goto-char (+ (match-beginning 0) 2))
1211         (insert "!")))))
1212
1213 (defun mml-insert-tag (name &rest plist)
1214   "Insert an MML tag described by NAME and PLIST."
1215   (when (symbolp name)
1216     (setq name (symbol-name name)))
1217   (insert "<#" name)
1218   (while plist
1219     (let ((key (pop plist))
1220           (value (pop plist)))
1221       (when value
1222         ;; Quote VALUE if it contains suspicious characters.
1223         (when (string-match "[\"'\\~/*;() \t\n]" value)
1224           (setq value (with-output-to-string
1225                         (let (print-escape-nonascii)
1226                           (prin1 value)))))
1227         (insert (format " %s=%s" key value)))))
1228   (insert ">\n"))
1229
1230 (defun mml-insert-empty-tag (name &rest plist)
1231   "Insert an empty MML tag described by NAME and PLIST."
1232   (when (symbolp name)
1233     (setq name (symbol-name name)))
1234   (apply #'mml-insert-tag name plist)
1235   (insert "<#/" name ">\n"))
1236
1237 ;;; Attachment functions.
1238
1239 (defcustom mml-dnd-protocol-alist
1240   '(("^file:///" . mml-dnd-attach-file)
1241     ("^file://"  . dnd-open-file)
1242     ("^file:"    . mml-dnd-attach-file))
1243   "The functions to call when a drop in `mml-mode' is made.
1244 See `dnd-protocol-alist' for more information.  When nil, behave
1245 as in other buffers."
1246   :type '(choice (repeat (cons (regexp) (function)))
1247                  (const :tag "Behave as in other buffers" nil))
1248   :version "22.1" ;; Gnus 5.10.9
1249   :group 'message)
1250
1251 (defcustom mml-dnd-attach-options nil
1252   "Which options should be queried when attaching a file via drag and drop.
1253
1254 If it is a list, valid members are `type', `description' and
1255 `disposition'.  `disposition' implies `type'.  If it is nil,
1256 don't ask for options.  If it is t, ask the user whether or not
1257 to specify options."
1258   :type '(choice
1259           (const :tag "None" nil)
1260           (const :tag "Query" t)
1261           (list :value (type description disposition)
1262            (set :inline t
1263                 (const type)
1264                 (const description)
1265                 (const disposition))))
1266   :version "22.1" ;; Gnus 5.10.9
1267   :group 'message)
1268
1269 (defun mml-attach-file (file &optional type description disposition)
1270   "Attach a file to the outgoing MIME message.
1271 The file is not inserted or encoded until you send the message with
1272 `\\[message-send-and-exit]' or `\\[message-send]'.
1273
1274 FILE is the name of the file to attach.  TYPE is its
1275 content-type, a string of the form \"type/subtype\".  DESCRIPTION
1276 is a one-line description of the attachment.  The DISPOSITION
1277 specifies how the attachment is intended to be displayed.  It can
1278 be either \"inline\" (displayed automatically within the message
1279 body) or \"attachment\" (separate from the body)."
1280   (interactive
1281    (let* ((file (mml-minibuffer-read-file "Attach file: "))
1282           (type (mml-minibuffer-read-type file))
1283           (description (mml-minibuffer-read-description))
1284           (disposition (mml-minibuffer-read-disposition type nil file)))
1285      (list file type description disposition)))
1286   (save-excursion
1287     (unless (message-in-body-p) (goto-char (point-max)))
1288     (mml-insert-empty-tag 'part
1289                           'type type
1290                           'filename file
1291                           'disposition (or disposition "attachment")
1292                           'description description)))
1293
1294 (defun mml-dnd-attach-file (uri action)
1295   "Attach a drag and drop file.
1296
1297 Ask for type, description or disposition according to
1298 `mml-dnd-attach-options'."
1299   (let ((file (dnd-get-local-file-name uri t)))
1300     (when (and file (file-regular-p file))
1301       (let ((mml-dnd-attach-options mml-dnd-attach-options)
1302             type description disposition)
1303         (setq mml-dnd-attach-options
1304               (when (and (eq mml-dnd-attach-options t)
1305                          (not
1306                           (y-or-n-p
1307                            "Use default type, disposition and description? ")))
1308                 '(type description disposition)))
1309         (when (or (memq 'type mml-dnd-attach-options)
1310                   (memq 'disposition mml-dnd-attach-options))
1311           (setq type (mml-minibuffer-read-type file)))
1312         (when (memq 'description mml-dnd-attach-options)
1313           (setq description (mml-minibuffer-read-description)))
1314         (when (memq 'disposition mml-dnd-attach-options)
1315           (setq disposition (mml-minibuffer-read-disposition type nil file)))
1316         (mml-attach-file file type description disposition)))))
1317
1318 (defun mml-attach-buffer (buffer &optional type description)
1319   "Attach a buffer to the outgoing MIME message.
1320 See `mml-attach-file' for details of operation."
1321   (interactive
1322    (let* ((buffer (read-buffer "Attach buffer: "))
1323           (type (mml-minibuffer-read-type buffer "text/plain"))
1324           (description (mml-minibuffer-read-description)))
1325      (list buffer type description)))
1326   (save-excursion
1327     (unless (message-in-body-p) (goto-char (point-max)))
1328     (mml-insert-empty-tag 'part 'type type 'buffer buffer
1329                           'disposition "attachment"
1330                           'description description)))
1331
1332 (defun mml-attach-external (file &optional type description)
1333   "Attach an external file into the buffer.
1334 FILE is an ange-ftp/efs specification of the part location.
1335 TYPE is the MIME type to use."
1336   (interactive
1337    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1338           (type (mml-minibuffer-read-type file))
1339           (description (mml-minibuffer-read-description)))
1340      (list file type description)))
1341   (save-excursion
1342     (unless (message-in-body-p) (goto-char (point-max)))
1343     (mml-insert-empty-tag 'external 'type type 'name file
1344                           'disposition "attachment" 'description description)))
1345
1346 (defun mml-insert-multipart (&optional type)
1347   (interactive (list (completing-read "Multipart type (default mixed): "
1348                                       '(("mixed") ("alternative") ("digest") ("parallel")
1349                                         ("signed") ("encrypted"))
1350                                       nil nil "mixed")))
1351   (or type
1352       (setq type "mixed"))
1353   (mml-insert-empty-tag "multipart" 'type type)
1354   (forward-line -1))
1355
1356 (defun mml-insert-part (&optional type)
1357   (interactive
1358    (list (mml-minibuffer-read-type "")))
1359   (mml-insert-tag 'part 'type type 'disposition "inline")
1360   (forward-line -1))
1361
1362 (declare-function message-subscribed-p "message" ())
1363 (declare-function message-make-mail-followup-to "message"
1364                   (&optional only-show-subscribed))
1365 (declare-function message-position-on-field "message" (header &rest afters))
1366
1367 (defun mml-preview-insert-mail-followup-to ()
1368   "Insert a Mail-Followup-To header before previewing an article.
1369 Should be adopted if code in `message-send-mail' is changed."
1370   (when (and (message-mail-p)
1371              (message-subscribed-p)
1372              (not (mail-fetch-field "mail-followup-to"))
1373              (message-make-mail-followup-to))
1374     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1375     (insert (message-make-mail-followup-to))))
1376
1377 (defvar mml-preview-buffer nil)
1378
1379 (autoload 'gnus-make-hashtable "gnus-util")
1380 (autoload 'widget-button-press "wid-edit" nil t)
1381 (declare-function widget-event-point "wid-edit" (event))
1382 ;; If gnus-buffer-configuration is bound this is loaded.
1383 (declare-function gnus-configure-windows "gnus-win" (setting &optional force))
1384 ;; Called after message-mail-p, which autoloads message.
1385 (declare-function message-news-p                "message" ())
1386 (declare-function message-options-set-recipient "message" ())
1387 (declare-function message-generate-headers      "message" (headers))
1388 (declare-function message-sort-headers          "message" ())
1389
1390 (defun mml-preview (&optional raw)
1391   "Display current buffer with Gnus, in a new buffer.
1392 If RAW, display a raw encoded MIME message.
1393
1394 The window layout for the preview buffer is controled by the variables
1395 `special-display-buffer-names', `special-display-regexps', or
1396 `gnus-buffer-configuration' (the first match made will be used),
1397 or the `pop-to-buffer' function."
1398   (interactive "P")
1399   (setq mml-preview-buffer (generate-new-buffer
1400                             (concat (if raw "*Raw MIME preview of "
1401                                       "*MIME preview of ") (buffer-name))))
1402   (save-excursion
1403     (let* ((buf (current-buffer))
1404            (message-options message-options)
1405            (message-this-is-mail (message-mail-p))
1406            (message-this-is-news (message-news-p))
1407            (message-posting-charset (or (gnus-setup-posting-charset
1408                                          (save-restriction
1409                                            (message-narrow-to-headers-or-head)
1410                                            (message-fetch-field "Newsgroups")))
1411                                         message-posting-charset)))
1412       (message-options-set-recipient)
1413       (when (boundp 'gnus-buffers)
1414         (push mml-preview-buffer gnus-buffers))
1415       (save-restriction
1416         (widen)
1417         (set-buffer mml-preview-buffer)
1418         (erase-buffer)
1419         (insert-buffer-substring buf))
1420       (mml-preview-insert-mail-followup-to)
1421       (let ((message-deletable-headers (if (message-news-p)
1422                                            nil
1423                                          message-deletable-headers)))
1424         (message-generate-headers
1425          (copy-sequence (if (message-news-p)
1426                             message-required-news-headers
1427                           message-required-mail-headers))))
1428       (if (re-search-forward
1429            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1430           (replace-match "\n"))
1431       (let ((mail-header-separator ""));; mail-header-separator is removed.
1432         (message-sort-headers)
1433         (mml-to-mime))
1434       (if raw
1435           (when (fboundp 'set-buffer-multibyte)
1436             (let ((s (buffer-string)))
1437               ;; Insert the content into unibyte buffer.
1438               (erase-buffer)
1439               (mm-disable-multibyte)
1440               (insert s)))
1441         (let ((gnus-newsgroup-charset (car message-posting-charset))
1442               gnus-article-prepare-hook gnus-original-article-buffer)
1443           (run-hooks 'gnus-article-decode-hook)
1444           (let ((gnus-newsgroup-name "dummy")
1445                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1446                                         (gnus-make-hashtable 5))))
1447             (gnus-article-prepare-display))))
1448       ;; Disable article-mode-map.
1449       (use-local-map nil)
1450       (gnus-make-local-hook 'kill-buffer-hook)
1451       (add-hook 'kill-buffer-hook
1452                 (lambda ()
1453                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1454       (setq buffer-read-only t)
1455       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1456       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1457       (local-set-key "\r"
1458                      (lambda ()
1459                        (interactive)
1460                        (widget-button-press (point))))
1461       (local-set-key gnus-mouse-2
1462                      (lambda (event)
1463                        (interactive "@e")
1464                        (widget-button-press (widget-event-point event) event)))
1465       ;; FIXME: Buffer is in article mode, but most tool bar commands won't
1466       ;; work.  Maybe only keep the following icons: search, print, quit
1467       (goto-char (point-min))))
1468   (if (and (not (mm-special-display-p (buffer-name mml-preview-buffer)))
1469            (boundp 'gnus-buffer-configuration)
1470            (assq 'mml-preview gnus-buffer-configuration))
1471       (let ((gnus-message-buffer (current-buffer)))
1472         (gnus-configure-windows 'mml-preview))
1473     (pop-to-buffer mml-preview-buffer)))
1474
1475 (defun mml-validate ()
1476   "Validate the current MML document."
1477   (interactive)
1478   (mml-parse))
1479
1480 (defun mml-tweak-part (cont)
1481   "Tweak a MML part."
1482   (let ((tweak (cdr (assq 'tweak cont)))
1483         func)
1484     (cond
1485      (tweak
1486       (setq func
1487             (or (cdr (assoc tweak mml-tweak-function-alist))
1488                 (intern tweak))))
1489      (mml-tweak-type-alist
1490       (let ((alist mml-tweak-type-alist)
1491             (type (or (cdr (assq 'type cont)) "text/plain")))
1492         (while alist
1493           (if (string-match (caar alist) type)
1494               (setq func (cdar alist)
1495                     alist nil)
1496             (setq alist (cdr alist)))))))
1497     (if func
1498         (funcall func cont)
1499       cont)
1500     (let ((alist mml-tweak-sexp-alist))
1501       (while alist
1502         (if (eval (caar alist))
1503             (funcall (cdar alist) cont))
1504         (setq alist (cdr alist)))))
1505   cont)
1506
1507 (defun mml-tweak-externalize-attachments (cont)
1508   "Tweak attached files as external parts."
1509   (let (filename-cons)
1510     (when (and (eq (car cont) 'part)
1511                (not (cdr (assq 'buffer cont)))
1512                (and (setq filename-cons (assq 'filename cont))
1513                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1514       (setcar cont 'external)
1515       (setcar filename-cons 'name))))
1516
1517 (provide 'mml)
1518
1519 ;;; arch-tag: 583c96cf-1ffe-451b-a5e5-4733ae9ddd12
1520 ;;; mml.el ends here