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