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