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