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