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