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