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