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