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