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