168fe4908c68d7c231602dbb8ba516abac15c38a
[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 (declare-function libxml-parse-html-region "xml.c"
463                   (start end &optional base-url))
464
465 (defun mml-generate-mime (&optional multipart-type)
466   "Generate a MIME message based on the current MML document.
467 MULTIPART-TYPE defaults to \"mixed\", but can also
468 be \"related\" or \"alternate\"."
469   (let ((cont (mml-parse))
470         (mml-multipart-number mml-multipart-number)
471         (options message-options))
472     (if (not cont)
473         nil
474       (when (and (consp (car cont))
475                  (= (length cont) 1)
476                  (fboundp 'libxml-parse-html-region)
477                  (equal (cdr (assq 'type (car cont))) "text/html"))
478         (setq cont (mml-expand-html-into-multipart-related (car cont))))
479       (prog1
480           (mm-with-multibyte-buffer
481             (setq message-options options)
482             (cond
483              ((and (consp (car cont))
484                    (= (length cont) 1))
485               (mml-generate-mime-1 (car cont)))
486              ((eq (car cont) 'multipart)
487               (mml-generate-mime-1 cont))
488              (t
489               (mml-generate-mime-1
490                (nconc (list 'multipart (cons 'type (or multipart-type "mixed")))
491                       cont))))
492             (setq options message-options)
493             (buffer-string))
494         (setq message-options options)))))
495
496 (defun mml-expand-html-into-multipart-related (cont)
497   (let ((new-parts nil)
498         (cid 1))
499     (mm-with-multibyte-buffer
500       (insert (cdr (assq 'contents cont)))
501       (goto-char (point-min))
502       (with-syntax-table mml-syntax-table
503         (while (re-search-forward "<img\\b" nil t)
504           (goto-char (match-beginning 0))
505           (let* ((start (point))
506                  (img (nth 2
507                            (nth 2
508                                 (libxml-parse-html-region
509                                  (point) (progn (forward-sexp) (point))))))
510                  (end (point))
511                  (parsed (url-generic-parse-url (cdr (assq 'src (cadr img))))))
512             (when (and (null (url-type parsed))
513                        (url-filename parsed)
514                        (file-exists-p (url-filename parsed)))
515               (goto-char start)
516               (when (search-forward (url-filename parsed) end t)
517                 (let ((cid (format "fsf.%d" cid)))
518                   (replace-match (concat "cid:" cid) t t)
519                   (push (list cid (url-filename parsed)) new-parts))
520                 (setq cid (1+ cid)))))))
521       ;; We have local images that we want to include.
522       (if (not new-parts)
523           (list cont)
524         (setcdr (assq 'contents cont) (buffer-string))
525         (setq cont
526               (nconc (list 'multipart (cons 'type "related"))
527                      (list cont)))
528         (dolist (new-part (nreverse new-parts))
529           (setq cont
530                 (nconc cont
531                        (list `(part (type . "image/png")
532                                     (filename . ,(nth 1 new-part))
533                                     (id . ,(concat "<" (nth 0 new-part)
534                                                    ">")))))))
535         cont))))
536
537 (defun mml-generate-mime-1 (cont)
538   (let ((mm-use-ultra-safe-encoding
539          (or mm-use-ultra-safe-encoding (assq 'sign cont))))
540     (save-restriction
541       (narrow-to-region (point) (point))
542       (mml-tweak-part cont)
543       (cond
544        ((or (eq (car cont) 'part) (eq (car cont) 'mml))
545         (let* ((raw (cdr (assq 'raw cont)))
546                (filename (cdr (assq 'filename cont)))
547                (type (or (cdr (assq 'type cont))
548                          (if filename
549                              (or (mm-default-file-encoding filename)
550                                  "application/octet-stream")
551                            "text/plain")))
552                (charset (cdr (assq 'charset cont)))
553                (coding (mm-charset-to-coding-system charset))
554                encoding flowed coded)
555           (cond ((eq coding 'ascii)
556                  (setq charset nil
557                        coding nil))
558                 (charset
559                  ;; The value of `charset' might be a bogus alias that
560                  ;; `mm-charset-synonym-alist' provides, like `utf8',
561                  ;; so we prefer the MIME charset that Emacs knows for
562                  ;; the coding system `coding'.
563                  (setq charset (or (mm-coding-system-to-mime-charset coding)
564                                    (intern (downcase charset))))))
565           (if (and (not raw)
566                    (member (car (split-string type "/")) '("text" "message")))
567               (progn
568                 (with-temp-buffer
569                   (cond
570                    ((cdr (assq 'buffer cont))
571                     (insert-buffer-substring (cdr (assq 'buffer cont))))
572                    ((and filename
573                          (not (equal (cdr (assq 'nofile cont)) "yes")))
574                     (let ((coding-system-for-read coding))
575                       (mm-insert-file-contents filename)))
576                    ((eq 'mml (car cont))
577                     (insert (cdr (assq 'contents cont))))
578                    (t
579                     (save-restriction
580                       (narrow-to-region (point) (point))
581                       (insert (cdr (assq 'contents cont)))
582                       ;; Remove quotes from quoted tags.
583                       (goto-char (point-min))
584                       (while (re-search-forward
585                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\|secure\\)"
586                               nil t)
587                         (delete-region (+ (match-beginning 0) 2)
588                                        (+ (match-beginning 0) 3))))))
589                   (cond
590                    ((eq (car cont) 'mml)
591                     (let ((mml-boundary (mml-compute-boundary cont))
592                           ;; It is necessary for the case where this
593                           ;; function is called recursively since
594                           ;; `m-g-d-t' will be bound to "message/rfc822"
595                           ;; when encoding an article to be forwarded.
596                           (mml-generate-default-type "text/plain"))
597                       (mml-to-mime)
598                       ;; Update handle so mml-compute-boundary can
599                       ;; detect collisions with the nested parts.
600                       (unless mml-inhibit-compute-boundary
601                         (setcdr (assoc 'contents cont) (buffer-string))))
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                    ((string= (car (split-string type "/")) "message")
606                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
607                       ;; ignore 0x1b, it is part of iso-2022-jp
608                       (setq encoding (mm-body-7-or-8))))
609                    (t
610                     ;; Only perform format=flowed filling on text/plain
611                     ;; parts where there either isn't a format parameter
612                     ;; in the mml tag or it says "flowed" and there
613                     ;; actually are hard newlines in the text.
614                     (let (use-hard-newlines)
615                       (when (and mml-enable-flowed
616                                  (string= type "text/plain")
617                                  (not (string= (cdr (assq 'sign cont)) "pgp"))
618                                  (or (null (assq 'format cont))
619                                      (string= (cdr (assq 'format cont))
620                                               "flowed"))
621                                  (setq use-hard-newlines
622                                        (text-property-any
623                                         (point-min) (point-max) 'hard 't)))
624                         (fill-flowed-encode)
625                         ;; Indicate that `mml-insert-mime-headers' should
626                         ;; insert a "; format=flowed" string unless the
627                         ;; user has already specified it.
628                         (setq flowed (null (assq 'format cont)))))
629                     ;; Prefer `utf-8' for text/calendar parts.
630                     (if (or charset
631                             (not (string= type "text/calendar")))
632                         (setq charset (mm-encode-body charset))
633                       (let ((mm-coding-system-priorities
634                              (cons 'utf-8 mm-coding-system-priorities)))
635                         (setq charset (mm-encode-body))))
636                     (setq encoding (mm-body-encoding
637                                     charset (cdr (assq 'encoding cont))))))
638                   (setq coded (buffer-string)))
639                 (mml-insert-mime-headers cont type charset encoding flowed)
640                 (insert "\n")
641                 (insert coded))
642             (mm-with-unibyte-buffer
643               (cond
644                ((cdr (assq 'buffer cont))
645                 (insert (mm-string-as-unibyte
646                          (with-current-buffer (cdr (assq 'buffer cont))
647                            (buffer-string)))))
648                ((and filename
649                      (not (equal (cdr (assq 'nofile cont)) "yes")))
650                 (let ((coding-system-for-read mm-binary-coding-system))
651                   (mm-insert-file-contents filename nil nil nil nil t))
652                 (unless charset
653                   (setq charset (mm-coding-system-to-mime-charset
654                                  (mm-find-buffer-file-coding-system
655                                   filename)))))
656                (t
657                 (let ((contents (cdr (assq 'contents cont))))
658                   (if (if (featurep 'xemacs)
659                           (string-match "[^\000-\377]" contents)
660                         (mm-multibyte-string-p contents))
661                       (progn
662                         (mm-enable-multibyte)
663                         (insert contents)
664                         (unless raw
665                           (setq charset (mm-encode-body charset))))
666                     (insert contents)))))
667               (if (setq encoding (cdr (assq 'encoding cont)))
668                   (setq encoding (intern (downcase encoding))))
669               (setq encoding (mm-encode-buffer type encoding)
670                     coded (mm-string-as-multibyte (buffer-string))))
671             (mml-insert-mime-headers cont type charset encoding nil)
672             (insert "\n" coded))))
673        ((eq (car cont) 'external)
674         (insert "Content-Type: message/external-body")
675         (let ((parameters (mml-parameter-string
676                            cont '(expiration size permission)))
677               (name (cdr (assq 'name cont)))
678               (url (cdr (assq 'url cont))))
679           (when name
680             (setq name (mml-parse-file-name name))
681             (if (stringp name)
682                 (mml-insert-parameter
683                  (mail-header-encode-parameter "name" name)
684                  "access-type=local-file")
685               (mml-insert-parameter
686                (mail-header-encode-parameter
687                 "name" (file-name-nondirectory (nth 2 name)))
688                (mail-header-encode-parameter "site" (nth 1 name))
689                (mail-header-encode-parameter
690                 "directory" (file-name-directory (nth 2 name))))
691               (mml-insert-parameter
692                (concat "access-type="
693                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
694                            "anon-ftp"
695                          "ftp")))))
696           (when url
697             (mml-insert-parameter
698              (mail-header-encode-parameter "url" url)
699              "access-type=url"))
700           (when parameters
701             (mml-insert-parameter-string
702              cont '(expiration size permission)))
703           (insert "\n\n")
704           (insert "Content-Type: "
705                   (or (cdr (assq 'type cont))
706                       (if name
707                           (or (mm-default-file-encoding name)
708                               "application/octet-stream")
709                         "text/plain"))
710                   "\n")
711           (insert "Content-ID: " (message-make-message-id) "\n")
712           (insert "Content-Transfer-Encoding: "
713                   (or (cdr (assq 'encoding cont)) "binary"))
714           (insert "\n\n")
715           (insert (or (cdr (assq 'contents cont))))
716           (insert "\n")))
717        ((eq (car cont) 'multipart)
718         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
719                (mml-generate-default-type (if (equal type "digest")
720                                               "message/rfc822"
721                                             "text/plain"))
722                (handler (assoc type mml-generate-multipart-alist)))
723           (if handler
724               (funcall (cdr handler) cont)
725             ;; No specific handler.  Use default one.
726             (let ((mml-boundary (mml-compute-boundary cont)))
727               (insert (format "Content-Type: multipart/%s; boundary=\"%s\""
728                               type mml-boundary)
729                       (if (cdr (assq 'start cont))
730                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
731                         "\n"))
732               (let ((cont cont) part)
733                 (while (setq part (pop cont))
734                   ;; Skip `multipart' and attributes.
735                   (when (and (consp part) (consp (cdr part)))
736                     (insert "\n--" mml-boundary "\n")
737                     (mml-generate-mime-1 part)
738                     (goto-char (point-max)))))
739               (insert "\n--" mml-boundary "--\n")))))
740        (t
741         (error "Invalid element: %S" cont)))
742       ;; handle sign & encrypt tags in a semi-smart way.
743       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
744             (encrypt-item (assoc (cdr (assq 'encrypt cont))
745                                  mml-encrypt-alist))
746             sender recipients)
747         (when (or sign-item encrypt-item)
748           (when (setq sender (cdr (assq 'sender cont)))
749             (message-options-set 'mml-sender sender)
750             (message-options-set 'message-sender sender))
751           (if (setq recipients (cdr (assq 'recipients cont)))
752               (message-options-set 'message-recipients recipients))
753           (let ((style (mml-signencrypt-style
754                         (first (or sign-item encrypt-item)))))
755             ;; check if: we're both signing & encrypting, both methods
756             ;; are the same (why would they be different?!), and that
757             ;; the signencrypt style allows for combined operation.
758             (if (and sign-item encrypt-item (equal (first sign-item)
759                                                    (first encrypt-item))
760                      (equal style 'combined))
761                 (funcall (nth 1 encrypt-item) cont t)
762               ;; otherwise, revert to the old behavior.
763               (when sign-item
764                 (funcall (nth 1 sign-item) cont))
765               (when encrypt-item
766                 (funcall (nth 1 encrypt-item) cont)))))))))
767
768 (defun mml-compute-boundary (cont)
769   "Return a unique boundary that does not exist in CONT."
770   (let ((mml-boundary (funcall mml-boundary-function
771                                (incf mml-multipart-number))))
772     (unless mml-inhibit-compute-boundary
773       ;; This function tries again and again until it has found
774       ;; a unique boundary.
775       (while (not (catch 'not-unique
776                     (mml-compute-boundary-1 cont)))))
777     mml-boundary))
778
779 (defun mml-compute-boundary-1 (cont)
780   (cond
781    ((member (car cont) '(part mml))
782     (mm-with-multibyte-buffer
783       (let ((mml-inhibit-compute-boundary t)
784             (mml-multipart-number 0)
785             mml-sign-alist mml-encrypt-alist)
786         (mml-generate-mime-1 cont))
787       (goto-char (point-min))
788       (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
789                                nil t)
790         (setq mml-boundary (funcall mml-boundary-function
791                                     (incf mml-multipart-number)))
792         (throw 'not-unique nil))))
793    ((eq (car cont) 'multipart)
794     (mapc 'mml-compute-boundary-1 (cddr cont))))
795   t)
796
797 (defun mml-make-boundary (number)
798   (concat (make-string (% number 60) ?=)
799           (if (> number 17)
800               (format "%x" number)
801             "")
802           mml-base-boundary))
803
804 (defun mml-content-disposition (type &optional filename)
805   "Return a default disposition name suitable to TYPE or FILENAME."
806   (let ((defs mml-content-disposition-alist)
807         disposition def types)
808     (while (and (not disposition) defs)
809       (setq def (pop defs))
810       (cond ((stringp (car def))
811              (when (and filename
812                         (string-match (car def) filename))
813                (setq disposition (cdr def))))
814             ((consp (cdr def))
815              (when (string= (car (setq types (split-string type "/")))
816                             (car def))
817                (setq type (cadr types)
818                      types (cdr def))
819                (while (and (not disposition) types)
820                  (setq def (pop types))
821                  (when (or (eq (car def) t) (string= type (car def)))
822                    (setq disposition (cdr def))))))
823             (t
824              (when (or (eq (car def) t) (string= type (car def)))
825                (setq disposition (cdr def))))))
826     (or disposition "attachment")))
827
828 (defun mml-insert-mime-headers (cont type charset encoding flowed)
829   (let (parameters id disposition description)
830     (setq parameters
831           (mml-parameter-string
832            cont mml-content-type-parameters))
833     (when (or charset
834               parameters
835               flowed
836               (not (equal type mml-generate-default-type))
837               mml-insert-mime-headers-always)
838       (when (consp charset)
839         (error
840          "Can't encode a part with several charsets"))
841       (insert "Content-Type: " type)
842       (when charset
843         (mml-insert-parameter
844          (mail-header-encode-parameter "charset" (symbol-name charset))))
845       (when flowed
846         (mml-insert-parameter "format=flowed"))
847       (when parameters
848         (mml-insert-parameter-string
849          cont mml-content-type-parameters))
850       (insert "\n"))
851     (when (setq id (cdr (assq 'id cont)))
852       (insert "Content-ID: " id "\n"))
853     (setq parameters
854           (mml-parameter-string
855            cont mml-content-disposition-parameters))
856     (when (or (setq disposition (cdr (assq 'disposition cont)))
857               parameters)
858       (insert "Content-Disposition: "
859               (or disposition
860                   (mml-content-disposition type (cdr (assq 'filename cont)))))
861       (when parameters
862         (mml-insert-parameter-string
863          cont mml-content-disposition-parameters))
864       (insert "\n"))
865     (unless (eq encoding '7bit)
866       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
867     (when (setq description (cdr (assq 'description cont)))
868       (insert "Content-Description: ")
869       (setq description (prog1
870                             (point)
871                           (insert description "\n")))
872       (mail-encode-encoded-word-region description (point)))))
873
874 (defun mml-parameter-string (cont types)
875   (let ((string "")
876         value type)
877     (while (setq type (pop types))
878       (when (setq value (cdr (assq type cont)))
879         ;; Strip directory component from the filename parameter.
880         (when (eq type 'filename)
881           (setq value (file-name-nondirectory value)))
882         (setq string (concat string "; "
883                              (mail-header-encode-parameter
884                               (symbol-name type) value)))))
885     (when (not (zerop (length string)))
886       string)))
887
888 (defun mml-insert-parameter-string (cont types)
889   (let (value type)
890     (while (setq type (pop types))
891       (when (setq value (cdr (assq type cont)))
892         ;; Strip directory component from the filename parameter.
893         (when (eq type 'filename)
894           (setq value (file-name-nondirectory value)))
895         (mml-insert-parameter
896          (mail-header-encode-parameter
897           (symbol-name type) value))))))
898
899 (defvar ange-ftp-name-format)
900 (defvar efs-path-regexp)
901
902 (defun mml-parse-file-name (path)
903   (if (if (boundp 'efs-path-regexp)
904           (string-match efs-path-regexp path)
905         (if (boundp 'ange-ftp-name-format)
906             (string-match (car ange-ftp-name-format) path)))
907       (list (match-string 1 path) (match-string 2 path)
908             (substring path (1+ (match-end 2))))
909     path))
910
911 (defun mml-insert-buffer (buffer)
912   "Insert BUFFER at point and quote any MML markup."
913   (save-restriction
914     (narrow-to-region (point) (point))
915     (insert-buffer-substring buffer)
916     (mml-quote-region (point-min) (point-max))
917     (goto-char (point-max))))
918
919 ;;;
920 ;;; Transforming MIME to MML
921 ;;;
922
923 ;; message-narrow-to-head autoloads message.
924 (declare-function message-remove-header "message"
925                   (header &optional is-regexp first reverse))
926
927 (defun mime-to-mml (&optional handles)
928   "Translate the current buffer (which should be a message) into MML.
929 If HANDLES is non-nil, use it instead reparsing the buffer."
930   ;; First decode the head.
931   (save-restriction
932     (message-narrow-to-head)
933     (let ((rfc2047-quote-decoded-words-containing-tspecials t))
934       (mail-decode-encoded-word-region (point-min) (point-max))))
935   (unless handles
936     (setq handles (mm-dissect-buffer t)))
937   (goto-char (point-min))
938   (search-forward "\n\n" nil t)
939   (delete-region (point) (point-max))
940   (if (stringp (car handles))
941       (mml-insert-mime handles)
942     (mml-insert-mime handles t))
943   (mm-destroy-parts handles)
944   (save-restriction
945     (message-narrow-to-head)
946     ;; Remove them, they are confusing.
947     (message-remove-header "Content-Type")
948     (message-remove-header "MIME-Version")
949     (message-remove-header "Content-Disposition")
950     (message-remove-header "Content-Transfer-Encoding")))
951
952 (autoload 'message-encode-message-body "message")
953 (declare-function message-narrow-to-headers-or-head "message" ())
954
955 ;;;###autoload
956 (defun mml-to-mime ()
957   "Translate the current buffer from MML to MIME."
958   ;; `message-encode-message-body' will insert an encoded Content-Description
959   ;; header in the message header if the body contains a single part
960   ;; that is specified by a user with a MML tag containing a description
961   ;; token.  So, we encode the message header first to prevent the encoded
962   ;; Content-Description header from being encoded again.
963   (save-restriction
964     (message-narrow-to-headers-or-head)
965     ;; Skip past any From_ headers.
966     (while (looking-at "From ")
967       (forward-line 1))
968     (let ((mail-parse-charset message-default-charset))
969       (mail-encode-encoded-word-buffer)))
970   (message-encode-message-body))
971
972 (defun mml-insert-mime (handle &optional no-markup)
973   (let (textp buffer mmlp)
974     ;; Determine type and stuff.
975     (unless (stringp (car handle))
976       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
977         (with-current-buffer (setq buffer (mml-generate-new-buffer " *mml*"))
978           (if (eq (mail-content-type-get (mm-handle-type handle) 'charset)
979                   'gnus-decoded)
980               ;; A part that mm-uu dissected from a non-MIME message
981               ;; because of `gnus-article-emulate-mime'.
982               (progn
983                 (mm-enable-multibyte)
984                 (insert-buffer-substring (mm-handle-buffer handle)))
985             (mm-insert-part handle 'no-cache)
986             (if (setq mmlp (equal (mm-handle-media-type handle)
987                                   "message/rfc822"))
988                 (mime-to-mml))))))
989     (if mmlp
990         (mml-insert-mml-markup handle nil t t)
991       (unless (and no-markup
992                    (equal (mm-handle-media-type handle) "text/plain"))
993         (mml-insert-mml-markup handle buffer textp)))
994     (cond
995      (mmlp
996       (insert-buffer-substring buffer)
997       (goto-char (point-max))
998       (insert "<#/mml>\n"))
999      ((stringp (car handle))
1000       (mapc 'mml-insert-mime (cdr handle))
1001       (insert "<#/multipart>\n"))
1002      (textp
1003       (let ((charset (mail-content-type-get
1004                       (mm-handle-type handle) 'charset))
1005             (start (point)))
1006         (if (eq charset 'gnus-decoded)
1007             (mm-insert-part handle)
1008           (insert (mm-decode-string (mm-get-part handle) charset)))
1009         (mml-quote-region start (point)))
1010       (goto-char (point-max)))
1011      (t
1012       (insert "<#/part>\n")))))
1013
1014 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
1015   "Take a MIME handle and insert an MML tag."
1016   (if (stringp (car handle))
1017       (progn
1018         (insert "<#multipart type=" (mm-handle-media-subtype handle))
1019         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
1020           (when start
1021             (insert " start=\"" start "\"")))
1022         (insert ">\n"))
1023     (if mmlp
1024         (insert "<#mml type=" (mm-handle-media-type handle))
1025       (insert "<#part type=" (mm-handle-media-type handle)))
1026     (dolist (elem (append (cdr (mm-handle-type handle))
1027                           (cdr (mm-handle-disposition handle))))
1028       (unless (symbolp (cdr elem))
1029         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
1030     (when (mm-handle-id handle)
1031       (insert " id=\"" (mm-handle-id handle) "\""))
1032     (when (mm-handle-disposition handle)
1033       (insert " disposition=" (car (mm-handle-disposition handle))))
1034     (when buffer
1035       (insert " buffer=\"" (buffer-name buffer) "\""))
1036     (when nofile
1037       (insert " nofile=yes"))
1038     (when (mm-handle-description handle)
1039       (insert " description=\"" (mm-handle-description handle) "\""))
1040     (insert ">\n")))
1041
1042 (defun mml-insert-parameter (&rest parameters)
1043   "Insert PARAMETERS in a nice way."
1044   (let (start end)
1045     (dolist (param parameters)
1046       (insert ";")
1047       (setq start (point))
1048       (insert " " param)
1049       (setq end (point))
1050       (goto-char start)
1051       (end-of-line)
1052       (if (> (current-column) 76)
1053           (progn
1054             (goto-char start)
1055             (insert "\n")
1056             (goto-char (1+ end)))
1057         (goto-char end)))))
1058
1059 ;;;
1060 ;;; Mode for inserting and editing MML forms
1061 ;;;
1062
1063 (defvar mml-mode-map
1064   (let ((sign (make-sparse-keymap))
1065         (encrypt (make-sparse-keymap))
1066         (signpart (make-sparse-keymap))
1067         (encryptpart (make-sparse-keymap))
1068         (map (make-sparse-keymap))
1069         (main (make-sparse-keymap)))
1070     (define-key map "\C-s" 'mml-secure-message-sign)
1071     (define-key map "\C-c" 'mml-secure-message-encrypt)
1072     (define-key map "\C-e" 'mml-secure-message-sign-encrypt)
1073     (define-key map "\C-p\C-s" 'mml-secure-sign)
1074     (define-key map "\C-p\C-c" 'mml-secure-encrypt)
1075     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
1076     (define-key sign "o" 'mml-secure-message-sign-pgp)
1077     (define-key sign "s" 'mml-secure-message-sign-smime)
1078     (define-key signpart "p" 'mml-secure-sign-pgpmime)
1079     (define-key signpart "o" 'mml-secure-sign-pgp)
1080     (define-key signpart "s" 'mml-secure-sign-smime)
1081     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
1082     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
1083     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
1084     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
1085     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
1086     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
1087     (define-key map "\C-n" 'mml-unsecure-message)
1088     (define-key map "f" 'mml-attach-file)
1089     (define-key map "b" 'mml-attach-buffer)
1090     (define-key map "e" 'mml-attach-external)
1091     (define-key map "q" 'mml-quote-region)
1092     (define-key map "m" 'mml-insert-multipart)
1093     (define-key map "p" 'mml-insert-part)
1094     (define-key map "v" 'mml-validate)
1095     (define-key map "P" 'mml-preview)
1096     (define-key map "s" sign)
1097     (define-key map "S" signpart)
1098     (define-key map "c" encrypt)
1099     (define-key map "C" encryptpart)
1100     ;;(define-key map "n" 'mml-narrow-to-part)
1101     ;; `M-m' conflicts with `back-to-indentation'.
1102     ;; (define-key main "\M-m" map)
1103     (define-key main "\C-c\C-m" map)
1104     main))
1105
1106 (easy-menu-define
1107   mml-menu mml-mode-map ""
1108   `("Attachments"
1109     ["Attach File..." mml-attach-file
1110      ,@(if (featurep 'xemacs) '(t)
1111          '(:help "Attach a file at point"))]
1112     ["Attach Buffer..." mml-attach-buffer
1113      ,@(if (featurep 'xemacs) '(t)
1114          '(:help "Attach a buffer to the outgoing message"))]
1115     ["Attach External..." mml-attach-external
1116      ,@(if (featurep 'xemacs) '(t)
1117          '(:help "Attach reference to an external file"))]
1118     ;; FIXME: Is it possible to do this without using
1119     ;; `gnus-gcc-externalize-attachments'?
1120     ["Externalize Attachments"
1121      (lambda ()
1122        (interactive)
1123        (if (not (and (boundp 'gnus-gcc-externalize-attachments)
1124                      (memq gnus-gcc-externalize-attachments
1125                            '(all t nil))))
1126            ;; Stupid workaround for XEmacs not honoring :visible.
1127            (message "Can't handle this value of `gnus-gcc-externalize-attachments'")
1128          (setq gnus-gcc-externalize-attachments
1129                (not gnus-gcc-externalize-attachments))
1130          (message "gnus-gcc-externalize-attachments is `%s'."
1131                   gnus-gcc-externalize-attachments)))
1132      ;; XEmacs barfs on :visible.
1133      ,@(if (featurep 'xemacs) nil
1134          '(:visible (and (boundp 'gnus-gcc-externalize-attachments)
1135                          (memq gnus-gcc-externalize-attachments
1136                                '(all t nil)))))
1137      :style toggle
1138      :selected gnus-gcc-externalize-attachments
1139      ,@(if (featurep 'xemacs) nil
1140          '(:help "Save attachments as external parts in Gcc copies"))]
1141     "----"
1142     ;;
1143     ("Change Security Method"
1144      ["PGP/MIME"
1145       (lambda () (interactive) (setq mml-secure-method "pgpmime"))
1146       ,@(if (featurep 'xemacs) nil
1147           '(:help "Set Security Method to PGP/MIME"))
1148       :style radio
1149       :selected (equal mml-secure-method "pgpmime") ]
1150      ["S/MIME"
1151       (lambda () (interactive) (setq mml-secure-method "smime"))
1152       ,@(if (featurep 'xemacs) nil
1153           '(:help "Set Security Method to S/MIME"))
1154       :style radio
1155       :selected (equal mml-secure-method "smime") ]
1156      ["Inline PGP"
1157       (lambda () (interactive) (setq mml-secure-method "pgp"))
1158       ,@(if (featurep 'xemacs) nil
1159           '(:help "Set Security Method to inline PGP"))
1160       :style radio
1161       :selected (equal mml-secure-method "pgp") ] )
1162     ;;
1163     ["Sign Message" mml-secure-message-sign t]
1164     ["Encrypt Message" mml-secure-message-encrypt t]
1165     ["Sign and Encrypt Message" mml-secure-message-sign-encrypt t]
1166     ["Encrypt/Sign off" mml-unsecure-message
1167      ,@(if (featurep 'xemacs) '(t)
1168          '(:help "Don't Encrypt/Sign Message"))]
1169     ;; Do we have separate encrypt and encrypt/sign commands for parts?
1170     ["Sign Part" mml-secure-sign t]
1171     ["Encrypt Part" mml-secure-encrypt t]
1172     "----"
1173     ;; Maybe we could remove these, because people who write MML most probably
1174     ;; don't use the menu:
1175     ["Insert Part..." mml-insert-part
1176      :active (message-in-body-p)]
1177     ["Insert Multipart..." mml-insert-multipart
1178      :active (message-in-body-p)]
1179     ;;
1180     ;;["Narrow" mml-narrow-to-part t]
1181     ["Quote MML in region" mml-quote-region
1182      :active (message-mark-active-p)
1183      ,@(if (featurep 'xemacs) nil
1184          '(:help "Quote MML tags in region"))]
1185     ["Validate MML" mml-validate t]
1186     ["Preview" mml-preview t]
1187     "----"
1188     ["Emacs MIME manual" (lambda () (interactive) (message-info 4))
1189      ,@(if (featurep 'xemacs) '(t)
1190          '(:help "Display the Emacs MIME manual"))]
1191     ["PGG manual" (lambda () (interactive) (message-info mml2015-use))
1192      ;; XEmacs barfs on :visible.
1193      ,@(if (featurep 'xemacs) nil
1194          '(:visible (and (boundp 'mml2015-use) (equal mml2015-use 'pgg))))
1195      ,@(if (featurep 'xemacs) '(t)
1196          '(:help "Display the PGG manual"))]
1197     ["EasyPG manual" (lambda () (interactive) (require 'mml2015) (message-info mml2015-use))
1198      ;; XEmacs barfs on :visible.
1199      ,@(if (featurep 'xemacs) nil
1200          '(:visible (and (boundp 'mml2015-use) (equal mml2015-use 'epg))))
1201      ,@(if (featurep 'xemacs) '(t)
1202          '(:help "Display the EasyPG manual"))]))
1203
1204 (define-minor-mode mml-mode
1205   "Minor mode for editing MML.
1206 MML is the MIME Meta Language, a minor mode for composing MIME articles.
1207 See Info node `(emacs-mime)Composing'.
1208
1209 \\{mml-mode-map}"
1210   :lighter " MML" :keymap mml-mode-map
1211   (when mml-mode
1212     (easy-menu-add mml-menu mml-mode-map)
1213     (when (boundp 'dnd-protocol-alist)
1214       (set (make-local-variable 'dnd-protocol-alist)
1215            (append mml-dnd-protocol-alist dnd-protocol-alist)))))
1216
1217 ;;;
1218 ;;; Helper functions for reading MIME stuff from the minibuffer and
1219 ;;; inserting stuff to the buffer.
1220 ;;;
1221
1222 (defcustom mml-default-directory mm-default-directory
1223   "The default directory where mml will find files.
1224 If not set, `default-directory' will be used."
1225   :type '(choice directory (const :tag "Default" nil))
1226   :version "23.1" ;; No Gnus
1227   :group 'message)
1228
1229 (defun mml-minibuffer-read-file (prompt)
1230   (let* ((completion-ignored-extensions nil)
1231          (file (read-file-name prompt
1232                                (or mml-default-directory default-directory)
1233                                nil t)))
1234     ;; Prevent some common errors.  This is inspired by similar code in
1235     ;; VM.
1236     (when (file-directory-p file)
1237       (error "%s is a directory, cannot attach" file))
1238     (unless (file-exists-p file)
1239       (error "No such file: %s" file))
1240     (unless (file-readable-p file)
1241       (error "Permission denied: %s" file))
1242     file))
1243
1244 (declare-function mailcap-parse-mimetypes "mailcap" (&optional path force))
1245 (declare-function mailcap-mime-types "mailcap" ())
1246
1247 (defun mml-minibuffer-read-type (name &optional default)
1248   (require 'mailcap)
1249   (mailcap-parse-mimetypes)
1250   (let* ((default (or default
1251                       (mm-default-file-encoding name)
1252                       ;; Perhaps here we should check what the file
1253                       ;; looks like, and offer text/plain if it looks
1254                       ;; like text/plain.
1255                       "application/octet-stream"))
1256          (string (gnus-completing-read
1257                   "Content type"
1258                   (mailcap-mime-types)
1259                   nil nil nil default)))
1260     (if (not (equal string ""))
1261         string
1262       default)))
1263
1264 (defun mml-minibuffer-read-description (&optional default)
1265   (let ((description (read-string "One line description: " default)))
1266     (when (string-match "\\`[ \t]*\\'" description)
1267       (setq description nil))
1268     description))
1269
1270 (defun mml-minibuffer-read-disposition (type &optional default filename)
1271   (unless default
1272     (setq default (mml-content-disposition type filename)))
1273   (let ((disposition (gnus-completing-read
1274                       "Disposition"
1275                       '("attachment" "inline")
1276                       t nil nil default)))
1277     (if (not (equal disposition ""))
1278         disposition
1279       default)))
1280
1281 (defun mml-quote-region (beg end)
1282   "Quote the MML tags in the region."
1283   (interactive "r")
1284   (save-excursion
1285     (save-restriction
1286       ;; Temporarily narrow the region to defend from changes
1287       ;; invalidating END.
1288       (narrow-to-region beg end)
1289       (goto-char (point-min))
1290       ;; Quote parts.
1291       (while (re-search-forward
1292               "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)" nil t)
1293         ;; Insert ! after the #.
1294         (goto-char (+ (match-beginning 0) 2))
1295         (insert "!")))))
1296
1297 (defun mml-insert-tag (name &rest plist)
1298   "Insert an MML tag described by NAME and PLIST."
1299   (when (symbolp name)
1300     (setq name (symbol-name name)))
1301   (insert "<#" name)
1302   (while plist
1303     (let ((key (pop plist))
1304           (value (pop plist)))
1305       (when value
1306         ;; Quote VALUE if it contains suspicious characters.
1307         (when (string-match "[\"'\\~/*;() \t\n]" value)
1308           (setq value (with-output-to-string
1309                         (let (print-escape-nonascii)
1310                           (prin1 value)))))
1311         (insert (format " %s=%s" key value)))))
1312   (insert ">\n"))
1313
1314 (defun mml-insert-empty-tag (name &rest plist)
1315   "Insert an empty MML tag described by NAME and PLIST."
1316   (when (symbolp name)
1317     (setq name (symbol-name name)))
1318   (apply #'mml-insert-tag name plist)
1319   (insert "<#/" name ">\n"))
1320
1321 ;;; Attachment functions.
1322
1323 (defcustom mml-dnd-protocol-alist
1324   '(("^file:///" . mml-dnd-attach-file)
1325     ("^file://"  . dnd-open-file)
1326     ("^file:"    . mml-dnd-attach-file))
1327   "The functions to call when a drop in `mml-mode' is made.
1328 See `dnd-protocol-alist' for more information.  When nil, behave
1329 as in other buffers."
1330   :type '(choice (repeat (cons (regexp) (function)))
1331                  (const :tag "Behave as in other buffers" nil))
1332   :version "22.1" ;; Gnus 5.10.9
1333   :group 'message)
1334
1335 (defcustom mml-dnd-attach-options nil
1336   "Which options should be queried when attaching a file via drag and drop.
1337
1338 If it is a list, valid members are `type', `description' and
1339 `disposition'.  `disposition' implies `type'.  If it is nil,
1340 don't ask for options.  If it is t, ask the user whether or not
1341 to specify options."
1342   :type '(choice
1343           (const :tag "None" nil)
1344           (const :tag "Query" t)
1345           (list :value (type description disposition)
1346            (set :inline t
1347                 (const type)
1348                 (const description)
1349                 (const disposition))))
1350   :version "22.1" ;; Gnus 5.10.9
1351   :group 'message)
1352
1353 ;;;###autoload
1354 (defun mml-attach-file (file &optional type description disposition)
1355   "Attach a file to the outgoing MIME message.
1356 The file is not inserted or encoded until you send the message with
1357 `\\[message-send-and-exit]' or `\\[message-send]' in Message mode,
1358 or `\\[mail-send-and-exit]' or `\\[mail-send]' in Mail mode.
1359
1360 FILE is the name of the file to attach.  TYPE is its
1361 content-type, a string of the form \"type/subtype\".  DESCRIPTION
1362 is a one-line description of the attachment.  The DISPOSITION
1363 specifies how the attachment is intended to be displayed.  It can
1364 be either \"inline\" (displayed automatically within the message
1365 body) or \"attachment\" (separate from the body)."
1366   (interactive
1367    (let* ((file (mml-minibuffer-read-file "Attach file: "))
1368           (type (mml-minibuffer-read-type file))
1369           (description (mml-minibuffer-read-description))
1370           (disposition (mml-minibuffer-read-disposition type nil file)))
1371      (list file type description disposition)))
1372   ;; If in the message header, attach at the end and leave point unchanged.
1373   (let ((head (unless (message-in-body-p) (point))))
1374     (if head (goto-char (point-max)))
1375     (mml-insert-empty-tag 'part
1376                           'type type
1377                           ;; icicles redefines read-file-name and returns a
1378                           ;; string w/ text properties :-/
1379                           'filename (mm-substring-no-properties file)
1380                           'disposition (or disposition "attachment")
1381                           'description description)
1382     ;; When using Mail mode, make sure it does the mime encoding
1383     ;; when you send the message.
1384     (or (eq mail-user-agent 'message-user-agent)
1385         (setq mail-encode-mml t))
1386     (when head
1387       (unless (pos-visible-in-window-p)
1388         (message "The file \"%s\" has been attached at the end of the message"
1389                  (file-name-nondirectory file)))
1390       (goto-char head))))
1391
1392 (defun mml-dnd-attach-file (uri action)
1393   "Attach a drag and drop file.
1394
1395 Ask for type, description or disposition according to
1396 `mml-dnd-attach-options'."
1397   (let ((file (dnd-get-local-file-name uri t)))
1398     (when (and file (file-regular-p file))
1399       (let ((mml-dnd-attach-options mml-dnd-attach-options)
1400             type description disposition)
1401         (setq mml-dnd-attach-options
1402               (when (and (eq mml-dnd-attach-options t)
1403                          (not
1404                           (y-or-n-p
1405                            "Use default type, disposition and description? ")))
1406                 '(type description disposition)))
1407         (when (or (memq 'type mml-dnd-attach-options)
1408                   (memq 'disposition mml-dnd-attach-options))
1409           (setq type (mml-minibuffer-read-type file)))
1410         (when (memq 'description mml-dnd-attach-options)
1411           (setq description (mml-minibuffer-read-description)))
1412         (when (memq 'disposition mml-dnd-attach-options)
1413           (setq disposition (mml-minibuffer-read-disposition type nil file)))
1414         (mml-attach-file file type description disposition)))))
1415
1416 (defun mml-attach-buffer (buffer &optional type description disposition)
1417   "Attach a buffer to the outgoing MIME message.
1418 BUFFER is the name of the buffer to attach.  See
1419 `mml-attach-file' for details of operation."
1420   (interactive
1421    (let* ((buffer (read-buffer "Attach buffer: "))
1422           (type (mml-minibuffer-read-type buffer "text/plain"))
1423           (description (mml-minibuffer-read-description))
1424           (disposition (mml-minibuffer-read-disposition type nil)))
1425      (list buffer type description disposition)))
1426   ;; If in the message header, attach at the end and leave point unchanged.
1427   (let ((head (unless (message-in-body-p) (point))))
1428     (if head (goto-char (point-max)))
1429     (mml-insert-empty-tag 'part 'type type 'buffer buffer
1430                           'disposition disposition
1431                           'description description)
1432     ;; When using Mail mode, make sure it does the mime encoding
1433     ;; when you send the message.
1434     (or (eq mail-user-agent 'message-user-agent)
1435         (setq mail-encode-mml t))
1436     (when head
1437       (unless (pos-visible-in-window-p)
1438         (message
1439          "The buffer \"%s\" has been attached at the end of the message"
1440          buffer))
1441       (goto-char head))))
1442
1443 (defun mml-attach-external (file &optional type description)
1444   "Attach an external file into the buffer.
1445 FILE is an ange-ftp/efs specification of the part location.
1446 TYPE is the MIME type to use."
1447   (interactive
1448    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1449           (type (mml-minibuffer-read-type file))
1450           (description (mml-minibuffer-read-description)))
1451      (list file type description)))
1452   ;; If in the message header, attach at the end and leave point unchanged.
1453   (let ((head (unless (message-in-body-p) (point))))
1454     (if head (goto-char (point-max)))
1455     (mml-insert-empty-tag 'external 'type type 'name file
1456                           'disposition "attachment" 'description description)
1457     ;; When using Mail mode, make sure it does the mime encoding
1458     ;; when you send the message.
1459     (or (eq mail-user-agent 'message-user-agent)
1460         (setq mail-encode-mml t))
1461     (when head
1462       (unless (pos-visible-in-window-p)
1463         (message "The file \"%s\" has been attached at the end of the message"
1464                  (file-name-nondirectory file)))
1465       (goto-char head))))
1466
1467 (defun mml-insert-multipart (&optional type)
1468   (interactive (if (message-in-body-p)
1469                    (list (gnus-completing-read "Multipart type"
1470                                                '("mixed" "alternative"
1471                                                  "digest" "parallel"
1472                                                  "signed" "encrypted")
1473                                                nil "mixed"))
1474                  (error "Use this command in the message body")))
1475   (or type
1476       (setq type "mixed"))
1477   (mml-insert-empty-tag "multipart" 'type type)
1478   ;; When using Mail mode, make sure it does the mime encoding
1479   ;; when you send the message.
1480   (or (eq mail-user-agent 'message-user-agent)
1481       (setq mail-encode-mml t))
1482   (forward-line -1))
1483
1484 (defun mml-insert-part (&optional type)
1485   (interactive (if (message-in-body-p)
1486                    (list (mml-minibuffer-read-type ""))
1487                  (error "Use this command in the message body")))
1488   ;; When using Mail mode, make sure it does the mime encoding
1489   ;; when you send the message.
1490   (or (eq mail-user-agent 'message-user-agent)
1491       (setq mail-encode-mml t))
1492   (mml-insert-tag 'part 'type type 'disposition "inline")
1493   (save-excursion
1494     (mml-insert-tag '/part)))
1495
1496 (declare-function message-subscribed-p "message" ())
1497 (declare-function message-make-mail-followup-to "message"
1498                   (&optional only-show-subscribed))
1499 (declare-function message-position-on-field "message" (header &rest afters))
1500
1501 (defun mml-preview-insert-mail-followup-to ()
1502   "Insert a Mail-Followup-To header before previewing an article.
1503 Should be adopted if code in `message-send-mail' is changed."
1504   (when (and (message-mail-p)
1505              (message-subscribed-p)
1506              (not (mail-fetch-field "mail-followup-to"))
1507              (message-make-mail-followup-to))
1508     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1509     (insert (message-make-mail-followup-to))))
1510
1511 (defvar mml-preview-buffer nil)
1512
1513 (autoload 'gnus-make-hashtable "gnus-util")
1514 (autoload 'widget-button-press "wid-edit" nil t)
1515 (declare-function widget-event-point "wid-edit" (event))
1516 ;; If gnus-buffer-configuration is bound this is loaded.
1517 (declare-function gnus-configure-windows "gnus-win" (setting &optional force))
1518 ;; Called after message-mail-p, which autoloads message.
1519 (declare-function message-news-p                "message" ())
1520 (declare-function message-options-set-recipient "message" ())
1521 (declare-function message-generate-headers      "message" (headers))
1522 (declare-function message-sort-headers          "message" ())
1523
1524 (defun mml-preview (&optional raw)
1525   "Display current buffer with Gnus, in a new buffer.
1526 If RAW, display a raw encoded MIME message.
1527
1528 The window layout for the preview buffer is controlled by the variables
1529 `special-display-buffer-names', `special-display-regexps', or
1530 `gnus-buffer-configuration' (the first match made will be used),
1531 or the `pop-to-buffer' function."
1532   (interactive "P")
1533   (setq mml-preview-buffer (generate-new-buffer
1534                             (concat (if raw "*Raw MIME preview of "
1535                                       "*MIME preview of ") (buffer-name))))
1536   (require 'gnus-msg)                 ; for gnus-setup-posting-charset
1537   (save-excursion
1538     (let* ((buf (current-buffer))
1539            (article-editing (eq major-mode 'gnus-article-edit-mode))
1540            (message-options message-options)
1541            (message-this-is-mail (message-mail-p))
1542            (message-this-is-news (message-news-p))
1543            (message-posting-charset (or (gnus-setup-posting-charset
1544                                          (save-restriction
1545                                            (message-narrow-to-headers-or-head)
1546                                            (message-fetch-field "Newsgroups")))
1547                                         message-posting-charset)))
1548       (message-options-set-recipient)
1549       (when (boundp 'gnus-buffers)
1550         (push mml-preview-buffer gnus-buffers))
1551       (save-restriction
1552         (widen)
1553         (set-buffer mml-preview-buffer)
1554         (erase-buffer)
1555         (insert-buffer-substring buf))
1556       (mml-preview-insert-mail-followup-to)
1557       (let ((message-deletable-headers (if (message-news-p)
1558                                            nil
1559                                          message-deletable-headers))
1560             (mail-header-separator (if article-editing
1561                                        ""
1562                                      mail-header-separator)))
1563         (message-generate-headers
1564          (copy-sequence (if (message-news-p)
1565                             message-required-news-headers
1566                           message-required-mail-headers)))
1567         (unless article-editing
1568           (if (re-search-forward
1569                (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1570               (replace-match "\n"))
1571           (setq mail-header-separator ""))
1572         (message-sort-headers)
1573         (mml-to-mime))
1574       (if raw
1575           (when (fboundp 'set-buffer-multibyte)
1576             (let ((s (buffer-string)))
1577               ;; Insert the content into unibyte buffer.
1578               (erase-buffer)
1579               (mm-disable-multibyte)
1580               (insert s)))
1581         (let ((gnus-newsgroup-charset (car message-posting-charset))
1582               gnus-article-prepare-hook gnus-original-article-buffer
1583               gnus-displaying-mime)
1584           (run-hooks 'gnus-article-decode-hook)
1585           (let ((gnus-newsgroup-name "dummy")
1586                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1587                                         (gnus-make-hashtable 5))))
1588             (gnus-article-prepare-display))))
1589       ;; Disable article-mode-map.
1590       (use-local-map nil)
1591       (gnus-make-local-hook 'kill-buffer-hook)
1592       (add-hook 'kill-buffer-hook
1593                 (lambda ()
1594                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1595       (setq buffer-read-only t)
1596       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1597       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1598       (local-set-key "\r"
1599                      (lambda ()
1600                        (interactive)
1601                        (widget-button-press (point))))
1602       (local-set-key gnus-mouse-2
1603                      (lambda (event)
1604                        (interactive "@e")
1605                        (widget-button-press (widget-event-point event) event)))
1606       ;; FIXME: Buffer is in article mode, but most tool bar commands won't
1607       ;; work.  Maybe only keep the following icons: search, print, quit
1608       (goto-char (point-min))))
1609   (if (and (not (mm-special-display-p (buffer-name mml-preview-buffer)))
1610            (boundp 'gnus-buffer-configuration)
1611            (assq 'mml-preview gnus-buffer-configuration))
1612       (let ((gnus-message-buffer (current-buffer)))
1613         (gnus-configure-windows 'mml-preview))
1614     (pop-to-buffer mml-preview-buffer)))
1615
1616 (defun mml-validate ()
1617   "Validate the current MML document."
1618   (interactive)
1619   (mml-parse))
1620
1621 (defun mml-tweak-part (cont)
1622   "Tweak a MML part."
1623   (let ((tweak (cdr (assq 'tweak cont)))
1624         func)
1625     (cond
1626      (tweak
1627       (setq func
1628             (or (cdr (assoc tweak mml-tweak-function-alist))
1629                 (intern tweak))))
1630      (mml-tweak-type-alist
1631       (let ((alist mml-tweak-type-alist)
1632             (type (or (cdr (assq 'type cont)) "text/plain")))
1633         (while alist
1634           (if (string-match (caar alist) type)
1635               (setq func (cdar alist)
1636                     alist nil)
1637             (setq alist (cdr alist)))))))
1638     (if func
1639         (funcall func cont)
1640       cont)
1641     (let ((alist mml-tweak-sexp-alist))
1642       (while alist
1643         (if (eval (caar alist))
1644             (funcall (cdar alist) cont))
1645         (setq alist (cdr alist)))))
1646   cont)
1647
1648 (defun mml-tweak-externalize-attachments (cont)
1649   "Tweak attached files as external parts."
1650   (let (filename-cons)
1651     (when (and (eq (car cont) 'part)
1652                (not (cdr (assq 'buffer cont)))
1653                (and (setq filename-cons (assq 'filename cont))
1654                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1655       (setcar cont 'external)
1656       (setcar filename-cons 'name))))
1657
1658 (provide 'mml)
1659
1660 ;;; mml.el ends here