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