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