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