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