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