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