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