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