tm 7.30.
[elisp/tm.git] / tm-edit.el
1 ;;;
2 ;;; tm-edit.el --- Simple MIME Composer for GNU Emacs
3 ;;;
4
5 ;; Copyright (C) 1993 UMEDA Masanobu
6 ;; Copyright (C) 1994,1995 MORIOKA Tomohiko
7
8 ;; Author: UMEDA Masanobu <umerin@mse.kyutech.ac.jp>
9 ;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
10 ;; Version: $Revision: 7.30 $
11 ;; Keywords: mail, news, MIME, multimedia, multilingual
12
13 ;; This file is not part of GNU Emacs.
14
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; any later version.
19
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING.  If not, write to
27 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
28
29 ;;; Commentary:
30
31 ;; This is an Emacs minor mode for editing Internet multimedia
32 ;; messages formatted in MIME (RFC 1521 and RFC 1522). All messages in
33 ;; this mode are composed in the tagged MIME format, that are
34 ;; described in the following examples. The messages composed in the
35 ;; tagged MIME format are automatically translated into a MIME
36 ;; compliant message when exiting the mode.
37
38 ;; Mule (a multilingual extension to Emacs 18 and 19) has a capability
39 ;; of handling multilingual text in limited ISO-2022 manner that is
40 ;; based on early experiences in Japanese Internet community and
41 ;; resulted in RFC 1468 (ISO-2022-JP charset for MIME). In order to
42 ;; enable multilingual capability in single text message in MIME,
43 ;; charset of multilingual text written in Mule is declared as either
44 ;; `ISO-2022-JP-2' [RFC 1554] or `ISO-2022-INT-1'. Mule is required
45 ;; for reading the such messages.
46
47 ;; This MIME composer can work with Mail mode, mh-e letter Mode, and
48 ;; News mode.  First of all, you need the following autoload
49 ;; definition to load mime/editor-mode automatically:
50 ;;
51 ;; (autoload 'mime/editor-mode "tm-edit"
52 ;;      "Minor mode for editing MIME message." t)
53 ;;
54 ;; In case of Mail mode (includes VM mode), you need the following
55 ;; hook definition:
56 ;;
57 ;; (add-hook 'mail-mode-hook 'mime/editor-mode)
58 ;; (add-hook 'mail-send-hook 'mime-editor/maybe-translate)
59 ;;
60 ;; In case of MH-E, you need the following hook definition:
61 ;;
62 ;; (add-hook 'mh-letter-mode-hook
63 ;;           (function
64 ;;            (lambda ()
65 ;;              (mime/editor-mode)
66 ;;              (make-local-variable 'mail-header-separator)
67 ;;              (setq mail-header-separator "--------")
68 ;;              ))))
69 ;; (add-hook 'mh-before-send-letter-hook 'mime-editor/maybe-translate)
70 ;;
71 ;; In case of News mode, you need the following hook definition:
72 ;;
73 ;; (add-hook 'news-reply-mode-hook 'mime/editor-mode)
74 ;; (add-hook 'news-inews-hook 'mime-editor/maybe-translate)
75 ;;
76 ;; In case of Emacs 19, it is possible to emphasize the message tags
77 ;; using font-lock mode as follows:
78 ;;
79 ;; (add-hook 'mime/editor-mode-hook
80 ;;           (function
81 ;;            (lambda ()
82 ;;              (font-lock-mode 1)
83 ;;              (setq font-lock-keywords (list mime-editor/tag-regexp))
84 ;;              ))))
85
86 ;; The message tag looks like:
87 ;;
88 ;;      --[[TYPE/SUBTYPE;PARAMETERS][ENCODING]]
89 ;;
90 ;; The tagged MIME message examples:
91 ;;
92 ;; This is a conventional plain text.  It should be translated into
93 ;; text/plain.
94 ;; 
95 ;;--[[text/plain]]
96 ;; This is also a plain text.  But, it is explicitly specified as is.
97 ;;
98 ;;--[[text/plain; charset=ISO-2022-JP]]
99 ;; \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9%H$G$9\e(B.
100 ;;
101 ;;--[[text/richtext]]
102 ;; <center>This is a richtext.</center>
103 ;;
104 ;;--[[image/gif][base64]]^M...image encoded in base64 comes here...
105 ;;
106 ;;--[[audio/basic][base64]]^M...audio encoded in base64 comes here...
107
108 ;; LCD Archive Entry:
109 ;; mime|Masanobu UMEDA|umerin@mse.kyutech.ac.jp|
110 ;; Simple MIME Composer|
111 ;; $Date: 1995/12/06 12:52:53 $|$Revision: 7.30 $|~/misc/mime.el.Z|
112
113 ;;; Code:
114
115 (require 'sendmail)
116 (require 'mail-utils)
117 (require 'mel)
118 (require 'tl-822)
119 (require 'tl-list)
120 (require 'tm-view)
121 (require 'tm-ew-e)
122 (require 'signature)
123
124
125 ;;; @ version
126 ;;;
127
128 (defconst mime-editor/RCS-ID
129   "$Id: tm-edit.el,v 7.30 1995/12/06 12:52:53 morioka Exp $")
130
131 (defconst mime-editor/version (get-version-string mime-editor/RCS-ID))
132
133
134 ;;; @ variables
135 ;;;
136
137 (defvar mime-prefix "\C-c\C-x"
138   "*Keymap prefix for MIME commands.")
139
140 (defvar mime-signature-file "~/.signature.rtf"
141   "*Signature file to be included as a part of a multipart message.")
142
143 (defvar mime-ignore-preceding-spaces nil
144   "*Ignore preceding white spaces if non-nil.")
145
146 (defvar mime-ignore-trailing-spaces nil
147   "*Ignore trailing white spaces if non-nil.")
148
149 (defvar mime-ignore-same-text-tag t
150   "*Ignore preceding text content-type tag that is same with new one.
151 If non-nil, the text tag is not inserted unless something different.")
152
153 (defvar mime-auto-hide-body t
154   "*Hide non-textual body encoded in base64 after insertion if non-nil.")
155
156 (defvar mime-body-charset-chooser
157   (cond ((boundp 'NEMACS)
158          (function mime-body-charset-chooser-for-nemacs))
159         ((featurep 'mule)
160          (function mime-body-charset-chooser-for-mule))
161         ((string-match "^19\\." emacs-version)
162          (function mime-body-charset-chooser-for-emacs19))
163         (t                              ;ASCII only emacs
164          (function mime-body-charset-chooser-for-emacs18)))
165   "*Function to identify charset and encoding of a text in a given region.
166 The value is a form of (CHARSET . ENCODING), where ENCODING must be a
167 full name, such as base64.")
168
169 (defvar mime-string-encoder
170   (cond ((boundp 'NEMACS)
171          (function mime-string-encoder-for-nemacs))
172         ((featurep 'mule)
173          (function mime-string-encoder-for-mule))
174         ((string-match "^19\\." emacs-version)
175          (function mime-string-encoder-for-emacs19))
176         (t                              ;ASCII only emacs
177          (function mime-string-encoder-for-emacs18)))
178   "*Function to encode a string for given encoding method.
179 The method is a form of (CHARSET . ENCODING).")
180
181 (defvar mime-voice-recorder
182   (function mime-voice-recorder-for-sun)
183   "*Function to record a voice message and return a buffer that contains it.")
184
185 (defvar mime/editor-mode-hook nil
186   "*Hook called when enter MIME mode.")
187
188 (defvar mime-editor/translate-hook nil
189   "*Hook called before translating into a MIME compliant message.
190 To insert a signature file specified by mime-signature-file
191 (`.signature.rtf' by default) automatically, call the function
192 `mime-editor/insert-signature' from this hook.")
193
194 (defvar mime-editor/exit-hook nil
195   "*Hook called when exit MIME mode.")
196
197 (defvar mime-content-types
198   '(("text"
199      ;; Charset parameter need not to be specified, since it is
200      ;; defined automatically while translation.
201      ("plain"
202       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
203       )
204      ("richtext"
205       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
206       )
207      ("enriched"
208       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
209       )
210      ("x-latex"
211       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
212       )
213      ("html"
214       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
215       )
216      ("x-rot13-47")
217      )
218     ("message"
219      ("external-body"
220       ("access-type"
221        ("anon-ftp"
222         ("site" "ftp.jaist.ac.jp" "wnoc-fuk.wide.ad.jp" "nic.karrn.ad.jp")
223         ("directory" "/pub/GNU/elisp/mime")
224         ("name")
225         ("mode" "image" "ascii" "local8"))
226        ("ftp"
227         ("site")
228         ("directory")
229         ("name")
230         ("mode" "image" "ascii" "local8"))
231        ("tftp"        ("site") ("name"))
232        ("afs"         ("site") ("name"))
233        ("local-file"  ("site") ("name"))
234        ("mail-server" ("server" "ftpmail@nic.karrn.ad.jp"))
235        ))
236      ("rfc822")
237      )
238     ("application"
239      ("octet-stream"
240       ("name")
241       ("type" "" "tar" "shar")
242       ("conversions"))
243      ("postscript")
244      ("x-kiss" ("x-cnf")))
245     ("image"
246      ("gif")
247      ("jpeg")
248      ("tiff")
249      ("x-pic")
250      ("x-xwd")
251      ("x-xbm")
252      )
253     ("audio" ("basic"))
254     ("video" ("mpeg"))
255     )
256   "*Alist of content-type, subtype, parameters and its values.")
257
258 (defvar mime-file-types
259   '(("\\.rtf$"
260      "text"     "richtext"      nil     nil)
261     ("\\.html$"
262      "text"     "html"          nil     nil)
263     ("\\.ps$"
264      "application" "postscript" nil     "quoted-printable")
265     ("\\.gif$"
266      "image"    "gif"           nil     "base64"
267      (("Content-Description" . file))
268      )
269     ("\\.jpg$"
270      "image"    "jpeg"          nil     "base64")
271     ("\\.xwd$"
272      "image"    "x-xwd"         nil     "base64")
273     ("\\.xbm$"
274      "image"    "x-xbm"         nil     "base64")
275     ("\\.pic$"
276      "image"    "x-pic"         nil     "base64"
277      (("Content-Description" . file))
278      )
279     ("\\.tiff$"
280      "image"    "tiff"          nil     "base64")
281     ("\\.au$"
282      "audio"    "basic"         nil     "base64")
283     ("\\.mpg$"
284      "video"    "mpeg"          nil     "base64")
285     ("\\.el$"
286      "application" "octet-stream" (("name" . file)
287                                    ("type" . "emacs-lisp")) "7bit")
288     ("\\.lsp$"
289      "application" "octet-stream" (("name" . file)
290                                    ("type" . "common-lisp")) "7bit")
291     ("\\.tar.gz$"
292      "application" "octet-stream" (("name" . file)
293                                    ("type" . "tar")
294                                    ("conversions" . "gzip")) nil)
295     ("\\.diff$"
296      "application" "octet-stream" (("name" . file)
297                                    ("type" . "patch")) nil)
298     ("\\.signature"
299      "text"     "plain"         nil     nil)
300     (".*"       nil             nil     nil     nil)
301     )
302   "*Alist of file name, types, parameters, and default encoding.
303 If encoding is nil, it is determined from its contents.")
304
305 ;;; @@ about message inserting
306 ;;;
307
308 (defvar mime-editor/yank-ignored-field-list
309   '("Received" "Sender" "Approved" "Path" "Status" "X-VM-.*" "X-UIDL")
310   "Delete these fields from original message when it is inserted
311 as message/rfc822 part.
312 Each elements are regexp of field-name. [tm-edit.el]")
313
314 (defvar mime-editor/yank-ignored-field-regexp
315   (concat "^"
316           (apply (function regexp-or) mime-editor/yank-ignored-field-list)
317           ":"))
318
319 (defvar mime-editor/message-inserter-alist nil)
320 (defvar mime-editor/mail-inserter-alist nil)
321
322 ;;; @@ about message splitting
323 ;;;
324
325 (defvar mime-editor/split-message t
326   "*Split large message if it is non-nil. [tm-edit.el]")
327
328 (defvar mime-editor/message-default-max-length 1000
329   "*Default maximum size of a message. [tm-edit.el]")
330
331 (defvar mime-editor/message-max-length-alist
332   '((news-reply-mode . 500)))
333
334 (defconst mime-editor/split-ignored-field-regexp
335   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\)")
336
337 (defvar mime-editor/split-blind-field-regexp
338   "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)")
339
340 (defvar mime-editor/message-default-sender-alist
341   '((mail-mode . mail-send-and-exit)
342     (mh-letter-mode . mh-send-letter)
343     (news-reply-mode . gnus-inews-news)
344     ))
345
346 (defvar mime-editor/split-message-sender-alist
347   '((mail-mode
348      . (lambda ()
349          (interactive)
350          (sendmail-send-it)
351          ))
352     (mh-letter-mode
353      . (lambda (&optional arg)
354          (interactive "P")
355          (write-region (point-min) (point-max)
356                        mime-editor/draft-file-name nil 'no-message)
357          (cond (arg
358                 (pop-to-buffer "MH mail delivery")
359                 (erase-buffer)
360                 (mh-exec-cmd-output mh-send-prog t "-watch" "-nopush"
361                                     "-nodraftfolder"
362                                     mh-send-args mime-editor/draft-file-name)
363                 (goto-char (point-max)) ; show the interesting part
364                 (recenter -1)
365                 (sit-for 1))
366                (t
367                 (apply 'mh-exec-cmd-quiet t mh-send-prog 
368                        (mh-list-to-string
369                         (list "-nopush" "-nodraftfolder"
370                               "-noverbose" "-nowatch"
371                               mh-send-args mime-editor/draft-file-name)))))
372          ))
373     ))
374
375 (defvar mime-editor/window-config-alist
376   '((mail-mode       . nil)
377     (mh-letter-mode  . mh-previous-window-config)
378     (news-reply-mode . (cond ((boundp 'gnus-winconf-post-news)
379                               (prog1
380                                   gnus-winconf-post-news
381                                 (setq gnus-winconf-post-news nil)
382                                 ))
383                              ((boundp 'gnus-prev-winconf)
384                               (prog1
385                                   gnus-prev-winconf
386                                 (setq gnus-prev-winconf nil)
387                                 ))
388                              ))
389     ))
390
391 (defvar mime-editor/news-reply-mode-server-running nil)
392
393 ;;; @@ about tag
394 ;;;
395
396 (defconst mime-editor/single-part-tag-regexp
397   "^--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
398   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
399
400 (defconst mime-editor/multipart-beginning-regexp "^--<<\\([^<>]+\\)>>-{\n")
401
402 (defconst mime-editor/multipart-end-regexp "^--}-<<\\([^<>]+\\)>>\n")
403
404 (defconst mime-editor/beginning-tag-regexp
405   (regexp-or mime-editor/single-part-tag-regexp
406              mime-editor/multipart-beginning-regexp))
407
408 (defconst mime-editor/end-tag-regexp
409   (regexp-or mime-editor/single-part-tag-regexp
410              mime-editor/multipart-end-regexp))
411
412 (defconst mime-editor/tag-regexp
413   (regexp-or mime-editor/single-part-tag-regexp
414              mime-editor/multipart-beginning-regexp
415              mime-editor/multipart-end-regexp))
416
417 (defvar mime-tag-format "--[[%s]]"
418   "*Control-string making a MIME tag.")
419
420 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
421   "*Control-string making a MIME tag with encoding.")
422
423 ;;; @@ multipart boundary
424 ;;;
425
426 (defvar mime-multipart-boundary "Multipart"
427   "*Boundary of a multipart message.")
428
429
430 ;;; @@ buffer local variables
431 ;;;
432
433 (defvar mime/editor-mode-old-local-map nil)
434 (defvar mime/editor-mode-old-selective-display nil)
435 (defvar mime/editing-buffer nil)
436
437 \f
438 ;;; @ constants
439 ;;;
440
441 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
442   "*Specify MIME tspecials.
443 Tspecials means any character that matches with it in header must be quoted.")
444
445 (defconst mime-editor/mime-version-value
446   (format "1.0 (generated by tm-edit %s)" mime-editor/version)
447   "MIME version number.")
448
449
450 ;;; @ keymap and menu
451 ;;;
452
453 (defvar mime/editor-mode-flag nil)
454 (make-variable-buffer-local 'mime/editor-mode-flag)
455
456 (set-alist 'minor-mode-alist 'mime/editor-mode-flag '(" MIME-Edit"))
457
458 (defun mime-editor/define-keymap (keymap)
459   "Add mime-editor commands to KEYMAP."
460   (if (not (keymapp keymap))
461       nil
462     (define-key keymap "\C-t" 'mime-editor/insert-text)
463     (define-key keymap "\C-i" 'mime-editor/insert-file)
464     (define-key keymap "\C-e" 'mime-editor/insert-external)
465     (define-key keymap "\C-v" 'mime-editor/insert-voice)
466     (define-key keymap "\C-y" 'mime-editor/insert-message)
467     (define-key keymap "\C-m" 'mime-editor/insert-mail)
468     (define-key keymap "\C-w" 'mime-editor/insert-signature)
469     (define-key keymap "\C-s" 'mime-editor/insert-signature)
470     (define-key keymap "t"    'mime-editor/insert-tag)
471     (define-key keymap "a"    'mime-editor/enclose-alternative-region)
472     (define-key keymap "p"    'mime-editor/enclose-parallel-region)
473     (define-key keymap "m"    'mime-editor/enclose-mixed-region)
474     (define-key keymap "d"    'mime-editor/enclose-digest-region)
475     (define-key keymap "\C-p" 'mime-editor/preview-message)
476     (define-key keymap "\C-z" 'mime-editor/exit)
477     (define-key keymap "?"    'mime-editor/help)
478     ))
479
480 (defconst mime-editor/menu-title "MIME-Edit")
481
482 (defconst mime-editor/menu-list
483   '((mime-help  "Describe MIME Mode"    mime-editor/help)
484     (file       "Insert File"           mime-editor/insert-file)
485     (external   "Insert External"       mime-editor/insert-external)
486     (voice      "Insert Voice"          mime-editor/insert-voice)
487     (message    "Insert Message"        mime-editor/insert-message)
488     (mail       "Insert Mail"           mime-editor/insert-mail)
489     (signature  "Insert Signature"      mime-editor/insert-signature)
490     (text       "Insert Text"           mime-editor/insert-text)
491     (tag        "Insert Tag"            mime-editor/insert-tag)
492     (alternative "Enclose as alternative"
493                  mime-editor/enclose-alternative-region)
494     (parallel   "Enclose as parallel"   mime-editor/enclose-parallel-region)
495     (mixed      "Enclose as serial"     mime-editor/enclose-mixed-region)
496     (digest     "Enclose as digest"     mime-editor/enclose-digest-region)
497     (preview    "Preview Message"       mime-editor/preview-message)
498     )
499   "MIME-edit menubar entry.")
500
501 (defun mime-editor/define-menu-for-emacs19 ()
502   "Define menu for Emacs 19."
503   (define-key (current-local-map) [menu-bar mime-edit]
504     (cons mime-editor/menu-title
505           (make-sparse-keymap mime-editor/menu-title)))
506   (mapcar (function
507            (lambda (item)
508              (define-key (current-local-map)
509                (vector 'menu-bar 'mime-edit (car item))
510                (cons (nth 1 item)(nth 2 item))
511                )
512              ))
513           (reverse mime-editor/menu-list)
514           ))
515
516 ;;; modified by Pekka Marjola <pema@niksula.hut.fi>
517 ;;;     1995/9/5 (c.f. [tm-eng:69])
518 (defun mime-editor/define-menu-for-xemacs ()
519   "Define menu for Emacs 19."
520   (cond ((featurep 'menubar)
521          (make-local-variable 'current-menubar)
522          (set-buffer-menubar current-menubar)
523          (add-submenu nil
524                       (cons mime-editor/menu-title
525                             (mapcar (function
526                                      (lambda (item)
527                                        (vector (nth 1 item)(nth 2 item)
528                                                mime/editor-mode-flag)
529                                        ))
530                                     mime-editor/menu-list)))
531          )))
532 ;;; end
533
534
535 ;;; @ functions
536 ;;;
537
538 ;;;###autoload
539 (defun mime/editor-mode ()
540   "MIME minor mode for editing the tagged MIME message.
541
542 In this mode, basically, the message is composed in the tagged MIME
543 format.  The message tag looks like:
544
545         `--[[text/plain; charset=ISO-2022-JP][7bit]]'.
546
547 The tag specifies the MIME content type, subtype, optional parameters
548 and transfer encoding of the message following the tag.  Messages
549 without any tag are treated as `text/plain' by default.  Charset and
550 transfer encoding are automatically defined unless explicitly
551 specified.  Binary messages such as audio and image are usually hidden
552 using selective-display facility.  The messages in the tagged MIME
553 format are automatically translated into a MIME compliant message when
554 exiting this mode.
555
556 Available charsets depend on Emacs version being used.  The following
557 lists the available charsets of each emacs.
558
559 Emacs18:        US-ASCII is only available.
560 NEmacs:         US-ASCII and ISO-2022-JP are available.
561 Emacs19:        US-ASCII and ISO-8859-1 are available.
562 Mule:           US-ASCII, ISO-8859-* (except for ISO-8859-6),
563                 ISO-2022-JP, ISO-2022-JP-2 and ISO-2022-INT-1 are available.
564
565 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in Mule is expected to
566 be used to represent multilingual text in intermixed manner.  Any
567 languages that has no registered charset are represented as either
568 ISO-2022-JP-2 or ISO-2022-INT-1 in Mule.
569
570 Following commands are available in addition to major mode commands:
571 \\[mime-editor/insert-text]     insert a text message.
572 \\[mime-editor/insert-file]     insert a (binary) file.
573 \\[mime-editor/insert-external] insert a reference to external body.
574 \\[mime-editor/insert-voice]    insert a voice message.
575 \\[mime-editor/insert-message]  insert a mail or news message.
576 \\[mime-editor/insert-mail]     insert a mail message.
577 \\[mime-editor/insert-signature]        insert a signature file at end.
578 \\[mime-editor/insert-tag]      insert a new MIME tag.
579 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
580 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
581 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
582 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
583 \\[mime-editor/preview-message] preview editing MIME message.
584 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
585 \\[mime-editor/maybe-translate] exit, translate and run the original command.
586 \\[mime-editor/help]    show this help.
587
588 Additional commands are available in some major modes:
589 C-c C-c         exit, translate and run the original command.
590 C-c C-s         exit, translate and run the original command.
591
592 The following is a message example written in the tagged MIME format.
593 TABs at the beginning of the line are not a part of the message:
594
595         This is a conventional plain text.  It should be translated
596         into text/plain.
597         --[[text/plain]]
598         This is also a plain text.  But, it is explicitly specified as
599         is.
600         --[[text/plain; charset=ISO-2022-JP]]
601         \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9\e(B
602         \e$B%H$G$9\e(B.
603         --[[text/richtext]]
604         <center>This is a richtext.</center>
605         --[[image/gif][base64]]^M...image encoded in base64 here...
606         --[[audio/basic][base64]]^M...audio encoded in base64 here...
607
608 User customizable variables (not documented all of them):
609  mime-prefix
610     Specifies a key prefix for MIME minor mode commands.
611
612  mime-signature-file
613     Specifies a signature file to be included as part of a multipart
614     message.
615
616  mime-ignore-preceding-spaces
617     Preceding white spaces in a message body are ignored if non-nil.
618
619  mime-ignore-trailing-spaces
620     Trailing white spaces in a message body are ignored if non-nil.
621
622  mime-auto-fill-header
623     Fill header fields that contain encoded-words if non-nil.
624
625  mime-auto-hide-body
626     Hide a non-textual body message encoded in base64 after insertion
627     if non-nil.
628
629  mime-body-charset-chooser
630     Specifies a function to identify charset and encoding of a text in
631     a given region.  The value is a form of (CHARSET . ENCODING),
632     where ENCODING must be a full name, such as base64.
633
634  mime-string-encoder
635     Specifies a function to encode a string for given encoding method.
636     The method is a form of (CHARSET . ENCODING).
637
638  mime-voice-recorder
639     Specifies a function to record a voice message and return a buffer
640     that contains it.  The function mime-voice-recorder-for-sun is for
641     Sun SparcStations.
642
643  mime/editor-mode-hook
644     Turning on MIME mode calls the value of mime/editor-mode-hook, if
645     it is non-nil.
646
647  mime-editor/translate-hook
648     The value of mime-editor/translate-hook is called just before translating
649     the tagged MIME format into a MIME compliant message if it is
650     non-nil.  If the hook call the function mime-editor/insert-signature,
651     the signature file will be inserted automatically.
652
653  mime-editor/exit-hook
654     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
655     non-nil."
656   (interactive)
657   (if mime/editor-mode-flag
658       (error "You are already editing a MIME message.")
659     (setq mime/editor-mode-flag t)
660     ;; Remember old key bindings.
661     (make-local-variable 'mime/editor-mode-old-local-map)
662     (setq mime/editor-mode-old-local-map (current-local-map))
663     ;; Add MIME commands to current local map.
664     (use-local-map (copy-keymap (current-local-map)))
665     (if (not (lookup-key (current-local-map) mime-prefix))
666         (define-key (current-local-map) mime-prefix (make-sparse-keymap)))
667     (mime-editor/define-keymap (lookup-key (current-local-map) mime-prefix))
668     
669     ;; Define menu.  Menus for other emacs implementations are
670     ;; welcome.
671     ;;  modified by Pekka Marjola <pema@niksula.hut.fi>
672     ;;          1995/9/5 (c.f. [tm-eng:69])
673     (cond ((string-match "XEmacs\\|Lucid" emacs-version)
674            (mime-editor/define-menu-for-xemacs))
675           ((string-match "^19\\." emacs-version)
676            (mime-editor/define-menu-for-emacs19)
677            ))
678     ;; end
679     
680     ;; Remember old selective-display.
681     (make-local-variable 'mime/editor-mode-old-selective-display)
682     (setq mime/editor-mode-old-selective-display selective-display)
683     (setq selective-display t)
684     ;; I don't care about saving these.
685     (setq paragraph-start
686           (concat mime-editor/single-part-tag-regexp "\\|" paragraph-start))
687     (setq paragraph-separate
688           (concat mime-editor/single-part-tag-regexp "\\|" paragraph-separate))
689     (run-hooks 'mime/editor-mode-hook)
690     (message
691      (substitute-command-keys
692       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
693     ))
694
695 ;;;###autoload
696 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
697 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
698
699 (defun mime-editor/exit (&optional nomime no-error)
700   "Translate the tagged MIME message into a MIME compliant message.
701 With no argument encode a message in the buffer into MIME, otherwise
702 just return to previous mode."
703   (interactive "P")
704   (if (not mime/editor-mode-flag)
705       (if (null no-error)
706           (error "You aren't editing a MIME message.")
707         )
708     (if (not nomime)
709         (progn
710           (run-hooks 'mime-editor/translate-hook)
711           (mime-editor/translate-buffer)))
712     ;; Restore previous state.
713     (setq mime/editor-mode-flag nil)
714     (use-local-map mime/editor-mode-old-local-map)
715     
716     ;; modified by Pekka Marjola <pema@niksula.hut.fi>
717     ;;  1995/9/5 (c.f. [tm-eng:69])
718     (if (string-match "XEmacs\\|Lucid" emacs-version)
719         (progn
720           (delete-menu-item (list mime-editor/menu-title))
721                                         ; should rather be const
722           ;; (while mime-editor/xemacs-old-bindings
723           ;;   (eval (pop mime-editor/xemacs-old-bindings)))
724           (local-unset-key mime-prefix)))
725     ;; end
726     
727     (setq selective-display mime/editor-mode-old-selective-display)
728     (set-buffer-modified-p (buffer-modified-p))
729     (run-hooks 'mime-editor/exit-hook)
730     (message "Exit MIME editor mode.")
731     ))
732
733 (defun mime-editor/maybe-translate ()
734   (interactive)
735   (mime-editor/exit nil t)
736   (call-interactively 'mime-editor/split-and-send)
737   )
738
739 (defun mime-editor/help ()
740   "Show help message about MIME mode."
741   (interactive)
742   (with-output-to-temp-buffer "*Help*"
743     (princ "MIME editor mode:\n")
744     (princ (documentation 'mime/editor-mode))
745     (print-help-return-message)))
746
747 (defun mime-editor/insert-text ()
748   "Insert a text message.
749 Charset is automatically obtained from the mime-body-charset-chooser."
750   (interactive)
751   (if (and (mime-editor/insert-tag "text" nil nil)
752            (looking-at mime-editor/single-part-tag-regexp))
753       (progn
754         ;; Make a space between the following message.
755         (insert "\n")
756         (forward-char -1)
757         )))
758
759 (defun mime-editor/insert-file (file)
760   "Insert a message from a file."
761   (interactive "fInsert file as MIME message: ")
762   (let*  ((guess (mime-find-file-type file))
763           (pritype (nth 0 guess))
764           (subtype (nth 1 guess))
765           (parameters (nth 2 guess))
766           (default (nth 3 guess))       ;Guess encoding from its file name.
767           (fields (nth 4 guess))
768           (encoding
769            (if (not (interactive-p))
770                default
771              (completing-read
772               (concat "What transfer encoding"
773                       (if default
774                           (concat " (default "
775                                   (if (string-equal default "")
776                                       "\"\""
777                                     default)
778                                   ")"
779                                   ))
780                       ": ")
781               mime-encoding-method-alist nil t nil))))
782     (if (string-equal encoding "")
783         (setq encoding default))
784     (if (or (consp parameters) (consp fields))
785         (let ((rest parameters) cell attribute value)
786           (setq parameters "")
787           (while rest
788             (setq cell (car rest))
789             (setq attribute (car cell))
790             (setq value (cdr cell))
791             (if (eq value 'file)
792                 (setq value (file-name-nondirectory file))
793               )
794             (setq parameters (concat parameters "; " attribute "=" value))
795             (setq rest (cdr rest))
796             )
797           (setq rest fields)
798           (while rest
799             (setq cell (car rest))
800             (setq attribute (car cell))
801             (setq value (cdr cell))
802             (if (eq value 'file)
803                 (setq value (file-name-nondirectory file))
804               )
805             (setq parameters (concat parameters "\n" attribute ": " value))
806             (setq rest (cdr rest))
807             )
808           ))
809     (mime-editor/insert-tag pritype subtype parameters)
810     (mime-editor/insert-binary-file file encoding)
811     ))
812
813 (defun mime-editor/insert-external ()
814   "Insert a reference to external body."
815   (interactive)
816   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
817   ;;(forward-char -1)
818   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
819   ;;(forward-line 1)
820   (let* ((pritype (mime-prompt-for-type))
821          (subtype (mime-prompt-for-subtype pritype))
822          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
823     (and pritype
824          subtype
825          (insert "Content-Type: "
826                  pritype "/" subtype (or parameters "") "\n")))
827   (if (and (not (eobp))
828            (not (looking-at mime-editor/single-part-tag-regexp)))
829       (insert (mime-make-text-tag) "\n")))
830
831 (defun mime-editor/insert-voice ()
832   "Insert a voice message."
833   (interactive)
834   (mime-editor/insert-tag "audio" "basic" nil)
835   (let ((buffer (funcall mime-voice-recorder)))
836     (unwind-protect
837         (mime-editor/insert-binary-buffer buffer "base64")
838       (kill-buffer buffer)
839       )))
840
841 (defun mime-editor/insert-signature (&optional arg)
842   "Insert a signature file specified by mime-signature-file."
843   (interactive "P")
844   (let ((signature
845          (expand-file-name
846           (if arg
847               (read-file-name "Insert your signature: "
848                               (concat signature-file-name "-")
849                               signature-file-name
850                               nil)
851             (signature/get-signature-file-name))))
852         )
853     (if signature-insert-at-eof
854         (goto-char (point-max))
855       )
856     (apply (function mime-editor/insert-tag)
857            (mime-find-file-type signature))
858     (if (file-readable-p signature)
859         (progn
860           (goto-char (point-max))
861           (if (not (bolp))
862               (insert "\n"))
863           (delete-blank-lines)
864           (insert-file-contents signature)
865           (set-buffer-modified-p (buffer-modified-p))
866                                         ; force mode line update
867           ))))
868
869 \f
870 ;; Insert a new tag around a point.
871
872 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
873   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
874 If nothing is inserted, return nil."
875   (interactive)
876   (let ((oldtag nil)
877         (newtag nil)
878         (current (point))
879         exist-prev-tag exist-next-tag)
880     (setq pritype
881           (or pritype
882               (mime-prompt-for-type)))
883     (setq subtype
884           (or subtype
885               (mime-prompt-for-subtype pritype)))
886     (setq parameters
887           (or parameters
888               (mime-prompt-for-parameters pritype subtype delimiter)))
889     ;; Make a new MIME tag.
890     (setq newtag (mime-make-tag pritype subtype parameters))
891     ;; Find an current MIME tag.
892     (setq oldtag
893           (save-excursion
894             (if (mime-editor/goto-tag)
895                 (progn
896                   (if (eq current (match-beginning 0))
897                       (setq exist-next-tag t)
898                     (setq exist-prev-tag t)
899                     )
900                   (buffer-substring (match-beginning 0) (match-end 0))
901                   )
902               ;; Assume content type is 'text/plan'.
903               (mime-make-tag "text" "plain")
904               )))
905     ;; We are only interested in TEXT.
906     (if (and oldtag
907              (not (mime-test-content-type
908                    (mime-editor/get-contype oldtag) "text")))
909         (setq oldtag nil))
910     (cond (exist-prev-tag (insert "\n"))
911           (exist-next-tag (save-excursion
912                             (insert "\n")
913                             )))
914     ;; (beginning-of-line)
915     ;; (cond ((and oldtag                  ;Text
916     ;;             (not (eobp))
917     ;;             (save-excursion
918     ;;               (forward-line -1)
919     ;;               (looking-at mime-editor/beginning-tag-regexp)
920     ;;               )
921     ;;             (or mime-ignore-same-text-tag
922     ;;                 (not (string-equal oldtag newtag))))
923     ;;        ;; If point is at the next of current tag, move to the
924     ;;        ;; beginning of the tag to disable insertion of extra tag.
925     ;;        (forward-line -1))
926     ;;       ((and oldtag                  ;Text
927     ;;             (not (eobp))
928     ;;             (not (looking-at mime-editor/tag-regexp))
929     ;;             (or mime-ignore-same-text-tag
930     ;;                 (not (string-equal oldtag newtag))))
931     ;;        ;; Copy current tag to break a text into two.
932     ;;        (save-excursion
933     ;;          (insert oldtag "\n")))
934     ;;       ((and (null oldtag)           ;Not text
935     ;;             (not (looking-at mime-editor/tag-regexp)))
936     ;;        ;; Adjust insertion point.  In the middle of text, it is
937     ;;        ;; okay to break the text into two.  However, it should not
938     ;;        ;; be broken into two, if otherwise.
939     ;;        (goto-char (mime-editor/content-end))
940     ;;        (if (eolp)
941     ;;            (forward-line 1))
942     ;;        (if (not (bolp))
943     ;;            (insert "\n"))
944     ;;        ))
945     (if (not (bolp))
946         (if exist-prev-tag
947             (forward-line 1)
948           (insert "\n")
949           ))
950     ;; Make a new tag.
951     (if (or (not oldtag)                ;Not text
952             (or mime-ignore-same-text-tag
953                 (not (string-equal oldtag newtag))))
954         (progn
955           ;; Mark the beginning of the tag for convenience.
956           (push-mark (point) 'nomsg)
957           (insert newtag "\n")
958           (list pritype subtype parameters) ;New tag is created.
959           )
960       ;; Restore previous point.
961       (goto-char current)
962       nil                               ;Nothing is created.
963       )
964     ))
965
966 ;; Insert the binary content after MIME tag.
967 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
968 ;;      for x-uue
969 (defun mime-editor/insert-binary-file (file &optional encoding)
970   "Insert binary FILE at point.
971 Optional argument ENCODING specifies an encoding method such as base64."
972   (let ((tmpbuf (get-buffer-create " *MIME insert*")))
973     (save-excursion
974       (set-buffer tmpbuf)
975       (erase-buffer)
976       (let ((mc-flag nil)               ;Mule
977             (file-coding-system-for-read
978              (if (featurep 'mule) *noconv*))
979             (kanji-flag nil)            ;NEmacs
980             (emx-binary-mode t)         ;Stop CRLF to LF conversion in OS/2
981             )
982         (let (jka-compr-compression-info-list
983               jam-zcat-filename-list)
984           (insert-file-contents file))))
985     (prog1
986         (if (and (stringp encoding)
987                  (string-equal (downcase encoding) "x-uue"))
988             (progn
989               (require 'mel-u)
990               (let ((uuencode-external-encoder
991                      (cons (car uuencode-external-encoder)
992                            (list (file-name-nondirectory file))
993                            )))
994                 (mime-editor/insert-binary-buffer tmpbuf encoding)
995                 ))
996           (mime-editor/insert-binary-buffer tmpbuf encoding))
997       (kill-buffer tmpbuf))))
998
999 ;; Insert the binary content after MIME tag.
1000 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
1001 ;;      for x-uue
1002 (defun mime-editor/insert-binary-buffer (buffer &optional encoding)
1003   "Insert binary BUFFER at point.
1004 Optional argument ENCODING specifies an encoding method such as base64."
1005   (let* ((tagend (1- (point)))          ;End of the tag
1006          (hide-p (and mime-auto-hide-body
1007                       (stringp encoding)
1008                       (let ((en (downcase encoding)))
1009                         (or (string-equal en "base64")
1010                             (string-equal en "x-uue")
1011                             ))))
1012          )
1013     (save-restriction
1014       (narrow-to-region (1- (point)) (point))
1015       (let ((start (point))
1016             (emx-binary-mode t))        ;Stop LF to CRLF conversion in OS/2
1017         (insert-buffer-substring buffer)
1018         ;; Encode binary message if necessary.
1019         (if encoding
1020             (mime-encode-region encoding start (point-max))))
1021       (if hide-p
1022           (progn
1023             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
1024             (goto-char (point-max)))
1025         ))
1026     ;; Define encoding even if it is 7bit.
1027     (if (stringp encoding)
1028         (save-excursion
1029           (goto-char tagend)            ;Make sure which line the tag is on.
1030           (mime-editor/define-encoding encoding)))
1031     ))
1032
1033 \f
1034 ;; Commands work on a current message flagment.
1035
1036 (defun mime-editor/goto-tag ()
1037   "Search for the beginning of the tagged MIME message."
1038   (let ((current (point)) multipart)
1039     (if (looking-at mime-editor/tag-regexp)
1040         t
1041       ;; At first, go to the end.
1042       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1043              (goto-char (match-beginning 0)) ;For multiline tag
1044              (forward-line -1)
1045              (end-of-line)
1046              )
1047             (t
1048              (goto-char (point-max))
1049              ))
1050       ;; Then search for the beginning. 
1051       (re-search-backward mime-editor/end-tag-regexp nil t)
1052       (beginning-of-line)
1053       (or (looking-at mime-editor/beginning-tag-regexp)
1054           ;; Restore previous point.
1055           (progn
1056             (goto-char current)
1057             nil
1058             ))
1059       )))
1060
1061 (defun mime-editor/content-beginning ()
1062   "Return the point of the beginning of content."
1063   (save-excursion
1064     (let ((beg (save-excursion
1065                  (beginning-of-line) (point))))
1066       (if (mime-editor/goto-tag)
1067           (let ((top (point)))
1068             (goto-char (match-end 0))
1069             (if (and (= beg top)
1070                      (= (following-char) ?\^M))
1071                 (point)
1072               (forward-line 1)
1073               (point)))
1074         ;; Default text/plain tag.
1075         (goto-char (point-min))
1076         (re-search-forward
1077          (concat "\n" (regexp-quote mail-header-separator)
1078                  (if mime-ignore-preceding-spaces
1079                      "[ \t\n]*\n" "\n")) nil 'move)
1080         (point))
1081       )))
1082
1083 (defun mime-editor/content-end ()
1084   "Return the point of the end of content."
1085   (save-excursion
1086     (let ((beg (save-excursion
1087                  (beginning-of-line) (point))))
1088       (if (mime-editor/goto-tag)
1089           (let ((top (point)))
1090             (goto-char (match-end 0))
1091             (if (and (= beg top)        ;Must be on the same line.
1092                      (= (following-char) ?\^M))
1093                 (progn
1094                   (end-of-line)
1095                   (point))
1096               ;; Move to the end of this text.
1097               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1098                   ;; Don't forget a multiline tag.
1099                   (goto-char (match-beginning 0)))
1100               (point)
1101               ))
1102         ;; Assume the message begins with text/plain.
1103         (goto-char (mime-editor/content-beginning))
1104         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1105             ;; Don't forget a multiline tag.
1106             (goto-char (match-beginning 0)))
1107         (point))
1108       )))
1109
1110 (defun mime-editor/define-charset (charset)
1111   "Set charset of current tag to CHARSET."
1112   (save-excursion
1113     (if (mime-editor/goto-tag)
1114         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1115           (delete-region (match-beginning 0) (match-end 0))
1116           (insert
1117            (mime-create-tag (mime-set-parameter
1118                              (mime-editor/get-contype tag) "charset" charset)
1119                             (mime-editor/get-encoding tag))))
1120       )))
1121
1122 (defun mime-editor/define-encoding (encoding)
1123   "Set encoding of current tag to ENCODING."
1124   (save-excursion
1125     (if (mime-editor/goto-tag)
1126         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1127           (delete-region (match-beginning 0) (match-end 0))
1128           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1129       )))
1130
1131 (defun mime-editor/choose-charset ()
1132   "Choose charset of a text following current point."
1133   (save-excursion
1134     (let* ((beg (point))
1135            (end (mime-editor/content-end)))
1136       (car (funcall mime-body-charset-chooser beg end)))))
1137
1138 (defun mime-editor/choose-encoding ()
1139   "Choose encoding of a text following current point."
1140   (save-excursion
1141     (let* ((beg (point))
1142            (end (mime-editor/content-end)))
1143       (cdr (funcall mime-body-charset-chooser beg end)))))
1144
1145 (defun mime-make-text-tag (&optional subtype)
1146   "Make a tag for a text after current point.
1147 Subtype of text type can be specified by an optional argument SUBTYPE.
1148 Otherwise, it is obtained from mime-content-types."
1149   (let* ((pritype "text")
1150          (subtype (or subtype
1151                       (car (car (cdr (assoc pritype mime-content-types)))))))
1152     ;; Charset should be defined later.
1153     (mime-make-tag pritype subtype)))
1154
1155 \f
1156 ;; Tag handling functions
1157
1158 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1159   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1160   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1161                            (or parameters ""))
1162                    encoding))
1163
1164 (defun mime-create-tag (contype &optional encoding)
1165   "Make a tag with CONTENT-TYPE and optional ENCODING."
1166   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1167           contype encoding))
1168
1169 (defun mime-editor/get-contype (tag)
1170   "Return Content-Type (including parameters) of TAG."
1171   (and (stringp tag)
1172        (or (string-match mime-editor/single-part-tag-regexp tag)
1173            (string-match mime-editor/multipart-beginning-regexp tag)
1174            (string-match mime-editor/multipart-end-regexp tag)
1175            )
1176        (substring tag (match-beginning 1) (match-end 1))
1177        ))
1178
1179 (defun mime-editor/get-encoding (tag)
1180   "Return encoding of TAG."
1181   (and (stringp tag)
1182        (string-match mime-editor/single-part-tag-regexp tag)
1183        (match-beginning 3)
1184        (not (= (match-beginning 3) (match-end 3)))
1185        (substring tag (match-beginning 3) (match-end 3))))
1186
1187 (defun mime-get-parameter (contype parameter)
1188   "For given CONTYPE return value for PARAMETER.
1189 Nil if no such parameter."
1190   (if (string-match
1191        (concat
1192         ";[ \t\n]*"
1193         (regexp-quote parameter)
1194         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1195        contype)
1196       (substring contype (match-beginning 1) (match-end 1))
1197     nil                                 ;No such parameter
1198     ))
1199
1200 (defun mime-set-parameter (contype parameter value)
1201   "For given CONTYPE set PARAMETER to VALUE."
1202   (if (string-match
1203        (concat
1204         ";[ \t\n]*\\("
1205         (regexp-quote parameter)
1206         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1207        contype)
1208       ;; Change value
1209       (concat (substring contype 0 (match-beginning 1))
1210               parameter "=" value
1211               (substring contype (match-end 1)))
1212     (concat contype "; " parameter "=" value)))
1213
1214 (defun mime-strip-parameters (contype)
1215   "Return primary content-type and subtype without parameters for CONTYPE."
1216   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1217       (substring contype (match-beginning 1) (match-end 1)) nil))
1218
1219 (defun mime-test-content-type (contype type &optional subtype)
1220   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1221   (and (stringp contype)
1222        (stringp type)
1223        (string-match
1224         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1225         (downcase contype))))
1226
1227 \f
1228 ;; Basic functions
1229
1230 (defun mime-find-file-type (file)
1231   "Guess Content-Type, subtype, and parameters from FILE."
1232   (let ((guess nil)
1233         (guesses mime-file-types))
1234     (while (and (not guess) guesses)
1235       (if (string-match (car (car guesses)) file)
1236           (setq guess (cdr (car guesses))))
1237       (setq guesses (cdr guesses)))
1238     guess
1239     ))
1240
1241 (defun mime-prompt-for-type ()
1242   "Ask for Content-type."
1243   (let ((type ""))
1244     ;; Repeat until primary content type is specified.
1245     (while (string-equal type "")
1246       (setq type
1247             (completing-read "What content type: "
1248                              mime-content-types
1249                              nil
1250                              'require-match ;Type must be specified.
1251                              nil
1252                              ))
1253       (if (string-equal type "")
1254           (progn
1255             (message "Content type is required.")
1256             (beep)
1257             (sit-for 1)
1258             ))
1259       )
1260     type
1261     ))
1262
1263 (defun mime-prompt-for-subtype (pritype)
1264   "Ask for Content-type subtype of Content-Type PRITYPE."
1265   (let* ((default (car (car (cdr (assoc pritype mime-content-types)))))
1266          (answer
1267           (completing-read
1268            (if default
1269                (concat
1270                 "What content subtype: (default " default ") ")
1271              "What content subtype: ")
1272            (cdr (assoc pritype mime-content-types))
1273            nil
1274            'require-match               ;Subtype must be specified.
1275            nil
1276            )))
1277     (if (string-equal answer "") default answer)))
1278
1279 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1280   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1281 Optional DELIMITER specifies parameter delimiter (';' by default)."
1282   (let* ((delimiter (or delimiter "; "))
1283          (parameters
1284           (mapconcat
1285            (function identity)
1286            (delq nil
1287                  (mime-prompt-for-parameters-1
1288                   (cdr (assoc subtype
1289                               (cdr (assoc pritype mime-content-types))))))
1290            delimiter
1291            )))
1292     (if (and (stringp parameters)
1293              (not (string-equal parameters "")))
1294         (concat delimiter parameters)
1295       ""                                ;"" if no parameters
1296       )))
1297
1298 (defun mime-prompt-for-parameters-1 (optlist)
1299   (apply (function append)
1300          (mapcar (function mime-prompt-for-parameter) optlist)))
1301
1302 (defun mime-prompt-for-parameter (parameter)
1303   "Ask for PARAMETER.
1304 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1305   (let* ((prompt (car parameter))
1306          (choices (mapcar (function
1307                            (lambda (e)
1308                              (if (consp e) e (list e))))
1309                           (cdr parameter)))
1310          (default (car (car choices)))
1311          (answer nil))
1312     (if choices
1313         (progn
1314           (setq answer
1315                 (completing-read
1316                  (concat "What " prompt
1317                          ": (default "
1318                          (if (string-equal default "") "\"\"" default)
1319                          ") ")
1320                  choices nil nil ""))
1321           ;; If nothing is selected, use default.
1322           (if (string-equal answer "")
1323               (setq answer default)))
1324       (setq answer
1325             (read-string (concat "What " prompt ": "))))
1326     (cons (if (and answer
1327                    (not (string-equal answer "")))
1328               (concat prompt "="
1329                       ;; Note: control characters ignored!
1330                       (if (string-match mime-tspecials-regexp answer)
1331                           (concat "\"" answer "\"") answer)))
1332           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1333     ))
1334
1335 (defun mime-encode-string (encoding string)
1336   "Using ENCODING encode a STRING.
1337 If the STRING is too long, the encoded string may be broken into
1338 several lines."
1339   (save-excursion
1340     (set-buffer (get-buffer-create " *MIME encoding*"))
1341     (erase-buffer)
1342     (insert string)
1343     (mime-encode-region encoding (point-min) (point-max))
1344     (prog1
1345         (buffer-substring (point-min) (point-max))
1346       (kill-buffer (current-buffer)))))
1347
1348 (defun mime-decode-string (encoding string)
1349   "Using ENCODING decode a STRING."
1350   (save-excursion
1351     (set-buffer (get-buffer-create " *MIME decoding*"))
1352     (erase-buffer)
1353     (insert string)
1354     (mime-decode-region encoding (point-min) (point-max))
1355     (prog1
1356         (buffer-substring (point-min) (point-max))
1357       (kill-buffer (current-buffer)))))
1358
1359 (defun mime-flag-region (from to flag)
1360   "Hides or shows lines from FROM to TO, according to FLAG.
1361 If FLAG is `\\n' (newline character) then text is shown,
1362 while if FLAG is `\\^M' (control-M) the text is hidden."
1363   (let ((buffer-read-only nil)          ;Okay even if write protected.
1364         (modp (buffer-modified-p)))
1365     (unwind-protect
1366         (subst-char-in-region from to
1367                               (if (= flag ?\n) ?\^M ?\n)
1368                               flag t)
1369       (set-buffer-modified-p modp))))
1370
1371 \f
1372 ;; Translate the tagged MIME messages into a MIME compliant message.
1373
1374 (defun mime-editor/translate-buffer ()
1375   "Encode the tagged MIME message in current buffer in MIME compliant message."
1376   (interactive)
1377   (mime/encode-message-header)
1378   (mime-editor/translate-body)
1379   )
1380
1381 (defun mime-editor/translate-body ()
1382   "Encode the tagged MIME body in current buffer in MIME compliant message."
1383   (interactive)
1384   (save-excursion
1385     (let ((boundary
1386            (concat mime-multipart-boundary " " (current-time-string)))
1387           (i 1)
1388           (time (current-time-string))
1389           ret)
1390       (while (mime-editor/process-multipart-1
1391               (format "%s %s-%d" mime-multipart-boundary time i))
1392         (setq i (1+ i))
1393         )
1394       (save-restriction
1395         ;; We are interested in message body.
1396         (let* ((beg
1397                 (progn
1398                   (goto-char (point-min))
1399                   (re-search-forward
1400                    (concat "\n" (regexp-quote mail-header-separator)
1401                            (if mime-ignore-preceding-spaces
1402                                "[ \t\n]*\n" "\n")) nil 'move)
1403                   (point)))
1404                (end
1405                 (progn
1406                   (goto-char (point-max))
1407                   (and mime-ignore-trailing-spaces
1408                        (re-search-backward "[^ \t\n]\n" beg t)
1409                        (forward-char 1))
1410                   (point))))
1411           (setq ret (mime-editor/translate-region
1412                      beg end
1413                      (format "%s %s-%d" mime-multipart-boundary time i)))
1414           ))
1415       (let ((contype (car ret))         ;Content-Type
1416             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1417             )
1418         ;; Make primary MIME headers.
1419         (or (mail-position-on-field "Mime-Version")
1420             (insert mime-editor/mime-version-value))
1421         ;; Remove old Content-Type and other fields.
1422         (save-restriction
1423           (goto-char (point-min))
1424           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1425           (narrow-to-region (point-min) (point))
1426           (goto-char (point-min))
1427           (mime-delete-field "Content-Type")
1428           (mime-delete-field "Content-Transfer-Encoding"))
1429         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1430         (mail-position-on-field "Content-Type")
1431         (insert contype)
1432         (if encoding
1433             (progn
1434               (mail-position-on-field "Content-Transfer-Encoding")
1435               (insert encoding)))
1436         ))))
1437
1438 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1439   (if (null boundary)
1440       (setq boundary
1441             (concat mime-multipart-boundary " " (current-time-string)))
1442     )
1443   (save-excursion
1444     (save-restriction
1445       (narrow-to-region beg end)
1446       (let ((tag nil)                   ;MIME tag
1447             (contype nil)               ;Content-Type
1448             (encoding nil)              ;Content-Transfer-Encoding
1449             (nparts 0))                 ;Number of body parts
1450         ;; Normalize the body part by inserting appropriate message
1451         ;; tags for every message contents.
1452         (mime-editor/normalize-body)
1453         ;; Counting the number of Content-Type.
1454         (goto-char (point-min))
1455         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1456           (setq nparts (1+ nparts)))
1457         ;; Begin translation.
1458         (cond ((and (<= nparts 1)(not multipart))
1459                ;; It's a singular message.
1460                (goto-char (point-min))
1461                (while (re-search-forward
1462                        mime-editor/single-part-tag-regexp nil t)
1463                  (setq tag
1464                        (buffer-substring (match-beginning 0) (match-end 0)))
1465                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1466                  (setq contype (mime-editor/get-contype tag))
1467                  (setq encoding (mime-editor/get-encoding tag))
1468                  ))
1469               (t
1470                ;; It's a multipart message.
1471                (goto-char (point-min))
1472                (while (re-search-forward
1473                        mime-editor/single-part-tag-regexp nil t)
1474                  (setq tag
1475                        (buffer-substring (match-beginning 0) (match-end 0)))
1476                  (delete-region (match-beginning 0) (match-end 0))
1477                  (setq contype (mime-editor/get-contype tag))
1478                  (setq encoding (mime-editor/get-encoding tag))
1479                  (insert "--" boundary "\n")
1480                  (insert "Content-Type: " contype "\n")
1481                  (if encoding
1482                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1483                  )
1484                ;; Define Content-Type as "multipart/mixed".
1485                (setq contype
1486                      (concat "multipart/mixed; boundary=\"" boundary "\""))
1487                ;; Content-Transfer-Encoding must be "7bit".
1488                ;; The following encoding can be `nil', but is
1489                ;; specified as is since there is no way that a user
1490                ;; specifies it.
1491                (setq encoding "7bit")
1492                ;; Insert the trailer.
1493                (goto-char (point-max))
1494                (if multipart
1495                    (insert "--" boundary "--\n")
1496                  (insert "\n--" boundary "--\n")
1497                  )))
1498         (list contype encoding boundary nparts)
1499         ))))
1500
1501 (defun mime-editor/normalize-body ()
1502   "Normalize the body part by inserting appropriate message tags."
1503   ;; Insert the first MIME tags if necessary.
1504   (goto-char (point-min))
1505   (if (not (looking-at mime-editor/single-part-tag-regexp))
1506       (insert (mime-make-text-tag) "\n"))
1507   ;; Check each tag, and add new tag or correct it if necessary.
1508   (goto-char (point-min))
1509   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1510     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1511            (contype (mime-editor/get-contype tag))
1512            (charset (mime-get-parameter contype "charset"))
1513            (encoding (mime-editor/get-encoding tag)))
1514       ;; Remove extra whitespaces after the tag.
1515       (if (looking-at "[ \t]+$")
1516           (delete-region (match-beginning 0) (match-end 0)))
1517       (cond ((= (following-char) ?\^M)
1518              ;; It must be image, audio or video.
1519              (let ((beg (point))
1520                    (end (mime-editor/content-end)))
1521                ;; Insert explicit MIME tags after hidden messages.
1522                (forward-line 1)
1523                (if (and (not (eobp))
1524                         (not (looking-at mime-editor/single-part-tag-regexp)))
1525                    (progn
1526                      (insert (mime-make-text-tag) "\n")
1527                      (forward-line -1)  ;Process it again as text.
1528                      ))
1529                ;; Show a hidden message.  The point is not altered
1530                ;; after the conversion.
1531                (mime-flag-region beg end ?\n)))
1532             ((mime-test-content-type contype "message")
1533              ;; Content-type "message" should be sent as is.
1534              (forward-line 1))
1535             ((mime-test-content-type contype "text")
1536              ;; Define charset for text if necessary.
1537              (setq charset (or charset (mime-editor/choose-charset)))
1538              (mime-editor/define-charset charset)
1539              (if (string-equal contype "text/x-rot13-47")
1540                  (save-excursion
1541                    (forward-line)
1542                    (set-mark (point))
1543                    (goto-char (mime-editor/content-end))
1544                    (tm:caesar-region)
1545                    ))
1546              ;; Point is now on current tag.
1547              ;; Define encoding and encode text if necessary.
1548              (if (null encoding)        ;Encoding is not specified.
1549                  (let* ((encoding (mime-editor/choose-encoding))
1550                         (beg (mime-editor/content-beginning))
1551                         (end (mime-editor/content-end))
1552                         (body (buffer-substring beg end))
1553                         (encoded (funcall mime-string-encoder
1554                                           (cons charset encoding) body)))
1555                    (if (not (string-equal body encoded))
1556                        (progn
1557                          (goto-char beg)
1558                          (delete-region beg end)
1559                          (insert encoded)
1560                          (goto-char beg)))
1561                    (mime-editor/define-encoding encoding)))
1562              (forward-line 1))
1563             ((null encoding)            ;Encoding is not specified.
1564              ;; Application, image, audio, video, and any other
1565              ;; unknown content-type without encoding should be
1566              ;; encoded.
1567              (let* ((encoding "base64") ;Encode in BASE64 by default.
1568                     (beg (mime-editor/content-beginning))
1569                     (end (mime-editor/content-end))
1570                     (body (buffer-substring beg end))
1571                     (encoded (funcall mime-string-encoder
1572                                       (cons nil encoding) body)))
1573                (if (not (string-equal body encoded))
1574                    (progn
1575                      (goto-char beg)
1576                      (delete-region beg end)
1577                      (insert encoded)
1578                      (goto-char beg)))
1579                (mime-editor/define-encoding encoding))
1580              (forward-line 1))
1581             )
1582       )))
1583
1584 (defun mime-delete-field (field)
1585   "Delete header FIELD."
1586   (let ((regexp (format "^%s:[ \t]*" field)))
1587     (goto-char (point-min))
1588     (while (re-search-forward regexp nil t)
1589       (delete-region (match-beginning 0)
1590                      (progn (forward-line 1) (point)))
1591       )))
1592
1593 \f
1594 ;;;
1595 ;;; Platform dependent functions
1596 ;;;
1597
1598 ;; Emacs 18 implementations
1599
1600 (defun mime-body-charset-chooser-for-emacs18 (begin end)
1601   "Return a cons of charset and encoding of a message in a given region.
1602 Encoding name must be a canonical name, such as `base64'."
1603   '("US-ASCII" . nil)                   ;Default charset of MIME.
1604   )
1605
1606 (defun mime-string-encoder-for-emacs18 (method string)
1607   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1608   (let ((charset (car method))
1609         (encoding (cdr method)))
1610     (cond ((stringp encoding)
1611            (mime-encode-string encoding string))
1612           ;; Return string without any encoding.
1613           (t string)
1614           )))
1615
1616 \f
1617 ;; Emacs 19 implementations
1618
1619 (defun mime-body-charset-chooser-for-emacs19 (begin end)
1620   "Return a cons of charset and encoding of a message in a given region.
1621 Encoding name must be a canonical name, such as `base64'.
1622 US-ASCII and ISO-8859-1 are supported on Emacs 19."
1623   (cond ((save-excursion
1624            (goto-char begin)
1625            (re-search-forward "[\200-\377]" end t))
1626          '("ISO-8859-1" . "quoted-printable"))
1627         (t
1628          '("US-ASCII" . nil))           ;Default charset of MIME.
1629         ))
1630
1631 (defun mime-string-encoder-for-emacs19 (method string)
1632   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1633   (let ((charset (car method))
1634         (encoding (cdr method)))
1635     (cond ((stringp encoding)
1636            (mime-encode-string encoding string))
1637           ;; Return string without any encoding.
1638           (t string)
1639           )))
1640
1641 \f
1642 ;; NEmacs implementations
1643
1644 (defun mime-body-charset-chooser-for-nemacs (begin end)
1645   "Return a cons of charset and encoding of a message in a given region.
1646 Encoding name must be a canonical name, such as `base64'.
1647 US-ASCII and ISO-2022-JP are supported on NEmacs."
1648   (cond ((check-region-kanji-code begin end)
1649          ;; The following are safe encoding methods for use in
1650          ;; USENET News systems that strip off all ESCs.
1651          ;; '("ISO-2022-JP" . "quoted-printable")
1652          ;; '("ISO-2022-JP" . "base64")
1653          ;; The following expects transport systems are all MIME
1654          ;; compliants.  For instance, ESCs are never stripped off.
1655          '("ISO-2022-JP" . nil))
1656         (t
1657          '("US-ASCII" . nil))           ;Default charset of MIME.
1658         ))
1659
1660 (defun mime-string-encoder-for-nemacs (method string)
1661   "For given METHOD that is a cons of charset and encoding, encode a STRING.
1662 US-ASCII and ISO-2022-JP are supported on NEmacs."
1663   (let ((charset (car method))
1664         (encoding (cdr method)))
1665     (cond ((stringp encoding)
1666            (mime-encode-string encoding
1667                                ;; Convert internal (EUC) to JIS code.
1668                                (convert-string-kanji-code string 3 2)
1669                                ))
1670           ;; NEmacs can convert into ISO-2022-JP automatically,
1671           ;; but can do it myself as follows:
1672           ;;(t (convert-string-kanji-code string 3 2))
1673
1674           ;; Return string without any encoding.
1675           (t string)
1676           )))
1677
1678 \f
1679 ;; Mule implementations
1680 ;; Thanks to contributions by wkenji@flab.fujitsu.co.jp (Kenji
1681 ;; WAKAMIYA) and handa@etl.go.jp (Kenichi Handa).
1682
1683 (defun mime-body-charset-chooser-for-mule (begin end)
1684   "Return a cons of charset and encoding of a message in a given
1685 region.  Encoding name must be a canonical name, such as `base64'.
1686 US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1687 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1688 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual text
1689 in Mule."
1690   (let ((lclist (find-charset-region begin end)))
1691     (cond ((null lclist)
1692            '("US-ASCII" . nil))         ;Default charset of MIME.
1693           ;; Multilingual capability requred.
1694           ((and (> (length lclist) 1)
1695                 (boundp '*iso-2022-int-1*))
1696            '("ISO-2022-INT-1" . nil))
1697           ((> (length lclist) 1)
1698            '("ISO-2022-JP-2" . nil))
1699           ;; Simple charset.
1700           ((memq lc-ltn1 lclist)
1701            '("ISO-8859-1" . "quoted-printable"))
1702           ((memq lc-ltn2 lclist)
1703            '("ISO-8859-2" . "quoted-printable"))
1704           ((memq lc-ltn3 lclist)
1705            '("ISO-8859-3" . "quoted-printable"))
1706           ((memq lc-ltn4 lclist)
1707            '("ISO-8859-4" . "quoted-printable"))
1708           ((memq lc-crl lclist)
1709            '("ISO-8859-5" . "quoted-printable"))
1710           ;;((memq lc-arb lclist)
1711           ;; '("ISO-8859-6" . "quoted-printable"))
1712           ((memq lc-grk lclist)
1713            '("ISO-8859-7" . "quoted-printable"))
1714           ((memq lc-hbw lclist)
1715            '("ISO-8859-8" . "quoted-printable"))
1716           ((memq lc-ltn5 lclist)
1717            '("ISO-8859-9" . "quoted-printable"))
1718           ((memq lc-jp lclist)
1719            '("ISO-2022-JP" . nil))
1720           ((memq lc-kr lclist)
1721            '("ISO-2022-KR" . nil))
1722           ;; Unknown charset.
1723           ((boundp '*iso-2022-int-1*)
1724            '("ISO-2022-INT-1" . nil))
1725           (t
1726            '("ISO-2022-JP-2" . nil))
1727           )))
1728
1729 (defun mime-string-encoder-for-mule (method string)
1730   "For given METHOD that is a cons of charset and encoding, encode a
1731 STRING.  US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1732 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1733 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual
1734 text."
1735   (let* ((charset (car method))
1736          (encoding (cdr method))
1737          (coding-system
1738           (cdr (assoc (and (stringp charset) (upcase charset))
1739                       '(("ISO-8859-1" . *ctext*)
1740                         ("ISO-8859-2" . *iso-8859-2*)
1741                         ("ISO-8859-3" . *iso-8859-3*)
1742                         ("ISO-8859-4" . *iso-8859-4*)
1743                         ("ISO-8859-5" . *iso-8859-5*)
1744                         ;;("ISO-8859-6" . *iso-8859-6*)
1745                         ("ISO-8859-7" . *iso-8859-7*)
1746                         ("ISO-8859-8" . *iso-8859-8*)
1747                         ("ISO-8859-9" . *iso-8859-9*)
1748                         ("ISO-2022-JP" . *junet*)
1749                         ("ISO-2022-JP-2" . *iso-2022-ss2-7*)
1750                         ("ISO-2022-KR" . *korean-mail*)
1751                         ("ISO-2022-INT-1" . *iso-2022-int-1*)
1752                         )))))
1753     ;; In bilingual environment it may be unnecessary to convert the
1754     ;; coding system of the string unless transfer encoding is
1755     ;; required since such conversion may be performed by mule
1756     ;; automatically.
1757     (if (not (null coding-system))
1758         (setq string (code-convert-string string *internal* coding-system)))
1759     (if (stringp encoding)
1760         (setq string (mime-encode-string encoding string)))
1761     string
1762     ))
1763
1764 \f
1765 ;; Sun implementations
1766
1767 (defun mime-voice-recorder-for-sun ()
1768   "Record voice in a buffer using Sun audio device, and return the buffer.
1769 If the environment variable AUDIOHOST is defined, its value is used as
1770 a recording host instead of local host."
1771   (let ((buffer (get-buffer-create " *MIME audio*"))
1772         (host (getenv "AUDIOHOST")))
1773     (message "Start the recording on %s.  Type C-g to finish the recording..."
1774              (or host (system-name)))
1775     (save-excursion
1776       (set-buffer buffer)
1777       (erase-buffer)
1778       (condition-case errorcode
1779           (let ((selective-display nil) ;Disable ^M to nl translation.
1780                 (mc-flag nil)           ;Mule
1781                 (kanji-flag nil))       ;NEmacs
1782             ;; If AUDIOHOST is defined, use the value as recording host.
1783             (cond ((not (null host))
1784                    ;; Disable automatic conversion of coding system if Mule.
1785                    (if (featurep 'mule)
1786                        (define-program-coding-system nil "rsh" *noconv*))
1787                    (call-process "rsh"
1788                                  nil
1789                                  buffer
1790                                  nil
1791                                  host
1792                                  "cat"
1793                                  "/dev/audio"
1794                                  ))
1795                   (t
1796                    ;; Disable automatic conversion of coding system if Mule.
1797                    (if (featurep 'mule)
1798                        (define-program-coding-system nil "cat" *noconv*))
1799                    (call-process "cat"
1800                                  "/dev/audio"
1801                                  buffer
1802                                  nil
1803                                  ))))
1804         (quit (message "Type C-g to finish recording... done.")
1805               buffer                    ;Return the buffer
1806               )))))
1807
1808 \f
1809 ;;; @ Other useful commands.
1810 ;;;
1811
1812 ;; Message forwarding commands as content-type "message/rfc822".
1813
1814 (defun mime-editor/insert-message (&optional message)
1815   (interactive)
1816   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1817     (if (and inserter (fboundp inserter))
1818         (progn
1819           (mime-editor/insert-tag "message" "rfc822")
1820           (funcall inserter message)
1821           )
1822       (message "Sorry, I don't have message inserter for your MUA.")
1823       )))
1824
1825 (defun mime-editor/insert-mail (&optional message)
1826   (interactive)
1827   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
1828     (if (and inserter (fboundp inserter))
1829         (progn
1830           (mime-editor/insert-tag "message" "rfc822")
1831           (funcall inserter message)
1832           )
1833       (message "Sorry, I don't have mail inserter for your MUA.")
1834       )))
1835
1836 (defun mime-editor/inserted-message-filter ()
1837   (save-excursion
1838     (save-restriction
1839       (let ((header-start (point))
1840             (case-fold-search t)
1841             beg end)
1842         ;; for Emacs 18
1843         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
1844         (if (re-search-forward "^$" (mark t))
1845             (narrow-to-region header-start (match-beginning 0))
1846           )
1847         (goto-char header-start)
1848         (while (and (re-search-forward
1849                      mime-editor/yank-ignored-field-regexp nil t)
1850                     (setq beg (match-beginning 0))
1851                     (setq end (1+ (rfc822/field-end)))
1852                     )
1853           (delete-region beg end)
1854           )
1855         ))))
1856
1857 ;;; mime.el ends here
1858
1859 (defun mime-editor/find-inmost ()
1860   (goto-char (point-min))
1861   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1862       (let ((bb (match-beginning 0))
1863             (be (match-end 0))
1864             (type (buffer-substring (match-beginning 1)(match-end 1)))
1865             end-exp eb ee)
1866         (setq end-exp (format "^--}-<<%s>>\n" type))
1867         (widen)
1868         (if (re-search-forward end-exp nil t)
1869             (progn
1870               (setq eb (match-beginning 0))
1871               (setq ee (match-end 0))
1872               )
1873           (setq eb (point-max))
1874           (setq ee (point-max))
1875           )
1876         (narrow-to-region be eb)
1877         (goto-char be)
1878         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1879             (let (ret)
1880               (narrow-to-region (match-beginning 0)(point-max))
1881               (mime-editor/find-inmost)
1882               )
1883           (widen)
1884           ;;(delete-region eb ee)
1885           (list type bb be eb)
1886           ))))
1887
1888 (defun mime-editor/process-multipart-1 (boundary)
1889   (let ((ret (mime-editor/find-inmost)))
1890     (if ret
1891         (let ((type (car ret))
1892               (bb (nth 1 ret))(be (nth 2 ret))
1893               (eb (nth 3 ret))
1894               )
1895           (narrow-to-region bb eb)
1896           (delete-region bb be)
1897           (setq bb (point-min))
1898           (setq eb (point-max))
1899           (widen)
1900           (goto-char eb)
1901           (if (looking-at mime-editor/multipart-end-regexp)
1902               (let ((beg (match-beginning 0))
1903                     (end (match-end 0))
1904                     )
1905                 (delete-region beg end)
1906                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1907                          (not (eobp)))
1908                     (insert (concat (mime-make-text-tag) "\n"))
1909                   )))
1910           (setq boundary
1911                 (nth 2 (mime-editor/translate-region bb eb
1912                                                      boundary t)))
1913           (goto-char bb)
1914           (insert
1915            (format "--[[multipart/%s; boundary=\"%s\"][7bit]]\n"
1916                    type boundary))
1917           boundary))))
1918
1919
1920 ;;; @ multipart enclosure
1921 ;;;
1922
1923 (defun mime-editor/enclose-region (type beg end)
1924   (save-excursion
1925     (goto-char beg)
1926     (let ((current (point))
1927           exist-prev-tag)
1928       (save-excursion
1929         (if (mime-editor/goto-tag)
1930             (or (eq current (match-beginning 0))
1931                 (setq exist-prev-tag t)
1932                 )))
1933       (save-restriction
1934         (narrow-to-region beg end)
1935         (goto-char beg)
1936         (if exist-prev-tag
1937             (insert "\n")
1938           )
1939         (insert (format "--<<%s>>-{\n" type))
1940         (goto-char (point-max))
1941         (insert (format "\n--}-<<%s>>\n" type))
1942         (goto-char (point-max))
1943         )
1944       (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1945                (not (eobp)))
1946           (insert (mime-make-text-tag) "\n")
1947         )
1948       )))
1949
1950 (defun mime-editor/enclose-mixed-region (beg end)
1951   (interactive "*r")
1952   (mime-editor/enclose-region "mixed" beg end)
1953   )
1954
1955 (defun mime-editor/enclose-parallel-region (beg end)
1956   (interactive "*r")
1957   (mime-editor/enclose-region "parallel" beg end)
1958   )
1959
1960 (defun mime-editor/enclose-digest-region (beg end)
1961   (interactive "*r")
1962   (mime-editor/enclose-region "digest" beg end)
1963   )
1964
1965 (defun mime-editor/enclose-alternative-region (beg end)
1966   (interactive "*r")
1967   (mime-editor/enclose-region "alternative" beg end)
1968   )
1969
1970
1971 ;;; @ split
1972 ;;;
1973
1974 (defun mime-editor/insert-partial-header
1975   (fields subject id number total separator)
1976   (insert fields)
1977   (insert (format "Subject: %s (%d/%d)\n" subject number total))
1978   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
1979                   mime-editor/version))
1980   (insert (format "\
1981 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
1982                   id number total separator))
1983   )
1984
1985 (defun mime-editor/split-and-send (&optional cmd)
1986   (interactive)
1987   (let ((mime-editor/message-max-length
1988          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
1989              mime-editor/message-default-max-length))
1990         (lines (count-lines (point-min) (point-max)))
1991         )
1992     (if (and (> lines mime-editor/message-max-length)
1993              mime-editor/split-message)
1994         (let* ((mime-editor/draft-file-name 
1995                 (or (buffer-file-name)
1996                     (make-temp-name
1997                      (expand-file-name "tm-draft" mime/tmp-dir))))
1998                (separator mail-header-separator)
1999                (config
2000                 (eval (cdr (assq major-mode mime-editor/window-config-alist))))
2001                (id (concat "\""
2002                            (replace-space-with-underline (current-time-string))
2003                            "@" (system-name) "\"")))
2004           (run-hooks 'mime-editor/before-split-hook)
2005           (let* ((header (rfc822/get-header-string-except
2006                           mime-editor/split-ignored-field-regexp separator))
2007                  (subject (mail-fetch-field "subject"))
2008                  (total (+ (/ lines mime-editor/message-max-length)
2009                            (if (> (mod lines mime-editor/message-max-length) 0)
2010                                1)))
2011                  (the-buf (current-buffer))
2012                  (buf (get-buffer "*tmp-send*"))
2013                  (command
2014                   (or cmd
2015                       (cdr
2016                        (assq major-mode
2017                              mime-editor/split-message-sender-alist))
2018                       (cdr
2019                        (assq major-mode
2020                              mime-editor/message-default-sender-alist))
2021                       ))
2022                  data)
2023             (goto-char (point-min))
2024             (if (re-search-forward (concat "^" (regexp-quote separator) "$")
2025                                    nil t)
2026                 (replace-match "")
2027               )
2028             (if buf
2029                 (progn
2030                   (switch-to-buffer buf)
2031                   (erase-buffer)
2032                   (switch-to-buffer the-buf)
2033                   )
2034               (setq buf (get-buffer-create "*tmp-send*"))
2035               )
2036             (switch-to-buffer buf)
2037             (make-local-variable 'mail-header-separator)
2038             (setq mail-header-separator separator)
2039             (switch-to-buffer the-buf)
2040             (goto-char (point-min))
2041             (re-search-forward "^$" nil t)
2042             (let ((mime-editor/partial-number 1))
2043               (setq data (buffer-substring
2044                           (point-min)
2045                           (progn
2046                             (goto-line mime-editor/message-max-length)
2047                             (point))
2048                           ))
2049               (delete-region (point-min)(point))
2050               (switch-to-buffer buf)
2051               (mime-editor/insert-partial-header
2052                header subject id mime-editor/partial-number total separator)
2053               (insert data)
2054               (save-excursion
2055                 (save-restriction
2056                   (goto-char (point-min))
2057                   (search-forward (concat "\n" mail-header-separator "\n"))
2058                   (narrow-to-region
2059                    (match-end 0)
2060                    (if (re-search-forward "^$" nil t)
2061                        (match-beginning 0)
2062                      (point-max)
2063                      ))
2064                   (goto-char (point-min))
2065                   (while (re-search-forward
2066                           mime-editor/split-blind-field-regexp nil t)
2067                     (delete-region (match-beginning 0)
2068                                    (let ((e (rfc822/field-end)))
2069                                      (if (< e (point-max))
2070                                          (1+ e)
2071                                        e)))
2072                     )
2073                   ))
2074               (save-excursion
2075                 (message (format "Sending %d/%d..."
2076                                  mime-editor/partial-number total))
2077                 (call-interactively command)
2078                 (message (format "Sending %d/%d... done"
2079                                  mime-editor/partial-number total))
2080                 )
2081               (erase-buffer)
2082               (switch-to-buffer the-buf)
2083               (setq mime-editor/partial-number 2)
2084               (while (< mime-editor/partial-number total)
2085                 (setq data (buffer-substring
2086                             (point-min)
2087                             (progn
2088                               (goto-line mime-editor/message-max-length)
2089                               (point))
2090                             ))
2091                 (delete-region (point-min)(point))
2092                 (switch-to-buffer buf)
2093                 (mime-editor/insert-partial-header
2094                  header subject id mime-editor/partial-number total separator)
2095                 (insert data)
2096                 (save-excursion
2097                   (message (format "Sending %d/%d..."
2098                                    mime-editor/partial-number total))
2099                   (call-interactively command)
2100                   (message (format "Sending %d/%d... done"
2101                                    mime-editor/partial-number total))
2102                   )
2103                 (erase-buffer)
2104                 (switch-to-buffer the-buf)
2105                 (setq mime-editor/partial-number
2106                       (1+ mime-editor/partial-number))
2107                 )
2108               (goto-char (point-min))
2109               (mime-editor/insert-partial-header
2110                header subject id mime-editor/partial-number total separator)
2111               (message (format "Sending %d/%d..."
2112                                mime-editor/partial-number total))
2113               ))))))
2114
2115
2116 ;;; @ preview message
2117 ;;;
2118
2119 (defun mime-editor/preview-message ()
2120   "preview editing MIME message. [tm-edit.el]"
2121   (interactive)
2122   (let* ((str (buffer-string))
2123          (separator mail-header-separator)
2124          (the-buf (current-buffer))
2125          (buf-name (buffer-name))
2126          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2127          (buf (get-buffer temp-buf-name))
2128          )
2129     (if buf
2130         (progn
2131           (switch-to-buffer buf)
2132           (erase-buffer)
2133           )
2134       (setq buf (get-buffer-create temp-buf-name))
2135       (switch-to-buffer buf)
2136       )
2137     (insert str)
2138     (setq major-mode 'mime/temporary-message-mode)
2139     (make-local-variable 'mail-header-separator)
2140     (setq mail-header-separator separator)
2141     (make-local-variable 'mime/editing-buffer)
2142     (setq mime/editing-buffer the-buf)
2143     
2144     (run-hooks 'mime-editor/translate-hook)
2145     (mime-editor/translate-buffer)
2146     (goto-char (point-min))
2147     (if (re-search-forward
2148          (concat "^" (regexp-quote separator) "$"))
2149         (replace-match "")
2150       )
2151     (mime/viewer-mode)
2152     ))
2153
2154 (defun mime-editor/quitting-method ()
2155   (let ((temp mime::preview/article-buffer)
2156         buf)
2157     (mime-viewer/kill-buffer)
2158     (set-buffer temp)
2159     (setq buf mime/editing-buffer)
2160     (kill-buffer temp)
2161     (switch-to-buffer buf)
2162     ))
2163
2164 (set-alist 'mime-viewer/quitting-method-alist
2165            'mime/temporary-message-mode
2166            (function mime-editor/quitting-method)
2167            )
2168
2169
2170 ;;; @ draft preview
2171 ;;; 
2172 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2173 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2174
2175 (defvar mime-editor/draft-header-separator-alist
2176   '((news-reply-mode . mail-header-separator)
2177     (mh-letter-mode . mail-header-separator)
2178     ))
2179
2180 (defvar mime::article/draft-header-separator nil)
2181
2182 (defun mime-editor/draft-preview ()
2183   (interactive)
2184   (let ((sep (assoc-value major-mode mime-editor/draft-header-separator-alist)))
2185     (or (stringp sep) (setq sep (eval sep)))
2186     (make-variable-buffer-local 'mime::article/draft-header-separator)
2187     (goto-char (point-min))
2188     (re-search-forward
2189      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2190     (setq mime::article/draft-header-separator
2191           (buffer-substring (match-beginning 0) (match-end 0)))
2192     (replace-match "")
2193     (mime/viewer-mode (current-buffer))
2194     (pop-to-buffer (current-buffer))
2195     ))
2196
2197 (defun mime-viewer::quitting-method/draft-preview ()
2198   (let ((mother mime::preview/mother-buffer))
2199     (save-excursion
2200       (switch-to-buffer mother)
2201       (goto-char (point-min))
2202       (if (and
2203            (re-search-forward
2204             (concat "^\\("
2205                     (regexp-quote mime::article/draft-header-separator)
2206                     "\\)?$") nil t)
2207            (bolp))
2208           (progn
2209             (insert mime::article/draft-header-separator)
2210             (set-buffer-modified-p (buffer-modified-p))
2211             )))
2212     (mime-viewer/kill-buffer)
2213     (pop-to-buffer mother)
2214     ))
2215
2216 (set-alist 'mime-viewer/quitting-method-alist
2217            'mh-letter-mode
2218            (function mime-viewer::quitting-method/draft-preview)
2219            )
2220
2221 (set-alist 'mime-viewer/quitting-method-alist
2222            'news-reply-mode
2223            (function mime-viewer::quitting-method/draft-preview)
2224            )
2225
2226
2227 ;;; @ etc
2228 ;;;
2229
2230 (defun replace-space-with-underline (str)
2231   (mapconcat (function
2232               (lambda (arg)
2233                 (char-to-string
2234                  (if (= arg 32)
2235                      ?_
2236                    arg)))) str "")
2237   )
2238
2239
2240 ;;; @ end
2241 ;;;
2242
2243 (provide 'tm-edit)
2244
2245 (run-hooks 'tm-edit-load-hook)