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