(mml-generate-mime-1,mml-compute-boundary-1): Update 'mml handles on recursive
[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
37 (autoload 'message-make-message-id "message")
38 (declare-function gnus-setup-posting-charset "gnus-msg" (group))
39 (autoload 'gnus-make-local-hook "gnus-util")
40 (autoload 'message-fetch-field "message")
41 (autoload 'message-mark-active-p "message")
42 (autoload 'message-info "message")
43 (autoload 'fill-flowed-encode "flow-fill")
44 (autoload 'message-posting-charset "message")
45 (autoload 'dnd-get-local-file-name "dnd")
46
47 (autoload 'message-options-set    "message")
48 (autoload 'message-narrow-to-head "message")
49 (autoload 'message-in-body-p      "message")
50 (autoload 'message-mail-p         "message")
51
52 (defvar gnus-article-mime-handles)
53 (defvar gnus-mouse-2)
54 (defvar gnus-newsrc-hashtb)
55 (defvar message-default-charset)
56 (defvar message-deletable-headers)
57 (defvar message-options)
58 (defvar message-posting-charset)
59 (defvar message-required-mail-headers)
60 (defvar message-required-news-headers)
61 (defvar dnd-protocol-alist)
62 (defvar mml-dnd-protocol-alist)
63
64 (defcustom mml-content-type-parameters
65   '(name access-type expiration size permission format)
66   "*A list of acceptable parameters in MML tag.
67 These parameters are generated in Content-Type header if exists."
68   :version "22.1"
69   :type '(repeat (symbol :tag "Parameter"))
70   :group 'message)
71
72 (defcustom mml-content-disposition-parameters
73   '(filename creation-date modification-date read-date)
74   "*A list of acceptable parameters in MML tag.
75 These parameters are generated in Content-Disposition header if exists."
76   :version "22.1"
77   :type '(repeat (symbol :tag "Parameter"))
78   :group 'message)
79
80 (defcustom mml-content-disposition-alist
81   '((text (rtf . "attachment") (t . "inline"))
82     (t . "attachment"))
83   "Alist of MIME types or regexps matching file names and default dispositions.
84 Each element should be one of the following three forms:
85
86   (REGEXP . DISPOSITION)
87   (SUPERTYPE (SUBTYPE . DISPOSITION) (SUBTYPE . DISPOSITION)...)
88   (TYPE . DISPOSITION)
89
90 Where REGEXP is a string which matches the file name (if any) of an
91 attachment, SUPERTYPE, SUBTYPE and TYPE should be symbols which are a
92 MIME supertype (e.g., text), a MIME subtype (e.g., plain) and a MIME
93 type (e.g., text/plain) respectively, and DISPOSITION should be either
94 the string \"attachment\" or the string \"inline\".  The value t for
95 SUPERTYPE, SUBTYPE or TYPE matches any of those types.  The first
96 match found will be used."
97   :version "23.1" ;; No Gnus
98   :type (let ((dispositions '(radio :format "DISPOSITION: %v"
99                                     :value "attachment"
100                                     (const :format "%v " "attachment")
101                                     (const :format "%v\n" "inline"))))
102           `(repeat
103             :offset 0
104             (choice :format "%[Value Menu%]%v"
105                     (cons :tag "(REGEXP . DISPOSITION)" :extra-offset 4
106                           (regexp :tag "REGEXP" :value ".*")
107                           ,dispositions)
108                     (cons :tag "(SUPERTYPE (SUBTYPE . DISPOSITION)...)"
109                           :indent 0
110                           (symbol :tag "    SUPERTYPE" :value text)
111                           (repeat :format "%v%i\n" :offset 0 :extra-offset 4
112                                   (cons :format "%v" :extra-offset 5
113                                         (symbol :tag "SUBTYPE" :value t)
114                                         ,dispositions)))
115                     (cons :tag "(TYPE . DISPOSITION)" :extra-offset 4
116                           (symbol :tag "TYPE" :value t)
117                           ,dispositions))))
118   :group 'message)
119
120 (defcustom mml-insert-mime-headers-always nil
121   "If non-nil, always put Content-Type: text/plain at top of empty parts.
122 It is necessary to work against a bug in certain clients."
123   :version "22.1"
124   :type 'boolean
125   :group 'message)
126
127 (defvar mml-tweak-type-alist nil
128   "A list of (TYPE . FUNCTION) for tweaking MML parts.
129 TYPE is a string containing a regexp to match the MIME type.  FUNCTION
130 is a Lisp function which is called with the MML handle to tweak the
131 part.  This variable is used only when no TWEAK parameter exists in
132 the MML handle.")
133
134 (defvar mml-tweak-function-alist nil
135   "A list of (NAME . FUNCTION) for tweaking MML parts.
136 NAME is a string containing the name of the TWEAK parameter in the MML
137 handle.  FUNCTION is a Lisp function which is called with the MML
138 handle to tweak the part.")
139
140 (defvar mml-tweak-sexp-alist
141   '((mml-externalize-attachments . mml-tweak-externalize-attachments))
142   "A list of (SEXP . FUNCTION) for tweaking MML parts.
143 SEXP is an s-expression.  If the evaluation of SEXP is non-nil, FUNCTION
144 is called.  FUNCTION is a Lisp function which is called with the MML
145 handle to tweak the part.")
146
147 (defvar mml-externalize-attachments nil
148   "*If non-nil, local-file attachments are generated as external parts.")
149
150 (defvar mml-generate-multipart-alist nil
151   "*Alist of multipart generation functions.
152 Each entry has the form (NAME . FUNCTION), where
153 NAME is a string containing the name of the part (without the
154 leading \"/multipart/\"),
155 FUNCTION is a Lisp function which is called to generate the part.
156
157 The Lisp function has to supply the appropriate MIME headers and the
158 contents of this part.")
159
160 (defvar mml-syntax-table
161   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
162     (modify-syntax-entry ?\\ "/" table)
163     (modify-syntax-entry ?< "(" table)
164     (modify-syntax-entry ?> ")" table)
165     (modify-syntax-entry ?@ "w" table)
166     (modify-syntax-entry ?/ "w" table)
167     (modify-syntax-entry ?= " " table)
168     (modify-syntax-entry ?* " " table)
169     (modify-syntax-entry ?\; " " table)
170     (modify-syntax-entry ?\' " " table)
171     table))
172
173 (defvar mml-boundary-function 'mml-make-boundary
174   "A function called to suggest a boundary.
175 The function may be called several times, and should try to make a new
176 suggestion each time.  The function is called with one parameter,
177 which is a number that says how many times the function has been
178 called for this message.")
179
180 (defvar mml-confirmation-set nil
181   "A list of symbols, each of which disables some warning.
182 `unknown-encoding': always send messages contain characters with
183 unknown encoding; `use-ascii': always use ASCII for those characters
184 with unknown encoding; `multipart': always send messages with more than
185 one charsets.")
186
187 (defvar mml-generate-default-type "text/plain"
188   "Content type by which the Content-Type header can be omitted.
189 The Content-Type header will not be put in the MIME part if the type
190 equals the value and there's no parameter (e.g. charset, format, etc.)
191 and `mml-insert-mime-headers-always' is nil.  The value will be bound
192 to \"message/rfc822\" when encoding an article to be forwarded as a MIME
193 part.  This is for the internal use, you should never modify the value.")
194
195 (defvar mml-buffer-list nil)
196
197 (defun mml-generate-new-buffer (name)
198   (let ((buf (generate-new-buffer name)))
199     (push buf mml-buffer-list)
200     buf))
201
202 (defun mml-destroy-buffers ()
203   (let (kill-buffer-hook)
204     (mapc 'kill-buffer mml-buffer-list)
205     (setq mml-buffer-list nil)))
206
207 (defun mml-parse ()
208   "Parse the current buffer as an MML document."
209   (save-excursion
210     (goto-char (point-min))
211     (with-syntax-table mml-syntax-table
212       (mml-parse-1))))
213
214 (defun mml-parse-1 ()
215   "Parse the current buffer as an MML document."
216   (let (struct tag point contents charsets warn use-ascii no-markup-p raw)
217     (while (and (not (eobp))
218                 (not (looking-at "<#/multipart")))
219       (cond
220        ((looking-at "<#secure")
221         ;; The secure part is essentially a meta-meta tag, which
222         ;; expands to either a part tag if there are no other parts in
223         ;; the document or a multipart tag if there are other parts
224         ;; included in the message
225         (let* (secure-mode
226                (taginfo (mml-read-tag))
227                (keyfile (cdr (assq 'keyfile taginfo)))
228                (certfile (cdr (assq 'certfile taginfo)))
229                (recipients (cdr (assq 'recipients taginfo)))
230                (sender (cdr (assq 'sender taginfo)))
231                (location (cdr (assq 'tag-location taginfo)))
232                (mode (cdr (assq 'mode taginfo)))
233                (method (cdr (assq 'method taginfo)))
234                tags)
235           (save-excursion
236             (if (re-search-forward
237                  "<#/?\\(multipart\\|part\\|external\\|mml\\)." nil t)
238                 (setq secure-mode "multipart")
239               (setq secure-mode "part")))
240           (save-excursion
241             (goto-char location)
242             (re-search-forward "<#secure[^\n]*>\n"))
243           (delete-region (match-beginning 0) (match-end 0))
244           (cond ((string= mode "sign")
245                  (setq tags (list "sign" method)))
246                 ((string= mode "encrypt")
247                  (setq tags (list "encrypt" method)))
248                 ((string= mode "signencrypt")
249                  (setq tags (list "sign" method "encrypt" method))))
250           (eval `(mml-insert-tag ,secure-mode
251                                  ,@tags
252                                  ,(if keyfile "keyfile")
253                                  ,keyfile
254                                  ,(if certfile "certfile")
255                                  ,certfile
256                                  ,(if recipients "recipients")
257                                  ,recipients
258                                  ,(if sender "sender")
259                                  ,sender))
260           ;; restart the parse
261           (goto-char location)))
262        ((looking-at "<#multipart")
263         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
264        ((looking-at "<#external")
265         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
266               struct))
267        (t
268         (if (or (looking-at "<#part") (looking-at "<#mml"))
269             (setq tag (mml-read-tag)
270                   no-markup-p nil
271                   warn nil)
272           (setq tag (list 'part '(type . "text/plain"))
273                 no-markup-p t
274                 warn t))
275         (setq raw (cdr (assq 'raw tag))
276               point (point)
277               contents (mml-read-part (eq 'mml (car tag)))
278               charsets (cond
279                         (raw nil)
280                         ((assq 'charset tag)
281                          (list
282                           (intern (downcase (cdr (assq 'charset tag))))))
283                         (t
284                          (mm-find-mime-charset-region point (point)
285                                                       mm-hack-charsets))))
286         (when (and (not raw) (memq nil charsets))
287           (if (or (memq 'unknown-encoding mml-confirmation-set)
288                   (message-options-get 'unknown-encoding)
289                   (and (y-or-n-p "\
290 Message contains characters with unknown encoding.  Really send? ")
291                        (message-options-set 'unknown-encoding t)))
292               (if (setq use-ascii
293                         (or (memq 'use-ascii mml-confirmation-set)
294                             (message-options-get 'use-ascii)
295                             (and (y-or-n-p "Use ASCII as charset? ")
296                                  (message-options-set 'use-ascii t))))
297                   (setq charsets (delq nil charsets))
298                 (setq warn nil))
299             (error "Edit your message to remove those characters")))
300         (if (or raw
301                 (eq 'mml (car tag))
302                 (< (length charsets) 2))
303             (if (or (not no-markup-p)
304                     (string-match "[^ \t\r\n]" contents))
305                 ;; Don't create blank parts.
306                 (push (nconc tag (list (cons 'contents contents)))
307                       struct))
308           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
309                           tag point (point) use-ascii)))
310             (when (and warn
311                        (not (memq 'multipart mml-confirmation-set))
312                        (not (message-options-get 'multipart))
313                        (not (and (y-or-n-p (format "\
314 A message part needs to be split into %d charset parts.  Really send? "
315                                                    (length nstruct)))
316                                  (message-options-set 'multipart t))))
317               (error "Edit your message to use only one charset"))
318             (setq struct (nconc nstruct struct)))))))
319     (unless (eobp)
320       (forward-line 1))
321     (nreverse struct)))
322
323 (defun mml-parse-singlepart-with-multiple-charsets
324   (orig-tag beg end &optional use-ascii)
325   (save-excursion
326     (save-restriction
327       (narrow-to-region beg end)
328       (goto-char (point-min))
329       (let ((current (or (mm-mime-charset (mm-charset-after))
330                          (and use-ascii 'us-ascii)))
331             charset struct space newline paragraph)
332         (while (not (eobp))
333           (setq charset (mm-mime-charset (mm-charset-after)))
334           (cond
335            ;; The charset remains the same.
336            ((eq charset 'us-ascii))
337            ((or (and use-ascii (not charset))
338                 (eq charset current))
339             (setq space nil
340                   newline nil
341                   paragraph nil))
342            ;; The initial charset was ascii.
343            ((eq current 'us-ascii)
344             (setq current charset
345                   space nil
346                   newline nil
347                   paragraph nil))
348            ;; We have a change in charsets.
349            (t
350             (push (append
351                    orig-tag
352                    (list (cons 'contents
353                                (buffer-substring-no-properties
354                                 beg (or paragraph newline space (point))))))
355                   struct)
356             (setq beg (or paragraph newline space (point))
357                   current charset
358                   space nil
359                   newline nil
360                   paragraph nil)))
361           ;; Compute places where it might be nice to break the part.
362           (cond
363            ((memq (following-char) '(?  ?\t))
364             (setq space (1+ (point))))
365            ((and (eq (following-char) ?\n)
366                  (not (bobp))
367                  (eq (char-after (1- (point))) ?\n))
368             (setq paragraph (point)))
369            ((eq (following-char) ?\n)
370             (setq newline (1+ (point)))))
371           (forward-char 1))
372         ;; Do the final part.
373         (unless (= beg (point))
374           (push (append orig-tag
375                         (list (cons 'contents
376                                     (buffer-substring-no-properties
377                                      beg (point)))))
378                 struct))
379         struct))))
380
381 (defun mml-read-tag ()
382   "Read a tag and return the contents."
383   (let ((orig-point (point))
384         contents name elem val)
385     (forward-char 2)
386     (setq name (buffer-substring-no-properties
387                 (point) (progn (forward-sexp 1) (point))))
388     (skip-chars-forward " \t\n")
389     (while (not (looking-at ">[ \t]*\n?"))
390       (setq elem (buffer-substring-no-properties
391                   (point) (progn (forward-sexp 1) (point))))
392       (skip-chars-forward "= \t\n")
393       (setq val (buffer-substring-no-properties
394                  (point) (progn (forward-sexp 1) (point))))
395       (when (string-match "\\`\"" val)
396         (setq val (read val))) ;; inverse of prin1 in mml-insert-tag
397       (push (cons (intern elem) val) contents)
398       (skip-chars-forward " \t\n"))
399     (goto-char (match-end 0))
400     ;; Don't skip the leading space.
401     ;;(skip-chars-forward " \t\n")
402     ;; Put the tag location into the returned contents
403     (setq contents (append (list (cons 'tag-location orig-point)) contents))
404     (cons (intern name) (nreverse contents))))
405
406 (defun mml-buffer-substring-no-properties-except-hard-newlines (start end)
407   (let ((str (buffer-substring-no-properties start end))
408         (bufstart start) tmp)
409     (while (setq tmp (text-property-any start end 'hard 't))
410       (set-text-properties (- tmp bufstart) (- tmp bufstart -1)
411                            '(hard t) str)
412       (setq start (1+ tmp)))
413     str))
414
415 (defun mml-read-part (&optional mml)
416   "Return the buffer up till the next part, multipart or closing part or multipart.
417 If MML is non-nil, return the buffer up till the correspondent mml tag."
418   (let ((beg (point)) (count 1))
419     ;; If the tag ended at the end of the line, we go to the next line.
420     (when (looking-at "[ \t]*\n")
421       (forward-line 1))
422     (if mml
423         (progn
424           (while (and (> count 0) (not (eobp)))
425             (if (re-search-forward "<#\\(/\\)?mml." nil t)
426                 (setq count (+ count (if (match-beginning 1) -1 1)))
427               (goto-char (point-max))))
428           (mml-buffer-substring-no-properties-except-hard-newlines
429            beg (if (> count 0)
430                    (point)
431                  (match-beginning 0))))
432       (if (re-search-forward
433            "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
434           (prog1
435               (mml-buffer-substring-no-properties-except-hard-newlines
436                beg (match-beginning 0))
437             (if (or (not (match-beginning 1))
438                     (equal (match-string 2) "multipart"))
439                 (goto-char (match-beginning 0))
440               (when (looking-at "[ \t]*\n")
441                 (forward-line 1))))
442         (mml-buffer-substring-no-properties-except-hard-newlines
443          beg (goto-char (point-max)))))))
444
445 (defvar mml-boundary nil)
446 (defvar mml-base-boundary "-=-=")
447 (defvar mml-multipart-number 0)
448
449 (defun mml-generate-mime ()
450   "Generate a MIME message based on the current MML document."
451   (let ((cont (mml-parse))
452         (mml-multipart-number mml-multipart-number))
453     (if (not cont)
454         nil
455       (mm-with-multibyte-buffer
456         (if (and (consp (car cont))
457                  (= (length cont) 1))
458             (mml-generate-mime-1 (car cont))
459           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
460                                       cont)))
461         (buffer-string)))))
462
463 (defun mml-generate-mime-1 (cont)
464   (let ((mm-use-ultra-safe-encoding
465          (or mm-use-ultra-safe-encoding (assq 'sign cont))))
466     (save-restriction
467       (narrow-to-region (point) (point))
468       (mml-tweak-part cont)
469       (cond
470        ((or (eq (car cont) 'part) (eq (car cont) 'mml))
471         (let* ((raw (cdr (assq 'raw cont)))
472                (filename (cdr (assq 'filename cont)))
473                (type (or (cdr (assq 'type cont))
474                          (if filename
475                              (or (mm-default-file-encoding filename)
476                                  "application/octet-stream")
477                            "text/plain")))
478                (charset (cdr (assq 'charset cont)))
479                (coding (mm-charset-to-coding-system charset))
480                encoding flowed coded)
481           (cond ((eq coding 'ascii)
482                  (setq charset nil
483                        coding nil))
484                 (charset
485                  ;; The value of `charset' might be a bogus alias that
486                  ;; `mm-charset-synonym-alist' provides, like `utf8',
487                  ;; so we prefer the MIME charset that Emacs knows for
488                  ;; the coding system `coding'.
489                  (setq charset (or (mm-coding-system-to-mime-charset coding)
490                                    (intern (downcase charset))))))
491           (if (and (not raw)
492                    (member (car (split-string type "/")) '("text" "message")))
493               (progn
494                 (with-temp-buffer
495                   (cond
496                    ((cdr (assq 'buffer cont))
497                     (insert-buffer-substring (cdr (assq 'buffer cont))))
498                    ((and filename
499                          (not (equal (cdr (assq 'nofile cont)) "yes")))
500                     (let ((coding-system-for-read coding))
501                       (mm-insert-file-contents filename)))
502                    ((eq 'mml (car cont))
503                     (insert (cdr (assq 'contents cont))))
504                    (t
505                     (save-restriction
506                       (narrow-to-region (point) (point))
507                       (insert (cdr (assq 'contents cont)))
508                       ;; Remove quotes from quoted tags.
509                       (goto-char (point-min))
510                       (while (re-search-forward
511                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\)"
512                               nil t)
513                         (delete-region (+ (match-beginning 0) 2)
514                                        (+ (match-beginning 0) 3))))))
515                   (cond
516                    ((eq (car cont) 'mml)
517                     (let ((mml-boundary (mml-compute-boundary cont))
518                           ;; It is necessary for the case where this
519                           ;; function is called recursively since
520                           ;; `m-g-d-t' will be bound to "message/rfc822"
521                           ;; when encoding an article to be forwarded.
522                           (mml-generate-default-type "text/plain"))
523                       (mml-to-mime)
524                       ;; Update handle so mml-compute-boundary can
525                       ;; detect collisions with the nested parts.
526                       (setcdr (assoc 'contents cont) (buffer-string)))
527                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
528                       ;; ignore 0x1b, it is part of iso-2022-jp
529                       (setq encoding (mm-body-7-or-8))))
530                    ((string= (car (split-string type "/")) "message")
531                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
532                       ;; ignore 0x1b, it is part of iso-2022-jp
533                       (setq encoding (mm-body-7-or-8))))
534                    (t
535                     ;; Only perform format=flowed filling on text/plain
536                     ;; parts where there either isn't a format parameter
537                     ;; in the mml tag or it says "flowed" and there
538                     ;; actually are hard newlines in the text.
539                     (let (use-hard-newlines)
540                       (when (and (string= type "text/plain")
541                                  (not (string= (cdr (assq 'sign cont)) "pgp"))
542                                  (or (null (assq 'format cont))
543                                      (string= (cdr (assq 'format cont))
544                                               "flowed"))
545                                  (setq use-hard-newlines
546                                        (text-property-any
547                                         (point-min) (point-max) 'hard 't)))
548                         (fill-flowed-encode)
549                         ;; Indicate that `mml-insert-mime-headers' should
550                         ;; insert a "; format=flowed" string unless the
551                         ;; user has already specified it.
552                         (setq flowed (null (assq 'format cont)))))
553                     ;; Prefer `utf-8' for text/calendar parts.
554                     (if (or charset
555                             (not (string= type "text/calendar")))
556                         (setq charset (mm-encode-body charset))
557                       (let ((mm-coding-system-priorities
558                              (cons 'utf-8 mm-coding-system-priorities)))
559                         (setq charset (mm-encode-body))))
560                     (setq encoding (mm-body-encoding
561                                     charset (cdr (assq 'encoding cont))))))
562                   (setq coded (buffer-string)))
563                 (mml-insert-mime-headers cont type charset encoding flowed)
564                 (insert "\n")
565                 (insert coded))
566             (mm-with-unibyte-buffer
567               (cond
568                ((cdr (assq 'buffer cont))
569                 (insert (mm-string-as-unibyte
570                          (with-current-buffer (cdr (assq 'buffer cont))
571                            (buffer-string)))))
572                ((and filename
573                      (not (equal (cdr (assq 'nofile cont)) "yes")))
574                 (let ((coding-system-for-read mm-binary-coding-system))
575                   (mm-insert-file-contents filename nil nil nil nil t))
576                 (unless charset
577                   (setq charset (mm-coding-system-to-mime-charset
578                                  (mm-find-buffer-file-coding-system
579                                   filename)))))
580                (t
581                 (let ((contents (cdr (assq 'contents cont))))
582                   (if (if (featurep 'xemacs)
583                           (string-match "[^\000-\377]" contents)
584                         (mm-multibyte-string-p contents))
585                       (progn
586                         (mm-enable-multibyte)
587                         (insert contents)
588                         (unless raw
589                           (setq charset (mm-encode-body charset))))
590                     (insert contents)))))
591               (if (setq encoding (cdr (assq 'encoding cont)))
592                   (setq encoding (intern (downcase encoding))))
593               (setq encoding (mm-encode-buffer type encoding)
594                     coded (mm-string-as-multibyte (buffer-string))))
595             (mml-insert-mime-headers cont type charset encoding nil)
596             (insert "\n" coded))))
597        ((eq (car cont) 'external)
598         (insert "Content-Type: message/external-body")
599         (let ((parameters (mml-parameter-string
600                            cont '(expiration size permission)))
601               (name (cdr (assq 'name cont)))
602               (url (cdr (assq 'url cont))))
603           (when name
604             (setq name (mml-parse-file-name name))
605             (if (stringp name)
606                 (mml-insert-parameter
607                  (mail-header-encode-parameter "name" name)
608                  "access-type=local-file")
609               (mml-insert-parameter
610                (mail-header-encode-parameter
611                 "name" (file-name-nondirectory (nth 2 name)))
612                (mail-header-encode-parameter "site" (nth 1 name))
613                (mail-header-encode-parameter
614                 "directory" (file-name-directory (nth 2 name))))
615               (mml-insert-parameter
616                (concat "access-type="
617                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
618                            "anon-ftp"
619                          "ftp")))))
620           (when url
621             (mml-insert-parameter
622              (mail-header-encode-parameter "url" url)
623              "access-type=url"))
624           (when parameters
625             (mml-insert-parameter-string
626              cont '(expiration size permission)))
627           (insert "\n\n")
628           (insert "Content-Type: "
629                   (or (cdr (assq 'type cont))
630                       (if name
631                           (or (mm-default-file-encoding name)
632                               "application/octet-stream")
633                         "text/plain"))
634                   "\n")
635           (insert "Content-ID: " (message-make-message-id) "\n")
636           (insert "Content-Transfer-Encoding: "
637                   (or (cdr (assq 'encoding cont)) "binary"))
638           (insert "\n\n")
639           (insert (or (cdr (assq 'contents cont))))
640           (insert "\n")))
641        ((eq (car cont) 'multipart)
642         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
643                (mml-generate-default-type (if (equal type "digest")
644                                               "message/rfc822"
645                                             "text/plain"))
646                (handler (assoc type mml-generate-multipart-alist)))
647           (if handler
648               (funcall (cdr handler) cont)
649             ;; No specific handler.  Use default one.
650             (let ((mml-boundary (mml-compute-boundary cont)))
651               (insert (format "Content-Type: multipart/%s; boundary=\"%s\""
652                               type mml-boundary)
653                       (if (cdr (assq 'start cont))
654                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
655                         "\n"))
656               (let ((cont cont) part)
657                 (while (setq part (pop cont))
658                   ;; Skip `multipart' and attributes.
659                   (when (and (consp part) (consp (cdr part)))
660                     (insert "\n--" mml-boundary "\n")
661                     (mml-generate-mime-1 part)
662                     (goto-char (point-max)))))
663               (insert "\n--" mml-boundary "--\n")))))
664        (t
665         (error "Invalid element: %S" cont)))
666       ;; handle sign & encrypt tags in a semi-smart way.
667       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
668             (encrypt-item (assoc (cdr (assq 'encrypt cont))
669                                  mml-encrypt-alist))
670             sender recipients)
671         (when (or sign-item encrypt-item)
672           (when (setq sender (cdr (assq 'sender cont)))
673             (message-options-set 'mml-sender sender)
674             (message-options-set 'message-sender sender))
675           (if (setq recipients (cdr (assq 'recipients cont)))
676               (message-options-set 'message-recipients recipients))
677           (let ((style (mml-signencrypt-style
678                         (first (or sign-item encrypt-item)))))
679             ;; check if: we're both signing & encrypting, both methods
680             ;; are the same (why would they be different?!), and that
681             ;; the signencrypt style allows for combined operation.
682             (if (and sign-item encrypt-item (equal (first sign-item)
683                                                    (first encrypt-item))
684                      (equal style 'combined))
685                 (funcall (nth 1 encrypt-item) cont t)
686               ;; otherwise, revert to the old behavior.
687               (when sign-item
688                 (funcall (nth 1 sign-item) cont))
689               (when encrypt-item
690                 (funcall (nth 1 encrypt-item) cont)))))))))
691
692 (defun mml-compute-boundary (cont)
693   "Return a unique boundary that does not exist in CONT."
694   (let ((mml-boundary (funcall mml-boundary-function
695                                (incf mml-multipart-number))))
696     ;; This function tries again and again until it has found
697     ;; a unique boundary.
698     (while (not (catch 'not-unique
699                   (mml-compute-boundary-1 cont))))
700     mml-boundary))
701
702 (defun mml-compute-boundary-1 (cont)
703   (let (filename)
704     (cond
705      ((member (car cont) '(part mml))
706       (with-temp-buffer
707         (cond
708          ((cdr (assq 'buffer cont))
709           (insert-buffer-substring (cdr (assq 'buffer cont))))
710          ((and (setq filename (cdr (assq 'filename cont)))
711                (not (equal (cdr (assq 'nofile cont)) "yes")))
712           (mm-insert-file-contents filename nil nil nil nil t))
713          (t
714           (insert (cdr (assq 'contents cont)))))
715         (goto-char (point-min))
716         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
717                                  nil t)
718           (setq mml-boundary (funcall mml-boundary-function
719                                       (incf mml-multipart-number)))
720           (throw 'not-unique nil))))
721      ((eq (car cont) 'multipart)
722       (mapc 'mml-compute-boundary-1 (cddr cont))))
723     t))
724
725 (defun mml-make-boundary (number)
726   (concat (make-string (% number 60) ?=)
727           (if (> number 17)
728               (format "%x" number)
729             "")
730           mml-base-boundary))
731
732 (defun mml-content-disposition (type &optional filename)
733   "Return a default disposition name suitable to TYPE or FILENAME."
734   (let ((defs mml-content-disposition-alist)
735         disposition def types)
736     (while (and (not disposition) defs)
737       (setq def (pop defs))
738       (cond ((stringp (car def))
739              (when (and filename
740                         (string-match (car def) filename))
741                (setq disposition (cdr def))))
742             ((consp (cdr def))
743              (when (string= (car (setq types (split-string type "/")))
744                             (car def))
745                (setq type (cadr types)
746                      types (cdr def))
747                (while (and (not disposition) types)
748                  (setq def (pop types))
749                  (when (or (eq (car def) t) (string= type (car def)))
750                    (setq disposition (cdr def))))))
751             (t
752              (when (or (eq (car def) t) (string= type (car def)))
753                (setq disposition (cdr def))))))
754     (or disposition "attachment")))
755
756 (defun mml-insert-mime-headers (cont type charset encoding flowed)
757   (let (parameters id disposition description)
758     (setq parameters
759           (mml-parameter-string
760            cont mml-content-type-parameters))
761     (when (or charset
762               parameters
763               flowed
764               (not (equal type mml-generate-default-type))
765               mml-insert-mime-headers-always)
766       (when (consp charset)
767         (error
768          "Can't encode a part with several charsets"))
769       (insert "Content-Type: " type)
770       (when charset
771         (mml-insert-parameter
772          (mail-header-encode-parameter "charset" (symbol-name charset))))
773       (when flowed
774         (mml-insert-parameter "format=flowed"))
775       (when parameters
776         (mml-insert-parameter-string
777          cont mml-content-type-parameters))
778       (insert "\n"))
779     (when (setq id (cdr (assq 'id cont)))
780       (insert "Content-ID: " id "\n"))
781     (setq parameters
782           (mml-parameter-string
783            cont mml-content-disposition-parameters))
784     (when (or (setq disposition (cdr (assq 'disposition cont)))
785               parameters)
786       (insert "Content-Disposition: "
787               (or disposition
788                   (mml-content-disposition type (cdr (assq 'filename cont)))))
789       (when parameters
790         (mml-insert-parameter-string
791          cont mml-content-disposition-parameters))
792       (insert "\n"))
793     (unless (eq encoding '7bit)
794       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
795     (when (setq description (cdr (assq 'description cont)))
796       (insert "Content-Description: ")
797       (setq description (prog1
798                             (point)
799                           (insert description "\n")))
800       (mail-encode-encoded-word-region description (point)))))
801
802 (defun mml-parameter-string (cont types)
803   (let ((string "")
804         value type)
805     (while (setq type (pop types))
806       (when (setq value (cdr (assq type cont)))
807         ;; Strip directory component from the filename parameter.
808         (when (eq type 'filename)
809           (setq value (file-name-nondirectory value)))
810         (setq string (concat string "; "
811                              (mail-header-encode-parameter
812                               (symbol-name type) value)))))
813     (when (not (zerop (length string)))
814       string)))
815
816 (defun mml-insert-parameter-string (cont types)
817   (let (value type)
818     (while (setq type (pop types))
819       (when (setq value (cdr (assq type cont)))
820         ;; Strip directory component from the filename parameter.
821         (when (eq type 'filename)
822           (setq value (file-name-nondirectory value)))
823         (mml-insert-parameter
824          (mail-header-encode-parameter
825           (symbol-name type) value))))))
826
827 (defvar ange-ftp-name-format)
828 (defvar efs-path-regexp)
829
830 (defun mml-parse-file-name (path)
831   (if (if (boundp 'efs-path-regexp)
832           (string-match efs-path-regexp path)
833         (if (boundp 'ange-ftp-name-format)
834             (string-match (car ange-ftp-name-format) path)))
835       (list (match-string 1 path) (match-string 2 path)
836             (substring path (1+ (match-end 2))))
837     path))
838
839 (defun mml-insert-buffer (buffer)
840   "Insert BUFFER at point and quote any MML markup."
841   (save-restriction
842     (narrow-to-region (point) (point))
843     (insert-buffer-substring buffer)
844     (mml-quote-region (point-min) (point-max))
845     (goto-char (point-max))))
846
847 ;;;
848 ;;; Transforming MIME to MML
849 ;;;
850
851 ;; message-narrow-to-head autoloads message.
852 (declare-function message-remove-header "message"
853                   (header &optional is-regexp first reverse))
854
855 (defun mime-to-mml (&optional handles)
856   "Translate the current buffer (which should be a message) into MML.
857 If HANDLES is non-nil, use it instead reparsing the buffer."
858   ;; First decode the head.
859   (save-restriction
860     (message-narrow-to-head)
861     (let ((rfc2047-quote-decoded-words-containing-tspecials t))
862       (mail-decode-encoded-word-region (point-min) (point-max))))
863   (unless handles
864     (setq handles (mm-dissect-buffer t)))
865   (goto-char (point-min))
866   (search-forward "\n\n" nil t)
867   (delete-region (point) (point-max))
868   (if (stringp (car handles))
869       (mml-insert-mime handles)
870     (mml-insert-mime handles t))
871   (mm-destroy-parts handles)
872   (save-restriction
873     (message-narrow-to-head)
874     ;; Remove them, they are confusing.
875     (message-remove-header "Content-Type")
876     (message-remove-header "MIME-Version")
877     (message-remove-header "Content-Disposition")
878     (message-remove-header "Content-Transfer-Encoding")))
879
880 (autoload 'message-encode-message-body "message")
881 (declare-function message-narrow-to-headers-or-head "message" ())
882
883 (defun mml-to-mime ()
884   "Translate the current buffer from MML to MIME."
885   ;; `message-encode-message-body' will insert an encoded Content-Description
886   ;; header in the message header if the body contains a single part
887   ;; that is specified by a user with a MML tag containing a description
888   ;; token.  So, we encode the message header first to prevent the encoded
889   ;; Content-Description header from being encoded again.
890   (save-restriction
891     (message-narrow-to-headers-or-head)
892     ;; Skip past any From_ headers.
893     (while (looking-at "From ")
894       (forward-line 1))
895     (let ((mail-parse-charset message-default-charset))
896       (mail-encode-encoded-word-buffer)))
897   (message-encode-message-body))
898
899 (defun mml-insert-mime (handle &optional no-markup)
900   (let (textp buffer mmlp)
901     ;; Determine type and stuff.
902     (unless (stringp (car handle))
903       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
904         (save-excursion
905           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
906           (if (eq (mail-content-type-get (mm-handle-type handle) 'charset)
907                   'gnus-decoded)
908               ;; A part that mm-uu dissected from a non-MIME message
909               ;; because of `gnus-article-emulate-mime'.
910               (progn
911                 (mm-enable-multibyte)
912                 (insert-buffer-substring (mm-handle-buffer handle)))
913             (mm-insert-part handle 'no-cache)
914             (if (setq mmlp (equal (mm-handle-media-type handle)
915                                   "message/rfc822"))
916                 (mime-to-mml))))))
917     (if mmlp
918         (mml-insert-mml-markup handle nil t t)
919       (unless (and no-markup
920                    (equal (mm-handle-media-type handle) "text/plain"))
921         (mml-insert-mml-markup handle buffer textp)))
922     (cond
923      (mmlp
924       (insert-buffer-substring buffer)
925       (goto-char (point-max))
926       (insert "<#/mml>\n"))
927      ((stringp (car handle))
928       (mapc 'mml-insert-mime (cdr handle))
929       (insert "<#/multipart>\n"))
930      (textp
931       (let ((charset (mail-content-type-get
932                       (mm-handle-type handle) 'charset))
933             (start (point)))
934         (if (eq charset 'gnus-decoded)
935             (mm-insert-part handle)
936           (insert (mm-decode-string (mm-get-part handle) charset)))
937         (mml-quote-region start (point)))
938       (goto-char (point-max)))
939      (t
940       (insert "<#/part>\n")))))
941
942 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
943   "Take a MIME handle and insert an MML tag."
944   (if (stringp (car handle))
945       (progn
946         (insert "<#multipart type=" (mm-handle-media-subtype handle))
947         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
948           (when start
949             (insert " start=\"" start "\"")))
950         (insert ">\n"))
951     (if mmlp
952         (insert "<#mml type=" (mm-handle-media-type handle))
953       (insert "<#part type=" (mm-handle-media-type handle)))
954     (dolist (elem (append (cdr (mm-handle-type handle))
955                           (cdr (mm-handle-disposition handle))))
956       (unless (symbolp (cdr elem))
957         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
958     (when (mm-handle-id handle)
959       (insert " id=\"" (mm-handle-id handle) "\""))
960     (when (mm-handle-disposition handle)
961       (insert " disposition=" (car (mm-handle-disposition handle))))
962     (when buffer
963       (insert " buffer=\"" (buffer-name buffer) "\""))
964     (when nofile
965       (insert " nofile=yes"))
966     (when (mm-handle-description handle)
967       (insert " description=\"" (mm-handle-description handle) "\""))
968     (insert ">\n")))
969
970 (defun mml-insert-parameter (&rest parameters)
971   "Insert PARAMETERS in a nice way."
972   (let (start end)
973     (dolist (param parameters)
974       (insert ";")
975       (setq start (point))
976       (insert " " param)
977       (setq end (point))
978       (goto-char start)
979       (end-of-line)
980       (if (> (current-column) 76)
981           (progn
982             (goto-char start)
983             (insert "\n")
984             (goto-char (1+ end)))
985         (goto-char end)))))
986
987 ;;;
988 ;;; Mode for inserting and editing MML forms
989 ;;;
990
991 (defvar mml-mode-map
992   (let ((sign (make-sparse-keymap))
993         (encrypt (make-sparse-keymap))
994         (signpart (make-sparse-keymap))
995         (encryptpart (make-sparse-keymap))
996         (map (make-sparse-keymap))
997         (main (make-sparse-keymap)))
998     (define-key map "\C-s" 'mml-secure-message-sign)
999     (define-key map "\C-c" 'mml-secure-message-encrypt)
1000     (define-key map "\C-e" 'mml-secure-message-sign-encrypt)
1001     (define-key map "\C-p\C-s" 'mml-secure-sign)
1002     (define-key map "\C-p\C-c" 'mml-secure-encrypt)
1003     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
1004     (define-key sign "o" 'mml-secure-message-sign-pgp)
1005     (define-key sign "s" 'mml-secure-message-sign-smime)
1006     (define-key signpart "p" 'mml-secure-sign-pgpmime)
1007     (define-key signpart "o" 'mml-secure-sign-pgp)
1008     (define-key signpart "s" 'mml-secure-sign-smime)
1009     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
1010     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
1011     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
1012     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
1013     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
1014     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
1015     (define-key map "\C-n" 'mml-unsecure-message)
1016     (define-key map "f" 'mml-attach-file)
1017     (define-key map "b" 'mml-attach-buffer)
1018     (define-key map "e" 'mml-attach-external)
1019     (define-key map "q" 'mml-quote-region)
1020     (define-key map "m" 'mml-insert-multipart)
1021     (define-key map "p" 'mml-insert-part)
1022     (define-key map "v" 'mml-validate)
1023     (define-key map "P" 'mml-preview)
1024     (define-key map "s" sign)
1025     (define-key map "S" signpart)
1026     (define-key map "c" encrypt)
1027     (define-key map "C" encryptpart)
1028     ;;(define-key map "n" 'mml-narrow-to-part)
1029     ;; `M-m' conflicts with `back-to-indentation'.
1030     ;; (define-key main "\M-m" map)
1031     (define-key main "\C-c\C-m" map)
1032     main))
1033
1034 (easy-menu-define
1035   mml-menu mml-mode-map ""
1036   `("Attachments"
1037     ["Attach File..." mml-attach-file
1038      ,@(if (featurep 'xemacs) '(t)
1039          '(:help "Attach a file at point"))]
1040     ["Attach Buffer..." mml-attach-buffer
1041      ,@(if (featurep 'xemacs) '(t)
1042          '(:help "Attach a buffer to the outgoing message"))]
1043     ["Attach External..." mml-attach-external
1044      ,@(if (featurep 'xemacs) '(t)
1045          '(:help "Attach reference to an external file"))]
1046     ;; FIXME: Is it possible to do this without using
1047     ;; `gnus-gcc-externalize-attachments'?
1048     ["Externalize Attachments"
1049      (lambda ()
1050        (interactive)
1051        (if (not (and (boundp 'gnus-gcc-externalize-attachments)
1052                      (memq gnus-gcc-externalize-attachments
1053                            '(all t nil))))
1054            ;; Stupid workaround for XEmacs not honoring :visible.
1055            (message "Can't handle this value of `gnus-gcc-externalize-attachments'")
1056          (setq gnus-gcc-externalize-attachments
1057                (not gnus-gcc-externalize-attachments))
1058          (message "gnus-gcc-externalize-attachments is `%s'."
1059                   gnus-gcc-externalize-attachments)))
1060      ;; XEmacs barfs on :visible.
1061      ,@(if (featurep 'xemacs) nil
1062          '(:visible (and (boundp 'gnus-gcc-externalize-attachments)
1063                          (memq gnus-gcc-externalize-attachments
1064                                '(all t nil)))))
1065      :style toggle
1066      :selected gnus-gcc-externalize-attachments
1067      ,@(if (featurep 'xemacs) nil
1068          '(:help "Save attachments as external parts in Gcc copies"))]
1069     "----"
1070     ;;
1071     ("Change Security Method"
1072      ["PGP/MIME"
1073       (lambda () (interactive) (setq mml-secure-method "pgpmime"))
1074       ,@(if (featurep 'xemacs) nil
1075           '(:help "Set Security Method to PGP/MIME"))
1076       :style radio
1077       :selected (equal mml-secure-method "pgpmime") ]
1078      ["S/MIME"
1079       (lambda () (interactive) (setq mml-secure-method "smime"))
1080       ,@(if (featurep 'xemacs) nil
1081           '(:help "Set Security Method to S/MIME"))
1082       :style radio
1083       :selected (equal mml-secure-method "smime") ]
1084      ["Inline PGP"
1085       (lambda () (interactive) (setq mml-secure-method "pgp"))
1086       ,@(if (featurep 'xemacs) nil
1087           '(:help "Set Security Method to inline PGP"))
1088       :style radio
1089       :selected (equal mml-secure-method "pgp") ] )
1090     ;;
1091     ["Sign Message" mml-secure-message-sign t]
1092     ["Encrypt Message" mml-secure-message-encrypt t]
1093     ["Sign and Encrypt Message" mml-secure-message-sign-encrypt t]
1094     ["Encrypt/Sign off" mml-unsecure-message
1095      ,@(if (featurep 'xemacs) '(t)
1096          '(:help "Don't Encrypt/Sign Message"))]
1097     ;; Do we have separate encrypt and encrypt/sign commands for parts?
1098     ["Sign Part" mml-secure-sign t]
1099     ["Encrypt Part" mml-secure-encrypt t]
1100     "----"
1101     ;; Maybe we could remove these, because people who write MML most probably
1102     ;; don't use the menu:
1103     ["Insert Part..." mml-insert-part
1104      :active (message-in-body-p)]
1105     ["Insert Multipart..." mml-insert-multipart
1106      :active (message-in-body-p)]
1107     ;;
1108     ;;["Narrow" mml-narrow-to-part t]
1109     ["Quote MML in region" mml-quote-region
1110      :active (message-mark-active-p)
1111      ,@(if (featurep 'xemacs) nil
1112          '(:help "Quote MML tags in region"))]
1113     ["Validate MML" mml-validate t]
1114     ["Preview" mml-preview t]
1115     "----"
1116     ["Emacs MIME manual" (lambda () (interactive) (message-info 4))
1117      ,@(if (featurep 'xemacs) '(t)
1118          '(:help "Display the Emacs MIME manual"))]
1119     ["PGG manual" (lambda () (interactive) (message-info mml2015-use))
1120      ;; XEmacs barfs on :visible.
1121      ,@(if (featurep 'xemacs) nil
1122          '(:visible (and (boundp 'mml2015-use) (equal mml2015-use 'pgg))))
1123      ,@(if (featurep 'xemacs) '(t)
1124          '(:help "Display the PGG manual"))]
1125     ["EasyPG manual" (lambda () (interactive) (require 'mml2015) (message-info mml2015-use))
1126      ;; XEmacs barfs on :visible.
1127      ,@(if (featurep 'xemacs) nil
1128          '(:visible (and (boundp 'mml2015-use) (equal mml2015-use 'epg))))
1129      ,@(if (featurep 'xemacs) '(t)
1130          '(:help "Display the EasyPG manual"))]))
1131
1132 (defvar mml-mode nil
1133   "Minor mode for editing MML.")
1134
1135 (defun mml-mode (&optional arg)
1136   "Minor mode for editing MML.
1137 MML is the MIME Meta Language, a minor mode for composing MIME articles.
1138 See Info node `(emacs-mime)Composing'.
1139
1140 \\{mml-mode-map}"
1141   (interactive "P")
1142   (when (set (make-local-variable 'mml-mode)
1143              (if (null arg) (not mml-mode)
1144                (> (prefix-numeric-value arg) 0)))
1145     (add-minor-mode 'mml-mode " MML" mml-mode-map)
1146     (easy-menu-add mml-menu mml-mode-map)
1147     (when (boundp 'dnd-protocol-alist)
1148       (set (make-local-variable 'dnd-protocol-alist)
1149            (append mml-dnd-protocol-alist dnd-protocol-alist)))
1150     (run-hooks 'mml-mode-hook)))
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