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