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