* canlock.el (canlock-insert-header): Remove excessive grouping in regexp.
[gnus] / lisp / mml.el
1 ;;; mml.el --- A package for parsing and validating MML documents
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mm-util)
28 (require 'mm-bodies)
29 (require 'mm-encode)
30 (require 'mm-decode)
31 (require 'mml-sec)
32 (eval-when-compile (require 'cl))
33
34 (eval-and-compile
35   (autoload 'message-make-message-id "message")
36   (autoload 'gnus-setup-posting-charset "gnus-msg")
37   (autoload 'gnus-make-local-hook "gnus-util")
38   (autoload 'message-fetch-field "message")
39   (autoload 'fill-flowed-encode "flow-fill")
40   (autoload 'message-posting-charset "message"))
41
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 (defcustom mml-insert-mime-headers-always nil
57   "If non-nil, always put Content-Type: text/plain at top of empty parts.
58 It is necessary to work against a bug in certain clients."
59   :type 'boolean
60   :group 'message)
61
62 (defvar mml-tweak-type-alist nil
63   "A list of (TYPE . FUNCTION) for tweaking MML parts.
64 TYPE is a string containing a regexp to match the MIME type.  FUNCTION
65 is a Lisp function which is called with the MML handle to tweak the
66 part.  This variable is used only when no TWEAK parameter exists in
67 the MML handle.")
68
69 (defvar mml-tweak-function-alist nil
70   "A list of (NAME . FUNCTION) for tweaking MML parts.
71 NAME is a string containing the name of the TWEAK parameter in the MML
72 handle.  FUNCTION is a Lisp function which is called with the MML
73 handle to tweak the part.")
74
75 (defvar mml-tweak-sexp-alist
76   '((mml-externalize-attachments . mml-tweak-externalize-attachments))
77   "A list of (SEXP . FUNCTION) for tweaking MML parts.
78 SEXP is an s-expression.  If the evaluation of SEXP is non-nil, FUNCTION
79 is called.  FUNCTION is a Lisp function which is called with the MML
80 handle to tweak the part.")
81
82 (defvar mml-externalize-attachments nil
83   "*If non-nil, local-file attachments are generated as external parts.")
84
85 (defvar mml-generate-multipart-alist nil
86   "*Alist of multipart generation functions.
87 Each entry has the form (NAME . FUNCTION), where
88 NAME is a string containing the name of the part (without the
89 leading \"/multipart/\"),
90 FUNCTION is a Lisp function which is called to generate the part.
91
92 The Lisp function has to supply the appropriate MIME headers and the
93 contents of this part.")
94
95 (defvar mml-syntax-table
96   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
97     (modify-syntax-entry ?\\ "/" table)
98     (modify-syntax-entry ?< "(" table)
99     (modify-syntax-entry ?> ")" table)
100     (modify-syntax-entry ?@ "w" table)
101     (modify-syntax-entry ?/ "w" table)
102     (modify-syntax-entry ?= " " table)
103     (modify-syntax-entry ?* " " table)
104     (modify-syntax-entry ?\; " " table)
105     (modify-syntax-entry ?\' " " table)
106     table))
107
108 (defvar mml-boundary-function 'mml-make-boundary
109   "A function called to suggest a boundary.
110 The function may be called several times, and should try to make a new
111 suggestion each time.  The function is called with one parameter,
112 which is a number that says how many times the function has been
113 called for this message.")
114
115 (defvar mml-confirmation-set nil
116   "A list of symbols, each of which disables some warning.
117 `unknown-encoding': always send messages contain characters with
118 unknown encoding; `use-ascii': always use ASCII for those characters
119 with unknown encoding; `multipart': always send messages with more than
120 one charsets.")
121
122 (defvar mml-generate-default-type "text/plain")
123
124 (defvar mml-buffer-list nil)
125
126 (defun mml-generate-new-buffer (name)
127   (let ((buf (generate-new-buffer name)))
128     (push buf mml-buffer-list)
129     buf))
130
131 (defun mml-destroy-buffers ()
132   (let (kill-buffer-hook)
133     (mapcar 'kill-buffer mml-buffer-list)
134     (setq mml-buffer-list nil)))
135
136 (defun mml-parse ()
137   "Parse the current buffer as an MML document."
138   (save-excursion
139     (goto-char (point-min))
140     (with-syntax-table mml-syntax-table
141       (mml-parse-1))))
142
143 (defun mml-parse-1 ()
144   "Parse the current buffer as an MML document."
145   (let (struct tag point contents charsets warn use-ascii no-markup-p raw)
146     (while (and (not (eobp))
147                 (not (looking-at "<#/multipart")))
148       (cond
149        ((looking-at "<#secure")
150         ;; The secure part is essentially a meta-meta tag, which
151         ;; expands to either a part tag if there are no other parts in
152         ;; the document or a multipart tag if there are other parts
153         ;; included in the message
154         (let* (secure-mode
155                (taginfo (mml-read-tag))
156                (recipients (cdr (assq 'recipients taginfo)))
157                (sender (cdr (assq 'sender taginfo)))
158                (location (cdr (assq 'tag-location taginfo)))
159                (mode (cdr (assq 'mode taginfo)))
160                (method (cdr (assq 'method taginfo)))
161                tags)
162           (save-excursion
163             (if (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 (mml-compute-boundary cont))
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\""
527                               type mml-boundary)
528                       (if (cdr (assq 'start cont))
529                           (format "; start=\"%s\"\n" (cdr (assq 'start cont)))
530                         "\n"))
531               (let ((cont cont) part)
532                 (while (setq part (pop cont))
533                   ;; Skip `multipart' and attributes.
534                   (when (and (consp part) (consp (cdr part)))
535                     (insert "\n--" mml-boundary "\n")
536                     (mml-generate-mime-1 part))))
537               (insert "\n--" mml-boundary "--\n")))))
538        (t
539         (error "Invalid element: %S" cont)))
540       ;; handle sign & encrypt tags in a semi-smart way.
541       (let ((sign-item (assoc (cdr (assq 'sign cont)) mml-sign-alist))
542             (encrypt-item (assoc (cdr (assq 'encrypt cont))
543                                  mml-encrypt-alist))
544             sender recipients)
545         (when (or sign-item encrypt-item)
546           (when (setq sender (cdr (assq 'sender cont)))
547             (message-options-set 'mml-sender sender)
548             (message-options-set 'message-sender sender))
549           (if (setq recipients (cdr (assq 'recipients cont)))
550               (message-options-set 'message-recipients recipients))
551           (let ((style (mml-signencrypt-style (first (or sign-item encrypt-item)))))
552             ;; check if: we're both signing & encrypting, both methods
553             ;; are the same (why would they be different?!), and that
554             ;; the signencrypt style allows for combined operation.
555             (if (and sign-item encrypt-item (equal (first sign-item)
556                                                    (first encrypt-item))
557                      (equal style 'combined))
558                 (funcall (nth 1 encrypt-item) cont t)
559               ;; otherwise, revert to the old behavior.
560               (when sign-item
561                 (funcall (nth 1 sign-item) cont))
562               (when encrypt-item
563                 (funcall (nth 1 encrypt-item) cont)))))))))
564
565 (defun mml-compute-boundary (cont)
566   "Return a unique boundary that does not exist in CONT."
567   (let ((mml-boundary (funcall mml-boundary-function
568                                (incf mml-multipart-number))))
569     ;; This function tries again and again until it has found
570     ;; a unique boundary.
571     (while (not (catch 'not-unique
572                   (mml-compute-boundary-1 cont))))
573     mml-boundary))
574
575 (defun mml-compute-boundary-1 (cont)
576   (let (filename)
577     (cond
578      ((eq (car cont) 'part)
579       (with-temp-buffer
580         (cond
581          ((cdr (assq 'buffer cont))
582           (insert-buffer-substring (cdr (assq 'buffer cont))))
583          ((and (setq filename (cdr (assq 'filename cont)))
584                (not (equal (cdr (assq 'nofile cont)) "yes")))
585           (mm-insert-file-contents filename))
586          (t
587           (insert (cdr (assq 'contents cont)))))
588         (goto-char (point-min))
589         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
590                                  nil t)
591           (setq mml-boundary (funcall mml-boundary-function
592                                       (incf mml-multipart-number)))
593           (throw 'not-unique nil))))
594      ((eq (car cont) 'multipart)
595       (mapcar 'mml-compute-boundary-1 (cddr cont))))
596     t))
597
598 (defun mml-make-boundary (number)
599   (concat (make-string (% number 60) ?=)
600           (if (> number 17)
601               (format "%x" number)
602             "")
603           mml-base-boundary))
604
605 (defun mml-insert-mime-headers (cont type charset encoding flowed)
606   (let (parameters id disposition description)
607     (setq parameters
608           (mml-parameter-string
609            cont mml-content-type-parameters))
610     (when (or charset
611               parameters
612               flowed
613               (not (equal type mml-generate-default-type))
614               mml-insert-mime-headers-always)
615       (when (consp charset)
616         (error
617          "Can't encode a part with several charsets"))
618       (insert "Content-Type: " type)
619       (when charset
620         (insert "; " (mail-header-encode-parameter
621                       "charset" (symbol-name charset))))
622       (when flowed
623         (insert "; format=flowed"))
624       (when parameters
625         (mml-insert-parameter-string
626          cont mml-content-type-parameters))
627       (insert "\n"))
628     (when (setq id (cdr (assq 'id cont)))
629       (insert "Content-ID: " id "\n"))
630     (setq parameters
631           (mml-parameter-string
632            cont mml-content-disposition-parameters))
633     (when (or (setq disposition (cdr (assq 'disposition cont)))
634               parameters)
635       (insert "Content-Disposition: " (or disposition "inline"))
636       (when parameters
637         (mml-insert-parameter-string
638          cont mml-content-disposition-parameters))
639       (insert "\n"))
640     (unless (eq encoding '7bit)
641       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
642     (when (setq description (cdr (assq 'description cont)))
643       (insert "Content-Description: "
644               (mail-encode-encoded-word-string description) "\n"))))
645
646 (defun mml-parameter-string (cont types)
647   (let ((string "")
648         value type)
649     (while (setq type (pop types))
650       (when (setq value (cdr (assq type cont)))
651         ;; Strip directory component from the filename parameter.
652         (when (eq type 'filename)
653           (setq value (file-name-nondirectory value)))
654         (setq string (concat string "; "
655                              (mail-header-encode-parameter
656                               (symbol-name type) value)))))
657     (when (not (zerop (length string)))
658       string)))
659
660 (defun mml-insert-parameter-string (cont types)
661   (let (value type)
662     (while (setq type (pop types))
663       (when (setq value (cdr (assq type cont)))
664         ;; Strip directory component from the filename parameter.
665         (when (eq type 'filename)
666           (setq value (file-name-nondirectory value)))
667         (mml-insert-parameter
668          (mail-header-encode-parameter
669           (symbol-name type) value))))))
670
671 (eval-when-compile
672   (defvar ange-ftp-name-format)
673   (defvar efs-path-regexp))
674 (defun mml-parse-file-name (path)
675   (if (if (boundp 'efs-path-regexp)
676           (string-match efs-path-regexp path)
677         (if (boundp 'ange-ftp-name-format)
678             (string-match (car ange-ftp-name-format) path)))
679       (list (match-string 1 path) (match-string 2 path)
680             (substring path (1+ (match-end 2))))
681     path))
682
683 (defun mml-insert-buffer (buffer)
684   "Insert BUFFER at point and quote any MML markup."
685   (save-restriction
686     (narrow-to-region (point) (point))
687     (insert-buffer-substring buffer)
688     (mml-quote-region (point-min) (point-max))
689     (goto-char (point-max))))
690
691 ;;;
692 ;;; Transforming MIME to MML
693 ;;;
694
695 (defun mime-to-mml (&optional handles)
696   "Translate the current buffer (which should be a message) into MML.
697 If HANDLES is non-nil, use it instead reparsing the buffer."
698   ;; First decode the head.
699   (save-restriction
700     (message-narrow-to-head)
701     (mail-decode-encoded-word-region (point-min) (point-max)))
702   (unless handles
703     (setq handles (mm-dissect-buffer t)))
704   (goto-char (point-min))
705   (search-forward "\n\n" nil t)
706   (delete-region (point) (point-max))
707   (if (stringp (car handles))
708       (mml-insert-mime handles)
709     (mml-insert-mime handles t))
710   (mm-destroy-parts handles)
711   (save-restriction
712     (message-narrow-to-head)
713     ;; Remove them, they are confusing.
714     (message-remove-header "Content-Type")
715     (message-remove-header "MIME-Version")
716     (message-remove-header "Content-Disposition")
717     (message-remove-header "Content-Transfer-Encoding")))
718
719 (defun mml-to-mime ()
720   "Translate the current buffer from MML to MIME."
721   (message-encode-message-body)
722   (save-restriction
723     (message-narrow-to-headers-or-head)
724     ;; Skip past any From_ headers.
725     (while (looking-at "From ")
726       (forward-line 1))
727     (let ((mail-parse-charset message-default-charset))
728       (mail-encode-encoded-word-buffer))))
729
730 (defun mml-insert-mime (handle &optional no-markup)
731   (let (textp buffer mmlp)
732     ;; Determine type and stuff.
733     (unless (stringp (car handle))
734       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
735         (save-excursion
736           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
737           (mm-insert-part handle)
738           (if (setq mmlp (equal (mm-handle-media-type handle)
739                                 "message/rfc822"))
740               (mime-to-mml)))))
741     (if mmlp
742         (mml-insert-mml-markup handle nil t t)
743       (unless (and no-markup
744                    (equal (mm-handle-media-type handle) "text/plain"))
745         (mml-insert-mml-markup handle buffer textp)))
746     (cond
747      (mmlp
748       (insert-buffer-substring buffer)
749       (goto-char (point-max))
750       (insert "<#/mml>\n"))
751      ((stringp (car handle))
752       (mapcar 'mml-insert-mime (cdr handle))
753       (insert "<#/multipart>\n"))
754      (textp
755       (let ((charset (mail-content-type-get
756                       (mm-handle-type handle) 'charset))
757             (start (point)))
758         (if (eq charset 'gnus-decoded)
759             (mm-insert-part handle)
760           (insert (mm-decode-string (mm-get-part handle) charset)))
761         (mml-quote-region start (point)))
762       (goto-char (point-max)))
763      (t
764       (insert "<#/part>\n")))))
765
766 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
767   "Take a MIME handle and insert an MML tag."
768   (if (stringp (car handle))
769       (progn
770         (insert "<#multipart type=" (mm-handle-media-subtype handle))
771         (let ((start (mm-handle-multipart-ctl-parameter handle 'start)))
772           (when start
773             (insert " start=\"" start "\"")))
774         (insert ">\n"))
775     (if mmlp
776         (insert "<#mml type=" (mm-handle-media-type handle))
777       (insert "<#part type=" (mm-handle-media-type handle)))
778     (dolist (elem (append (cdr (mm-handle-type handle))
779                           (cdr (mm-handle-disposition handle))))
780       (unless (symbolp (cdr elem))
781         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
782     (when (mm-handle-id handle)
783       (insert " id=\"" (mm-handle-id handle) "\""))
784     (when (mm-handle-disposition handle)
785       (insert " disposition=" (car (mm-handle-disposition handle))))
786     (when buffer
787       (insert " buffer=\"" (buffer-name buffer) "\""))
788     (when nofile
789       (insert " nofile=yes"))
790     (when (mm-handle-description handle)
791       (insert " description=\"" (mm-handle-description handle) "\""))
792     (insert ">\n")))
793
794 (defun mml-insert-parameter (&rest parameters)
795   "Insert PARAMETERS in a nice way."
796   (dolist (param parameters)
797     (insert ";")
798     (let ((point (point)))
799       (insert " " param)
800       (when (> (current-column) 71)
801         (goto-char point)
802         (insert "\n ")
803         (end-of-line)))))
804
805 ;;;
806 ;;; Mode for inserting and editing MML forms
807 ;;;
808
809 (defvar mml-mode-map
810   (let ((sign (make-sparse-keymap))
811         (encrypt (make-sparse-keymap))
812         (signpart (make-sparse-keymap))
813         (encryptpart (make-sparse-keymap))
814         (map (make-sparse-keymap))
815         (main (make-sparse-keymap)))
816     (define-key sign "p" 'mml-secure-message-sign-pgpmime)
817     (define-key sign "o" 'mml-secure-message-sign-pgp)
818     (define-key sign "s" 'mml-secure-message-sign-smime)
819     (define-key signpart "p" 'mml-secure-sign-pgpmime)
820     (define-key signpart "o" 'mml-secure-sign-pgp)
821     (define-key signpart "s" 'mml-secure-sign-smime)
822     (define-key encrypt "p" 'mml-secure-message-encrypt-pgpmime)
823     (define-key encrypt "o" 'mml-secure-message-encrypt-pgp)
824     (define-key encrypt "s" 'mml-secure-message-encrypt-smime)
825     (define-key encryptpart "p" 'mml-secure-encrypt-pgpmime)
826     (define-key encryptpart "o" 'mml-secure-encrypt-pgp)
827     (define-key encryptpart "s" 'mml-secure-encrypt-smime)
828     (define-key map "\C-n" 'mml-unsecure-message)
829     (define-key map "f" 'mml-attach-file)
830     (define-key map "b" 'mml-attach-buffer)
831     (define-key map "e" 'mml-attach-external)
832     (define-key map "q" 'mml-quote-region)
833     (define-key map "m" 'mml-insert-multipart)
834     (define-key map "p" 'mml-insert-part)
835     (define-key map "v" 'mml-validate)
836     (define-key map "P" 'mml-preview)
837     (define-key map "s" sign)
838     (define-key map "S" signpart)
839     (define-key map "c" encrypt)
840     (define-key map "C" encryptpart)
841     ;;(define-key map "n" 'mml-narrow-to-part)
842     ;; `M-m' conflicts with `back-to-indentation'.
843     ;; (define-key main "\M-m" map)
844     (define-key main "\C-c\C-m" map)
845     main))
846
847 (easy-menu-define
848   mml-menu mml-mode-map ""
849   `("Attachments"
850     ["Attach File..." mml-attach-file
851      ,@(if (featurep 'xemacs) '(t)
852          '(:help "Attach a file at point"))]
853     ["Attach Buffer..." mml-attach-buffer t]
854     ["Attach External..." mml-attach-external t]
855     ["Insert Part..." mml-insert-part t]
856     ["Insert Multipart..." mml-insert-multipart t]
857     ["PGP/MIME Sign" mml-secure-message-sign-pgpmime t]
858     ["PGP/MIME Encrypt" mml-secure-message-encrypt-pgpmime t]
859     ["PGP Sign" mml-secure-message-sign-pgp t]
860     ["PGP Encrypt" mml-secure-message-encrypt-pgp t]
861     ["S/MIME Sign" mml-secure-message-sign-smime t]
862     ["S/MIME Encrypt" mml-secure-message-encrypt-smime t]
863     ("Secure MIME part"
864      ["PGP/MIME Sign Part" mml-secure-sign-pgpmime t]
865      ["PGP/MIME Encrypt Part" mml-secure-encrypt-pgpmime t]
866      ["PGP Sign Part" mml-secure-sign-pgp t]
867      ["PGP Encrypt Part" mml-secure-encrypt-pgp t]
868      ["S/MIME Sign Part" mml-secure-sign-smime t]
869      ["S/MIME Encrypt Part" mml-secure-encrypt-smime t])
870     ["Encrypt/Sign off" mml-unsecure-message t]
871     ;;["Narrow" mml-narrow-to-part t]
872     ["Quote MML" mml-quote-region t]
873     ["Validate MML" mml-validate t]
874     ["Preview" mml-preview t]))
875
876 (defvar mml-mode nil
877   "Minor mode for editing MML.")
878
879 (defun mml-mode (&optional arg)
880   "Minor mode for editing MML.
881 MML is the MIME Meta Language, a minor mode for composing MIME articles.
882 See Info node `(emacs-mime)Composing'.
883
884 \\{mml-mode-map}"
885   (interactive "P")
886   (when (set (make-local-variable 'mml-mode)
887              (if (null arg) (not mml-mode)
888                (> (prefix-numeric-value arg) 0)))
889     (add-minor-mode 'mml-mode " MML" mml-mode-map)
890     (easy-menu-add mml-menu mml-mode-map)
891     (run-hooks 'mml-mode-hook)))
892
893 ;;;
894 ;;; Helper functions for reading MIME stuff from the minibuffer and
895 ;;; inserting stuff to the buffer.
896 ;;;
897
898 (defun mml-minibuffer-read-file (prompt)
899   (let* ((completion-ignored-extensions nil)
900          (file (read-file-name prompt nil nil t)))
901     ;; Prevent some common errors.  This is inspired by similar code in
902     ;; VM.
903     (when (file-directory-p file)
904       (error "%s is a directory, cannot attach" file))
905     (unless (file-exists-p file)
906       (error "No such file: %s" file))
907     (unless (file-readable-p file)
908       (error "Permission denied: %s" file))
909     file))
910
911 (defun mml-minibuffer-read-type (name &optional default)
912   (mailcap-parse-mimetypes)
913   (let* ((default (or default
914                       (mm-default-file-encoding name)
915                       ;; Perhaps here we should check what the file
916                       ;; looks like, and offer text/plain if it looks
917                       ;; like text/plain.
918                       "application/octet-stream"))
919          (string (completing-read
920                   (format "Content type (default %s): " default)
921                   (mapcar 'list (mailcap-mime-types)))))
922     (if (not (equal string ""))
923         string
924       default)))
925
926 (defun mml-minibuffer-read-description ()
927   (let ((description (read-string "One line description: ")))
928     (when (string-match "\\`[ \t]*\\'" description)
929       (setq description nil))
930     description))
931
932 (defun mml-minibuffer-read-disposition (type &optional default)
933   (let* ((default (or default
934                       (if (string-match "^text/.*" type)
935                           "inline"
936                         "attachment")))
937         (disposition (completing-read 
938                       (format "Disposition: (default %s): " default)
939                       '(("attachment") ("inline") (""))
940                       nil
941                       nil)))
942     (if (not (equal disposition ""))
943         disposition
944       default)))
945
946 (defun mml-quote-region (beg end)
947   "Quote the MML tags in the region."
948   (interactive "r")
949   (save-excursion
950     (save-restriction
951       ;; Temporarily narrow the region to defend from changes
952       ;; invalidating END.
953       (narrow-to-region beg end)
954       (goto-char (point-min))
955       ;; Quote parts.
956       (while (re-search-forward
957               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
958         ;; Insert ! after the #.
959         (goto-char (+ (match-beginning 0) 2))
960         (insert "!")))))
961
962 (defun mml-insert-tag (name &rest plist)
963   "Insert an MML tag described by NAME and PLIST."
964   (when (symbolp name)
965     (setq name (symbol-name name)))
966   (insert "<#" name)
967   (while plist
968     (let ((key (pop plist))
969           (value (pop plist)))
970       (when value
971         ;; Quote VALUE if it contains suspicious characters.
972         (when (string-match "[\"'\\~/*;() \t\n]" value)
973           (setq value (with-output-to-string
974                         (let (print-escape-nonascii)
975                           (prin1 value)))))
976         (insert (format " %s=%s" key value)))))
977   (insert ">\n"))
978
979 (defun mml-insert-empty-tag (name &rest plist)
980   "Insert an empty MML tag described by NAME and PLIST."
981   (when (symbolp name)
982     (setq name (symbol-name name)))
983   (apply #'mml-insert-tag name plist)
984   (insert "<#/" name ">\n"))
985
986 ;;; Attachment functions.
987
988 (defun mml-attach-file (file &optional type description disposition)
989   "Attach a file to the outgoing MIME message.
990 The file is not inserted or encoded until you send the message with
991 `\\[message-send-and-exit]' or `\\[message-send]'.
992
993 FILE is the name of the file to attach.  TYPE is its content-type, a
994 string of the form \"type/subtype\".  DESCRIPTION is a one-line
995 description of the attachment."
996   (interactive
997    (let* ((file (mml-minibuffer-read-file "Attach file: "))
998           (type (mml-minibuffer-read-type file))
999           (description (mml-minibuffer-read-description))
1000           (disposition (mml-minibuffer-read-disposition type)))
1001      (list file type description disposition)))
1002   (mml-insert-empty-tag 'part
1003                         'type type
1004                         'filename file
1005                         'disposition (or disposition "attachment")
1006                         'description description))
1007
1008 (defun mml-attach-buffer (buffer &optional type description)
1009   "Attach a buffer to the outgoing MIME message.
1010 See `mml-attach-file' for details of operation."
1011   (interactive
1012    (let* ((buffer (read-buffer "Attach buffer: "))
1013           (type (mml-minibuffer-read-type buffer "text/plain"))
1014           (description (mml-minibuffer-read-description)))
1015      (list buffer type description)))
1016   (mml-insert-empty-tag 'part 'type type 'buffer buffer
1017                         'disposition "attachment" 'description description))
1018
1019 (defun mml-attach-external (file &optional type description)
1020   "Attach an external file into the buffer.
1021 FILE is an ange-ftp/efs specification of the part location.
1022 TYPE is the MIME type to use."
1023   (interactive
1024    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
1025           (type (mml-minibuffer-read-type file))
1026           (description (mml-minibuffer-read-description)))
1027      (list file type description)))
1028   (mml-insert-empty-tag 'external 'type type 'name file
1029                         'disposition "attachment" 'description description))
1030
1031 (defun mml-insert-multipart (&optional type)
1032   (interactive (list (completing-read "Multipart type (default mixed): "
1033                                       '(("mixed") ("alternative") ("digest") ("parallel")
1034                                         ("signed") ("encrypted"))
1035                                       nil nil "mixed")))
1036   (or type
1037       (setq type "mixed"))
1038   (mml-insert-empty-tag "multipart" 'type type)
1039   (forward-line -1))
1040
1041 (defun mml-insert-part (&optional type)
1042   (interactive
1043    (list (mml-minibuffer-read-type "")))
1044   (mml-insert-tag 'part 'type type 'disposition "inline")
1045   (forward-line -1))
1046
1047 (defun mml-preview-insert-mail-followup-to ()
1048   "Insert a Mail-Followup-To header before previewing an article.
1049 Should be adopted if code in `message-send-mail' is changed."
1050   (when (and (message-mail-p)
1051              (message-subscribed-p)
1052              (not (mail-fetch-field "mail-followup-to"))
1053              (message-make-mail-followup-to))
1054     (message-position-on-field "Mail-Followup-To" "X-Draft-From")
1055     (insert (message-make-mail-followup-to))))
1056
1057 (defun mml-preview (&optional raw)
1058   "Display current buffer with Gnus, in a new buffer.
1059 If RAW, don't highlight the article."
1060   (interactive "P")
1061   (save-excursion
1062     (let* ((buf (current-buffer))
1063            (message-options message-options)
1064            (message-this-is-mail (message-mail-p))
1065            (message-this-is-news (message-news-p))
1066            (message-posting-charset (or (gnus-setup-posting-charset
1067                                          (save-restriction
1068                                            (message-narrow-to-headers-or-head)
1069                                            (message-fetch-field "Newsgroups")))
1070                                         message-posting-charset)))
1071       (message-options-set-recipient)
1072       (switch-to-buffer (generate-new-buffer
1073                          (concat (if raw "*Raw MIME preview of "
1074                                    "*MIME preview of ") (buffer-name))))
1075       (when (boundp 'gnus-buffers)
1076         (push (current-buffer) gnus-buffers))
1077       (erase-buffer)
1078       (insert-buffer-substring buf)
1079       (mml-preview-insert-mail-followup-to)
1080       (let ((message-deletable-headers (if (message-news-p)
1081                                            nil
1082                                          message-deletable-headers)))
1083         (message-generate-headers
1084          (copy-sequence (if (message-news-p)
1085                             message-required-news-headers
1086                           message-required-mail-headers))))
1087       (if (re-search-forward
1088            (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1089           (replace-match "\n"))
1090       (let ((mail-header-separator ""));; mail-header-separator is removed.
1091         (mml-to-mime))
1092       (if raw
1093           (when (fboundp 'set-buffer-multibyte)
1094             (let ((s (buffer-string)))
1095               ;; Insert the content into unibyte buffer.
1096               (erase-buffer)
1097               (mm-disable-multibyte)
1098               (insert s)))
1099         (let ((gnus-newsgroup-charset (car message-posting-charset))
1100               gnus-article-prepare-hook gnus-original-article-buffer)
1101           (run-hooks 'gnus-article-decode-hook)
1102           (let ((gnus-newsgroup-name "dummy")
1103                 (gnus-newsrc-hashtb (or gnus-newsrc-hashtb
1104                                         (gnus-make-hashtable 5))))
1105             (gnus-article-prepare-display))))
1106       ;; Disable article-mode-map.
1107       (use-local-map nil)
1108       (gnus-make-local-hook 'kill-buffer-hook)
1109       (add-hook 'kill-buffer-hook
1110                 (lambda ()
1111                   (mm-destroy-parts gnus-article-mime-handles)) nil t)
1112       (setq buffer-read-only t)
1113       (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
1114       (local-set-key "=" (lambda () (interactive) (delete-other-windows)))
1115       (local-set-key "\r"
1116                      (lambda ()
1117                        (interactive)
1118                        (widget-button-press (point))))
1119       (local-set-key gnus-mouse-2
1120                      (lambda (event)
1121                        (interactive "@e")
1122                        (widget-button-press (widget-event-point event) event)))
1123       (goto-char (point-min)))))
1124
1125 (defun mml-validate ()
1126   "Validate the current MML document."
1127   (interactive)
1128   (mml-parse))
1129
1130 (defun mml-tweak-part (cont)
1131   "Tweak a MML part."
1132   (let ((tweak (cdr (assq 'tweak cont)))
1133         func)
1134     (cond
1135      (tweak
1136       (setq func
1137             (or (cdr (assoc tweak mml-tweak-function-alist))
1138                 (intern tweak))))
1139      (mml-tweak-type-alist
1140       (let ((alist mml-tweak-type-alist)
1141             (type (or (cdr (assq 'type cont)) "text/plain")))
1142         (while alist
1143           (if (string-match (caar alist) type)
1144               (setq func (cdar alist)
1145                     alist nil)
1146             (setq alist (cdr alist)))))))
1147     (if func
1148         (funcall func cont)
1149       cont)
1150     (let ((alist mml-tweak-sexp-alist))
1151       (while alist
1152         (if (eval (caar alist))
1153             (funcall (cdar alist) cont))
1154         (setq alist (cdr alist)))))
1155   cont)
1156
1157 (defun mml-tweak-externalize-attachments (cont)
1158   "Tweak attached files as external parts."
1159   (let (filename-cons)
1160     (when (and (eq (car cont) 'part)
1161                (not (cdr (assq 'buffer cont)))
1162                (and (setq filename-cons (assq 'filename cont))
1163                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
1164       (setcar cont 'external)
1165       (setcar filename-cons 'name))))
1166
1167 (provide 'mml)
1168
1169 ;;; mml.el ends here