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