tm 7.25.
[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/15 14:17:09 $|$Revision: 7.25 $|~/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.25 1995/11/15 14:17:09 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 ()
839   "Insert a signature file specified by mime-signature-file."
840   (interactive)
841   (save-restriction
842     (apply (function mime-editor/insert-tag)
843            (prog1
844                (mime-find-file-type (insert-signature))
845              (narrow-to-region (point-min)(point))
846              ))
847     ))
848 \f
849 ;; Insert a new tag around a point.
850
851 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
852   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
853 If nothing is inserted, return nil."
854   (interactive)
855   (let ((oldtag nil)
856         (newtag nil)
857         (current (point)))
858     (setq pritype
859           (or pritype
860               (mime-prompt-for-type)))
861     (setq subtype
862           (or subtype
863               (mime-prompt-for-subtype pritype)))
864     (setq parameters
865           (or parameters
866               (mime-prompt-for-parameters pritype subtype delimiter)))
867     ;; Make a new MIME tag.
868     (setq newtag (mime-make-tag pritype subtype parameters))
869     ;; Find an current MIME tag.
870     (setq oldtag
871           (save-excursion
872             (if (mime-editor/goto-tag)
873                 (buffer-substring (match-beginning 0) (match-end 0))
874               ;; Assume content type is 'text/plan'.
875               (mime-make-tag "text" "plain")
876               )))
877     ;; We are only interested in TEXT.
878     (if (and oldtag
879              (not (mime-test-content-type
880                    (mime-editor/get-contype oldtag) "text")))
881         (setq oldtag nil))
882     (beginning-of-line)
883     (cond ((and oldtag                  ;Text
884                 (not (eobp))
885                 (save-excursion
886                   (forward-line -1)
887                   (looking-at mime-editor/beginning-tag-regexp)
888                   )
889                 (or mime-ignore-same-text-tag
890                     (not (string-equal oldtag newtag))))
891            ;; If point is at the next of current tag, move to the
892            ;; beginning of the tag to disable insertion of extra tag.
893            (forward-line -1))
894           ((and oldtag                  ;Text
895                 (not (eobp))
896                 (not (looking-at mime-editor/tag-regexp))
897                 (or mime-ignore-same-text-tag
898                     (not (string-equal oldtag newtag))))
899            ;; Copy current tag to break a text into two.
900            (save-excursion
901              (insert oldtag "\n")))
902           ((and (null oldtag)           ;Not text
903                 (not (looking-at mime-editor/tag-regexp)))
904            ;; Adjust insertion point.  In the middle of text, it is
905            ;; okay to break the text into two.  However, it should not
906            ;; be broken into two, if otherwise.
907            (goto-char (mime-editor/content-end))
908            (if (eolp)
909                (forward-line 1))
910            (if (not (bolp))
911                (insert "\n"))
912            ))
913     ;; Make a new tag.
914     (if (or (not oldtag)                ;Not text
915             (or mime-ignore-same-text-tag
916                 (not (string-equal oldtag newtag))))
917         (progn
918           ;; Mark the beginning of the tag for convenience.
919           (push-mark (point) 'nomsg)
920           (insert newtag "\n")
921           (list pritype subtype parameters) ;New tag is created.
922           )
923       ;; Restore previous point.
924       (goto-char current)
925       nil                               ;Nothing is created.
926       )
927     ))
928
929 ;; Insert the binary content after MIME tag.
930 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
931 ;;      for x-uue
932 (defun mime-editor/insert-binary-file (file &optional encoding)
933   "Insert binary FILE at point.
934 Optional argument ENCODING specifies an encoding method such as base64."
935   (let ((tmpbuf (get-buffer-create " *MIME insert*")))
936     (save-excursion
937       (set-buffer tmpbuf)
938       (erase-buffer)
939       (let ((mc-flag nil)               ;Mule
940             (file-coding-system-for-read
941              (if (featurep 'mule) *noconv*))
942             (kanji-flag nil)            ;NEmacs
943             (emx-binary-mode t)         ;Stop CRLF to LF conversion in OS/2
944             )
945         (let (jka-compr-compression-info-list
946               jam-zcat-filename-list)
947           (insert-file-contents file))))
948     (prog1
949         (if (and (stringp encoding)
950                  (string-equal (downcase encoding) "x-uue"))
951             (progn
952               (require 'mel-u)
953               (let ((uuencode-external-encoder
954                      (cons (car uuencode-external-encoder)
955                            (list (file-name-nondirectory file))
956                            )))
957                 (mime-editor/insert-binary-buffer tmpbuf encoding)
958                 ))
959           (mime-editor/insert-binary-buffer tmpbuf encoding))
960       (kill-buffer tmpbuf))))
961
962 ;; Insert the binary content after MIME tag.
963 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
964 ;;      for x-uue
965 (defun mime-editor/insert-binary-buffer (buffer &optional encoding)
966   "Insert binary BUFFER at point.
967 Optional argument ENCODING specifies an encoding method such as base64."
968   (let* ((tagend (1- (point)))          ;End of the tag
969          (hide-p (and mime-auto-hide-body
970                       (stringp encoding)
971                       (let ((en (downcase encoding)))
972                         (or (string-equal en "base64")
973                             (string-equal en "x-uue")
974                             ))))
975          )
976     (save-restriction
977       (narrow-to-region (1- (point)) (point))
978       (let ((start (point))
979             (emx-binary-mode t))        ;Stop LF to CRLF conversion in OS/2
980         (insert-buffer-substring buffer)
981         ;; Encode binary message if necessary.
982         (if encoding
983             (mime-encode-region encoding start (point-max))))
984       (if hide-p
985           (progn
986             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
987             (goto-char (point-max)))
988         ))
989     ;; Define encoding even if it is 7bit.
990     (if (stringp encoding)
991         (save-excursion
992           (goto-char tagend)            ;Make sure which line the tag is on.
993           (mime-editor/define-encoding encoding)))
994     ))
995
996 \f
997 ;; Commands work on a current message flagment.
998
999 (defun mime-editor/goto-tag ()
1000   "Search for the beginning of the tagged MIME message."
1001   (let ((current (point)) multipart)
1002     (if (looking-at mime-editor/tag-regexp)
1003         t
1004       ;; At first, go to the end.
1005       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1006              (goto-char (match-beginning 0)) ;For multiline tag
1007              (forward-line -1)
1008              (end-of-line)
1009              )
1010             (t
1011              (goto-char (point-max))
1012              ))
1013       ;; Then search for the beginning. 
1014       (re-search-backward mime-editor/end-tag-regexp nil t)
1015       (beginning-of-line)
1016       (or (looking-at mime-editor/beginning-tag-regexp)
1017           ;; Restore previous point.
1018           (progn
1019             (goto-char current)
1020             nil
1021             ))
1022       )))
1023
1024 (defun mime-editor/content-beginning ()
1025   "Return the point of the beginning of content."
1026   (save-excursion
1027     (let ((beg (save-excursion
1028                  (beginning-of-line) (point))))
1029       (if (mime-editor/goto-tag)
1030           (let ((top (point)))
1031             (goto-char (match-end 0))
1032             (if (and (= beg top)
1033                      (= (following-char) ?\^M))
1034                 (point)
1035               (forward-line 1)
1036               (point)))
1037         ;; Default text/plain tag.
1038         (goto-char (point-min))
1039         (re-search-forward
1040          (concat "\n" (regexp-quote mail-header-separator)
1041                  (if mime-ignore-preceding-spaces
1042                      "[ \t\n]*\n" "\n")) nil 'move)
1043         (point))
1044       )))
1045
1046 (defun mime-editor/content-end ()
1047   "Return the point of the end of content."
1048   (save-excursion
1049     (let ((beg (save-excursion
1050                  (beginning-of-line) (point))))
1051       (if (mime-editor/goto-tag)
1052           (let ((top (point)))
1053             (goto-char (match-end 0))
1054             (if (and (= beg top)        ;Must be on the same line.
1055                      (= (following-char) ?\^M))
1056                 (progn
1057                   (end-of-line)
1058                   (point))
1059               ;; Move to the end of this text.
1060               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1061                   ;; Don't forget a multiline tag.
1062                   (goto-char (match-beginning 0)))
1063               (point)
1064               ))
1065         ;; Assume the message begins with text/plain.
1066         (goto-char (mime-editor/content-beginning))
1067         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1068             ;; Don't forget a multiline tag.
1069             (goto-char (match-beginning 0)))
1070         (point))
1071       )))
1072
1073 (defun mime-editor/define-charset (charset)
1074   "Set charset of current tag to CHARSET."
1075   (save-excursion
1076     (if (mime-editor/goto-tag)
1077         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1078           (delete-region (match-beginning 0) (match-end 0))
1079           (insert
1080            (mime-create-tag (mime-set-parameter
1081                              (mime-editor/get-contype tag) "charset" charset)
1082                             (mime-editor/get-encoding tag))))
1083       )))
1084
1085 (defun mime-editor/define-encoding (encoding)
1086   "Set encoding of current tag to ENCODING."
1087   (save-excursion
1088     (if (mime-editor/goto-tag)
1089         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1090           (delete-region (match-beginning 0) (match-end 0))
1091           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1092       )))
1093
1094 (defun mime-editor/choose-charset ()
1095   "Choose charset of a text following current point."
1096   (save-excursion
1097     (let* ((beg (point))
1098            (end (mime-editor/content-end)))
1099       (car (funcall mime-body-charset-chooser beg end)))))
1100
1101 (defun mime-editor/choose-encoding ()
1102   "Choose encoding of a text following current point."
1103   (save-excursion
1104     (let* ((beg (point))
1105            (end (mime-editor/content-end)))
1106       (cdr (funcall mime-body-charset-chooser beg end)))))
1107
1108 (defun mime-make-text-tag (&optional subtype)
1109   "Make a tag for a text after current point.
1110 Subtype of text type can be specified by an optional argument SUBTYPE.
1111 Otherwise, it is obtained from mime-content-types."
1112   (let* ((pritype "text")
1113          (subtype (or subtype
1114                       (car (car (cdr (assoc pritype mime-content-types)))))))
1115     ;; Charset should be defined later.
1116     (mime-make-tag pritype subtype)))
1117
1118 \f
1119 ;; Tag handling functions
1120
1121 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1122   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1123   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1124                            (or parameters ""))
1125                    encoding))
1126
1127 (defun mime-create-tag (contype &optional encoding)
1128   "Make a tag with CONTENT-TYPE and optional ENCODING."
1129   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1130           contype encoding))
1131
1132 (defun mime-editor/get-contype (tag)
1133   "Return Content-Type (including parameters) of TAG."
1134   (and (stringp tag)
1135        (or (string-match mime-editor/single-part-tag-regexp tag)
1136            (string-match mime-editor/multipart-beginning-regexp tag)
1137            (string-match mime-editor/multipart-end-regexp tag)
1138            )
1139        (substring tag (match-beginning 1) (match-end 1))
1140        ))
1141
1142 (defun mime-editor/get-encoding (tag)
1143   "Return encoding of TAG."
1144   (and (stringp tag)
1145        (string-match mime-editor/single-part-tag-regexp tag)
1146        (match-beginning 3)
1147        (not (= (match-beginning 3) (match-end 3)))
1148        (substring tag (match-beginning 3) (match-end 3))))
1149
1150 (defun mime-get-parameter (contype parameter)
1151   "For given CONTYPE return value for PARAMETER.
1152 Nil if no such parameter."
1153   (if (string-match
1154        (concat
1155         ";[ \t\n]*"
1156         (regexp-quote parameter)
1157         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1158        contype)
1159       (substring contype (match-beginning 1) (match-end 1))
1160     nil                                 ;No such parameter
1161     ))
1162
1163 (defun mime-set-parameter (contype parameter value)
1164   "For given CONTYPE set PARAMETER to VALUE."
1165   (if (string-match
1166        (concat
1167         ";[ \t\n]*\\("
1168         (regexp-quote parameter)
1169         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1170        contype)
1171       ;; Change value
1172       (concat (substring contype 0 (match-beginning 1))
1173               parameter "=" value
1174               (substring contype (match-end 1)))
1175     (concat contype "; " parameter "=" value)))
1176
1177 (defun mime-strip-parameters (contype)
1178   "Return primary content-type and subtype without parameters for CONTYPE."
1179   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1180       (substring contype (match-beginning 1) (match-end 1)) nil))
1181
1182 (defun mime-test-content-type (contype type &optional subtype)
1183   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1184   (and (stringp contype)
1185        (stringp type)
1186        (string-match
1187         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1188         (downcase contype))))
1189
1190 \f
1191 ;; Basic functions
1192
1193 (defun mime-find-file-type (file)
1194   "Guess Content-Type, subtype, and parameters from FILE."
1195   (let ((guess nil)
1196         (guesses mime-file-types))
1197     (while (and (not guess) guesses)
1198       (if (string-match (car (car guesses)) file)
1199           (setq guess (cdr (car guesses))))
1200       (setq guesses (cdr guesses)))
1201     guess
1202     ))
1203
1204 (defun mime-prompt-for-type ()
1205   "Ask for Content-type."
1206   (let ((type ""))
1207     ;; Repeat until primary content type is specified.
1208     (while (string-equal type "")
1209       (setq type
1210             (completing-read "What content type: "
1211                              mime-content-types
1212                              nil
1213                              'require-match ;Type must be specified.
1214                              nil
1215                              ))
1216       (if (string-equal type "")
1217           (progn
1218             (message "Content type is required.")
1219             (beep)
1220             (sit-for 1)
1221             ))
1222       )
1223     type
1224     ))
1225
1226 (defun mime-prompt-for-subtype (pritype)
1227   "Ask for Content-type subtype of Content-Type PRITYPE."
1228   (let* ((default (car (car (cdr (assoc pritype mime-content-types)))))
1229          (answer
1230           (completing-read
1231            (if default
1232                (concat
1233                 "What content subtype: (default " default ") ")
1234              "What content subtype: ")
1235            (cdr (assoc pritype mime-content-types))
1236            nil
1237            'require-match               ;Subtype must be specified.
1238            nil
1239            )))
1240     (if (string-equal answer "") default answer)))
1241
1242 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1243   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1244 Optional DELIMITER specifies parameter delimiter (';' by default)."
1245   (let* ((delimiter (or delimiter "; "))
1246          (parameters
1247           (mapconcat
1248            (function identity)
1249            (delq nil
1250                  (mime-prompt-for-parameters-1
1251                   (cdr (assoc subtype
1252                               (cdr (assoc pritype mime-content-types))))))
1253            delimiter
1254            )))
1255     (if (and (stringp parameters)
1256              (not (string-equal parameters "")))
1257         (concat delimiter parameters)
1258       ""                                ;"" if no parameters
1259       )))
1260
1261 (defun mime-prompt-for-parameters-1 (optlist)
1262   (apply (function append)
1263          (mapcar (function mime-prompt-for-parameter) optlist)))
1264
1265 (defun mime-prompt-for-parameter (parameter)
1266   "Ask for PARAMETER.
1267 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1268   (let* ((prompt (car parameter))
1269          (choices (mapcar (function
1270                            (lambda (e)
1271                              (if (consp e) e (list e))))
1272                           (cdr parameter)))
1273          (default (car (car choices)))
1274          (answer nil))
1275     (if choices
1276         (progn
1277           (setq answer
1278                 (completing-read
1279                  (concat "What " prompt
1280                          ": (default "
1281                          (if (string-equal default "") "\"\"" default)
1282                          ") ")
1283                  choices nil nil ""))
1284           ;; If nothing is selected, use default.
1285           (if (string-equal answer "")
1286               (setq answer default)))
1287       (setq answer
1288             (read-string (concat "What " prompt ": "))))
1289     (cons (if (and answer
1290                    (not (string-equal answer "")))
1291               (concat prompt "="
1292                       ;; Note: control characters ignored!
1293                       (if (string-match mime-tspecials-regexp answer)
1294                           (concat "\"" answer "\"") answer)))
1295           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1296     ))
1297
1298 (defun mime-encode-string (encoding string)
1299   "Using ENCODING encode a STRING.
1300 If the STRING is too long, the encoded string may be broken into
1301 several lines."
1302   (save-excursion
1303     (set-buffer (get-buffer-create " *MIME encoding*"))
1304     (erase-buffer)
1305     (insert string)
1306     (mime-encode-region encoding (point-min) (point-max))
1307     (prog1
1308         (buffer-substring (point-min) (point-max))
1309       (kill-buffer (current-buffer)))))
1310
1311 (defun mime-decode-string (encoding string)
1312   "Using ENCODING decode a STRING."
1313   (save-excursion
1314     (set-buffer (get-buffer-create " *MIME decoding*"))
1315     (erase-buffer)
1316     (insert string)
1317     (mime-decode-region encoding (point-min) (point-max))
1318     (prog1
1319         (buffer-substring (point-min) (point-max))
1320       (kill-buffer (current-buffer)))))
1321
1322 (defun mime-flag-region (from to flag)
1323   "Hides or shows lines from FROM to TO, according to FLAG.
1324 If FLAG is `\\n' (newline character) then text is shown,
1325 while if FLAG is `\\^M' (control-M) the text is hidden."
1326   (let ((buffer-read-only nil)          ;Okay even if write protected.
1327         (modp (buffer-modified-p)))
1328     (unwind-protect
1329         (subst-char-in-region from to
1330                               (if (= flag ?\n) ?\^M ?\n)
1331                               flag t)
1332       (set-buffer-modified-p modp))))
1333
1334 \f
1335 ;; Translate the tagged MIME messages into a MIME compliant message.
1336
1337 (defun mime-editor/translate-buffer ()
1338   "Encode the tagged MIME message in current buffer in MIME compliant message."
1339   (interactive)
1340   (mime/encode-message-header)
1341   (mime-editor/translate-body)
1342   )
1343
1344 (defun mime-editor/translate-body ()
1345   "Encode the tagged MIME body in current buffer in MIME compliant message."
1346   (interactive)
1347   (save-excursion
1348     (let ((boundary
1349            (concat mime-multipart-boundary " " (current-time-string)))
1350           (i 1)
1351           (time (current-time-string))
1352           ret)
1353       (while (mime-editor/process-multipart-1
1354               (format "%s %s-%d" mime-multipart-boundary time i))
1355         (setq i (1+ i))
1356         )
1357       (save-restriction
1358         ;; We are interested in message body.
1359         (let* ((beg
1360                 (progn
1361                   (goto-char (point-min))
1362                   (re-search-forward
1363                    (concat "\n" (regexp-quote mail-header-separator)
1364                            (if mime-ignore-preceding-spaces
1365                                "[ \t\n]*\n" "\n")) nil 'move)
1366                   (point)))
1367                (end
1368                 (progn
1369                   (goto-char (point-max))
1370                   (and mime-ignore-trailing-spaces
1371                        (re-search-backward "[^ \t\n]\n" beg t)
1372                        (forward-char 1))
1373                   (point))))
1374           (setq ret (mime-editor/translate-region
1375                      beg end
1376                      (format "%s %s-%d" mime-multipart-boundary time i)))
1377           ))
1378       (let ((contype (car ret))         ;Content-Type
1379             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1380             )
1381         ;; Make primary MIME headers.
1382         (or (mail-position-on-field "Mime-Version")
1383             (insert mime-editor/mime-version-value))
1384         ;; Remove old Content-Type and other fields.
1385         (save-restriction
1386           (goto-char (point-min))
1387           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1388           (narrow-to-region (point-min) (point))
1389           (goto-char (point-min))
1390           (mime-delete-field "Content-Type")
1391           (mime-delete-field "Content-Transfer-Encoding"))
1392         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1393         (mail-position-on-field "Content-Type")
1394         (insert contype)
1395         (if encoding
1396             (progn
1397               (mail-position-on-field "Content-Transfer-Encoding")
1398               (insert encoding)))
1399         ))))
1400
1401 (defun mime-editor/normalize-body ()
1402   "Normalize the body part by inserting appropriate message tags."
1403   ;; Insert the first MIME tags if necessary.
1404   (goto-char (point-min))
1405   (if (not (looking-at mime-editor/single-part-tag-regexp))
1406       (insert (mime-make-text-tag) "\n"))
1407   ;; Check each tag, and add new tag or correct it if necessary.
1408   (goto-char (point-min))
1409   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1410     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1411            (contype (mime-editor/get-contype tag))
1412            (charset (mime-get-parameter contype "charset"))
1413            (encoding (mime-editor/get-encoding tag)))
1414       ;; Remove extra whitespaces after the tag.
1415       (if (looking-at "[ \t]+$")
1416           (delete-region (match-beginning 0) (match-end 0)))
1417       (cond ((= (following-char) ?\^M)
1418              ;; It must be image, audio or video.
1419              (let ((beg (point))
1420                    (end (mime-editor/content-end)))
1421                ;; Insert explicit MIME tags after hidden messages.
1422                (forward-line 1)
1423                (if (and (not (eobp))
1424                         (not (looking-at mime-editor/single-part-tag-regexp)))
1425                    (progn
1426                      (insert (mime-make-text-tag) "\n")
1427                      (forward-line -1)  ;Process it again as text.
1428                      ))
1429                ;; Show a hidden message.  The point is not altered
1430                ;; after the conversion.
1431                (mime-flag-region beg end ?\n)))
1432             ((mime-test-content-type contype "message")
1433              ;; Content-type "message" should be sent as is.
1434              (forward-line 1))
1435             ((mime-test-content-type contype "text")
1436              ;; Define charset for text if necessary.
1437              (setq charset (or charset (mime-editor/choose-charset)))
1438              (mime-editor/define-charset charset)
1439              (if (string-equal contype "text/x-rot13-47")
1440                  (save-excursion
1441                    (forward-line)
1442                    (set-mark (point))
1443                    (goto-char (mime-editor/content-end))
1444                    (tm:caesar-region)
1445                    ))
1446              ;; Point is now on current tag.
1447              ;; Define encoding and encode text if necessary.
1448              (if (null encoding)        ;Encoding is not specified.
1449                  (let* ((encoding (mime-editor/choose-encoding))
1450                         (beg (mime-editor/content-beginning))
1451                         (end (mime-editor/content-end))
1452                         (body (buffer-substring beg end))
1453                         (encoded (funcall mime-string-encoder
1454                                           (cons charset encoding) body)))
1455                    (if (not (string-equal body encoded))
1456                        (progn
1457                          (goto-char beg)
1458                          (delete-region beg end)
1459                          (insert encoded)
1460                          (goto-char beg)))
1461                    (mime-editor/define-encoding encoding)))
1462              (forward-line 1))
1463             ((null encoding)            ;Encoding is not specified.
1464              ;; Application, image, audio, video, and any other
1465              ;; unknown content-type without encoding should be
1466              ;; encoded.
1467              (let* ((encoding "base64") ;Encode in BASE64 by default.
1468                     (beg (mime-editor/content-beginning))
1469                     (end (mime-editor/content-end))
1470                     (body (buffer-substring beg end))
1471                     (encoded (funcall mime-string-encoder
1472                                       (cons nil encoding) body)))
1473                (if (not (string-equal body encoded))
1474                    (progn
1475                      (goto-char beg)
1476                      (delete-region beg end)
1477                      (insert encoded)
1478                      (goto-char beg)))
1479                (mime-editor/define-encoding encoding))
1480              (forward-line 1))
1481             )
1482       )))
1483
1484 (defun mime-delete-field (field)
1485   "Delete header FIELD."
1486   (let ((regexp (format "^%s:[ \t]*" field)))
1487     (goto-char (point-min))
1488     (while (re-search-forward regexp nil t)
1489       (delete-region (match-beginning 0)
1490                      (progn (forward-line 1) (point)))
1491       )))
1492
1493 \f
1494 ;;;
1495 ;;; Platform dependent functions
1496 ;;;
1497
1498 ;; Emacs 18 implementations
1499
1500 (defun mime-body-charset-chooser-for-emacs18 (begin end)
1501   "Return a cons of charset and encoding of a message in a given region.
1502 Encoding name must be a canonical name, such as `base64'."
1503   '("US-ASCII" . nil)                   ;Default charset of MIME.
1504   )
1505
1506 (defun mime-string-encoder-for-emacs18 (method string)
1507   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1508   (let ((charset (car method))
1509         (encoding (cdr method)))
1510     (cond ((stringp encoding)
1511            (mime-encode-string encoding string))
1512           ;; Return string without any encoding.
1513           (t string)
1514           )))
1515
1516 \f
1517 ;; Emacs 19 implementations
1518
1519 (defun mime-body-charset-chooser-for-emacs19 (begin end)
1520   "Return a cons of charset and encoding of a message in a given region.
1521 Encoding name must be a canonical name, such as `base64'.
1522 US-ASCII and ISO-8859-1 are supported on Emacs 19."
1523   (cond ((save-excursion
1524            (goto-char begin)
1525            (re-search-forward "[\200-\377]" end t))
1526          '("ISO-8859-1" . "quoted-printable"))
1527         (t
1528          '("US-ASCII" . nil))           ;Default charset of MIME.
1529         ))
1530
1531 (defun mime-string-encoder-for-emacs19 (method string)
1532   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1533   (let ((charset (car method))
1534         (encoding (cdr method)))
1535     (cond ((stringp encoding)
1536            (mime-encode-string encoding string))
1537           ;; Return string without any encoding.
1538           (t string)
1539           )))
1540
1541 \f
1542 ;; NEmacs implementations
1543
1544 (defun mime-body-charset-chooser-for-nemacs (begin end)
1545   "Return a cons of charset and encoding of a message in a given region.
1546 Encoding name must be a canonical name, such as `base64'.
1547 US-ASCII and ISO-2022-JP are supported on NEmacs."
1548   (cond ((check-region-kanji-code begin end)
1549          ;; The following are safe encoding methods for use in
1550          ;; USENET News systems that strip off all ESCs.
1551          ;; '("ISO-2022-JP" . "quoted-printable")
1552          ;; '("ISO-2022-JP" . "base64")
1553          ;; The following expects transport systems are all MIME
1554          ;; compliants.  For instance, ESCs are never stripped off.
1555          '("ISO-2022-JP" . nil))
1556         (t
1557          '("US-ASCII" . nil))           ;Default charset of MIME.
1558         ))
1559
1560 (defun mime-string-encoder-for-nemacs (method string)
1561   "For given METHOD that is a cons of charset and encoding, encode a STRING.
1562 US-ASCII and ISO-2022-JP are supported on NEmacs."
1563   (let ((charset (car method))
1564         (encoding (cdr method)))
1565     (cond ((stringp encoding)
1566            (mime-encode-string encoding
1567                                ;; Convert internal (EUC) to JIS code.
1568                                (convert-string-kanji-code string 3 2)
1569                                ))
1570           ;; NEmacs can convert into ISO-2022-JP automatically,
1571           ;; but can do it myself as follows:
1572           ;;(t (convert-string-kanji-code string 3 2))
1573
1574           ;; Return string without any encoding.
1575           (t string)
1576           )))
1577
1578 \f
1579 ;; Mule implementations
1580 ;; Thanks to contributions by wkenji@flab.fujitsu.co.jp (Kenji
1581 ;; WAKAMIYA) and handa@etl.go.jp (Kenichi Handa).
1582
1583 (defun mime-body-charset-chooser-for-mule (begin end)
1584   "Return a cons of charset and encoding of a message in a given
1585 region.  Encoding name must be a canonical name, such as `base64'.
1586 US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1587 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1588 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual text
1589 in Mule."
1590   (let ((lclist (find-charset-region begin end)))
1591     (cond ((null lclist)
1592            '("US-ASCII" . nil))         ;Default charset of MIME.
1593           ;; Multilingual capability requred.
1594           ((and (> (length lclist) 1)
1595                 (boundp '*iso-2022-int-1*))
1596            '("ISO-2022-INT-1" . nil))
1597           ((> (length lclist) 1)
1598            '("ISO-2022-JP-2" . nil))
1599           ;; Simple charset.
1600           ((memq lc-ltn1 lclist)
1601            '("ISO-8859-1" . "quoted-printable"))
1602           ((memq lc-ltn2 lclist)
1603            '("ISO-8859-2" . "quoted-printable"))
1604           ((memq lc-ltn3 lclist)
1605            '("ISO-8859-3" . "quoted-printable"))
1606           ((memq lc-ltn4 lclist)
1607            '("ISO-8859-4" . "quoted-printable"))
1608           ((memq lc-crl lclist)
1609            '("ISO-8859-5" . "quoted-printable"))
1610           ;;((memq lc-arb lclist)
1611           ;; '("ISO-8859-6" . "quoted-printable"))
1612           ((memq lc-grk lclist)
1613            '("ISO-8859-7" . "quoted-printable"))
1614           ((memq lc-hbw lclist)
1615            '("ISO-8859-8" . "quoted-printable"))
1616           ((memq lc-ltn5 lclist)
1617            '("ISO-8859-9" . "quoted-printable"))
1618           ((memq lc-jp lclist)
1619            '("ISO-2022-JP" . nil))
1620           ;; Unknown charset.
1621           ((boundp '*iso-2022-int-1*)
1622            '("ISO-2022-INT-1" . nil))
1623           (t
1624            '("ISO-2022-JP-2" . nil))
1625           )))
1626
1627 (defun mime-string-encoder-for-mule (method string)
1628   "For given METHOD that is a cons of charset and encoding, encode a
1629 STRING.  US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1630 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1631 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual
1632 text."
1633   (let* ((charset (car method))
1634          (encoding (cdr method))
1635          (coding-system
1636           (cdr (assoc (and (stringp charset) (upcase charset))
1637                       '(("ISO-8859-1" . *ctext*)
1638                         ("ISO-8859-2" . *iso-8859-2*)
1639                         ("ISO-8859-3" . *iso-8859-3*)
1640                         ("ISO-8859-4" . *iso-8859-4*)
1641                         ("ISO-8859-5" . *iso-8859-5*)
1642                         ;;("ISO-8859-6" . *iso-8859-6*)
1643                         ("ISO-8859-7" . *iso-8859-7*)
1644                         ("ISO-8859-8" . *iso-8859-8*)
1645                         ("ISO-8859-9" . *iso-8859-9*)
1646                         ("ISO-2022-JP" . *junet*)
1647                         ("ISO-2022-JP-2" . *iso-2022-ss2-7*)
1648                         ("ISO-2022-INT-1" . *iso-2022-int-1*)
1649                         )))))
1650     ;; In bilingual environment it may be unnecessary to convert the
1651     ;; coding system of the string unless transfer encoding is
1652     ;; required since such conversion may be performed by mule
1653     ;; automatically.
1654     (if (not (null coding-system))
1655         (setq string (code-convert-string string *internal* coding-system)))
1656     (if (stringp encoding)
1657         (setq string (mime-encode-string encoding string)))
1658     string
1659     ))
1660
1661 \f
1662 ;; Sun implementations
1663
1664 (defun mime-voice-recorder-for-sun ()
1665   "Record voice in a buffer using Sun audio device, and return the buffer.
1666 If the environment variable AUDIOHOST is defined, its value is used as
1667 a recording host instead of local host."
1668   (let ((buffer (get-buffer-create " *MIME audio*"))
1669         (host (getenv "AUDIOHOST")))
1670     (message "Start the recording on %s.  Type C-g to finish the recording..."
1671              (or host (system-name)))
1672     (save-excursion
1673       (set-buffer buffer)
1674       (erase-buffer)
1675       (condition-case errorcode
1676           (let ((selective-display nil) ;Disable ^M to nl translation.
1677                 (mc-flag nil)           ;Mule
1678                 (kanji-flag nil))       ;NEmacs
1679             ;; If AUDIOHOST is defined, use the value as recording host.
1680             (cond ((not (null host))
1681                    ;; Disable automatic conversion of coding system if Mule.
1682                    (if (featurep 'mule)
1683                        (define-program-coding-system nil "rsh" *noconv*))
1684                    (call-process "rsh"
1685                                  nil
1686                                  buffer
1687                                  nil
1688                                  host
1689                                  "cat"
1690                                  "/dev/audio"
1691                                  ))
1692                   (t
1693                    ;; Disable automatic conversion of coding system if Mule.
1694                    (if (featurep 'mule)
1695                        (define-program-coding-system nil "cat" *noconv*))
1696                    (call-process "cat"
1697                                  "/dev/audio"
1698                                  buffer
1699                                  nil
1700                                  ))))
1701         (quit (message "Type C-g to finish recording... done.")
1702               buffer                    ;Return the buffer
1703               )))))
1704
1705 \f
1706 ;;; @ Other useful commands.
1707 ;;;
1708
1709 ;; Message forwarding commands as content-type "message/rfc822".
1710
1711 (defun mime-editor/insert-message (&optional message)
1712   (interactive)
1713   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1714     (if (and inserter (fboundp inserter))
1715         (progn
1716           (mime-editor/insert-tag "message" "rfc822")
1717           (funcall inserter message)
1718           )
1719       (message "Sorry, I don't have message inserter for your MUA.")
1720       )))
1721
1722 (defun mime-editor/insert-mail (&optional message)
1723   (interactive)
1724   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
1725     (if (and inserter (fboundp inserter))
1726         (progn
1727           (mime-editor/insert-tag "message" "rfc822")
1728           (funcall inserter message)
1729           )
1730       (message "Sorry, I don't have mail inserter for your MUA.")
1731       )))
1732
1733 (defun mime-editor/inserted-message-filter ()
1734   (save-excursion
1735     (save-restriction
1736       (let ((header-start (point))
1737             (case-fold-search t)
1738             beg end)
1739         (if (re-search-forward "^$" (mark t))
1740             (narrow-to-region header-start (match-beginning 0))
1741           )
1742         (goto-char header-start)
1743         (while (and (re-search-forward
1744                      mime-editor/yank-ignored-field-regexp nil t)
1745                     (setq beg (match-beginning 0))
1746                     (setq end (1+ (rfc822/field-end)))
1747                     )
1748           (delete-region beg end)
1749           )
1750         ))))
1751
1752 ;;; mime.el ends here
1753
1754 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1755   (if (null boundary)
1756       (setq boundary
1757             (concat mime-multipart-boundary " " (current-time-string)))
1758     )
1759   (save-excursion
1760     (save-restriction
1761       (narrow-to-region beg end)
1762       (let ((tag nil)                   ;MIME tag
1763             (contype nil)               ;Content-Type
1764             (encoding nil)              ;Content-Transfer-Encoding
1765             (nparts 0))                 ;Number of body parts
1766         ;; Normalize the body part by inserting appropriate message
1767         ;; tags for every message contents.
1768         (mime-editor/normalize-body)
1769         ;; Counting the number of Content-Type.
1770         (goto-char (point-min))
1771         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1772           (setq nparts (1+ nparts)))
1773         ;; Begin translation.
1774         (cond ((and (<= nparts 1)(not multipart))
1775                ;; It's a singular message.
1776                (goto-char (point-min))
1777                (while (re-search-forward
1778                        mime-editor/single-part-tag-regexp nil t)
1779                  (setq tag
1780                        (buffer-substring (match-beginning 0) (match-end 0)))
1781                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1782                  (setq contype (mime-editor/get-contype tag))
1783                  (setq encoding (mime-editor/get-encoding tag))
1784                  ))
1785               (t
1786                ;; It's a multipart message.
1787                (goto-char (point-min))
1788                (while (re-search-forward
1789                        mime-editor/single-part-tag-regexp nil t)
1790                  (setq tag
1791                        (buffer-substring (match-beginning 0) (match-end 0)))
1792                  (delete-region (match-beginning 0) (match-end 0))
1793                  (setq contype (mime-editor/get-contype tag))
1794                  (setq encoding (mime-editor/get-encoding tag))
1795                  (insert "--" boundary "\n")
1796                  (insert "Content-Type: " contype "\n")
1797                  (if encoding
1798                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1799                  )
1800                ;; Define Content-Type as "multipart/mixed".
1801                (setq contype
1802                      (concat "multipart/mixed; boundary=\"" boundary "\""))
1803                ;; Content-Transfer-Encoding must be "7bit".
1804                ;; The following encoding can be `nil', but is
1805                ;; specified as is since there is no way that a user
1806                ;; specifies it.
1807                (setq encoding "7bit")
1808                ;; Insert the trailer.
1809                (goto-char (point-max))
1810                (if (not (= (preceding-char) ?\n))
1811                    ;; Boundary must start with a newline.
1812                    (insert "\n"))
1813                (insert "--" boundary "--\n")))
1814         (list contype encoding boundary nparts)
1815         ))))
1816
1817
1818 (defun mime-editor/find-inmost ()
1819   (goto-char (point-min))
1820   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1821       (let ((bb (match-beginning 0))
1822             (be (match-end 0))
1823             (type (buffer-substring (match-beginning 1)(match-end 1)))
1824             end-exp eb ee)
1825         (setq end-exp (format "^--}-<<%s>>\n" type))
1826         (widen)
1827         (if (re-search-forward end-exp nil t)
1828             (progn
1829               (setq eb (match-beginning 0))
1830               (setq ee (match-end 0))
1831               )
1832           (setq eb (point-max))
1833           (setq ee (point-max))
1834           )
1835         (narrow-to-region be eb)
1836         (goto-char be)
1837         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1838             (let (ret)
1839               (narrow-to-region (match-beginning 0)(point-max))
1840               (mime-editor/find-inmost)
1841               )
1842           (widen)
1843           ;;(delete-region eb ee)
1844           (list type bb be eb)
1845           ))))
1846
1847 (defun mime-editor/process-multipart-1 (boundary)
1848   (let ((ret (mime-editor/find-inmost)))
1849     (if ret
1850         (let ((type (car ret))
1851               (bb (nth 1 ret))(be (nth 2 ret))
1852               (eb (nth 3 ret))
1853               )
1854           (narrow-to-region bb eb)
1855           (delete-region bb be)
1856           (setq bb (point-min))
1857           (setq eb (point-max))
1858           (widen)
1859           (goto-char eb)
1860           (if (looking-at mime-editor/multipart-end-regexp)
1861               (let ((beg (match-beginning 0))
1862                     (end (match-end 0))
1863                     )
1864                 (delete-region beg end)
1865                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1866                          (not (eobp)))
1867                     (insert (concat (mime-make-text-tag) "\n"))
1868                   )))
1869           (setq boundary
1870                 (nth 2 (mime-editor/translate-region bb eb
1871                                                      boundary t)))
1872           (goto-char bb)
1873           (insert
1874            (format "--[[multipart/%s; boundary=\"%s\"][7bit]]\n"
1875                    type boundary))
1876           boundary))))
1877
1878
1879 ;;; @ multipart enclosure
1880 ;;;
1881
1882 (defun mime-editor/enclose-region (type beg end)
1883   (save-excursion
1884     (goto-char beg)
1885     (let ((f (bolp)))
1886       (save-restriction
1887         (narrow-to-region beg end)
1888         (goto-char beg)
1889         (if (not f)
1890             (insert "\n")
1891           )
1892         (insert (format "--<<%s>>-{\n" type))
1893         (goto-char (point-max))
1894         (setq f (bolp))
1895         (if (not f)
1896             (insert (format "\n--}-<<%s>>" type))
1897           (insert (format "--}-<<%s>>\n" type))
1898           )
1899         (goto-char (point-max))
1900         )
1901       (if (not (eobp))
1902           (progn
1903             (if (not f)
1904                 (if (not (eolp))
1905                     (insert "\n")
1906                   (forward-char)
1907                   )
1908               )
1909             (if (not (looking-at mime-editor/single-part-tag-regexp))
1910                 (insert (mime-make-text-tag) "\n")
1911               )
1912             )
1913         (if (not f)
1914             (insert "\n")
1915           ))
1916       )))
1917
1918 (defun mime-editor/enclose-mixed-region (beg end)
1919   (interactive "*r")
1920   (mime-editor/enclose-region "mixed" beg end)
1921   )
1922
1923 (defun mime-editor/enclose-parallel-region (beg end)
1924   (interactive "*r")
1925   (mime-editor/enclose-region "parallel" beg end)
1926   )
1927
1928 (defun mime-editor/enclose-digest-region (beg end)
1929   (interactive "*r")
1930   (mime-editor/enclose-region "digest" beg end)
1931   )
1932
1933 (defun mime-editor/enclose-alternative-region (beg end)
1934   (interactive "*r")
1935   (mime-editor/enclose-region "alternative" beg end)
1936   )
1937
1938
1939 ;;; @ split
1940 ;;;
1941
1942 (defun mime-editor/insert-partial-header
1943   (fields subject id number total separator)
1944   (insert fields)
1945   (insert (format "Subject: %s (%d/%d)\n" subject number total))
1946   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
1947                   mime-editor/version))
1948   (insert (format "\
1949 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
1950                   id number total separator))
1951   )
1952
1953 (defun mime-editor/split-and-send (&optional cmd)
1954   (interactive)
1955   (let ((mime-editor/message-max-length
1956          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
1957              mime-editor/message-default-max-length))
1958         (lines (count-lines (point-min) (point-max)))
1959         )
1960     (if (and (> lines mime-editor/message-max-length)
1961              mime-editor/split-message)
1962         (let* ((mime-editor/draft-file-name 
1963                 (or (buffer-file-name)
1964                     (make-temp-name
1965                      (expand-file-name "tm-draft" mime/tmp-dir))))
1966                (separator mail-header-separator)
1967                (config
1968                 (eval (cdr (assq major-mode mime-editor/window-config-alist))))
1969                (id (concat "\""
1970                            (replace-space-with-underline (current-time-string))
1971                            "@" (system-name) "\"")))
1972           (run-hooks 'mime-editor/before-split-hook)
1973           (let* ((header (rfc822/get-header-string-except
1974                           mime-editor/split-ignored-field-regexp separator))
1975                  (subject (mail-fetch-field "subject"))
1976                  (total (+ (/ lines mime-editor/message-max-length)
1977                            (if (> (mod lines mime-editor/message-max-length) 0)
1978                                1)))
1979                  (the-buf (current-buffer))
1980                  (buf (get-buffer "*tmp-send*"))
1981                  (command
1982                   (or cmd
1983                       (cdr
1984                        (assq major-mode
1985                              mime-editor/split-message-sender-alist))
1986                       (cdr
1987                        (assq major-mode
1988                              mime-editor/message-default-sender-alist))
1989                       ))
1990                  data)
1991             (goto-char (point-min))
1992             (if (re-search-forward (concat "^" (regexp-quote separator) "$")
1993                                    nil t)
1994                 (replace-match "")
1995               )
1996             (if buf
1997                 (progn
1998                   (switch-to-buffer buf)
1999                   (erase-buffer)
2000                   (switch-to-buffer the-buf)
2001                   )
2002               (setq buf (get-buffer-create "*tmp-send*"))
2003               )
2004             (switch-to-buffer buf)
2005             (make-variable-buffer-local 'mail-header-separator)
2006             (setq mail-header-separator separator)
2007             (switch-to-buffer the-buf)
2008             (goto-char (point-min))
2009             (re-search-forward "^$" nil t)
2010             (let ((mime-editor/partial-number 1))
2011               (setq data (buffer-substring
2012                           (point-min)
2013                           (progn
2014                             (goto-line mime-editor/message-max-length)
2015                             (point))
2016                           ))
2017               (delete-region (point-min)(point))
2018               (switch-to-buffer buf)
2019               (mime-editor/insert-partial-header
2020                header subject id mime-editor/partial-number total separator)
2021               (insert data)
2022               (save-excursion
2023                 (save-restriction
2024                   (goto-char (point-min))
2025                   (search-forward (concat "\n" mail-header-separator "\n"))
2026                   (narrow-to-region
2027                    (match-end 0)
2028                    (if (re-search-forward "^$" nil t)
2029                        (match-beginning 0)
2030                      (point-max)
2031                      ))
2032                   (goto-char (point-min))
2033                   (while (re-search-forward
2034                           mime-editor/split-blind-field-regexp nil t)
2035                     (delete-region (match-beginning 0)
2036                                    (let ((e (rfc822/field-end)))
2037                                      (if (< e (point-max))
2038                                          (1+ e)
2039                                        e)))
2040                     )
2041                   ))
2042               (save-excursion
2043                 (message (format "Sending %d/%d..."
2044                                  mime-editor/partial-number total))
2045                 (call-interactively command)
2046                 (message (format "Sending %d/%d... done"
2047                                  mime-editor/partial-number total))
2048                 )
2049               (erase-buffer)
2050               (switch-to-buffer the-buf)
2051               (setq mime-editor/partial-number 2)
2052               (while (< mime-editor/partial-number total)
2053                 (setq data (buffer-substring
2054                             (point-min)
2055                             (progn
2056                               (goto-line mime-editor/message-max-length)
2057                               (point))
2058                             ))
2059                 (delete-region (point-min)(point))
2060                 (switch-to-buffer buf)
2061                 (mime-editor/insert-partial-header
2062                  header subject id mime-editor/partial-number total separator)
2063                 (insert data)
2064                 (save-excursion
2065                   (message (format "Sending %d/%d..."
2066                                    mime-editor/partial-number total))
2067                   (call-interactively command)
2068                   (message (format "Sending %d/%d... done"
2069                                    mime-editor/partial-number total))
2070                   )
2071                 (erase-buffer)
2072                 (switch-to-buffer the-buf)
2073                 (setq mime-editor/partial-number
2074                       (1+ mime-editor/partial-number))
2075                 )
2076               (goto-char (point-min))
2077               (mime-editor/insert-partial-header
2078                header subject id mime-editor/partial-number total separator)
2079               (message (format "Sending %d/%d..."
2080                                mime-editor/partial-number total))
2081               ))))))
2082
2083
2084 ;;; @ preview message
2085 ;;;
2086
2087 (defun mime-editor/preview-message ()
2088   "preview editing MIME message. [tm-edit.el]"
2089   (interactive)
2090   (let* ((str (buffer-string))
2091          (separator mail-header-separator)
2092          (the-buf (current-buffer))
2093          (buf-name (buffer-name))
2094          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2095          (buf (get-buffer temp-buf-name))
2096          )
2097     (if buf
2098         (progn
2099           (switch-to-buffer buf)
2100           (erase-buffer)
2101           )
2102       (setq buf (get-buffer-create temp-buf-name))
2103       (switch-to-buffer buf)
2104       )
2105     (insert str)
2106     (setq major-mode 'mime/temporary-message-mode)
2107     (make-local-variable 'mail-header-separator)
2108     (setq mail-header-separator separator)
2109     (make-local-variable 'mime/editing-buffer)
2110     (setq mime/editing-buffer the-buf)
2111     
2112     (run-hooks 'mime-editor/translate-hook)
2113     (mime-editor/translate-buffer)
2114     (goto-char (point-min))
2115     (if (re-search-forward
2116          (concat "^" (regexp-quote separator) "$"))
2117         (replace-match "")
2118       )
2119     (mime/viewer-mode)
2120     ))
2121
2122 (defun mime-editor/quitting-method ()
2123   (let ((temp mime::preview/article-buffer)
2124         buf)
2125     (mime-viewer/kill-buffer)
2126     (set-buffer temp)
2127     (setq buf mime/editing-buffer)
2128     (kill-buffer temp)
2129     (switch-to-buffer buf)
2130     ))
2131
2132 (set-alist 'mime-viewer/quitting-method-alist
2133            'mime/temporary-message-mode
2134            (function mime-editor/quitting-method)
2135            )
2136
2137
2138 ;;; @ draft preview
2139 ;;; 
2140 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2141 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2142
2143 (defvar mime-editor/draft-header-separator-alist
2144   '((news-reply-mode . mail-header-separator)
2145     (mh-letter-mode . mail-header-separator)
2146     ))
2147
2148 (defvar mime::article/draft-header-separator nil)
2149
2150 (defun mime-editor/draft-preview ()
2151   (interactive)
2152   (let ((sep (assoc-value major-mode mime-editor/draft-header-separator-alist)))
2153     (or (stringp sep) (setq sep (eval sep)))
2154     (make-variable-buffer-local 'mime::article/draft-header-separator)
2155     (goto-char (point-min))
2156     (re-search-forward
2157      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2158     (setq mime::article/draft-header-separator
2159           (buffer-substring (match-beginning 0) (match-end 0)))
2160     (replace-match "")
2161     (mime/viewer-mode (current-buffer))
2162     (pop-to-buffer (current-buffer))
2163     ))
2164
2165 (defun mime-viewer::quitting-method/draft-preview ()
2166   (let ((mother mime::preview/mother-buffer))
2167     (save-excursion
2168       (switch-to-buffer mother)
2169       (goto-char (point-min))
2170       (if (and
2171            (re-search-forward
2172             (concat "^\\("
2173                     (regexp-quote mime::article/draft-header-separator)
2174                     "\\)?$") nil t)
2175            (bolp))
2176           (progn
2177             (insert mime::article/draft-header-separator)
2178             (set-buffer-modified-p (buffer-modified-p))
2179             )))
2180     (mime-viewer/kill-buffer)
2181     (pop-to-buffer mother)
2182     ))
2183
2184 (set-alist 'mime-viewer/quitting-method-alist
2185            'mh-letter-mode
2186            (function mime-viewer::quitting-method/draft-preview)
2187            )
2188
2189 (set-alist 'mime-viewer/quitting-method-alist
2190            'news-reply-mode
2191            (function mime-viewer::quitting-method/draft-preview)
2192            )
2193
2194
2195 ;;; @ etc
2196 ;;;
2197
2198 (defun replace-space-with-underline (str)
2199   (mapconcat (function
2200               (lambda (arg)
2201                 (char-to-string
2202                  (if (= arg 32)
2203                      ?_
2204                    arg)))) str "")
2205   )
2206
2207
2208 ;;; @ end
2209 ;;;
2210
2211 (provide 'tm-edit)
2212
2213 (run-hooks 'tm-edit-load-hook)