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