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