8bb6a855e3953a47ee8456578067694f61911abb
[elisp/gnus.git-] / lisp / mml.el
1 ;;; mml.el --- A package for parsing and validating MML documents
2 ;; Copyright (C) 1998,99 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
30 (eval-and-compile
31   (autoload 'message-make-message-id "message"))
32
33 (defvar mml-syntax-table
34   (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
35     (modify-syntax-entry ?\\ "/" table)
36     (modify-syntax-entry ?< "(" table)
37     (modify-syntax-entry ?> ")" table)
38     (modify-syntax-entry ?@ "w" table)
39     (modify-syntax-entry ?/ "w" table)
40     (modify-syntax-entry ?= " " table)
41     (modify-syntax-entry ?* " " table)
42     (modify-syntax-entry ?\; " " table)
43     (modify-syntax-entry ?\' " " table)
44     table))
45
46 (defun mml-parse ()
47   "Parse the current buffer as an MML document."
48   (goto-char (point-min))
49   (let ((table (syntax-table)))
50     (unwind-protect
51         (progn
52           (set-syntax-table mml-syntax-table)
53           (mml-parse-1))
54       (set-syntax-table table))))
55
56 (defun mml-parse-1 ()
57   "Parse the current buffer as an MML document."
58   (let (struct tag point contents charsets warn)
59     (while (and (not (eobp))
60                 (not (looking-at "<#/multipart")))
61       (cond
62        ((looking-at "<#multipart")
63         (push (nconc (mml-read-tag) (mml-parse-1)) struct))
64        ((looking-at "<#external")
65         (push (nconc (mml-read-tag) (list (cons 'contents (mml-read-part))))
66               struct))
67        (t
68         (if (looking-at "<#part")
69             (setq tag (mml-read-tag))
70           (setq tag (list 'part '(type . "text/plain"))
71                 warn t))
72         (setq point (point)
73               contents (mml-read-part)
74               charsets (delq 'ascii (mm-find-charset-region point (point))))
75         (if (< (length charsets) 2)
76             (push (nconc tag (list (cons 'contents contents)))
77                   struct)
78           (let ((nstruct (mml-parse-singlepart-with-multiple-charsets
79                           tag point (point))))
80             (when (and warn
81                        (not
82                         (y-or-n-p
83                          (format
84                           "Warning: Your message contains %d parts.  Really send? "
85                           (length nstruct)))))
86               (error "Edit your message to use only one charset"))
87             (setq struct (nconc nstruct struct)))))))
88     (unless (eobp)
89       (forward-line 1))
90     (nreverse struct)))
91
92 (defun mml-parse-singlepart-with-multiple-charsets (orig-tag beg end)
93   (save-excursion
94     (narrow-to-region beg end)
95     (goto-char (point-min))
96     (let ((current (char-charset (following-char)))
97           charset struct space newline paragraph)
98       (while (not (eobp))
99         (cond
100          ;; The charset remains the same.
101          ((or (eq (setq charset (char-charset (following-char))) 'ascii)
102               (eq charset current)))
103          ;; The initial charset was ascii.
104          ((eq current 'ascii)
105           (setq current charset
106                 space nil
107                 newline nil
108                 paragraph nil))
109          ;; We have a change in charsets.
110          (t
111           (push (append
112                  orig-tag
113                  (list (cons 'contents
114                              (buffer-substring-no-properties
115                               beg (or paragraph newline space (point))))))
116                 struct)
117           (setq beg (or paragraph newline space (point))
118                 current charset
119                 space nil
120                 newline nil
121                 paragraph nil)))
122         ;; Compute places where it might be nice to break the part.
123         (cond
124          ((memq (following-char) '(?  ?\t))
125           (setq space (1+ (point))))
126          ((eq (following-char) ?\n)
127           (setq newline (1+ (point))))
128          ((and (eq (following-char) ?\n)
129                (not (bobp))
130                (eq (char-after (1- (point))) ?\n))
131           (setq paragraph (point))))
132         (forward-char 1))
133       ;; Do the final part.
134       (unless (= beg (point))
135         (push (append orig-tag
136                       (list (cons 'contents
137                                   (buffer-substring-no-properties
138                                    beg (point)))))
139               struct))
140       struct)))
141
142 (defun mml-read-tag ()
143   "Read a tag and return the contents."
144   (let (contents name elem val)
145     (forward-char 2)
146     (setq name (buffer-substring-no-properties
147                 (point) (progn (forward-sexp 1) (point))))
148     (skip-chars-forward " \t\n")
149     (while (not (looking-at ">"))
150       (setq elem (buffer-substring-no-properties
151                   (point) (progn (forward-sexp 1) (point))))
152       (skip-chars-forward "= \t\n")
153       (setq val (buffer-substring-no-properties
154                  (point) (progn (forward-sexp 1) (point))))
155       (when (string-match "^\"\\(.*\\)\"$" val)
156         (setq val (match-string 1 val)))
157       (push (cons (intern elem) val) contents)
158       (skip-chars-forward " \t\n"))
159     (forward-char 1)
160     (cons (intern name) (nreverse contents))))
161
162 (defun mml-read-part ()
163   "Return the buffer up till the next part, multipart or closing part or multipart."
164   (let ((beg (point)))
165     ;; If the tag ended at the end of the line, we go to the next line.
166     (when (looking-at "[ \t]*\n")
167       (forward-line 1))
168     (if (re-search-forward
169          "<#\\(/\\)?\\(multipart\\|part\\|external\\)." nil t)
170         (prog1
171             (buffer-substring-no-properties beg (match-beginning 0))
172           (if (or (not (match-beginning 1))
173                   (equal (match-string 2) "multipart"))
174               (goto-char (match-beginning 0))
175             (when (looking-at "[ \t]*\n")
176               (forward-line 1))))
177       (buffer-substring-no-properties beg (goto-char (point-max))))))
178
179 (defvar mml-boundary nil)
180 (defvar mml-base-boundary "-=-=")
181 (defvar mml-multipart-number 0)
182
183 (defun mml-generate-mime ()
184   "Generate a MIME message based on the current MML document."
185   (let ((cont (mml-parse))
186         (mml-multipart-number 0))
187     (if (not cont)
188         nil
189       (with-temp-buffer
190         (if (and (consp (car cont))
191                  (= (length cont) 1))
192             (mml-generate-mime-1 (car cont))
193           (mml-generate-mime-1 (nconc (list 'multipart '(type . "mixed"))
194                                       cont)))
195         (buffer-string)))))
196
197 (defun mml-generate-mime-1 (cont)
198   (cond
199    ((eq (car cont) 'part)
200     (let (coded encoding charset filename type)
201       (setq type (or (cdr (assq 'type cont)) "text/plain"))
202       (if (equal (car (split-string type "/")) "text")
203           (with-temp-buffer
204             (if (setq filename (cdr (assq 'filename cont)))
205                 (insert-file-contents-literally filename)
206               (save-restriction
207                 (narrow-to-region (point) (point))
208                 (insert (cdr (assq 'contents cont)))
209                 ;; Remove quotes from quoted tags.
210                 (goto-char (point-min))
211                 (while (re-search-forward
212                         "<#!+/?\\(part\\|multipart\\|external\\)" nil t)
213                   (delete-region (+ (match-beginning 0) 2)
214                                  (+ (match-beginning 0) 3)))))
215             (setq charset (mm-encode-body)
216                   encoding (mm-body-encoding))
217             (setq coded (buffer-string)))
218         (mm-with-unibyte-buffer
219           (if (setq filename (cdr (assq 'filename cont)))
220               (insert-file-contents-literally filename)
221             (insert (cdr (assq 'contents cont))))
222           (setq encoding (mm-encode-buffer type)
223                 coded (buffer-string))))
224       (mml-insert-mime-headers cont type charset encoding)
225       (insert "\n")
226       (insert coded)))
227    ((eq (car cont) 'external)
228     (insert "Content-Type: message/external-body")
229     (let ((parameters (mml-parameter-string
230                        cont '(expiration size permission)))
231           (name (cdr (assq 'name cont))))
232       (when name
233         (setq name (mml-parse-file-name name))
234         (if (stringp name)
235             (insert ";\n " (mail-header-encode-parameter "name" name)
236                     "\";\n access-type=local-file")
237           (insert
238            (format ";\n "
239                    (mail-header-encode-parameter
240                     "name" (file-name-nondirectory (nth 2 name)))
241                    (mail-header-encode-parameter "site" (nth 1 name))
242                    (mail-header-encode-parameter
243                     "directory" (file-name-directory (nth 2 name)))))
244           (insert ";\n access-type="
245                   (if (member (nth 0 name) '("ftp@" "anonymous@"))
246                       "anon-ftp"
247                     "ftp"))))
248       (when parameters
249         (insert parameters)))
250     (insert "\n\n")
251     (insert "Content-Type: " (cdr (assq 'type cont)) "\n")
252     (insert "Content-ID: " (message-make-message-id) "\n")
253     (insert "Content-Transfer-Encoding: "
254             (or (cdr (assq 'encoding cont)) "binary"))
255     (insert "\n\n")
256     (insert (or (cdr (assq 'contents cont))))
257     (insert "\n"))
258    ((eq (car cont) 'multipart)
259     (let ((mml-boundary (mml-compute-boundary cont)))
260       (insert (format "Content-Type: multipart/%s; boundary=\"%s\"\n"
261                       (or (cdr (assq 'type cont)) "mixed")
262                       mml-boundary))
263       (insert "\n")
264       (setq cont (cddr cont))
265       (while cont
266         (insert "\n--" mml-boundary "\n")
267         (mml-generate-mime-1 (pop cont)))
268       (insert "\n--" mml-boundary "--\n")))
269    (t
270     (error "Invalid element: %S" cont))))
271
272 (defun mml-compute-boundary (cont)
273   "Return a unique boundary that does not exist in CONT."
274   (let ((mml-boundary (mml-make-boundary)))
275     ;; This function tries again and again until it has found
276     ;; a unique boundary.
277     (while (not (catch 'not-unique
278                   (mml-compute-boundary-1 cont))))
279     mml-boundary))
280
281 (defun mml-compute-boundary-1 (cont)
282   (let (filename)
283     (cond
284      ((eq (car cont) 'part)
285       (with-temp-buffer
286         (if (setq filename (cdr (assq 'filename cont)))
287             (insert-file-contents-literally filename)
288           (insert (cdr (assq 'contents cont))))
289         (goto-char (point-min))
290         (when (re-search-forward (concat "^--" (regexp-quote mml-boundary))
291                                  nil t)
292           (setq mml-boundary (mml-make-boundary))
293           (throw 'not-unique nil))))
294      ((eq (car cont) 'multipart)
295       (mapcar 'mml-compute-boundary-1 (cddr cont))))
296     t))
297
298 (defun mml-make-boundary ()
299   (concat (make-string (% (incf mml-multipart-number) 60) ?=)
300           (if (> mml-multipart-number 17)
301               (format "%x" mml-multipart-number)
302             "")
303           mml-base-boundary))
304
305 (defun mml-make-string (num string)
306   (let ((out ""))
307     (while (not (zerop (decf num)))
308       (setq out (concat out string)))
309     out))
310
311 (defun mml-insert-mime-headers (cont type charset encoding)
312   (let (parameters disposition description)
313     (setq parameters
314           (mml-parameter-string
315            cont '(name access-type expiration size permission)))
316     (when (or charset
317               parameters
318               (not (equal type "text/plain")))
319       (when (consp charset)
320         (error
321          "Can't encode a part with several charsets."))
322       (insert "Content-Type: " type)
323       (when charset
324         (insert "; " (mail-header-encode-parameter
325                       "charset" (symbol-name charset))))
326       (when parameters
327         (insert parameters))
328       (insert "\n"))
329     (setq parameters
330           (mml-parameter-string
331            cont '(filename creation-date modification-date read-date)))
332     (when (or (setq disposition (cdr (assq 'disposition cont)))
333               parameters)
334       (insert "Content-Disposition: " (or disposition "inline"))
335       (when parameters
336         (insert parameters))
337       (insert "\n"))
338     (unless (eq encoding '7bit)
339       (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
340     (when (setq description (cdr (assq 'description cont)))
341       (insert "Content-Description: "
342               (mail-encode-encoded-word-string description) "\n"))))
343
344 (defun mml-parameter-string (cont types)
345   (let ((string "")
346         value type)
347     (while (setq type (pop types))
348       (when (setq value (cdr (assq type cont)))
349         ;; Strip directory component from the filename parameter.
350         (when (eq type 'filename)
351           (setq value (file-name-nondirectory value)))
352         (setq string (concat string ";\n "
353                              (mail-header-encode-parameter
354                               (symbol-name type) value)))))
355     (when (not (zerop (length string)))
356       string)))
357
358 (defvar ange-ftp-path-format)
359 (defvar efs-path-regexp)
360 (defun mml-parse-file-name (path)
361   (if (if (boundp 'efs-path-regexp)
362           (string-match efs-path-regexp path)
363         (if (boundp 'ange-ftp-path-format)
364             (string-match (car ange-ftp-path-format))))
365       (list (match-string 1 path) (match-string 2 path)
366             (substring path (1+ (match-end 2))))
367     path))
368
369 (defun mml-quote-region (beg end)
370   "Quote the MML tags in the region."
371   (interactive "r")
372   (save-excursion
373     (goto-char beg)
374     ;; Quote parts.
375     (while (re-search-forward
376             "<#/?!*\\(multipart\\|part\\|external\\)" end t)
377       (goto-char (match-beginning 1))
378       (insert "!"))))
379
380 (provide 'mml)
381
382 ;;; mml.el ends here