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