Fix typo.
[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$"
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               (next-single-property-change (point) 'mime-edit-invisible)
1281             ;; Move to the end of this text.
1282             (if (re-search-forward mime-edit-tag-regexp nil 'move)
1283                 ;; Don't forget a multiline tag.
1284                 (goto-char (match-beginning 0)))
1285             (point)))
1286       ;; Assume the message begins with text/plain.
1287       (goto-char (mime-edit-content-beginning))
1288       (if (re-search-forward mime-edit-tag-regexp nil 'move)
1289           ;; Don't forget a multiline tag.
1290           (goto-char (match-beginning 0)))
1291       (point))))
1292
1293 (defun mime-edit-define-charset (charset)
1294   "Set charset of current tag to CHARSET."
1295   (save-excursion
1296     (if (mime-edit-goto-tag)
1297         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1298           (delete-region (match-beginning 0) (match-end 0))
1299           (insert
1300            (mime-create-tag
1301             (mime-edit-set-parameter
1302              (mime-edit-get-contype tag)
1303              "charset"
1304              (let ((comment (get charset 'mime-charset-comment)))
1305                (if comment
1306                    (concat (upcase (symbol-name charset)) " (" comment ")")
1307                  (upcase (symbol-name charset)))))
1308             (mime-edit-get-encoding tag)))))))
1309
1310 (defun mime-edit-define-encoding (encoding)
1311   "Set encoding of current tag to ENCODING."
1312   (save-excursion
1313     (if (mime-edit-goto-tag)
1314         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1315           (delete-region (match-beginning 0) (match-end 0))
1316           (insert (mime-create-tag (mime-edit-get-contype tag) encoding))))))
1317
1318 (defun mime-edit-choose-charset ()
1319   "Choose charset of a text following current point."
1320   (detect-mime-charset-region (point) (mime-edit-content-end)))
1321
1322 (defun mime-make-text-tag (&optional subtype)
1323   "Make a tag for a text after current point.
1324 Subtype of text type can be specified by an optional argument SUBTYPE.
1325 Otherwise, it is obtained from mime-content-types."
1326   (let* ((pritype "text")
1327          (subtype (or subtype
1328                       (car (car (cdr (assoc pritype mime-content-types)))))))
1329     ;; Charset should be defined later.
1330     (mime-make-tag pritype subtype)))
1331
1332 \f
1333 ;; Tag handling functions
1334
1335 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1336   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1337   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1338                            (or parameters ""))
1339                    encoding))
1340
1341 (defun mime-create-tag (contype &optional encoding)
1342   "Make a tag with CONTENT-TYPE and optional ENCODING."
1343   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1344           contype encoding))
1345
1346 (defun mime-edit-get-contype (tag)
1347   "Return Content-Type (including parameters) of TAG."
1348   (and (stringp tag)
1349        (or (string-match mime-edit-single-part-tag-regexp tag)
1350            (string-match mime-edit-multipart-beginning-regexp tag)
1351            (string-match mime-edit-multipart-end-regexp tag))
1352        (substring tag (match-beginning 1) (match-end 1))))
1353
1354 (defun mime-edit-get-encoding (tag)
1355   "Return encoding of TAG."
1356   (and (stringp tag)
1357        (string-match mime-edit-single-part-tag-regexp tag)
1358        (match-beginning 3)
1359        (not (= (match-beginning 3) (match-end 3)))
1360        (substring tag (match-beginning 3) (match-end 3))))
1361
1362 (defun mime-get-parameter (contype parameter)
1363   "For given CONTYPE return value for PARAMETER.
1364 Nil if no such parameter."
1365   (if (string-match
1366        (concat
1367         ";[ \t\n]*"
1368         (regexp-quote parameter)
1369         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1370        contype)
1371       (substring contype (match-beginning 1) (match-end 1))
1372     nil                                 ;No such parameter
1373     ))
1374
1375 (defun mime-edit-set-parameter (contype parameter value)
1376   "For given CONTYPE set PARAMETER to VALUE."
1377   (let (ctype opt-fields)
1378     (if (string-match "\n[^ \t\n\r]+:" contype)
1379         (setq ctype (substring contype 0 (match-beginning 0))
1380               opt-fields (substring contype (match-beginning 0)))
1381       (setq ctype contype))
1382     (if (string-match
1383          (concat
1384           ";[ \t\n]*\\("
1385           (regexp-quote parameter)
1386           "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1387          ctype)
1388         ;; Change value
1389         (concat (substring ctype 0 (match-beginning 1))
1390                 parameter "=" value
1391                 (substring ctype (match-end 1))
1392                 opt-fields)
1393       (concat ctype "; " parameter "=" value opt-fields)
1394       )))
1395
1396 (defun mime-strip-parameters (contype)
1397   "Return primary content-type and subtype without parameters for CONTYPE."
1398   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1399       (substring contype (match-beginning 1) (match-end 1)) nil))
1400
1401 (defun mime-test-content-type (contype type &optional subtype)
1402   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1403   (and (stringp contype)
1404        (stringp type)
1405        (string-match
1406         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1407         (downcase contype))))
1408
1409 \f
1410 ;; Basic functions
1411
1412 (defun mime-find-file-type (file)
1413   "Guess Content-Type, subtype, and parameters from FILE."
1414   (let ((guess nil)
1415         (guesses mime-file-types))
1416     (while (and (not guess) guesses)
1417       (if (string-match (car (car guesses)) file)
1418           (setq guess (cdr (car guesses))))
1419       (setq guesses (cdr guesses)))
1420     guess))
1421
1422 (defun mime-prompt-for-type (&optional default)
1423   "Ask for Content-type."
1424   (let ((type ""))
1425     ;; Repeat until primary content type is specified.
1426     (while (string-equal type "")
1427       (setq type
1428             (completing-read "What content type: "
1429                              mime-content-types
1430                              nil
1431                              'require-match ;Type must be specified.
1432                              default))
1433       (if (string-equal type "")
1434           (progn
1435             (message "Content type is required.")
1436             (beep)
1437             (sit-for 1))))
1438     type))
1439
1440 (defun mime-prompt-for-subtype (type &optional default)
1441   "Ask for subtype of media-type TYPE."
1442   (let ((subtypes (cdr (assoc type mime-content-types))))
1443     (or (and default
1444              (assoc default subtypes))
1445         (setq default (car (car subtypes)))))
1446   (let* ((answer
1447           (completing-read
1448            (if default
1449                (concat
1450                 "What content subtype: (default " default ") ")
1451              "What content subtype: ")
1452            (cdr (assoc type mime-content-types))
1453            nil
1454            'require-match               ;Subtype must be specified.
1455            nil)))
1456     (if (string-equal answer "") default answer)))
1457
1458 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1459   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1460 Optional DELIMITER specifies parameter delimiter (';' by default)."
1461   (let* ((delimiter (or delimiter "; "))
1462          (parameters
1463           (mapconcat
1464            (function identity)
1465            (delq nil
1466                  (mime-prompt-for-parameters-1
1467                   (cdr (assoc subtype
1468                               (cdr (assoc pritype mime-content-types))))))
1469            delimiter)))
1470     (if (and (stringp parameters)
1471              (not (string-equal parameters "")))
1472         (concat delimiter parameters)
1473       ""                                ;"" if no parameters
1474       )))
1475
1476 (defun mime-prompt-for-parameters-1 (optlist)
1477   (apply (function append)
1478          (mapcar (function mime-prompt-for-parameter) optlist)))
1479
1480 (defun mime-prompt-for-parameter (parameter)
1481   "Ask for PARAMETER.
1482 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1483   (let* ((prompt (car parameter))
1484          (choices (mapcar (function
1485                            (lambda (e)
1486                              (if (consp e) e (list e))))
1487                           (cdr parameter)))
1488          (default (car (car choices)))
1489          (answer nil))
1490     (if choices
1491         (progn
1492           (setq answer
1493                 (completing-read
1494                  (concat "What " prompt
1495                          ": (default "
1496                          (if (string-equal default "") "\"\"" default)
1497                          ") ")
1498                  choices nil nil ""))
1499           ;; If nothing is selected, use default.
1500           (if (string-equal answer "")
1501               (setq answer default)))
1502       (setq answer
1503             (read-string (concat "What " prompt ": "))))
1504     (cons (if (and answer
1505                    (not (string-equal answer "")))
1506               (concat prompt "="
1507                       ;; Note: control characters ignored!
1508                       (if (string-match mime-tspecials-regexp answer)
1509                           (concat "\"" answer "\"") answer)))
1510           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))))
1511
1512 (defun mime-prompt-for-encoding (default)
1513   "Ask for Content-Transfer-Encoding."
1514   (let (encoding)
1515     (while (string=
1516             (setq encoding
1517                   (completing-read
1518                    "What transfer encoding: "
1519                    (mime-encoding-alist) nil t default))
1520             ""))
1521     encoding))
1522
1523 \f
1524 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1525 ;;;
1526
1527 (defvar mime-edit-translate-buffer-hook
1528   '(mime-edit-pgp-enclose-buffer
1529     mime-edit-translate-body
1530     mime-edit-translate-header))
1531
1532 (defun mime-edit-translate-header ()
1533   "Encode the message header into network representation."
1534   (mime-encode-header-in-buffer 'code-conversion)
1535   (run-hooks 'mime-edit-translate-header-hook))
1536
1537 (defun mime-edit-translate-buffer ()
1538   "Encode the tagged MIME message in current buffer in MIME compliant message."
1539   (interactive)
1540   (undo-boundary)
1541   (if (catch 'mime-edit-error
1542         (save-excursion
1543           (run-hooks 'mime-edit-translate-buffer-hook)))
1544       (progn
1545         (undo)
1546         (error "Translation error!"))))
1547
1548 (defun mime-edit-find-inmost ()
1549   (goto-char (point-min))
1550   (if (re-search-forward mime-edit-multipart-beginning-regexp nil t)
1551       (let ((bb (match-beginning 0))
1552             (be (match-end 0))
1553             (type (buffer-substring (match-beginning 1)(match-end 1)))
1554             end-exp eb)
1555         (setq end-exp (format "--}-<<%s>>\n" type))
1556         (widen)
1557         (if (re-search-forward end-exp nil t)
1558             (setq eb (match-beginning 0))
1559           (setq eb (point-max)))
1560         (narrow-to-region be eb)
1561         (goto-char be)
1562         (if (re-search-forward mime-edit-multipart-beginning-regexp nil t)
1563             (progn
1564               (narrow-to-region (match-beginning 0)(point-max))
1565               (mime-edit-find-inmost))
1566           (widen)
1567           (list type bb be eb)))))
1568
1569 (defun mime-edit-process-multipart-1 (boundary)
1570   (let ((ret (mime-edit-find-inmost)))
1571     (if ret
1572         (let ((type (car ret))
1573               (bb (nth 1 ret))(be (nth 2 ret))
1574               (eb (nth 3 ret)))
1575           (narrow-to-region bb eb)
1576           (delete-region bb be)
1577           (setq bb (point-min))
1578           (setq eb (point-max))
1579           (widen)
1580           (goto-char eb)
1581           (if (looking-at mime-edit-multipart-end-regexp)
1582               (let ((beg (match-beginning 0))
1583                     (end (match-end 0)))
1584                 (delete-region beg end)
1585                 (or (looking-at mime-edit-beginning-tag-regexp)
1586                     (eobp)
1587                     (insert (concat (mime-make-text-tag) "\n")))))
1588           (cond ((string-equal type "quote")
1589                  (mime-edit-enquote-region bb eb))
1590                 ((string-equal type "pgp-signed")
1591                  (mime-edit-sign-pgp-mime bb eb boundary))
1592                 ((string-equal type "pgp-encrypted")
1593                  (mime-edit-encrypt-pgp-mime bb eb boundary))
1594                 ((string-equal type "kazu-signed")
1595                  (mime-edit-sign-pgp-kazu bb eb boundary))
1596                 ((string-equal type "kazu-encrypted")
1597                  (mime-edit-encrypt-pgp-kazu bb eb boundary))
1598                 ((string-equal type "smime-signed")
1599                  (mime-edit-sign-smime bb eb boundary))
1600                 ((string-equal type "smime-encrypted")
1601                  (mime-edit-encrypt-smime bb eb boundary))
1602                 (t
1603                  (setq boundary
1604                        (nth 2 (mime-edit-translate-region bb eb
1605                                                             boundary t)))
1606                  (goto-char bb)
1607                  (insert
1608                   (format "--[[multipart/%s;
1609  boundary=\"%s\"][7bit]]\n"
1610                           type boundary))))
1611           boundary))))
1612
1613 (defun mime-edit-enquote-region (beg end)
1614   (save-excursion
1615     (save-restriction
1616       (narrow-to-region beg end)
1617       (goto-char beg)
1618       (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1619         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1620           (replace-match (concat "- " (substring tag 1))))))))
1621
1622 (defun mime-edit-dequote-region (beg end)
1623   (save-excursion
1624     (save-restriction
1625       (narrow-to-region beg end)
1626       (goto-char beg)
1627       (while (re-search-forward
1628               mime-edit-quoted-single-part-tag-regexp nil t)
1629         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1630           (replace-match (concat "-" (substring tag 2))))))))
1631
1632 (defvar mime-edit-pgp-user-id nil)
1633
1634 (defun mime-edit-sign-pgp-mime (beg end boundary)
1635   (save-excursion
1636     (save-restriction
1637       (let* ((from (std11-field-body "From" mail-header-separator))
1638              (ret (progn 
1639                     (narrow-to-region beg end)
1640                     (mime-edit-translate-region beg end boundary)))
1641              (ctype    (car ret))
1642              (encoding (nth 1 ret))
1643              (pgp-boundary (concat "pgp-sign-" boundary))
1644              micalg)
1645         (goto-char beg)
1646         (insert (format "Content-Type: %s\n" ctype))
1647         (if encoding
1648             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1649         (insert "\n")
1650         (or (let ((pgg-default-user-id 
1651                    (or mime-edit-pgp-user-id
1652                        (if from 
1653                            (nth 1 (std11-extract-address-components from))
1654                          pgg-default-user-id))))
1655               (pgg-sign-region (point-min)(point-max)))
1656             (throw 'mime-edit-error 'pgp-error))
1657         (setq micalg
1658               (cdr (assq 'hash-algorithm
1659                          (cdar (with-current-buffer pgg-output-buffer
1660                                  (pgg-parse-armor-region 
1661                                   (point-min)(point-max))))))
1662               micalg 
1663               (if micalg
1664                   (concat "; micalg=pgp-" (downcase (symbol-name micalg)))
1665                 ""))
1666         (goto-char beg)
1667         (insert (format "--[[multipart/signed;
1668  boundary=\"%s\"%s;
1669  protocol=\"application/pgp-signature\"][7bit]]
1670 --%s
1671 " pgp-boundary micalg pgp-boundary))
1672         (goto-char (point-max))
1673         (insert (format "\n--%s
1674 Content-Type: application/pgp-signature
1675 Content-Transfer-Encoding: 7bit
1676
1677 " pgp-boundary))
1678         (insert-buffer-substring pgg-output-buffer)
1679         (goto-char (point-max))
1680         (insert (format "\n--%s--\n" pgp-boundary))))))
1681
1682 (defvar mime-edit-encrypt-recipient-fields-list '("To" "cc"))
1683
1684 (defun mime-edit-make-encrypt-recipient-header ()
1685   (let* ((names mime-edit-encrypt-recipient-fields-list)
1686          (values
1687           (std11-field-bodies (cons "From" names)
1688                               nil mail-header-separator))
1689          (from (prog1
1690                    (car values)
1691                  (setq values (cdr values))))
1692          (header (and (stringp from)
1693                       (if (string-equal from "")
1694                           ""
1695                         (format "From: %s\n" from))))
1696          recipients)
1697     (while (and names values)
1698       (let ((name (car names))
1699             (value (car values)))
1700         (and (stringp value)
1701              (or (string-equal value "")
1702                  (progn
1703                    (setq header (concat header name ": " value "\n")
1704                          recipients (if recipients
1705                                         (concat recipients " ," value)
1706                                       value))))))
1707       (setq names (cdr names)
1708             values (cdr values)))
1709     (vector from recipients header)))
1710
1711 (defun mime-edit-encrypt-pgp-mime (beg end boundary)
1712   (save-excursion
1713     (save-restriction
1714       (let (from recipients header)
1715         (let ((ret (mime-edit-make-encrypt-recipient-header)))
1716           (setq from (aref ret 0)
1717                 recipients (aref ret 1)
1718                 header (aref ret 2)))
1719         (narrow-to-region beg end)
1720         (let* ((ret
1721                 (mime-edit-translate-region beg end boundary))
1722                (ctype    (car ret))
1723                (encoding (nth 1 ret))
1724                (pgp-boundary (concat "pgp-" boundary)))
1725           (goto-char beg)
1726           (insert header)
1727           (insert (format "Content-Type: %s\n" ctype))
1728           (if encoding
1729               (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1730           (insert "\n")
1731           (mime-encode-header-in-buffer)
1732           (or (let ((pgg-default-user-id 
1733                      (or mime-edit-pgp-user-id
1734                          (if from 
1735                              (nth 1 (std11-extract-address-components from))
1736                            pgg-default-user-id))))                   
1737                 (pgg-encrypt-region 
1738                  (point-min) (point-max) 
1739                  (mapcar (lambda (recipient)
1740                            (nth 1 (std11-extract-address-components
1741                                    recipient)))
1742                          (split-string recipients 
1743                                        "\\([ \t\n]*,[ \t\n]*\\)+"))))
1744               (throw 'mime-edit-error 'pgp-error))
1745           (delete-region (point-min)(point-max))
1746           (goto-char beg)
1747           (insert (format "--[[multipart/encrypted;
1748  boundary=\"%s\";
1749  protocol=\"application/pgp-encrypted\"][7bit]]
1750 --%s
1751 Content-Type: application/pgp-encrypted
1752
1753 --%s
1754 Content-Type: application/octet-stream
1755 Content-Transfer-Encoding: 7bit
1756
1757 " pgp-boundary pgp-boundary pgp-boundary))
1758           (insert-buffer-substring pgg-output-buffer)
1759           (goto-char (point-max))
1760           (insert (format "\n--%s--\n" pgp-boundary)))))))
1761
1762 (defun mime-edit-sign-pgp-kazu (beg end boundary)
1763   (save-excursion
1764     (save-restriction
1765       (narrow-to-region beg end)
1766       (let* ((ret
1767               (mime-edit-translate-region beg end boundary))
1768              (ctype    (car ret))
1769              (encoding (nth 1 ret)))
1770         (goto-char beg)
1771         (insert (format "Content-Type: %s\n" ctype))
1772         (if encoding
1773             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1774         (insert "\n")
1775         (or (pgg-sign-region beg (point-max) 'clearsign)
1776             (throw 'mime-edit-error 'pgp-error))
1777         (goto-char beg)
1778         (insert
1779          "--[[application/pgp; format=mime][7bit]]\n")
1780         ))))
1781
1782 (defun mime-edit-encrypt-pgp-kazu (beg end boundary)
1783   (save-excursion
1784     (let (recipients header)
1785       (let ((ret (mime-edit-make-encrypt-recipient-header)))
1786         (setq recipients (aref ret 1)
1787               header (aref ret 2)))
1788       (save-restriction
1789         (narrow-to-region beg end)
1790         (let* ((ret
1791                 (mime-edit-translate-region beg end boundary))
1792                (ctype    (car ret))
1793                (encoding (nth 1 ret)))
1794           (goto-char beg)
1795           (insert header)
1796           (insert (format "Content-Type: %s\n" ctype))
1797           (if encoding
1798               (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1799           (insert "\n")
1800           (or (pgg-encrypt-region beg (point-max) recipients)
1801               (throw 'mime-edit-error 'pgp-error))
1802           (goto-char beg)
1803           (insert
1804            "--[[application/pgp; format=mime][7bit]]\n")
1805           )))))
1806
1807 (defun mime-edit-sign-smime (beg end boundary)
1808   (save-excursion
1809     (save-restriction
1810       (let* ((ret (progn 
1811                     (narrow-to-region beg end)
1812                     (mime-edit-translate-region beg end boundary)))
1813              (ctype    (car ret))
1814              (encoding (nth 1 ret))
1815              (smime-boundary (concat "smime-sign-" boundary)))
1816         (goto-char beg)
1817         (insert (format "Content-Type: %s\n" ctype))
1818         (if encoding
1819             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1820         (insert "\n")
1821         (let (buffer-undo-list)
1822           (goto-char (point-min))
1823           (while (progn (end-of-line) (not (eobp)))
1824             (insert "\r")
1825             (forward-line 1))
1826           (or (smime-sign-buffer)
1827               (throw 'mime-edit-error 'pgp-error)))
1828         (goto-char beg)
1829         (if (re-search-forward "^Content-Type:\\s-*" nil t)
1830             (let* ((start (match-beginning 0))
1831                    (body (buffer-substring (match-end 0) (std11-field-end))))
1832               (delete-region start (line-beginning-position 2))
1833               (goto-char beg)
1834               (insert "--[[" body "][7bit]]\n")))))))
1835
1836 (defun mime-edit-encrypt-smime (beg end boundary)
1837   (save-excursion
1838     (save-restriction
1839       (let* ((ret (progn 
1840                     (narrow-to-region beg end)
1841                     (mime-edit-translate-region beg end boundary)))
1842              (ctype    (car ret))
1843              (encoding (nth 1 ret)))
1844         (goto-char beg)
1845         (insert (format "Content-Type: %s\n" ctype))
1846         (if encoding
1847             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1848         (insert "\n")
1849         (goto-char (point-min))
1850         (while (progn (end-of-line) (not (eobp)))
1851           (insert "\r")
1852           (forward-line 1))
1853         (or (smime-encrypt-buffer)
1854             (throw 'mime-edit-error 'pgp-error))
1855         (goto-char beg)
1856         (if (re-search-forward "^Content-Type:\\s-*" nil t)
1857             (let* ((start (match-beginning 0))
1858                    (body (buffer-substring (match-end 0) (std11-field-end))))
1859               (delete-region start (line-beginning-position 2))
1860               (goto-char beg)
1861               (insert "--[[" body "]]\n")))))))
1862
1863 (defsubst replace-space-with-underline (str)
1864   (mapconcat (function
1865               (lambda (arg)
1866                 (char-to-string
1867                  (if (eq arg ?\ )
1868                      ?_
1869                    arg)))) str ""))
1870
1871 (defun mime-edit-make-boundary ()
1872   (concat mime-multipart-boundary "_"
1873           (replace-space-with-underline (current-time-string))))
1874
1875 (defun mime-edit-translate-body ()
1876   "Encode the tagged MIME body in current buffer in MIME compliant message."
1877   (interactive)
1878   (save-excursion
1879     (let ((boundary (mime-edit-make-boundary))
1880           (i 1)
1881           ret)
1882       (while (mime-edit-process-multipart-1
1883               (format "%s-%d" boundary i))
1884         (setq i (1+ i)))
1885       (save-restriction
1886         ;; We are interested in message body.
1887         (let* ((beg
1888                 (progn
1889                   (goto-char (point-min))
1890                   (re-search-forward
1891                    (concat "\n" (regexp-quote mail-header-separator)
1892                            (if mime-ignore-preceding-spaces
1893                                "[ \t\n]*\n" "\n")) nil 'move)
1894                   (point)))
1895                (end
1896                 (progn
1897                   (goto-char (point-max))
1898                   (and mime-ignore-trailing-spaces
1899                        (re-search-backward "[^ \t\n]\n" beg t)
1900                        (forward-char 1))
1901                   (point))))
1902           (setq ret (mime-edit-translate-region
1903                      beg end
1904                      (format "%s-%d" boundary i)))))
1905       (mime-edit-dequote-region (point-min)(point-max))
1906       (let ((contype (car ret))         ;Content-Type
1907             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1908             )
1909         ;; Insert User-Agent field
1910         (and mime-edit-insert-user-agent-field
1911              (or (mail-position-on-field "User-Agent")
1912                  (insert mime-edit-user-agent-value)))
1913         ;; Make primary MIME headers.
1914         (or (mail-position-on-field "MIME-Version")
1915             (insert mime-edit-mime-version-value))
1916         ;; Remove old Content-Type and other fields.
1917         (save-restriction
1918           (goto-char (point-min))
1919           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1920           (narrow-to-region (point-min) (point))
1921           (goto-char (point-min))
1922           (mime-delete-field "Content-Type")
1923           (mime-delete-field "Content-Transfer-Encoding"))
1924         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1925         (mail-position-on-field "Content-Type")
1926         (insert contype)
1927         (if encoding
1928             (progn
1929               (mail-position-on-field "Content-Transfer-Encoding")
1930               (insert encoding)))))))
1931
1932 (defun mime-edit-translate-single-part-tag (boundary &optional prefix)
1933   "Translate single-part-tag to MIME header."
1934   (if (re-search-forward mime-edit-single-part-tag-regexp nil t)
1935       (let* ((beg (match-beginning 0))
1936              (end (match-end 0))
1937              (tag (buffer-substring beg end)))
1938         (delete-region beg end)
1939         (let ((contype (mime-edit-get-contype tag))
1940               (encoding (mime-edit-get-encoding tag)))
1941           (insert (concat prefix "--" boundary "\n"))
1942           (save-restriction
1943             (narrow-to-region (point)(point))
1944             (insert "Content-Type: " contype "\n")
1945             (if encoding
1946                 (insert "Content-Transfer-Encoding: " encoding "\n"))
1947             (mime-encode-header-in-buffer))
1948           (cons (and contype
1949                      (downcase contype))
1950                 (and encoding
1951                      (downcase encoding)))))))
1952
1953 (defun mime-edit-translate-region (beg end &optional boundary multipart)
1954   (or boundary
1955       (setq boundary (mime-edit-make-boundary)))
1956   (save-excursion
1957     (save-restriction
1958       (narrow-to-region beg end)
1959       (let ((tag nil)                   ;MIME tag
1960             (contype nil)               ;Content-Type
1961             (encoding nil)              ;Content-Transfer-Encoding
1962             (nparts 0))                 ;Number of body parts
1963         ;; Normalize the body part by inserting appropriate message
1964         ;; tags for every message contents.
1965         (mime-edit-normalize-body)
1966         ;; Counting the number of Content-Type.
1967         (goto-char (point-min))
1968         (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1969           (setq nparts (1+ nparts)))
1970         ;; Begin translation.
1971         (cond
1972          ((and (<= nparts 1)(not multipart))
1973           ;; It's a singular message.
1974           (goto-char (point-min))
1975           (while (re-search-forward
1976                   mime-edit-single-part-tag-regexp nil t)
1977             (setq tag
1978                   (buffer-substring (match-beginning 0) (match-end 0)))
1979             (delete-region (match-beginning 0) (1+ (match-end 0)))
1980             (setq contype (mime-edit-get-contype tag))
1981             (setq encoding (mime-edit-get-encoding tag))))
1982          (t
1983           ;; It's a multipart message.
1984           (goto-char (point-min))
1985           (let ((prio mime-content-transfer-encoding-priority-list)
1986                 part-info nprio)
1987             (when (setq part-info
1988                         (mime-edit-translate-single-part-tag boundary))
1989               (and (setq nprio (member (cdr part-info) prio))
1990                    (setq prio nprio))
1991               (while (setq part-info
1992                            (mime-edit-translate-single-part-tag boundary "\n"))
1993                 (and (setq nprio (member (cdr part-info) prio))
1994                      (setq prio nprio))))
1995             ;; Define Content-Type as "multipart/mixed".
1996             (setq contype
1997                   (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1998             (setq encoding (car prio))
1999             ;; Insert the trailer.
2000             (goto-char (point-max))
2001             (insert "\n--" boundary "--\n"))))
2002          (list contype encoding boundary nparts)))))
2003
2004 (defun mime-edit-normalize-body ()
2005   "Normalize the body part by inserting appropriate message tags."
2006   ;; Insert the first MIME tags if necessary.
2007   (goto-char (point-min))
2008   (if (not (looking-at mime-edit-single-part-tag-regexp))
2009       (insert (mime-make-text-tag) "\n"))
2010   ;; Check each tag, and add new tag or correct it if necessary.
2011   (goto-char (point-min))
2012   (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
2013     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
2014            (contype (mime-edit-get-contype tag))
2015            (charset (mime-get-parameter contype "charset"))
2016            (encoding (mime-edit-get-encoding tag)))
2017       ;; Remove extra whitespaces after the tag.
2018       (if (looking-at "[ \t]+$")
2019           (delete-region (match-beginning 0) (match-end 0)))
2020       (let ((beg (point))
2021             (end (mime-edit-content-end)))
2022         (if (= end (point-max))
2023             nil
2024           (goto-char end)
2025           (or (looking-at mime-edit-beginning-tag-regexp)
2026               (eobp)
2027               (insert (mime-make-text-tag) "\n")))
2028         (remove-text-properties beg end '(invisible mime-edit-invisible))
2029         (goto-char beg))
2030       (cond
2031        ((mime-test-content-type contype "message")
2032         ;; Content-type "message" should be sent as is.
2033         (forward-line 1))
2034        ((mime-test-content-type contype "text")
2035         ;; Define charset for text if necessary.
2036         (setq charset (if charset
2037                           (intern (downcase charset))
2038                         (mime-edit-choose-charset)))
2039         (mime-edit-define-charset charset)
2040         (cond ((string-equal contype "text/x-rot13-47-48")
2041                (save-excursion
2042                  (forward-line)
2043                  (mule-caesar-region (point) (mime-edit-content-end))))
2044               ((string-equal contype "text/enriched")
2045                (save-excursion
2046                  (let ((beg (progn
2047                               (forward-line)
2048                               (point)))
2049                        (end (mime-edit-content-end)))
2050                    ;; Patch for hard newlines
2051                    ;; (save-excursion
2052                    ;;   (goto-char beg)
2053                    ;;   (while (search-forward "\n" end t)
2054                    ;;     (put-text-property (match-beginning 0)
2055                    ;;                        (point)
2056                    ;;                        'hard t)))
2057                    ;; End patch for hard newlines
2058                    (enriched-encode beg end nil)
2059                    (goto-char beg)
2060                    (if (search-forward "\n\n")
2061                        (delete-region beg (match-end 0)))))))
2062         ;; Point is now on current tag.
2063         ;; Define encoding and encode text if necessary.
2064         (or encoding    ;Encoding is not specified.
2065             (let* ((encoding
2066                     (let (bits conv)
2067                       (let ((ret (cdr (assq charset mime-charset-type-list))))
2068                         (if ret
2069                             (setq bits (car ret)
2070                                   conv (nth 1 ret))
2071                           (setq bits 8
2072                                 conv "quoted-printable")))
2073                       (if (<= bits mime-transfer-level)
2074                           (mime-encoding-name bits)
2075                         conv)))
2076                    (beg (mime-edit-content-beginning)))
2077               (encode-mime-charset-region beg (mime-edit-content-end)
2078                                           charset)
2079               ;; Protect "From " in beginning of line
2080               (save-restriction
2081                 (narrow-to-region beg (mime-edit-content-end))
2082                 (goto-char beg)
2083                 (let (case-fold-search)
2084                   (if (re-search-forward "^From " nil t)
2085                       (unless encoding
2086                         (if (memq charset '(iso-2022-jp
2087                                             iso-2022-jp-2
2088                                             iso-2022-int-1
2089                                             x-ctext))
2090                             (while (progn
2091                                      (replace-match "\e(BFrom ")
2092                                      (re-search-forward "^From " nil t)))
2093                           (setq encoding "quoted-printable"))))))
2094               ;; canonicalize line break code
2095               (or (member encoding '(nil "7bit" "8bit" "quoted-printable"))
2096                   (save-restriction
2097                     (narrow-to-region beg (mime-edit-content-end))
2098                     (goto-char beg)
2099                     (while (re-search-forward "\\(\\=\\|[^\r]\\)\n" nil t)
2100                       (replace-match "\\1\r\n"))))
2101               (goto-char beg)
2102               (mime-encode-region beg (mime-edit-content-end)
2103                                   (or encoding "7bit"))
2104               (mime-edit-define-encoding encoding)))
2105         (goto-char (mime-edit-content-end)))
2106        ((null encoding)         ;Encoding is not specified.
2107         ;; Application, image, audio, video, and any other
2108         ;; unknown content-type without encoding should be
2109         ;; encoded.
2110         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2111                (beg (mime-edit-content-beginning))
2112                (end (mime-edit-content-end)))
2113           (mime-encode-region beg end encoding)
2114           (mime-edit-define-encoding encoding))
2115         (forward-line 1))))))
2116
2117 (defun mime-delete-field (field)
2118   "Delete header FIELD."
2119   (let ((regexp (format "^%s:[ \t]*" field)))
2120     (goto-char (point-min))
2121     (while (re-search-forward regexp nil t)
2122       (delete-region (match-beginning 0)
2123                      (1+ (std11-field-end))))))
2124
2125 \f
2126 ;;;
2127 ;;; Platform dependent functions
2128 ;;;
2129
2130 ;; Sun implementations
2131
2132 (defun mime-edit-voice-recorder-for-sun (encoding)
2133   "Record voice in a buffer using Sun audio device,
2134 and insert data encoded as ENCODING."
2135   (message "Start the recording on %s.  Type C-g to finish the recording..."
2136            (system-name))
2137   (mime-insert-encoded-file "/dev/audio" encoding))
2138
2139 \f
2140 ;;; @ Other useful commands.
2141 ;;;
2142
2143 ;; Message forwarding commands as content-type "message/rfc822".
2144
2145 (defun mime-edit-insert-message (&optional message)
2146   (interactive)
2147   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2148     (if (and inserter (fboundp inserter))
2149         (progn
2150           (mime-edit-insert-tag "message" "rfc822")
2151           (funcall inserter message))
2152       (message "Sorry, I don't have message inserter for your MUA."))))
2153
2154 (defun mime-edit-insert-mail (&optional message)
2155   (interactive)
2156   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2157     (if (and inserter (fboundp inserter))
2158         (progn
2159           (mime-edit-insert-tag "message" "rfc822")
2160           (funcall inserter message))
2161       (message "Sorry, I don't have mail inserter for your MUA."))))
2162
2163 (defun mime-edit-inserted-message-filter ()
2164   (save-excursion
2165     (save-restriction
2166       (let ((header-start (point))
2167             (case-fold-search t)
2168             beg end)
2169         ;; for Emacs 18
2170         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2171         (if (re-search-forward "^$" (mark t))
2172             (narrow-to-region header-start (match-beginning 0)))
2173         (goto-char header-start)
2174         (while (and (re-search-forward
2175                      mime-edit-yank-ignored-field-regexp nil t)
2176                     (setq beg (match-beginning 0))
2177                     (setq end (1+ (std11-field-end))))
2178           (delete-region beg end))))))
2179
2180
2181 ;;; @ multipart enclosure
2182 ;;;
2183
2184 (defun mime-edit-enclose-region-internal (type beg end)
2185   (save-excursion
2186     (goto-char beg)
2187     (save-restriction
2188       (narrow-to-region beg end)
2189       (insert (format "--<<%s>>-{\n" type))
2190       (goto-char (point-max))
2191       (insert (format "--}-<<%s>>\n" type))
2192       (goto-char (point-max)))
2193     (or (looking-at mime-edit-beginning-tag-regexp)
2194         (eobp)
2195         (insert (mime-make-text-tag) "\n"))))
2196
2197 (defun mime-edit-enclose-quote-region (beg end)
2198   (interactive "*r")
2199   (mime-edit-enclose-region-internal 'quote beg end))
2200
2201 (defun mime-edit-enclose-mixed-region (beg end)
2202   (interactive "*r")
2203   (mime-edit-enclose-region-internal 'mixed beg end))
2204
2205 (defun mime-edit-enclose-parallel-region (beg end)
2206   (interactive "*r")
2207   (mime-edit-enclose-region-internal 'parallel beg end))
2208
2209 (defun mime-edit-enclose-digest-region (beg end)
2210   (interactive "*r")
2211   (mime-edit-enclose-region-internal 'digest beg end))
2212
2213 (defun mime-edit-enclose-alternative-region (beg end)
2214   (interactive "*r")
2215   (mime-edit-enclose-region-internal 'alternative beg end))
2216
2217 (defun mime-edit-enclose-pgp-signed-region (beg end)
2218   (interactive "*r")
2219   (mime-edit-enclose-region-internal 'pgp-signed beg end))
2220
2221 (defun mime-edit-enclose-pgp-encrypted-region (beg end)
2222   (interactive "*r")
2223   (mime-edit-enclose-region-internal 'pgp-encrypted beg end))
2224
2225 (defun mime-edit-enclose-kazu-signed-region (beg end)
2226   (interactive "*r")
2227   (mime-edit-enclose-region-internal 'kazu-signed beg end))
2228
2229 (defun mime-edit-enclose-kazu-encrypted-region (beg end)
2230   (interactive "*r")
2231   (mime-edit-enclose-region-internal 'kazu-encrypted beg end))
2232
2233 (defun mime-edit-enclose-smime-signed-region (beg end)
2234   (interactive "*r")
2235   (mime-edit-enclose-region-internal 'smime-signed beg end))
2236
2237 (defun mime-edit-enclose-smime-encrypted-region (beg end)
2238   (interactive "*r")
2239   (mime-edit-enclose-region-internal 'smime-encrypted beg end))
2240
2241 (defun mime-edit-insert-key (&optional arg)
2242   "Insert a pgp public key."
2243   (interactive "P")
2244   (mime-edit-insert-tag "application" "pgp-keys")
2245   (mime-edit-define-encoding "7bit")
2246   (pgg-insert-key)
2247   (if (and (not (eobp))
2248            (not (looking-at mime-edit-single-part-tag-regexp)))
2249       (insert (mime-make-text-tag) "\n")))
2250
2251
2252 ;;; @ flag setting
2253 ;;;
2254
2255 (defun mime-edit-set-split (arg)
2256   (interactive
2257    (list
2258     (y-or-n-p "Do you want to enable split? ")))
2259   (setq mime-edit-split-message arg)
2260   (if arg
2261       (message "This message is enabled to split.")
2262     (message "This message is not enabled to split.")))
2263
2264 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2265   "Toggle transfer-level is 7bit or 8bit through.
2266
2267 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2268   (interactive)
2269   (if (numberp transfer-level)
2270       (setq mime-transfer-level transfer-level)
2271     (if (< mime-transfer-level 8)
2272         (setq mime-transfer-level 8)
2273       (setq mime-transfer-level 7)))
2274   (message (format "Current transfer-level is %d bit"
2275                    mime-transfer-level))
2276   (setq mime-transfer-level-string
2277         (mime-encoding-name mime-transfer-level 'not-omit))
2278   (force-mode-line-update))
2279
2280 (defun mime-edit-set-transfer-level-7bit ()
2281   (interactive)
2282   (mime-edit-toggle-transfer-level 7))
2283
2284 (defun mime-edit-set-transfer-level-8bit ()
2285   (interactive)
2286   (mime-edit-toggle-transfer-level 8))
2287
2288
2289 ;;; @ pgp
2290 ;;;
2291
2292 (defvar mime-edit-pgp-processing nil)
2293 (make-variable-buffer-local 'mime-edit-pgp-processing)
2294
2295 (defun mime-edit-set-sign (arg)
2296   (interactive
2297    (list
2298     (y-or-n-p "Do you want to sign? ")))
2299   (if arg
2300       (progn
2301         (or (memq 'sign mime-edit-pgp-processing)
2302             (setq mime-edit-pgp-processing 
2303                   (nconc mime-edit-pgp-processing 
2304                          (copy-sequence '(sign)))))
2305         (message "This message will be signed."))
2306     (setq mime-edit-pgp-processing 
2307           (delq 'sign mime-edit-pgp-processing))
2308     (message "This message will not be signed.")))
2309
2310 (defun mime-edit-set-encrypt (arg)
2311   (interactive
2312    (list
2313     (y-or-n-p "Do you want to encrypt? ")))
2314   (if arg
2315       (progn
2316         (or (memq 'encrypt mime-edit-pgp-processing)
2317             (setq mime-edit-pgp-processing 
2318                   (nconc mime-edit-pgp-processing 
2319                          (copy-sequence '(encrypt)))))
2320         (message "This message will be encrypt."))
2321     (setq mime-edit-pgp-processing
2322           (delq 'encrypt mime-edit-pgp-processing))
2323     (message "This message will not be encrypt.")))
2324
2325 (defun mime-edit-pgp-enclose-buffer ()
2326   (let ((beg (save-excursion
2327                (goto-char (point-min))
2328                (if (search-forward (concat "\n" mail-header-separator "\n"))
2329                    (match-end 0)))))
2330     (if beg
2331         (dolist (pgp-processing mime-edit-pgp-processing)
2332           (case pgp-processing
2333             (sign
2334              (mime-edit-enclose-pgp-signed-region 
2335               beg (point-max)))
2336             (encrypt
2337              (mime-edit-enclose-pgp-encrypted-region 
2338               beg (point-max))))))))
2339
2340
2341 ;;; @ split
2342 ;;;
2343
2344 (defun mime-edit-insert-partial-header (fields subject
2345                                                id number total separator)
2346   (insert fields)
2347   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2348   (insert mime-edit-mime-version-field-for-message/partial)
2349   (insert (format "\
2350 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2351                   id number total separator)))
2352
2353 (defun mime-edit-split-and-send
2354   (&optional cmd lines mime-edit-message-max-length)
2355   (interactive)
2356   (or lines
2357       (setq lines
2358             (count-lines (point-min) (point-max))))
2359   (or mime-edit-message-max-length
2360       (setq mime-edit-message-max-length
2361             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2362                 mime-edit-message-default-max-lines)))
2363   (let* ((mime-edit-draft-file-name
2364           (or (buffer-file-name)
2365               (make-temp-name
2366                (expand-file-name "mime-draft" temporary-file-directory))))
2367          (separator mail-header-separator)
2368          (id (concat "\""
2369                      (replace-space-with-underline (current-time-string))
2370                      "@" (system-name) "\"")))
2371     (run-hooks 'mime-edit-before-split-hook)
2372     (let ((the-buf (current-buffer))
2373           (copy-buf (get-buffer-create " *Original Message*"))
2374           (header (std11-header-string-except
2375                    mime-edit-split-ignored-field-regexp separator))
2376           (subject (mail-fetch-field "subject"))
2377           (total (+ (/ lines mime-edit-message-max-length)
2378                     (if (> (mod lines mime-edit-message-max-length) 0)
2379                         1)))
2380           (command
2381            (or cmd
2382                (cdr
2383                 (assq major-mode
2384                       mime-edit-split-message-sender-alist))
2385                (function
2386                 (lambda ()
2387                   (interactive)
2388                   (error "Split sender is not specified for `%s'." major-mode)))))
2389           (mime-edit-partial-number 1)
2390           data)
2391       (save-excursion
2392         (set-buffer copy-buf)
2393         (erase-buffer)
2394         (insert-buffer the-buf)
2395         (save-restriction
2396           (if (re-search-forward
2397                (concat "^" (regexp-quote separator) "$") nil t)
2398               (let ((he (match-beginning 0)))
2399                 (replace-match "")
2400                 (narrow-to-region (point-min) he)))
2401           (goto-char (point-min))
2402           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2403             (delete-region (match-beginning 0)
2404                            (1+ (std11-field-end))))))
2405       (while (< mime-edit-partial-number total)
2406         (erase-buffer)
2407         (save-excursion
2408           (set-buffer copy-buf)
2409           (setq data (buffer-substring
2410                       (point-min)
2411                       (progn
2412                         (goto-line mime-edit-message-max-length)
2413                         (point))))
2414           (delete-region (point-min)(point)))
2415         (mime-edit-insert-partial-header
2416          header subject id mime-edit-partial-number total separator)
2417         (insert data)
2418         (save-excursion
2419           (message (format "Sending %d/%d..."
2420                            mime-edit-partial-number total))
2421           (call-interactively command)
2422           (message (format "Sending %d/%d... done"
2423                            mime-edit-partial-number total)))
2424         (setq mime-edit-partial-number
2425               (1+ mime-edit-partial-number)))
2426       (erase-buffer)
2427       (save-excursion
2428         (set-buffer copy-buf)
2429         (setq data (buffer-string))
2430         (erase-buffer))
2431       (mime-edit-insert-partial-header
2432        header subject id mime-edit-partial-number total separator)
2433       (insert data)
2434       (save-excursion
2435         (message (format "Sending %d/%d..."
2436                          mime-edit-partial-number total))
2437         (message (format "Sending %d/%d... done"
2438                          mime-edit-partial-number total))))))
2439
2440 (defun mime-edit-maybe-split-and-send (&optional cmd)
2441   (interactive)
2442   (run-hooks 'mime-edit-before-send-hook)
2443   (let ((mime-edit-message-max-length
2444          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2445              mime-edit-message-default-max-lines))
2446         (lines (count-lines (point-min) (point-max))))
2447     (if (and (> lines mime-edit-message-max-length)
2448              mime-edit-split-message)
2449         (mime-edit-split-and-send cmd lines mime-edit-message-max-length))))
2450
2451
2452 ;;; @ preview message
2453 ;;;
2454
2455 (defvar mime-edit-buffer nil) ; buffer local variable
2456
2457 (defun mime-edit-preview-message ()
2458   "preview editing MIME message."
2459   (interactive)
2460   (let* ((str (buffer-string))
2461          (separator mail-header-separator)
2462          (the-buf (current-buffer))
2463          (buf-name (buffer-name))
2464          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2465          (buf (get-buffer temp-buf-name))
2466          (pgp-processing mime-edit-pgp-processing))
2467     (if buf
2468         (progn
2469           (switch-to-buffer buf)
2470           (erase-buffer))
2471       (setq buf (get-buffer-create temp-buf-name))
2472       (switch-to-buffer buf))
2473     (insert str)
2474     (setq major-mode 'mime-temp-message-mode)
2475     (make-local-variable 'mail-header-separator)
2476     (setq mail-header-separator separator)
2477     (make-local-variable 'mime-edit-buffer)
2478     (setq mime-edit-buffer the-buf)
2479     (setq mime-edit-pgp-processing pgp-processing)
2480
2481     (run-hooks 'mime-edit-translate-hook)
2482     (mime-edit-translate-buffer)
2483     (goto-char (point-min))
2484     (if (re-search-forward
2485          (concat "^" (regexp-quote separator) "$"))
2486         (replace-match ""))
2487     (mime-view-buffer)
2488     (make-local-variable 'mime-edit-temp-message-buffer)
2489     (setq mime-edit-temp-message-buffer buf)))
2490
2491 (defun mime-edit-quitting-method ()
2492   "Quitting method for mime-view."
2493   (let* ((temp mime-edit-temp-message-buffer)
2494          buf)
2495     (mime-preview-kill-buffer)
2496     (set-buffer temp)
2497     (setq buf mime-edit-buffer)
2498     (kill-buffer temp)
2499     (switch-to-buffer buf)))
2500
2501 (set-alist 'mime-preview-quitting-method-alist
2502            'mime-temp-message-mode
2503            #'mime-edit-quitting-method)
2504
2505
2506 ;;; @ edit again
2507 ;;;
2508
2509 (defvar mime-edit-again-ignored-field-regexp
2510   (concat "^\\(" "Content-.*\\|Mime-Version"
2511           (if mime-edit-insert-user-agent-field "\\|User-Agent")
2512           "\\):")
2513   "Regexp for deleted header fields when `mime-edit-again' is called.")
2514
2515 (defsubst eliminate-top-spaces (string)
2516   "Eliminate top sequence of space or tab in STRING."
2517   (if (string-match "^[ \t]+" string)
2518       (substring string (match-end 0))
2519     string))
2520
2521 (defun mime-edit-decode-multipart-in-buffer (content-type not-decode-text)
2522   (let* ((subtype
2523           (or
2524            (cdr (assoc (mime-content-type-parameter content-type "protocol")
2525                        '(("application/pgp-encrypted" . pgp-encrypted)
2526                          ("application/pgp-signature" . pgp-signed))))
2527            (mime-content-type-subtype content-type)))
2528          (boundary (mime-content-type-parameter content-type "boundary"))
2529          (boundary-pat (concat "\n--" (regexp-quote boundary) "[ \t]*\n")))
2530     (re-search-forward boundary-pat nil t)
2531     (let ((bb (match-beginning 0)) eb tag)
2532       (setq tag (format "\n--<<%s>>-{\n" subtype))
2533       (goto-char bb)
2534       (insert tag)
2535       (setq bb (+ bb (length tag)))
2536       (re-search-forward
2537        (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2538        nil t)
2539       (setq eb (match-beginning 0))
2540       (replace-match (format "--}-<<%s>>\n" subtype))
2541       (save-restriction
2542         (narrow-to-region bb eb)
2543         (goto-char (point-min))
2544         (while (re-search-forward boundary-pat nil t)
2545           (let ((beg (match-beginning 0))
2546                 end)
2547             (delete-region beg (match-end 0))
2548             (save-excursion
2549               (if (re-search-forward boundary-pat nil t)
2550                   (setq end (match-beginning 0))
2551                 (setq end (point-max)))
2552               (save-restriction
2553                 (narrow-to-region beg end)
2554                 (cond
2555                  ((eq subtype 'pgp-encrypted)
2556                   (when (and
2557                          (progn
2558                            (goto-char (point-min))
2559                            (re-search-forward "^-+BEGIN PGP MESSAGE-+$"
2560                                               nil t))
2561                          (prog1 
2562                              (save-window-excursion
2563                                (pgg-decrypt-region (match-beginning 0)
2564                                                    (point-max)))
2565                            (delete-region (point-min)(point-max))))
2566                     (insert-buffer-substring pgg-output-buffer)
2567                     (mime-edit-decode-message-in-buffer 
2568                      nil not-decode-text)
2569                     (delete-region (goto-char (point-min))
2570                                    (if (search-forward "\n\n" nil t)
2571                                        (match-end 0)
2572                                      (point-min)))
2573                     (goto-char (point-max))))
2574                  (t 
2575                   (mime-edit-decode-message-in-buffer
2576                    (if (eq subtype 'digest)
2577                        (eval-when-compile
2578                          (make-mime-content-type 'message 'rfc822)))
2579                    not-decode-text)
2580                   (goto-char (point-max))))))))))
2581     (goto-char (point-min))
2582     (or (= (point-min) 1)
2583         (delete-region (point-min)
2584                        (if (search-forward "\n\n" nil t)
2585                            (match-end 0)
2586                          (point-min))))))
2587
2588 (defun mime-edit-decode-single-part-in-buffer
2589   (content-type not-decode-text &optional content-disposition)
2590   (let* ((type (mime-content-type-primary-type content-type))
2591          (subtype (mime-content-type-subtype content-type))
2592          (ctype (format "%s/%s" type subtype))
2593          charset
2594          (pstr (let ((bytes (+ 14 (length ctype))))
2595                  (mapconcat (function
2596                              (lambda (attr)
2597                                (if (string= (car attr) "charset")
2598                                    (progn
2599                                      (setq charset (cdr attr))
2600                                      "")
2601                                  (let* ((str (concat (car attr)
2602                                                      "=" (cdr attr)))
2603                                         (bs (length str)))
2604                                    (setq bytes (+ bytes bs 2))
2605                                    (if (< bytes 76)
2606                                        (concat "; " str)
2607                                      (setq bytes (+ bs 1))
2608                                      (concat ";\n " str)
2609                                      )))))
2610                             (mime-content-type-parameters content-type) "")))
2611          encoding
2612          encoded
2613          (limit (save-excursion
2614                   (if (search-forward "\n\n" nil t)
2615                       (1- (point)))))
2616          (disposition-type
2617           (mime-content-disposition-type content-disposition))
2618          (disposition-str
2619           (if disposition-type
2620               (let ((bytes (+ 21 (length (format "%s" disposition-type)))))
2621                 (mapconcat (function
2622                             (lambda (attr)
2623                               (let* ((str (concat
2624                                            (car attr)
2625                                            "="
2626                                            (if (string-equal "filename"
2627                                                              (car attr))
2628                                                (std11-wrap-as-quoted-string
2629                                                 (cdr attr))
2630                                              (cdr attr))))
2631                                      (bs (length str)))
2632                                 (setq bytes (+ bytes bs 2))
2633                                 (if (< bytes 76)
2634                                     (concat "; " str)
2635                                   (setq bytes (+ bs 1))
2636                                   (concat ";\n " str)
2637                                   ))))
2638                            (mime-content-disposition-parameters
2639                             content-disposition)
2640                            "")))))
2641     (if disposition-type
2642         (setq pstr (format "%s\nContent-Disposition: %s%s"
2643                            pstr disposition-type disposition-str)))
2644     (save-excursion
2645       (if (re-search-forward
2646            "^Content-Transfer-Encoding:" limit t)
2647           (let ((beg (match-beginning 0))
2648                 (hbeg (match-end 0))
2649                 (end (std11-field-end limit)))
2650             (setq encoding
2651                   (downcase
2652                    (eliminate-top-spaces
2653                     (std11-unfold-string
2654                      (buffer-substring hbeg end)))))
2655             (if (or charset (eq type 'text))
2656                 (progn
2657                   (delete-region beg (1+ end))
2658                   (goto-char (point-min))
2659                   (if (search-forward "\n\n" nil t)
2660                       (progn
2661                         (mime-decode-region
2662                          (match-end 0)(point-max) encoding)
2663                         (setq encoded t
2664                               encoding nil))))))))
2665     (if (or encoded (not not-decode-text))
2666         (progn
2667           (save-excursion
2668             (goto-char (point-min))
2669             (while (re-search-forward "\r\n" nil t)
2670               (replace-match "\n")))
2671           (decode-mime-charset-region (point-min)(point-max)
2672                                       (or charset default-mime-charset))))
2673     (let ((he (if (re-search-forward "^$" nil t)
2674                   (match-end 0)
2675                 (point-min))))
2676       (if (and (eq type 'text)
2677                (eq subtype 'x-rot13-47-48))
2678           (mule-caesar-region he (point-max)))
2679       (if (= (point-min) 1)
2680           (progn
2681             (goto-char he)
2682             (insert
2683              (concat "\n"
2684                      (mime-create-tag
2685                       (format "%s/%s%s" type subtype pstr)
2686                       encoding))))
2687         (delete-region (point-min) he)
2688         (insert
2689          (mime-create-tag (format "%s/%s%s" type subtype pstr)
2690                           encoding))))))
2691
2692 ;;;###autoload
2693 (defun mime-edit-decode-message-in-buffer (&optional default-content-type
2694                                                      not-decode-text)
2695   (save-excursion
2696     (goto-char (point-min))
2697     (let ((ctl (or (mime-read-Content-Type)
2698                    default-content-type)))
2699       (if ctl
2700           (let ((type (mime-content-type-primary-type ctl)))
2701             (cond
2702              ((and (eq type 'application)
2703                    (eq (mime-content-type-subtype ctl) 'pgp-signature))
2704               (delete-region (point-min)(point-max)))
2705              ((eq type 'multipart)
2706               (mime-edit-decode-multipart-in-buffer ctl not-decode-text))
2707              (t
2708               (mime-edit-decode-single-part-in-buffer
2709                ctl not-decode-text (mime-read-Content-Disposition)))))
2710         (or not-decode-text
2711             (decode-mime-charset-region (point-min) (point-max)
2712                                         default-mime-charset)))
2713       (if (= (point-min) 1)
2714           (progn
2715             (save-restriction
2716               (std11-narrow-to-header)
2717               (goto-char (point-min))
2718               (while (re-search-forward
2719                       mime-edit-again-ignored-field-regexp nil t)
2720                 (delete-region (match-beginning 0) (1+ (std11-field-end)))))
2721             (mime-decode-header-in-buffer (not not-decode-text)))))))
2722
2723 ;;;###autoload
2724 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2725   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2726 Content-Type and Content-Transfer-Encoding header fields will be
2727 converted to MIME-Edit tags."
2728   (interactive)
2729   (goto-char (point-min))
2730   (if (search-forward
2731        (concat "\n" (regexp-quote mail-header-separator) "\n")
2732        nil t)
2733       (replace-match "\n\n"))
2734   (mime-edit-decode-message-in-buffer nil not-decode-text)
2735   (goto-char (point-min))
2736   (or no-separator
2737       (and (re-search-forward "^$")
2738            (replace-match mail-header-separator)))
2739   (or not-turn-on
2740       (turn-on-mime-edit)))
2741
2742
2743 ;;; @ end
2744 ;;;
2745
2746 (provide 'mime-edit)
2747
2748 (run-hooks 'mime-edit-load-hook)
2749
2750 ;;; mime-edit.el ends here