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