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