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