Import Oort Gnus v0.09.
[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, 2003 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                (sender (cdr (assq 'sender taginfo)))
155                (location (cdr (assq 'tag-location taginfo)))
156                (mode (cdr (assq 'mode taginfo)))
157                (method (cdr (assq 'method taginfo)))
158                tags)
159           (save-excursion
160             (if
161                 (re-search-forward
162                  "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
163                 (setq secure-mode "multipart")
164               (setq secure-mode "part")))
165           (save-excursion
166             (goto-char location)
167             (re-search-forward "<#secure[^\n]*>\n"))
168           (delete-region (match-beginning 0) (match-end 0))
169           (cond ((string= mode "sign")
170                  (setq tags (list "sign" method)))
171                 ((string= mode "encrypt")
172                  (setq tags (list "encrypt" method)))
173                 ((string= mode "signencrypt")
174                  (setq tags (list "sign" method "encrypt" method))))
175           (eval `(mml-insert-tag ,secure-mode
176                                  ,@tags
177                                  ,(if recipients "recipients")
178                                  ,recipients
179                                  ,(if sender "sender")
180                                  ,sender))
181           ;; restart the parse
182           (goto-char location)))
183        ((looking-at "<#multipart")
184         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
185        ((looking-at "<#external")
186         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
187               struct))
188        (t
189         (if (or (looking-at "<#part") (looking-at "<#mml"))
190             (setq tag (mml-read-tag)
191                   no-markup-p nil
192                   warn nil)
193           (setq tag (list 'part '(type . "text/plain"))
194                 no-markup-p t
195                 warn t))
196         (setq raw (cdr (assq 'raw tag))
197               point (point)
198               contents (mml-read-part (eq 'mml (car tag)))
199               charsets (cond
200                         (raw nil)
201                         ((assq 'charset tag)
202                          (list
203                           (intern (downcase (cdr (assq 'charset tag))))))
204                         (t
205                          (mm-find-mime-charset-region point (point)
206                                                       mm-hack-charsets))))
207         (when (and (not raw) (memq nil charsets))
208           (if (or (memq 'unknown-encoding mml-confirmation-set)
209                   (message-options-get 'unknown-encoding)
210                   (and (y-or-n-p "\
211 Message contains characters with unknown encoding.  Really send?")
212                        (message-options-set 'unknown-encoding t)))
213               (if (setq use-ascii
214                         (or (memq 'use-ascii mml-confirmation-set)
215                             (message-options-get 'use-ascii)
216                             (and (y-or-n-p "Use ASCII as charset?")
217                                  (message-options-set 'use-ascii t))))
218                   (setq charsets (delq nil charsets))
219                 (setq warn nil))
220             (error "Edit your message to remove those characters")))
221         (if (or raw
222                 (eq 'mml (car tag))
223                 (< (length charsets) 2))
224             (if (or (not no-markup-p)
225                     (string-match "[^ \t\r\n]" contents))
226                 ;; Don't create blank parts.
227                 (push (nconc tag (list (cons 'contents contents)))
228                       struct))
229           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
230                           tag point (point) use-ascii)))
231             (when (and warn
232                        (not (memq 'multipart mml-confirmation-set))
233                        (not (message-options-get 'multipart))
234                        (not (and (y-or-n-p (format "\
235 A message part needs to be split into %d charset parts.  Really send? "
236                                                    (length nstruct)))
237                                  (message-options-set 'multipart t))))
238               (error "Edit your message to use only one charset"))
239             (setq struct (nconc nstruct struct)))))))
240     (unless (eobp)
241       (forward-line 1))
242     (nreverse struct)))
243
244 (defun mml-parse-singlepart-with-multiple-charsets
245   (orig-tag beg end &optional use-ascii)
246   (save-excursion
247     (save-restriction
248       (narrow-to-region beg end)
249       (goto-char (point-min))
250       (let ((current (or (mm-mime-charset (mm-charset-after))
251                          (and use-ascii 'us-ascii)))
252             charset struct space newline paragraph)
253         (while (not (eobp))
254           (setq charset (mm-mime-charset (mm-charset-after)))
255           (cond
256            ;; The charset remains the same.
257            ((eq charset 'us-ascii))
258            ((or (and use-ascii (not charset))
259                 (eq charset current))
260             (setq space nil
261                   newline nil
262                   paragraph nil))
263            ;; The initial charset was ascii.
264            ((eq current 'us-ascii)
265             (setq current charset
266                   space nil
267                   newline nil
268                   paragraph nil))
269            ;; We have a change in charsets.
270            (t
271             (push (append
272                    orig-tag
273                    (list (cons 'contents
274                                (buffer-substring-no-properties
275                                 beg (or paragraph newline space (point))))))
276                   struct)
277             (setq beg (or paragraph newline space (point))
278                   current charset
279                   space nil
280                   newline nil
281                   paragraph nil)))
282           ;; Compute places where it might be nice to break the part.
283           (cond
284            ((memq (following-char) '(?  ?\t))
285             (setq space (1+ (point))))
286            ((and (eq (following-char) ?\n)
287                  (not (bobp))
288                  (eq (char-after (1- (point))) ?\n))
289             (setq paragraph (point)))
290            ((eq (following-char) ?\n)
291             (setq newline (1+ (point)))))
292           (forward-char 1))
293         ;; Do the final part.
294         (unless (= beg (point))
295           (push (append orig-tag
296                         (list (cons 'contents
297                                     (buffer-substring-no-properties
298                                      beg (point)))))
299                 struct))
300         struct))))
301
302 (defun mml-read-tag ()
303   "Read a tag and return the contents."
304   (let ((orig-point (point))
305         contents name elem val)
306     (forward-char 2)
307     (setq name (buffer-substring-no-properties
308                 (point) (progn (forward-sexp 1) (point))))
309     (skip-chars-forward " \t\n")
310     (while (not (looking-at ">[ \t]*\n?"))
311       (setq elem (buffer-substring-no-properties
312                   (point) (progn (forward-sexp 1) (point))))
313       (skip-chars-forward "= \t\n")
314       (setq val (buffer-substring-no-properties
315                  (point) (progn (forward-sexp 1) (point))))
316       (when (string-match "^\"\\(.*\\)\"$" val)
317         (setq val (match-string 1 val)))
318       (push (cons (intern elem) val) contents)
319       (skip-chars-forward " \t\n"))
320     (goto-char (match-end 0))
321     ;; Don't skip the leading space.
322     ;;(skip-chars-forward " \t\n")
323     ;; Put the tag location into the returned contents
324     (setq contents (append (list (cons 'tag-location orig-point)) contents))
325     (cons (intern name) (nreverse contents))))
326
327 (defun mml-buffer-substring-no-properties-except-hard-newlines (start end)
328   (let ((str (buffer-substring-no-properties start end))
329         (bufstart start) tmp)
330     (while (setq tmp (text-property-any start end 'hard 't))
331       (set-text-properties (- tmp bufstart) (- tmp bufstart -1)
332                            '(hard t) str)
333       (setq start (1+ tmp)))
334     str))
335
336 (defun mml-read-part (&optional mml)
337   "Return the buffer up till the next part, multipart or closing part or multipart.
338 If MML is non-nil, return the buffer up till the correspondent mml tag."
339   (let ((beg (point)) (count 1))
340     ;; If the tag ended at the end of the line, we go to the next line.
341     (when (looking-at "[ \t]*\n")
342       (forward-line 1))
343     (if mml
344         (progn
345           (while (and (> count 0) (not (eobp)))
346             (if (re-search-forward "<#\\(/\\)?mml." nil t)
347                 (setq count (+ count (if (match-beginning 1) -1 1)))
348               (goto-char (point-max))))
349           (mml-buffer-substring-no-properties-except-hard-newlines
350            beg (if (> count 0)
351                    (point)
352                  (match-beginning 0))))
353       (if (re-search-forward
354            "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)." nil t)
355           (prog1
356               (mml-buffer-substring-no-properties-except-hard-newlines
357                beg (match-beginning 0))
358             (if (or (not (match-beginning 1))
359                     (equal (match-string 2) "multipart"))
360                 (goto-char (match-beginning 0))
361               (when (looking-at "[ \t]*\n")
362                 (forward-line 1))))
363         (mml-buffer-substring-no-properties-except-hard-newlines
364          beg (goto-char (point-max)))))))
365
366 (defvar mml-boundary nil)
367 (defvar mml-base-boundary "-=-=")
368 (defvar mml-multipart-number 0)
369
370 (defun mml-generate-mime ()
371   "Generate a MIME message based on the current MML document."
372   (let ((cont (mml-parse))
373         (mml-multipart-number mml-multipart-number))
374     (if (not cont)
375         nil
376       (with-temp-buffer
377         (if (and (consp (car cont))
378                  (= (length cont) 1))
379             (mml-generate-mime-1 (car cont))
380           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
381                                       cont)))
382         (buffer-string)))))
383
384 (defun mml-generate-mime-1 (cont)
385   (let ((mm-use-ultra-safe-encoding
386          (or mm-use-ultra-safe-encoding (assq 'sign cont))))
387     (save-restriction
388       (narrow-to-region (point) (point))
389       (mml-tweak-part cont)
390       (cond
391        ((or (eq (car cont) 'part) (eq (car cont) 'mml))
392         (let ((raw (cdr (assq 'raw cont)))
393               coded encoding charset filename type flowed)
394           (setq type (or (cdr (assq 'type cont)) "text/plain"))
395           (if (and (not raw)
396                    (member (car (split-string type "/")) '("text" "message")))
397               (progn
398                 (with-temp-buffer
399                   (setq charset (mm-charset-to-coding-system
400                                  (cdr (assq 'charset cont))))
401                   (when (eq charset 'ascii)
402                     (setq charset nil))
403                   (cond
404                    ((cdr (assq 'buffer cont))
405                     (insert-buffer-substring (cdr (assq 'buffer cont))))
406                    ((and (setq filename (cdr (assq 'filename cont)))
407                          (not (equal (cdr (assq 'nofile cont)) "yes")))
408                     (let ((coding-system-for-read charset))
409                       (mm-insert-file-contents filename)))
410                    ((eq 'mml (car cont))
411                     (insert (cdr (assq 'contents cont))))
412                    (t
413                     (save-restriction
414                       (narrow-to-region (point) (point))
415                       (insert (cdr (assq 'contents cont)))
416                       ;; Remove quotes from quoted tags.
417                       (goto-char (point-min))
418                       (while (re-search-forward
419                               "<#!+/?\\(part\\|multipart\\|external\\|mml\\)"
420                               nil t)
421                         (delete-region (+ (match-beginning 0) 2)
422                                        (+ (match-beginning 0) 3))))))
423                   (cond
424                    ((eq (car cont) 'mml)
425                     (let ((mml-boundary (funcall mml-boundary-function
426                                                  (incf mml-multipart-number)))
427                           (mml-generate-default-type "text/plain"))
428                       (mml-to-mime))
429                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
430                       ;; ignore 0x1b, it is part of iso-2022-jp
431                       (setq encoding (mm-body-7-or-8))))
432                    ((string= (car (split-string type "/")) "message")
433                     (let ((mm-7bit-chars (concat mm-7bit-chars "\x1b")))
434                       ;; ignore 0x1b, it is part of iso-2022-jp
435                       (setq encoding (mm-body-7-or-8))))
436                    (t
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 charset (mm-encode-body charset))
455                     (setq encoding (mm-body-encoding
456                                     charset (cdr (assq 'encoding cont))))))
457                   (setq coded (buffer-string)))
458                 (mml-insert-mime-headers cont type charset encoding flowed)
459                 (insert "\n")
460                 (insert coded))
461             (mm-with-unibyte-buffer
462               (cond
463                ((cdr (assq 'buffer cont))
464                 (insert-buffer-substring (cdr (assq 'buffer cont))))
465                ((and (setq filename (cdr (assq 'filename cont)))
466                      (not (equal (cdr (assq 'nofile cont)) "yes")))
467                 (let ((coding-system-for-read mm-binary-coding-system))
468                   (mm-insert-file-contents filename nil nil nil nil t)))
469                (t
470                 (insert (cdr (assq 'contents cont)))))
471               (setq encoding (mm-encode-buffer type)
472                     coded (mm-string-as-multibyte (buffer-string))))
473             (mml-insert-mime-headers cont type charset encoding nil)
474             (insert "\n")
475             (mm-with-unibyte-current-buffer
476               (insert coded)))))
477        ((eq (car cont) 'external)
478         (insert "Content-Type: message/external-body")
479         (let ((parameters (mml-parameter-string
480                            cont '(expiration size permission)))
481               (name (cdr (assq 'name cont)))
482               (url (cdr (assq 'url cont))))
483           (when name
484             (setq name (mml-parse-file-name name))
485             (if (stringp name)
486                 (mml-insert-parameter
487                  (mail-header-encode-parameter "name" name)
488                  "access-type=local-file")
489               (mml-insert-parameter
490                (mail-header-encode-parameter
491                 "name" (file-name-nondirectory (nth 2 name)))
492                (mail-header-encode-parameter "site" (nth 1 name))
493                (mail-header-encode-parameter
494                 "directory" (file-name-directory (nth 2 name))))
495               (mml-insert-parameter
496                (concat "access-type="
497                        (if (member (nth 0 name) '("ftp@" "anonymous@"))
498                            "anon-ftp"
499                          "ftp")))))
500           (when url
501             (mml-insert-parameter
502              (mail-header-encode-parameter "url" url)
503              "access-type=url"))
504           (when parameters
505             (mml-insert-parameter-string
506              cont '(expiration size permission))))
507         (insert "\n\n")
508         (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
509         (insert "Content-ID: " (message-make-message-id) "\n")
510         (insert "Content-Transfer-Encoding: "
511                 (or (cdr (assq 'encoding cont)) "binary"))
512         (insert "\n\n")
513         (insert (or (cdr (assq 'contents cont))))
514         (insert "\n"))
515        ((eq (car cont) 'multipart)
516         (let* ((type (or (cdr (assq 'type cont)) "mixed"))
517                (mml-generate-default-type (if (equal type "digest")
518                                               "message/rfc822"
519                                             "text/plain"))
520                (handler (assoc type mml-generate-multipart-alist)))
521           (if handler
522               (funcall (cdr handler) cont)
523             ;; No specific handler.  Use default one.
524             (let ((mml-boundary (mml-compute-boundary cont)))
525               (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
526                               type mml-boundary))
527               (let ((cont cont) part)
528                 (while (setq part (pop cont))
529                   ;; Skip `multipart' and attributes.
530                   (when (and (consp part) (consp (cdr part)))
531                     (insert "\n--" mml-boundary "\n")
532                     (mml-generate-mime-1 part))))
533               (insert "\n--" mml-boundary "--\n")))))
534        (t
535         (error "Invalid element: %S" cont)))
536       ;; handle sign & encrypt tags in a semi-smart way.
537       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
538             (encrypt-item (assoc (cdr (assq 'encrypt cont))
539                                  mml-encrypt-alist))
540             sender recipients)
541         (when (or sign-item encrypt-item)
542           (if (setq sender (cdr (assq 'sender cont)))
543               (message-options-set 'message-sender sender))
544           (if (setq recipients (cdr (assq 'recipients cont)))
545               (message-options-set 'message-recipients recipients))
546           (let ((style (mml-signencrypt-style (first (or sign-item encrypt-item)))))
547             ;; check if: we're both signing & encrypting, both methods
548             ;; are the same (why would they be different?!), and that
549             ;; the signencrypt style allows for combined operation.
550             (if (and sign-item encrypt-item (equal (first sign-item)
551                                                    (first encrypt-item))
552                      (equal style 'combined))
553                 (funcall (nth 1 encrypt-item) cont t)
554               ;; otherwise, revert to the old behavior.
555               (when sign-item
556                 (funcall (nth 1 sign-item) cont))
557               (when encrypt-item
558                 (funcall (nth 1 encrypt-item) cont)))))))))
559
560 (defun mml-compute-boundary (cont)
561   "Return a unique boundary that does not exist in CONT."
562   (let ((mml-boundary (funcall mml-boundary-function
563                                (incf mml-multipart-number))))
564     ;; This function tries again and again until it has found
565     ;; a unique boundary.
566     (while (not (catch 'not-unique
567                   (mml-compute-boundary-1 cont))))
568     mml-boundary))
569
570 (defun mml-compute-boundary-1 (cont)
571   (let (filename)
572     (cond
573      ((eq (car cont) 'part)
574       (with-temp-buffer
575         (cond
576          ((cdr (assq 'buffer cont))
577           (insert-buffer-substring (cdr (assq 'buffer cont))))
578          ((and (setq filename (cdr (assq 'filename cont)))
579                (not (equal (cdr (assq 'nofile cont)) "yes")))
580           (mm-insert-file-contents filename))
581          (t
582           (insert (cdr (assq 'contents cont)))))
583         (goto-char (point-min))
584         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
585                                  nil t)
586           (setq mml-boundary (funcall mml-boundary-function
587                                       (incf mml-multipart-number)))
588           (throw 'not-unique nil))))
589      ((eq (car cont) 'multipart)
590       (mapcar 'mml-compute-boundary-1 (cddr cont))))
591     t))
592
593 (defun mml-make-boundary (number)
594   (concat (make-string (% number 60) ?=)
595           (if (> number 17)
596               (format "%x" number)
597             "")
598           mml-base-boundary))
599
600 (defun mml-insert-mime-headers (cont type charset encoding flowed)
601   (let (parameters disposition description)
602     (setq parameters
603           (mml-parameter-string
604            cont mml-content-type-parameters))
605     (when (or charset
606               parameters
607               flowed
608               (not (equal type mml-generate-default-type)))
609       (when (consp charset)
610         (error
611          "Can't encode a part with several charsets."))
612       (insert "Content-Type: " type)
613       (when charset
614         (insert "; " (mail-header-encode-parameter
615                       "charset" (symbol-name charset))))
616       (when flowed
617         (insert "; format=flowed"))
618       (when parameters
619         (mml-insert-parameter-string
620          cont mml-content-type-parameters))
621       (insert "\n"))
622     (setq parameters
623           (mml-parameter-string
624            cont mml-content-disposition-parameters))
625     (when (or (setq disposition (cdr (assq 'disposition cont)))
626               parameters)
627       (insert "Content-Disposition: " (or disposition "inline"))
628       (when parameters
629         (mml-insert-parameter-string
630          cont mml-content-disposition-parameters))
631       (insert "\n"))
632     (unless (eq encoding '7bit)
633       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
634     (when (setq description (cdr (assq 'description cont)))
635       (insert "Content-Description: "
636               (mail-encode-encoded-word-string description) "\n"))))
637
638 (defun mml-parameter-string (cont types)
639   (let ((string "")
640         value type)
641     (while (setq type (pop types))
642       (when (setq value (cdr (assq type cont)))
643         ;; Strip directory component from the filename parameter.
644         (when (eq type 'filename)
645           (setq value (file-name-nondirectory value)))
646         (setq string (concat string "; "
647                              (mail-header-encode-parameter
648                               (symbol-name type) value)))))
649     (when (not (zerop (length string)))
650       string)))
651
652 (defun mml-insert-parameter-string (cont types)
653   (let (value type)
654     (while (setq type (pop types))
655       (when (setq value (cdr (assq type cont)))
656         ;; Strip directory component from the filename parameter.
657         (when (eq type 'filename)
658           (setq value (file-name-nondirectory value)))
659         (mml-insert-parameter
660          (mail-header-encode-parameter
661           (symbol-name type) value))))))
662
663 (eval-when-compile
664   (defvar ange-ftp-name-format)
665   (defvar efs-path-regexp))
666 (defun mml-parse-file-name (path)
667   (if (if (boundp 'efs-path-regexp)
668           (string-match efs-path-regexp path)
669         (if (boundp 'ange-ftp-name-format)
670             (string-match (car ange-ftp-name-format) path)))
671       (list (match-string 1 path) (match-string 2 path)
672             (substring path (1+ (match-end 2))))
673     path))
674
675 (defun mml-insert-buffer (buffer)
676   "Insert BUFFER at point and quote any MML markup."
677   (save-restriction
678     (narrow-to-region (point) (point))
679     (insert-buffer-substring buffer)
680     (mml-quote-region (point-min) (point-max))
681     (goto-char (point-max))))
682
683 ;;;
684 ;;; Transforming MIME to MML
685 ;;;
686
687 (defun mime-to-mml (&optional handles)
688   "Translate the current buffer (which should be a message) into MML.
689 If HANDLES is non-nil, use it instead reparsing the buffer."
690   ;; First decode the head.
691   (save-restriction
692     (message-narrow-to-head)
693     (mail-decode-encoded-word-region (point-min) (point-max)))
694   (unless handles
695     (setq handles (mm-dissect-buffer t)))
696   (goto-char (point-min))
697   (search-forward "\n\n" nil t)
698   (delete-region (point) (point-max))
699   (if (stringp (car handles))
700       (mml-insert-mime handles)
701     (mml-insert-mime handles t))
702   (mm-destroy-parts handles)
703   (save-restriction
704     (message-narrow-to-head)
705     ;; Remove them, they are confusing.
706     (message-remove-header "Content-Type")
707     (message-remove-header "MIME-Version")
708     (message-remove-header "Content-Disposition")
709     (message-remove-header "Content-Transfer-Encoding")))
710
711 (defun mml-to-mime ()
712   "Translate the current buffer from MML to MIME."
713   (message-encode-message-body)
714   (save-restriction
715     (message-narrow-to-headers-or-head)
716     ;; Skip past any From_ headers.
717     (while (looking-at "From ")
718       (forward-line 1))
719     (let ((mail-parse-charset message-default-charset))
720       (mail-encode-encoded-word-buffer))))
721
722 (defun mml-insert-mime (handle &optional no-markup)
723   (let (textp buffer mmlp)
724     ;; Determine type and stuff.
725     (unless (stringp (car handle))
726       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
727         (save-excursion
728           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
729           (mm-insert-part handle)
730           (if (setq mmlp (equal (mm-handle-media-type handle)
731                                 "message/rfc822"))
732               (mime-to-mml)))))
733     (if mmlp
734         (mml-insert-mml-markup handle nil t t)
735       (unless (and no-markup
736                    (equal (mm-handle-media-type handle) "text/plain"))
737         (mml-insert-mml-markup handle buffer textp)))
738     (cond
739      (mmlp
740       (insert-buffer buffer)
741       (goto-char (point-max))
742       (insert "<#/mml>\n"))
743      ((stringp (car handle))
744       (mapcar 'mml-insert-mime (cdr handle))
745       (insert "<#/multipart>\n"))
746      (textp
747       (let ((charset (mail-content-type-get
748                       (mm-handle-type handle) 'charset)))
749         (if (eq charset 'gnus-decoded)
750             (mm-insert-part handle)
751           (insert (mm-decode-string (mm-get-part handle) charset))))
752       (goto-char (point-max)))
753      (t
754       (insert "<#/part>\n")))))
755
756 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
757   "Take a MIME handle and insert an MML tag."
758   (if (stringp (car handle))
759       (insert "<#multipart type=" (mm-handle-media-subtype handle)
760               ">\n")
761     (if mmlp
762         (insert "<#mml type=" (mm-handle-media-type handle))
763       (insert "<#part type=" (mm-handle-media-type handle)))
764     (dolist (elem (append (cdr (mm-handle-type handle))
765                           (cdr (mm-handle-disposition handle))))
766       (unless (symbolp (cdr elem))
767         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
768     (when (mm-handle-disposition handle)
769       (insert " disposition=" (car (mm-handle-disposition handle))))
770     (when buffer
771       (insert " buffer=\"" (buffer-name buffer) "\""))
772     (when nofile
773       (insert " nofile=yes"))
774     (when (mm-handle-description handle)
775       (insert " description=\"" (mm-handle-description handle) "\""))
776     (insert ">\n")))
777
778 (defun mml-insert-parameter (&rest parameters)
779   "Insert PARAMETERS in a nice way."
780   (dolist (param parameters)
781     (insert ";")
782     (let ((point (point)))
783       (insert " " param)
784       (when (> (current-column) 71)
785         (goto-char point)
786         (insert "\n ")
787         (end-of-line)))))
788
789 ;;;
790 ;;; Mode for inserting and editing MML forms
791 ;;;
792
793 (defvar mml-mode-map
794   (let ((sign (make-sparse-keymap))
795         (encrypt (make-sparse-keymap))
796         (signpart (make-sparse-keymap))
797         (encryptpart (make-sparse-keymap))
798         (map (make-sparse-keymap))
799         (main (make-sparse-keymap)))
800     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
801     (define-key sign "o" 'mml-secure-message-sign-pgp)
802     (define-key sign "s" 'mml-secure-message-sign-smime)
803     (define-key signpart "p" 'mml-secure-sign-pgpmime)
804     (define-key signpart "o" 'mml-secure-sign-pgp)
805     (define-key signpart "s" 'mml-secure-sign-smime)
806     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
807     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
808     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
809     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
810     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
811     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
812     (define-key map "\C-n" 'mml-unsecure-message)
813     (define-key map "f" 'mml-attach-file)
814     (define-key map "b" 'mml-attach-buffer)
815     (define-key map "e" 'mml-attach-external)
816     (define-key map "q" 'mml-quote-region)
817     (define-key map "m" 'mml-insert-multipart)
818     (define-key map "p" 'mml-insert-part)
819     (define-key map "v" 'mml-validate)
820     (define-key map "P" 'mml-preview)
821     (define-key map "s" sign)
822     (define-key map "S" signpart)
823     (define-key map "c" encrypt)
824     (define-key map "C" encryptpart)
825     ;;(define-key map "n" 'mml-narrow-to-part)
826     ;; `M-m' conflicts with `back-to-indentation'.
827     ;; (define-key main "\M-m" map)
828     (define-key main "\C-c\C-m" map)
829     main))
830
831 (easy-menu-define
832   mml-menu mml-mode-map ""
833   `("Attachments"
834     ["Attach File..." mml-attach-file
835      ,@(if (featurep 'xemacs) '(t)
836          '(:help "Attach a file at point"))]
837     ["Attach Buffer..." mml-attach-buffer t]
838     ["Attach External..." mml-attach-external t]
839     ["Insert Part..." mml-insert-part t]
840     ["Insert Multipart..." mml-insert-multipart t]
841     ["PGP/MIME Sign" mml-secure-message-sign-pgpmime t]
842     ["PGP/MIME Encrypt" mml-secure-message-encrypt-pgpmime t]
843     ["PGP Sign" mml-secure-message-sign-pgp t]
844     ["PGP Encrypt" mml-secure-message-encrypt-pgp t]
845     ["S/MIME Sign" mml-secure-message-sign-smime t]
846     ["S/MIME Encrypt" mml-secure-message-encrypt-smime t]
847     ("Secure MIME part"
848      ["PGP/MIME Sign Part" mml-secure-sign-pgpmime t]
849      ["PGP/MIME Encrypt Part" mml-secure-encrypt-pgpmime t]
850      ["PGP Sign Part" mml-secure-sign-pgp t]
851      ["PGP Encrypt Part" mml-secure-encrypt-pgp t]
852      ["S/MIME Sign Part" mml-secure-sign-smime t]
853      ["S/MIME Encrypt Part" mml-secure-encrypt-smime t])
854     ["Encrypt/Sign off" mml-unsecure-message t]
855     ;;["Narrow" mml-narrow-to-part t]
856     ["Quote MML" mml-quote-region t]
857     ["Validate MML" mml-validate t]
858     ["Preview" mml-preview t]))
859
860 (defvar mml-mode nil
861   "Minor mode for editing MML.")
862
863 (defun mml-mode (&optional arg)
864   "Minor mode for editing MML.
865 MML is the MIME Meta Language, a minor mode for composing MIME articles.
866 See Info node `(emacs-mime)Composing'.
867
868 \\{mml-mode-map}"
869   (interactive "P")
870   (when (set (make-local-variable 'mml-mode)
871              (if (null arg) (not mml-mode)
872                (> (prefix-numeric-value arg) 0)))
873     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
874     (easy-menu-add mml-menu mml-mode-map)
875     (run-hooks 'mml-mode-hook)))
876
877 ;;;
878 ;;; Helper functions for reading MIME stuff from the minibuffer and
879 ;;; inserting stuff to the buffer.
880 ;;;
881
882 (defun mml-minibuffer-read-file (prompt)
883   (let ((file (read-file-name prompt nil nil t)))
884     ;; Prevent some common errors.  This is inspired by similar code in
885     ;; VM.
886     (when (file-directory-p file)
887       (error "%s is a directory, cannot attach" file))
888     (unless (file-exists-p file)
889       (error "No such file: %s" file))
890     (unless (file-readable-p file)
891       (error "Permission denied: %s" file))
892     file))
893
894 (defun mml-minibuffer-read-type (name &optional default)
895   (mailcap-parse-mimetypes)
896   (let* ((default (or default
897                       (mm-default-file-encoding name)
898                       ;; Perhaps here we should check what the file
899                       ;; looks like, and offer text/plain if it looks
900                       ;; like text/plain.
901                       "application/octet-stream"))
902          (string (completing-read
903                   (format "Content type (default %s): " default)
904                   (mapcar 'list (mailcap-mime-types)))))
905     (if (not (equal string ""))
906         string
907       default)))
908
909 (defun mml-minibuffer-read-description ()
910   (let ((description (read-string "One line description: ")))
911     (when (string-match "\\`[ \t]*\\'" description)
912       (setq description nil))
913     description))
914
915 (defun mml-quote-region (beg end)
916   "Quote the MML tags in the region."
917   (interactive "r")
918   (save-excursion
919     (save-restriction
920       ;; Temporarily narrow the region to defend from changes
921       ;; invalidating END.
922       (narrow-to-region beg end)
923       (goto-char (point-min))
924       ;; Quote parts.
925       (while (re-search-forward
926               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
927         ;; Insert ! after the #.
928         (goto-char (+ (match-beginning 0) 2))
929         (insert "!")))))
930
931 (defun mml-insert-tag (name &rest plist)
932   "Insert an MML tag described by NAME and PLIST."
933   (when (symbolp name)
934     (setq name (symbol-name name)))
935   (insert "<#" name)
936   (while plist
937     (let ((key (pop plist))
938           (value (pop plist)))
939       (when value
940         ;; Quote VALUE if it contains suspicious characters.
941         (when (string-match "[\"'\\~/*;() \t\n]" value)
942           (setq value (with-output-to-string
943                         (let (print-escape-nonascii)
944                           (prin1 value)))))
945         (insert (format " %s=%s" key value)))))
946   (insert ">\n"))
947
948 (defun mml-insert-empty-tag (name &rest plist)
949   "Insert an empty MML tag described by NAME and PLIST."
950   (when (symbolp name)
951     (setq name (symbol-name name)))
952   (apply #'mml-insert-tag name plist)
953   (insert "<#/" name ">\n"))
954
955 ;;; Attachment functions.
956
957 (defun mml-attach-file (file &optional type description)
958   "Attach a file to the outgoing MIME message.
959 The file is not inserted or encoded until you send the message with
960 `\\[message-send-and-exit]' or `\\[message-send]'.
961
962 FILE is the name of the file to attach.  TYPE is its content-type, a
963 string of the form \"type/subtype\".  DESCRIPTION is a one-line
964 description of the attachment."
965   (interactive
966    (let* ((file (mml-minibuffer-read-file "Attach file: "))
967           (type (mml-minibuffer-read-type file))
968           (description (mml-minibuffer-read-description)))
969      (list file type description)))
970   (mml-insert-empty-tag 'part 'type type 'filename file
971                         'disposition "attachment" 'description description))
972
973 (defun mml-attach-buffer (buffer &optional type description)
974   "Attach a buffer to the outgoing MIME message.
975 See `mml-attach-file' for details of operation."
976   (interactive
977    (let* ((buffer (read-buffer "Attach buffer: "))
978           (type (mml-minibuffer-read-type buffer "text/plain"))
979           (description (mml-minibuffer-read-description)))
980      (list buffer type description)))
981   (mml-insert-empty-tag 'part 'type type 'buffer buffer
982                         'disposition "attachment" 'description description))
983
984 (defun mml-attach-external (file &optional type description)
985   "Attach an external file into the buffer.
986 FILE is an ange-ftp/efs specification of the part location.
987 TYPE is the MIME type to use."
988   (interactive
989    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
990           (type (mml-minibuffer-read-type file))
991           (description (mml-minibuffer-read-description)))
992      (list file type description)))
993   (mml-insert-empty-tag 'external 'type type 'name file
994                         'disposition "attachment" 'description description))
995
996 (defun mml-insert-multipart (&optional type)
997   (interactive (list (completing-read "Multipart type (default mixed): "
998                                       '(("mixed") ("alternative") ("digest") ("parallel")
999                                         ("signed") ("encrypted"))
1000                                       nil nil "mixed")))
1001   (or type
1002       (setq type "mixed"))
1003   (mml-insert-empty-tag "multipart" 'type type)
1004   (forward-line -1))
1005
1006 (defun mml-insert-part (&optional type)
1007   (interactive
1008    (list (mml-minibuffer-read-type "")))
1009   (mml-insert-tag 'part 'type type 'disposition "inline")
1010   (forward-line -1))
1011
1012 (defun mml-preview-insert-mft ()
1013   "Insert a Mail-Followup-To header before previewing an article.
1014 Should be adopted if code in `message-send-mail' is changed."
1015   (when (and (message-mail-p)
1016              (message-subscribed-p)
1017              (not (mail-fetch-field "mail-followup-to"))
1018              (message-make-mft))
1019     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1020     (insert (message-make-mft))))
1021
1022 (defun mml-preview (&optional raw)
1023   "Display current buffer with Gnus, in a new buffer.
1024 If RAW, don't highlight the article."
1025   (interactive "P")
1026   (save-excursion
1027     (let* ((buf (current-buffer))
1028            (message-options message-options)
1029            (message-this-is-mail (message-mail-p))
1030            (message-this-is-news (message-news-p))
1031            (message-posting-charset (or (gnus-setup-posting-charset
1032                                          (save-restriction
1033                                            (message-narrow-to-headers-or-head)
1034                                            (message-fetch-field "Newsgroups")))
1035                                         message-posting-charset)))
1036       (message-options-set-recipient)
1037       (switch-to-buffer (generate-new-buffer
1038                          (concat (if raw "*Raw MIME preview of "
1039                                    "*MIME preview of ") (buffer-name))))
1040       (erase-buffer)
1041       (insert-buffer buf)
1042       (mml-preview-insert-mft)
1043       (let ((message-deletable-headers (if (message-news-p)
1044                                            nil
1045                                          message-deletable-headers)))
1046         (message-generate-headers
1047          (copy-sequence (if (message-news-p)
1048                             message-required-news-headers
1049                           message-required-mail-headers))))
1050       (if (re-search-forward
1051            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1052           (replace-match "\n"))
1053       (let ((mail-header-separator ""));; mail-header-separator is removed.
1054         (mml-to-mime))
1055       (if raw
1056           (when (fboundp 'set-buffer-multibyte)
1057             (let ((s (buffer-string)))
1058               ;; Insert the content into unibyte buffer.
1059               (erase-buffer)
1060               (mm-disable-multibyte)
1061               (insert s)))
1062         (let ((gnus-newsgroup-charset (car message-posting-charset))
1063               gnus-article-prepare-hook gnus-original-article-buffer)
1064           (run-hooks 'gnus-article-decode-hook)
1065           (let ((gnus-newsgroup-name "dummy")
1066                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1067                                         (gnus-make-hashtable 5))))
1068             (gnus-article-prepare-display))))
1069       ;; Disable article-mode-map.
1070       (use-local-map nil)
1071       (setq buffer-read-only t)
1072       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1073       (goto-char (point-min)))))
1074
1075 (defun mml-validate ()
1076   "Validate the current MML document."
1077   (interactive)
1078   (mml-parse))
1079
1080 (defun mml-tweak-part (cont)
1081   "Tweak a MML part."
1082   (let ((tweak (cdr (assq 'tweak cont)))
1083         func)
1084     (cond
1085      (tweak
1086       (setq func
1087             (or (cdr (assoc tweak mml-tweak-function-alist))
1088                 (intern tweak))))
1089      (mml-tweak-type-alist
1090       (let ((alist mml-tweak-type-alist)
1091             (type (or (cdr (assq 'type cont)) "text/plain")))
1092         (while alist
1093           (if (string-match (caar alist) type)
1094               (setq func (cdar alist)
1095                     alist nil)
1096             (setq alist (cdr alist)))))))
1097     (if func
1098         (funcall func cont)
1099       cont)
1100     (let ((alist mml-tweak-sexp-alist))
1101       (while alist
1102         (if (eval (caar alist))
1103             (funcall (cdar alist) cont))
1104         (setq alist (cdr alist)))))
1105   cont)
1106
1107 (defun mml-tweak-externalize-attachments (cont)
1108   "Tweak attached files as external parts."
1109   (let (filename-cons)
1110     (when (and (eq (car cont) 'part)
1111                (not (cdr (assq 'buffer cont)))
1112                (and (setq filename-cons (assq 'filename cont))
1113                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1114       (setcar cont 'external)
1115       (setcar filename-cons 'name))))
1116
1117 (provide 'mml)
1118
1119 ;;; mml.el ends here