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