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