* gnus-art.el (gnus-article-reply-with-original): New command.
[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-sender 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-sender 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     (let ((mail-parse-charset message-default-charset))
640       (mail-encode-encoded-word-buffer))))
641
642 (defun mml-insert-mime (handle &optional no-markup)
643   (let (textp buffer mmlp)
644     ;; Determine type and stuff.
645     (unless (stringp (car handle))
646       (unless (setq textp (equal (mm-handle-media-supertype handle) "text"))
647         (save-excursion
648           (set-buffer (setq buffer (mml-generate-new-buffer " *mml*")))
649           (mm-insert-part handle)
650           (if (setq mmlp (equal (mm-handle-media-type handle)
651                                 "message/rfc822"))
652               (mime-to-mml)))))
653     (if mmlp
654         (mml-insert-mml-markup handle nil t t)
655       (unless (and no-markup
656                    (equal (mm-handle-media-type handle) "text/plain"))
657         (mml-insert-mml-markup handle buffer textp)))
658     (cond
659      (mmlp
660       (insert-buffer buffer)
661       (goto-char (point-max))
662       (insert "<#/mml>\n"))
663      ((stringp (car handle))
664       (mapcar 'mml-insert-mime (cdr handle))
665       (insert "<#/multipart>\n"))
666      (textp
667       (let ((charset (mail-content-type-get
668                       (mm-handle-type handle) 'charset)))
669         (if (eq charset 'gnus-decoded)
670             (mm-insert-part handle)
671           (insert (mm-decode-string (mm-get-part handle) charset))))
672       (goto-char (point-max)))
673      (t
674       (insert "<#/part>\n")))))
675
676 (defun mml-insert-mml-markup (handle &optional buffer nofile mmlp)
677   "Take a MIME handle and insert an MML tag."
678   (if (stringp (car handle))
679       (insert "<#multipart type=" (mm-handle-media-subtype handle)
680               ">\n")
681     (if mmlp
682         (insert "<#mml type=" (mm-handle-media-type handle))
683       (insert "<#part type=" (mm-handle-media-type handle)))
684     (dolist (elem (append (cdr (mm-handle-type handle))
685                           (cdr (mm-handle-disposition handle))))
686       (unless (symbolp (cdr elem))
687         (insert " " (symbol-name (car elem)) "=\"" (cdr elem) "\"")))
688     (when (mm-handle-disposition handle)
689       (insert " disposition=" (car (mm-handle-disposition handle))))
690     (when buffer
691       (insert " buffer=\"" (buffer-name buffer) "\""))
692     (when nofile
693       (insert " nofile=yes"))
694     (when (mm-handle-description handle)
695       (insert " description=\"" (mm-handle-description handle) "\""))
696     (insert ">\n")))
697
698 (defun mml-insert-parameter (&rest parameters)
699   "Insert PARAMETERS in a nice way."
700   (dolist (param parameters)
701     (insert ";")
702     (let ((point (point)))
703       (insert " " param)
704       (when (> (current-column) 71)
705         (goto-char point)
706         (insert "\n ")
707         (end-of-line)))))
708
709 ;;;
710 ;;; Mode for inserting and editing MML forms
711 ;;;
712
713 (defvar mml-mode-map
714   (let ((sign (make-sparse-keymap))
715         (encrypt (make-sparse-keymap))
716         (map (make-sparse-keymap))
717         (main (make-sparse-keymap)))
718     (define-key sign "p" 'mml-secure-sign-pgpmime)
719     (define-key sign "o" 'mml-secure-sign-pgp)
720     (define-key sign "s" 'mml-secure-sign-smime)
721     (define-key encrypt "p" 'mml-secure-encrypt-pgpmime)
722     (define-key encrypt "o" 'mml-secure-encrypt-pgp)
723     (define-key encrypt "s" 'mml-secure-encrypt-smime)
724     (define-key map "f" 'mml-attach-file)
725     (define-key map "b" 'mml-attach-buffer)
726     (define-key map "e" 'mml-attach-external)
727     (define-key map "q" 'mml-quote-region)
728     (define-key map "m" 'mml-insert-multipart)
729     (define-key map "p" 'mml-insert-part)
730     (define-key map "v" 'mml-validate)
731     (define-key map "P" 'mml-preview)
732     (define-key map "s" sign)
733     (define-key map "c" encrypt)
734     ;;(define-key map "n" 'mml-narrow-to-part)
735     ;; `M-m' conflicts with `back-to-indentation'.
736     ;; (define-key main "\M-m" map)
737     (define-key main "\C-c\C-m" map)
738     main))
739
740 (easy-menu-define
741   mml-menu mml-mode-map ""
742   `("Attachments"
743     ["Attach File" mml-attach-file
744      ,@(if (featurep 'xemacs) '(t)
745          '(:help "Attach a file at point"))]
746     ["Attach Buffer" mml-attach-buffer t]
747     ["Attach External" mml-attach-external t]
748     ["Insert Part" mml-insert-part t]
749     ["Insert Multipart" mml-insert-multipart t]
750     ["PGP/MIME Sign" mml-secure-sign-pgpmime t]
751     ["PGP/MIME Encrypt" mml-secure-encrypt-pgpmime t]
752     ["PGP Sign" mml-secure-sign-pgp t]
753     ["PGP Encrypt" mml-secure-encrypt-pgp t]
754     ["S/MIME Sign" mml-secure-sign-smime t]
755     ["S/MIME Encrypt" mml-secure-encrypt-smime t]
756     ;;["Narrow" mml-narrow-to-part t]
757     ["Quote MML" mml-quote-region t]
758     ["Validate MML" mml-validate t]
759     ["Preview" mml-preview t]))
760
761 (defvar mml-mode nil
762   "Minor mode for editing MML.")
763
764 (defun mml-mode (&optional arg)
765   "Minor mode for editing MML.
766 MML is the MIME Meta Language, a minor mode for composing MIME articles.
767 See Info node `(emacs-mime)Composing'.
768
769 \\{mml-mode-map}"
770   (interactive "P")
771   (when (set (make-local-variable 'mml-mode)
772              (if (null arg) (not mml-mode)
773                (> (prefix-numeric-value arg) 0)))
774     (gnus-add-minor-mode 'mml-mode " MML" mml-mode-map)
775     (easy-menu-add mml-menu mml-mode-map)
776     (run-hooks 'mml-mode-hook)))
777
778 ;;;
779 ;;; Helper functions for reading MIME stuff from the minibuffer and
780 ;;; inserting stuff to the buffer.
781 ;;;
782
783 (defun mml-minibuffer-read-file (prompt)
784   (let ((file (read-file-name prompt nil nil t)))
785    ;; Prevent some common errors.  This is inspired by similar code in
786     ;; VM.
787     (when (file-directory-p file)
788       (error "%s is a directory, cannot attach" file))
789     (unless (file-exists-p file)
790       (error "No such file: %s" file))
791     (unless (file-readable-p file)
792       (error "Permission denied: %s" file))
793     file))
794
795 (defun mml-minibuffer-read-type (name &optional default)
796   (mailcap-parse-mimetypes)
797   (let* ((default (or default
798                       (mm-default-file-encoding name)
799                       ;; Perhaps here we should check what the file
800                       ;; looks like, and offer text/plain if it looks
801                       ;; like text/plain.
802                       "application/octet-stream"))
803          (string (completing-read
804                   (format "Content type (default %s): " default)
805                   (mapcar 'list (mailcap-mime-types)))))
806     (if (not (equal string ""))
807         string
808       default)))
809
810 (defun mml-minibuffer-read-description ()
811   (let ((description (read-string "One line description: ")))
812     (when (string-match "\\`[ \t]*\\'" description)
813       (setq description nil))
814     description))
815
816 (defun mml-quote-region (beg end)
817   "Quote the MML tags in the region."
818   (interactive "r")
819   (save-excursion
820     (save-restriction
821       ;; Temporarily narrow the region to defend from changes
822       ;; invalidating END.
823       (narrow-to-region beg end)
824       (goto-char (point-min))
825       ;; Quote parts.
826       (while (re-search-forward
827               "<#!*/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
828         ;; Insert ! after the #.
829         (goto-char (+ (match-beginning 0) 2))
830         (insert "!")))))
831
832 (defun mml-insert-tag (name &rest plist)
833   "Insert an MML tag described by NAME and PLIST."
834   (when (symbolp name)
835     (setq name (symbol-name name)))
836   (insert "<#" name)
837   (while plist
838     (let ((key (pop plist))
839           (value (pop plist)))
840       (when value
841         ;; Quote VALUE if it contains suspicious characters.
842         (when (string-match "[\"'\\~/*;() \t\n]" value)
843           (setq value (prin1-to-string value)))
844         (insert (format " %s=%s" key value)))))
845   (insert ">\n"))
846
847 (defun mml-insert-empty-tag (name &rest plist)
848   "Insert an empty MML tag described by NAME and PLIST."
849   (when (symbolp name)
850     (setq name (symbol-name name)))
851   (apply #'mml-insert-tag name plist)
852   (insert "<#/" name ">\n"))
853
854 ;;; Attachment functions.
855
856 (defun mml-attach-file (file &optional type description)
857   "Attach a file to the outgoing MIME message.
858 The file is not inserted or encoded until you send the message with
859 `\\[message-send-and-exit]' or `\\[message-send]'.
860
861 FILE is the name of the file to attach.  TYPE is its content-type, a
862 string of the form \"type/subtype\".  DESCRIPTION is a one-line
863 description of the attachment."
864   (interactive
865    (let* ((file (mml-minibuffer-read-file "Attach file: "))
866           (type (mml-minibuffer-read-type file))
867           (description (mml-minibuffer-read-description)))
868      (list file type description)))
869   (mml-insert-empty-tag 'part 'type type 'filename file
870                         'disposition "attachment" 'description description))
871
872 (defun mml-attach-buffer (buffer &optional type description)
873   "Attach a buffer to the outgoing MIME message.
874 See `mml-attach-file' for details of operation."
875   (interactive
876    (let* ((buffer (read-buffer "Attach buffer: "))
877           (type (mml-minibuffer-read-type buffer "text/plain"))
878           (description (mml-minibuffer-read-description)))
879      (list buffer type description)))
880   (mml-insert-empty-tag 'part 'type type 'buffer buffer
881                         'disposition "attachment" 'description description))
882
883 (defun mml-attach-external (file &optional type description)
884   "Attach an external file into the buffer.
885 FILE is an ange-ftp/efs specification of the part location.
886 TYPE is the MIME type to use."
887   (interactive
888    (let* ((file (mml-minibuffer-read-file "Attach external file: "))
889           (type (mml-minibuffer-read-type file))
890           (description (mml-minibuffer-read-description)))
891      (list file type description)))
892   (mml-insert-empty-tag 'external 'type type 'name file
893                         'disposition "attachment" 'description description))
894
895 (defun mml-insert-multipart (&optional type)
896   (interactive (list (completing-read "Multipart type (default mixed): "
897                                       '(("mixed") ("alternative") ("digest") ("parallel")
898                                         ("signed") ("encrypted"))
899                                       nil nil "mixed")))
900   (or type
901       (setq type "mixed"))
902   (mml-insert-empty-tag "multipart" 'type type)
903   (forward-line -1))
904
905 (defun mml-insert-part (&optional type)
906   (interactive
907    (list (mml-minibuffer-read-type "")))
908   (mml-insert-tag 'part 'type type 'disposition "inline")
909   (forward-line -1))
910
911 (defun mml-preview (&optional raw)
912   "Display current buffer with Gnus, in a new buffer.
913 If RAW, don't highlight the article."
914   (interactive "P")
915   (let* ((buf (current-buffer))
916          (message-options message-options)
917          (message-this-is-news (message-news-p))
918          (message-posting-charset (or (gnus-setup-posting-charset
919                                        (save-restriction
920                                          (message-narrow-to-headers-or-head)
921                                          (message-fetch-field "Newsgroups")))
922                                       message-posting-charset)))
923     (message-options-set-recipient)
924     (switch-to-buffer (generate-new-buffer
925                        (concat (if raw "*Raw MIME preview of "
926                                  "*MIME preview of ") (buffer-name))))
927     (erase-buffer)
928     (insert-buffer buf)
929     (if (re-search-forward
930          (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
931         (replace-match "\n"))
932     (let ((mail-header-separator "")) ;; mail-header-separator is removed.
933       (mml-to-mime))
934     (if raw
935         (when (fboundp 'set-buffer-multibyte)
936           (let ((s (buffer-string)))
937             ;; Insert the content into unibyte buffer.
938             (erase-buffer)
939             (mm-disable-multibyte)
940             (insert s)))
941       (let ((gnus-newsgroup-charset (car message-posting-charset)))
942         (run-hooks 'gnus-article-decode-hook)
943         (let ((gnus-newsgroup-name "dummy"))
944           (gnus-article-prepare-display))))
945     ;; Disable article-mode-map.
946     (use-local-map nil)
947     (setq buffer-read-only t)
948     (local-set-key "q" (lambda () (interactive) (kill-buffer nil)))
949     (goto-char (point-min))))
950
951 (defun mml-validate ()
952   "Validate the current MML document."
953   (interactive)
954   (mml-parse))
955
956 (defun mml-tweak-part (cont)
957   "Tweak a MML part."
958   (let ((tweak (cdr (assq 'tweak cont)))
959         func)
960     (cond
961      (tweak
962       (setq func
963             (or (cdr (assoc tweak mml-tweak-function-alist))
964                 (intern tweak))))
965      (mml-tweak-type-alist
966       (let ((alist mml-tweak-type-alist)
967             (type (or (cdr (assq 'type cont)) "text/plain")))
968         (while alist
969           (if (string-match (caar alist) type)
970               (setq func (cdar alist)
971                     alist nil)
972             (setq alist (cdr alist)))))))
973     (if func
974         (funcall func cont)
975       cont)
976     (let ((alist mml-tweak-sexp-alist))
977       (while alist
978         (if (eval (caar alist))
979             (funcall (cdar alist) cont))
980         (setq alist (cdr alist)))))
981   cont)
982
983 (defun mml-tweak-externalize-attachments (cont)
984   "Tweak attached files as external parts."
985   (let (filename-cons)
986     (when (and (eq (car cont) 'part) 
987                (not (cdr (assq 'buffer cont)))
988                (and (setq filename-cons (assq 'filename cont))
989                     (not (equal (cdr (assq 'nofile cont)) "yes"))))
990       (setcar cont 'external)
991       (setcar filename-cons 'name))))
992
993 (provide 'mml)
994
995 ;;; mml.el ends here