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