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