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