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