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