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