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