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