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