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