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