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