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