Don't resolve user-id.
[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     (while (setq index (string-match "\n" string index))
1878       (setq string (replace-match "\r\n" nil nil string)
1879             index (+ index 2)))         ;(length "\r\n")
1880     string))
1881       
1882 (defun mime-edit-sign-smime (beg end boundary)
1883   (save-excursion
1884     (save-restriction
1885       (let* ((from (std11-field-body "From" mail-header-separator))
1886              (ret (progn 
1887                     (narrow-to-region beg end)
1888                     (mime-edit-translate-region beg end boundary)))
1889              (ctype    (car ret))
1890              (encoding (nth 1 ret))
1891              (smime-boundary (concat "smime-sign-" boundary))
1892              (context (epg-make-context 'CMS))
1893              signature micalg)
1894         (goto-char beg)
1895         (insert (format "Content-Type: %s\n" ctype))
1896         (if encoding
1897             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1898         (insert "\n")
1899         (epg-context-set-signers
1900          context
1901          (epa-select-keys
1902           context
1903           "\
1904 Select keys for signing.
1905 If no one is selected, default secret key is used.  "
1906           (if from 
1907               (list (nth 1 (std11-extract-address-components from))))
1908           t))
1909         (condition-case error
1910             (setq signature
1911                   (epg-sign-string context
1912                                    (mime-edit-convert-lbt-string
1913                                     (buffer-substring (point-min) (point-max)))
1914                                    'detached))
1915           (error (signal 'mime-edit-error (cdr error))))
1916         (setq micalg (cdr (assq 'digest-algorithm
1917                                 (car (epg-context-result-for context 'sign)))))
1918         (goto-char beg)
1919         (insert (format "--[[multipart/signed;
1920  boundary=\"%s\"%s;
1921  protocol=\"application/pkcs7-signature\"][7bit]]
1922 --%s
1923 "
1924                         smime-boundary
1925                         (if micalg
1926                             (concat "; micalg="
1927                                     (downcase
1928                                      (cdr (assq micalg
1929                                                 epg-digest-algorithm-alist))))
1930                           "")
1931                         smime-boundary))
1932         (goto-char (point-max))
1933         (insert (format "\n--%s
1934 Content-Type: application/pkcs7-signature; name=smime.p7s
1935 Content-Transfer-Encoding: base64
1936 Content-Disposition: attachment; filename=smime.p7s
1937 Content-Description: S/MIME Digital Signature
1938
1939 " smime-boundary)
1940                 (base64-encode-string signature))))))
1941
1942 (defun mime-edit-encrypt-smime (beg end boundary)
1943   (save-excursion
1944     (save-restriction
1945       (let (recipients header)
1946         (let ((ret (mime-edit-make-encrypt-recipient-header)))
1947           (setq recipients (aref ret 1)
1948                 header (aref ret 2)))
1949         (narrow-to-region beg end)
1950         (let* ((ret
1951                 (mime-edit-translate-region beg end boundary))
1952                (ctype    (car ret))
1953                (encoding (nth 1 ret))
1954                (context (epg-make-context 'CMS))
1955                cipher)
1956           (goto-char beg)
1957           (insert header)
1958           (insert (format "Content-Type: %s\n" ctype))
1959           (if encoding
1960               (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1961           (insert "\n")
1962           (mime-encode-header-in-buffer)
1963           (condition-case error
1964               (setq cipher
1965                     (epg-encrypt-string
1966                      context
1967                      (buffer-substring (point-min) (point-max))
1968                      (epa-select-keys
1969                       context
1970                       "\
1971 Select recipents for encryption.
1972 If no one is selected, symmetric encryption will be performed.  "
1973                       (mapcar (lambda (recipient)
1974                                 (nth 1 (std11-extract-address-components
1975                                         recipient)))
1976                               (split-string recipients 
1977                                             "\\([ \t\n]*,[ \t\n]*\\)+")))))
1978             (error (signal 'mime-edit-error (cdr error))))
1979           (delete-region (point-min)(point-max))
1980           (goto-char beg)
1981           (insert (format "--[[application/pkcs7-mime;
1982  smime-type=enveloped-data;
1983  name=smime.p7m
1984 Content-Disposition: attachment; filename=smime.p7m][base64]]
1985
1986 ")
1987                   (base64-encode-string cipher)))))))
1988
1989 (defsubst replace-space-with-underline (str)
1990   (mapconcat (function
1991               (lambda (arg)
1992                 (char-to-string
1993                  (if (eq arg ?\ )
1994                      ?_
1995                    arg)))) str ""))
1996
1997 (defun mime-edit-make-boundary ()
1998   (concat mime-multipart-boundary "_"
1999           (replace-space-with-underline (current-time-string))))
2000
2001 (defun mime-edit-translate-body ()
2002   "Encode the tagged MIME body in current buffer in MIME compliant message."
2003   (interactive)
2004   (save-excursion
2005     (let ((boundary (mime-edit-make-boundary))
2006           (i 1)
2007           ret)
2008       (while (mime-edit-process-multipart-1
2009               (format "%s-%d" boundary i))
2010         (setq i (1+ i)))
2011       (save-restriction
2012         ;; We are interested in message body.
2013         (let* ((beg
2014                 (progn
2015                   (goto-char (point-min))
2016                   (re-search-forward
2017                    (concat "\n" (regexp-quote mail-header-separator)
2018                            (if mime-ignore-preceding-spaces
2019                                "[ \t\n]*\n" "\n")) nil 'move)
2020                   (point)))
2021                (end
2022                 (progn
2023                   (goto-char (point-max))
2024                   (and mime-ignore-trailing-spaces
2025                        (re-search-backward "[^ \t\n]\n" beg t)
2026                        (forward-char 1))
2027                   (point))))
2028           (setq ret (mime-edit-translate-region
2029                      beg end
2030                      (format "%s-%d" boundary i)))))
2031       (mime-edit-dequote-region (point-min)(point-max))
2032       (let ((contype (car ret))         ;Content-Type
2033             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
2034             )
2035         ;; Insert User-Agent field
2036         (and mime-edit-insert-user-agent-field
2037              (or (mail-position-on-field "User-Agent")
2038                  (insert mime-edit-user-agent-value)))
2039         ;; Make primary MIME headers.
2040         (or (mail-position-on-field "MIME-Version")
2041             (insert mime-edit-mime-version-value))
2042         ;; Remove old Content-Type and other fields.
2043         (save-restriction
2044           (goto-char (point-min))
2045           (search-forward (concat "\n" mail-header-separator "\n") nil t)
2046           (narrow-to-region (point-min) (point))
2047           (goto-char (point-min))
2048           (mime-delete-field "Content-Type")
2049           (mime-delete-field "Content-Transfer-Encoding"))
2050         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
2051         (mail-position-on-field "Content-Type")
2052         (insert contype)
2053         (if encoding
2054             (progn
2055               (mail-position-on-field "Content-Transfer-Encoding")
2056               (insert encoding)))))))
2057
2058 (defun mime-edit-translate-single-part-tag (boundary &optional prefix)
2059   "Translate single-part-tag to MIME header."
2060   (if (re-search-forward mime-edit-single-part-tag-regexp nil t)
2061       (let* ((beg (match-beginning 0))
2062              (end (match-end 0))
2063              (tag (buffer-substring beg end)))
2064         (delete-region beg end)
2065         (let ((contype (mime-edit-get-contype tag))
2066               (encoding (mime-edit-get-encoding tag)))
2067           (insert (concat prefix "--" boundary "\n"))
2068           (save-restriction
2069             (narrow-to-region (point)(point))
2070             (insert "Content-Type: " contype "\n")
2071             (if encoding
2072                 (insert "Content-Transfer-Encoding: " encoding "\n"))
2073             (mime-encode-header-in-buffer))
2074           (cons (and contype
2075                      (downcase contype))
2076                 (and encoding
2077                      (downcase encoding)))))))
2078
2079 (defun mime-edit-translate-region (beg end &optional boundary multipart)
2080   (or boundary
2081       (setq boundary (mime-edit-make-boundary)))
2082   (save-excursion
2083     (save-restriction
2084       (narrow-to-region beg end)
2085       (let ((tag nil)                   ;MIME tag
2086             (contype nil)               ;Content-Type
2087             (encoding nil)              ;Content-Transfer-Encoding
2088             (nparts 0))                 ;Number of body parts
2089         ;; Normalize the body part by inserting appropriate message
2090         ;; tags for every message contents.
2091         (mime-edit-normalize-body)
2092         ;; Counting the number of Content-Type.
2093         (goto-char (point-min))
2094         (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
2095           (setq nparts (1+ nparts)))
2096         ;; Begin translation.
2097         (cond
2098          ((and (<= nparts 1)(not multipart))
2099           ;; It's a singular message.
2100           (goto-char (point-min))
2101           (while (re-search-forward
2102                   mime-edit-single-part-tag-regexp nil t)
2103             (setq tag
2104                   (buffer-substring (match-beginning 0) (match-end 0)))
2105             (delete-region (match-beginning 0) (1+ (match-end 0)))
2106             (setq contype (mime-edit-get-contype tag))
2107             (setq encoding (mime-edit-get-encoding tag))))
2108          (t
2109           ;; It's a multipart message.
2110           (goto-char (point-min))
2111           (let ((prio mime-content-transfer-encoding-priority-list)
2112                 part-info nprio)
2113             (when (setq part-info
2114                         (mime-edit-translate-single-part-tag boundary))
2115               (and (setq nprio (member (cdr part-info) prio))
2116                    (setq prio nprio))
2117               (while (setq part-info
2118                            (mime-edit-translate-single-part-tag boundary "\n"))
2119                 (and (setq nprio (member (cdr part-info) prio))
2120                      (setq prio nprio))))
2121             ;; Define Content-Type as "multipart/mixed".
2122             (setq contype
2123                   (concat "multipart/mixed;\n boundary=\"" boundary "\""))
2124             (setq encoding (car prio))
2125             ;; Insert the trailer.
2126             (goto-char (point-max))
2127             (insert "\n--" boundary "--\n"))))
2128          (list contype encoding boundary nparts)))))
2129
2130 (defun mime-edit-normalize-body ()
2131   "Normalize the body part by inserting appropriate message tags."
2132   ;; Insert the first MIME tags if necessary.
2133   (goto-char (point-min))
2134   (if (not (looking-at mime-edit-single-part-tag-regexp))
2135       (insert (mime-make-text-tag) "\n"))
2136   ;; Check each tag, and add new tag or correct it if necessary.
2137   (goto-char (point-min))
2138   (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
2139     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
2140            (contype (mime-edit-get-contype tag))
2141            (charset (mime-get-parameter contype "charset"))
2142            (encoding (mime-edit-get-encoding tag)))
2143       ;; Remove extra whitespaces after the tag.
2144       (if (looking-at "[ \t]+$")
2145           (delete-region (match-beginning 0) (match-end 0)))
2146       (let ((beg (point))
2147             (end (mime-edit-content-end)))
2148         (if (= end (point-max))
2149             nil
2150           (goto-char end)
2151           (or (looking-at mime-edit-beginning-tag-regexp)
2152               (eobp)
2153               (insert (mime-make-text-tag) "\n")))
2154         (remove-text-properties beg end '(invisible mime-edit-invisible))
2155         (goto-char beg))
2156       (cond
2157        ((mime-test-content-type contype "message")
2158         ;; Content-type "message" should be sent as is.
2159         (forward-line 1))
2160        ((mime-test-content-type contype "text")
2161         ;; Define charset for text if necessary.
2162         (setq charset (if charset
2163                           (intern (downcase charset))
2164                         (mime-edit-choose-charset)))
2165         (mime-edit-define-charset charset)
2166         (cond ((string-equal contype "text/x-rot13-47-48")
2167                (save-excursion
2168                  (forward-line)
2169                  (mule-caesar-region (point) (mime-edit-content-end))))
2170               ((string-equal contype "text/enriched")
2171                (save-excursion
2172                  (let ((beg (progn
2173                               (forward-line)
2174                               (point)))
2175                        (end (mime-edit-content-end)))
2176                    ;; Patch for hard newlines
2177                    ;; (save-excursion
2178                    ;;   (goto-char beg)
2179                    ;;   (while (search-forward "\n" end t)
2180                    ;;     (put-text-property (match-beginning 0)
2181                    ;;                        (point)
2182                    ;;                        'hard t)))
2183                    ;; End patch for hard newlines
2184                    (enriched-encode beg end nil)
2185                    (goto-char beg)
2186                    (if (search-forward "\n\n")
2187                        (delete-region beg (match-end 0)))))))
2188         ;; Point is now on current tag.
2189         ;; Define encoding and encode text if necessary.
2190         (or encoding    ;Encoding is not specified.
2191             (let* ((encoding
2192                     (let (bits conv)
2193                       (let ((ret (cdr (assq charset mime-charset-type-list))))
2194                         (if ret
2195                             (setq bits (car ret)
2196                                   conv (nth 1 ret))
2197                           (setq bits 8
2198                                 conv "quoted-printable")))
2199                       (if (<= bits mime-transfer-level)
2200                           (mime-encoding-name bits)
2201                         conv)))
2202                    (beg (mime-edit-content-beginning)))
2203               (encode-mime-charset-region beg (mime-edit-content-end)
2204                                           charset)
2205               ;; Protect "From " in beginning of line
2206               (save-restriction
2207                 (narrow-to-region beg (mime-edit-content-end))
2208                 (goto-char beg)
2209                 (let (case-fold-search)
2210                   (if (re-search-forward "^From " nil t)
2211                       (unless encoding
2212                         (if (memq charset '(iso-2022-jp
2213                                             iso-2022-jp-2
2214                                             iso-2022-int-1
2215                                             x-ctext))
2216                             (while (progn
2217                                      (replace-match "\e(BFrom ")
2218                                      (re-search-forward "^From " nil t)))
2219                           (setq encoding "quoted-printable"))))))
2220               ;; canonicalize line break code
2221               (or (member encoding '(nil "7bit" "8bit" "quoted-printable"))
2222                   (save-restriction
2223                     (narrow-to-region beg (mime-edit-content-end))
2224                     (goto-char beg)
2225                     (while (re-search-forward "\\(\\=\\|[^\r]\\)\n" nil t)
2226                       ;; In a certain period, `replace-match' with "\\N"
2227                       ;; converted 8-bit characters into multibyte string,
2228                       ;; but it has been fixed at 2004-01-15.
2229                       ;;(replace-match "\\1\r\n"))))
2230                       (backward-char 1)
2231                       (insert "\r")
2232                       (forward-char 1))))
2233               (goto-char beg)
2234               (mime-encode-region beg (mime-edit-content-end)
2235                                   (or encoding "7bit"))
2236               (mime-edit-define-encoding encoding)))
2237         (goto-char (mime-edit-content-end)))
2238        ((null encoding)         ;Encoding is not specified.
2239         ;; Application, image, audio, video, and any other
2240         ;; unknown content-type without encoding should be
2241         ;; encoded.
2242         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2243                (beg (mime-edit-content-beginning))
2244                (end (mime-edit-content-end)))
2245           (mime-encode-region beg end encoding)
2246           (mime-edit-define-encoding encoding))
2247         (forward-line 1))))))
2248
2249 (defun mime-delete-field (field)
2250   "Delete header FIELD."
2251   (let ((regexp (format "^%s:[ \t]*" field)))
2252     (goto-char (point-min))
2253     (while (re-search-forward regexp nil t)
2254       (delete-region (match-beginning 0)
2255                      (1+ (std11-field-end))))))
2256
2257 \f
2258 ;;;
2259 ;;; Platform dependent functions
2260 ;;;
2261
2262 ;; Sun implementations
2263
2264 (defun mime-edit-voice-recorder-for-sun (encoding)
2265   "Record voice in a buffer using Sun audio device,
2266 and insert data encoded as ENCODING."
2267   (message "Start the recording on %s.  Type C-g to finish the recording..."
2268            (system-name))
2269   (mime-insert-encoded-file "/dev/audio" encoding))
2270
2271 \f
2272 ;;; @ Other useful commands.
2273 ;;;
2274
2275 ;; Message forwarding commands as content-type "message/rfc822".
2276
2277 (defun mime-edit-insert-message (&optional message)
2278   (interactive)
2279   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2280     (if (and inserter (fboundp inserter))
2281         (progn
2282           (mime-edit-insert-tag "message" "rfc822")
2283           (funcall inserter message))
2284       (message "Sorry, I don't have message inserter for your MUA."))))
2285
2286 (defun mime-edit-insert-mail (&optional message)
2287   (interactive)
2288   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2289     (if (and inserter (fboundp inserter))
2290         (progn
2291           (mime-edit-insert-tag "message" "rfc822")
2292           (funcall inserter message))
2293       (message "Sorry, I don't have mail inserter for your MUA."))))
2294
2295 (defun mime-edit-inserted-message-filter ()
2296   (save-excursion
2297     (save-restriction
2298       (let ((header-start (point))
2299             (case-fold-search t)
2300             beg end)
2301         ;; for Emacs 18
2302         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2303         (if (re-search-forward "^$" (mark t))
2304             (narrow-to-region header-start (match-beginning 0)))
2305         (goto-char header-start)
2306         (while (and (re-search-forward
2307                      mime-edit-yank-ignored-field-regexp nil t)
2308                     (setq beg (match-beginning 0))
2309                     (setq end (1+ (std11-field-end))))
2310           (delete-region beg end))))))
2311
2312
2313 ;;; @ multipart enclosure
2314 ;;;
2315
2316 (defun mime-edit-enclose-region-internal (type beg end)
2317   (save-excursion
2318     (goto-char beg)
2319     (save-restriction
2320       (narrow-to-region beg end)
2321       (insert (format "--<<%s>>-{\n" type))
2322       (goto-char (point-max))
2323       (insert (format "--}-<<%s>>\n" type))
2324       (goto-char (point-max)))
2325     (or (looking-at mime-edit-beginning-tag-regexp)
2326         (eobp)
2327         (insert (mime-make-text-tag) "\n"))))
2328
2329 (defun mime-edit-enclose-quote-region (beg end)
2330   (interactive "*r")
2331   (mime-edit-enclose-region-internal 'quote beg end))
2332
2333 (defun mime-edit-enclose-mixed-region (beg end)
2334   (interactive "*r")
2335   (mime-edit-enclose-region-internal 'mixed beg end))
2336
2337 (defun mime-edit-enclose-parallel-region (beg end)
2338   (interactive "*r")
2339   (mime-edit-enclose-region-internal 'parallel beg end))
2340
2341 (defun mime-edit-enclose-digest-region (beg end)
2342   (interactive "*r")
2343   (mime-edit-enclose-region-internal 'digest beg end))
2344
2345 (defun mime-edit-enclose-alternative-region (beg end)
2346   (interactive "*r")
2347   (mime-edit-enclose-region-internal 'alternative beg end))
2348
2349 (defun mime-edit-enclose-pgp-signed-region (beg end)
2350   (interactive "*r")
2351   (mime-edit-enclose-region-internal 'pgp-signed beg end))
2352
2353 (defun mime-edit-enclose-pgp-encrypted-region (beg end)
2354   (interactive "*r")
2355   (mime-edit-enclose-region-internal 'pgp-encrypted beg end))
2356
2357 (defun mime-edit-enclose-kazu-signed-region (beg end)
2358   (interactive "*r")
2359   (mime-edit-enclose-region-internal 'kazu-signed beg end))
2360
2361 (defun mime-edit-enclose-kazu-encrypted-region (beg end)
2362   (interactive "*r")
2363   (mime-edit-enclose-region-internal 'kazu-encrypted beg end))
2364
2365 (defun mime-edit-enclose-smime-signed-region (beg end)
2366   (interactive "*r")
2367   (mime-edit-enclose-region-internal 'smime-signed beg end))
2368
2369 (defun mime-edit-enclose-smime-encrypted-region (beg end)
2370   (interactive "*r")
2371   (mime-edit-enclose-region-internal 'smime-encrypted beg end))
2372
2373 (defun mime-edit-insert-key (&optional arg)
2374   "Insert a pgp public key."
2375   (interactive "P")
2376   (mime-edit-insert-tag "application" "pgp-keys")
2377   (mime-edit-define-encoding "7bit")
2378   (let ((context (epg-make-context)))
2379     (epg-context-set-armor context t)
2380     (epg-export-keys-to-string context
2381                                (epa-select-keys context
2382                                                 "Select keys for export.  ")))
2383   (if (and (not (eobp))
2384            (not (looking-at mime-edit-single-part-tag-regexp)))
2385       (insert (mime-make-text-tag) "\n")))
2386
2387
2388 ;;; @ flag setting
2389 ;;;
2390
2391 (defun mime-edit-set-split (arg)
2392   (interactive
2393    (list
2394     (y-or-n-p "Do you want to enable split? ")))
2395   (setq mime-edit-split-message arg)
2396   (if arg
2397       (message "This message is enabled to split.")
2398     (message "This message is not enabled to split.")))
2399
2400 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2401   "Toggle transfer-level is 7bit or 8bit through.
2402
2403 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2404   (interactive)
2405   (if (numberp transfer-level)
2406       (setq mime-transfer-level transfer-level)
2407     (if (< mime-transfer-level 8)
2408         (setq mime-transfer-level 8)
2409       (setq mime-transfer-level 7)))
2410   (message (format "Current transfer-level is %d bit"
2411                    mime-transfer-level))
2412   (setq mime-transfer-level-string
2413         (mime-encoding-name mime-transfer-level 'not-omit))
2414   (force-mode-line-update))
2415
2416 (defun mime-edit-set-transfer-level-7bit ()
2417   (interactive)
2418   (mime-edit-toggle-transfer-level 7))
2419
2420 (defun mime-edit-set-transfer-level-8bit ()
2421   (interactive)
2422   (mime-edit-toggle-transfer-level 8))
2423
2424
2425 ;;; @ pgp
2426 ;;;
2427
2428 (defvar mime-edit-pgp-processing nil)
2429 (make-variable-buffer-local 'mime-edit-pgp-processing)
2430
2431 (defun mime-edit-set-sign (arg)
2432   (interactive
2433    (list
2434     (y-or-n-p "Do you want to sign? ")))
2435   (if arg
2436       (progn
2437         (or (memq 'sign mime-edit-pgp-processing)
2438             (setq mime-edit-pgp-processing 
2439                   (nconc mime-edit-pgp-processing 
2440                          (copy-sequence '(sign)))))
2441         (message "This message will be signed."))
2442     (setq mime-edit-pgp-processing 
2443           (delq 'sign mime-edit-pgp-processing))
2444     (message "This message will not be signed.")))
2445
2446 (defun mime-edit-set-encrypt (arg)
2447   (interactive
2448    (list
2449     (y-or-n-p "Do you want to encrypt? ")))
2450   (if arg
2451       (progn
2452         (or (memq 'encrypt mime-edit-pgp-processing)
2453             (setq mime-edit-pgp-processing 
2454                   (nconc mime-edit-pgp-processing 
2455                          (copy-sequence '(encrypt)))))
2456         (message "This message will be encrypt."))
2457     (setq mime-edit-pgp-processing
2458           (delq 'encrypt mime-edit-pgp-processing))
2459     (message "This message will not be encrypt.")))
2460
2461 (defun mime-edit-pgp-enclose-buffer ()
2462   (let ((beg (save-excursion
2463                (goto-char (point-min))
2464                (if (search-forward (concat "\n" mail-header-separator "\n"))
2465                    (match-end 0)))))
2466     (if beg
2467         (dolist (pgp-processing mime-edit-pgp-processing)
2468           (case pgp-processing
2469             (sign
2470              (mime-edit-enclose-pgp-signed-region 
2471               beg (point-max)))
2472             (encrypt
2473              (mime-edit-enclose-pgp-encrypted-region 
2474               beg (point-max))))))))
2475
2476
2477 ;;; @ split
2478 ;;;
2479
2480 (defun mime-edit-insert-partial-header (fields subject
2481                                                id number total separator)
2482   (insert fields)
2483   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2484   (insert mime-edit-mime-version-field-for-message/partial)
2485   (insert (format "\
2486 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2487                   id number total separator)))
2488
2489 (defun mime-edit-split-and-send
2490   (&optional cmd lines mime-edit-message-max-length)
2491   (interactive)
2492   (or lines
2493       (setq lines
2494             (count-lines (point-min) (point-max))))
2495   (or mime-edit-message-max-length
2496       (setq mime-edit-message-max-length
2497             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2498                 mime-edit-message-default-max-lines)))
2499   (let ((separator mail-header-separator)
2500         (id (concat "\""
2501                     (replace-space-with-underline (current-time-string))
2502                     "@" (system-name) "\"")))
2503     (run-hooks 'mime-edit-before-split-hook)
2504     (let ((the-buf (current-buffer))
2505           (copy-buf (get-buffer-create " *Original Message*"))
2506           (header (std11-header-string-except
2507                    mime-edit-split-ignored-field-regexp separator))
2508           (subject (mail-fetch-field "subject"))
2509           (total (+ (/ lines mime-edit-message-max-length)
2510                     (if (> (mod lines mime-edit-message-max-length) 0)
2511                         1)))
2512           (command
2513            (or cmd
2514                (cdr
2515                 (assq major-mode
2516                       mime-edit-split-message-sender-alist))
2517                (function
2518                 (lambda ()
2519                   (interactive)
2520                   (error "Split sender is not specified for `%s'." major-mode)))))
2521           (mime-edit-partial-number 1)
2522           data)
2523       (save-excursion
2524         (set-buffer copy-buf)
2525         (erase-buffer)
2526         (insert-buffer the-buf)
2527         (save-restriction
2528           (if (re-search-forward
2529                (concat "^" (regexp-quote separator) "$") nil t)
2530               (let ((he (match-beginning 0)))
2531                 (replace-match "")
2532                 (narrow-to-region (point-min) he)))
2533           (goto-char (point-min))
2534           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2535             (delete-region (match-beginning 0)
2536                            (1+ (std11-field-end))))))
2537       (while (< mime-edit-partial-number total)
2538         (erase-buffer)
2539         (save-excursion
2540           (set-buffer copy-buf)
2541           (setq data (buffer-substring
2542                       (point-min)
2543                       (progn
2544                         (goto-line mime-edit-message-max-length)
2545                         (point))))
2546           (delete-region (point-min)(point)))
2547         (mime-edit-insert-partial-header
2548          header subject id mime-edit-partial-number total separator)
2549         (insert data)
2550         (save-excursion
2551           (message (format "Sending %d/%d..."
2552                            mime-edit-partial-number total))
2553           (call-interactively command)
2554           (message (format "Sending %d/%d...done"
2555                            mime-edit-partial-number total)))
2556         (setq mime-edit-partial-number
2557               (1+ mime-edit-partial-number)))
2558       (erase-buffer)
2559       (save-excursion
2560         (set-buffer copy-buf)
2561         (setq data (buffer-string))
2562         (erase-buffer))
2563       (mime-edit-insert-partial-header
2564        header subject id mime-edit-partial-number total separator)
2565       (insert data)
2566       (save-excursion
2567         (message (format "Sending %d/%d..."
2568                          mime-edit-partial-number total))
2569         (message (format "Sending %d/%d...done"
2570                          mime-edit-partial-number total))))))
2571
2572 (defun mime-edit-maybe-split-and-send (&optional cmd)
2573   (interactive)
2574   (run-hooks 'mime-edit-before-send-hook)
2575   (let ((mime-edit-message-max-length
2576          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2577              mime-edit-message-default-max-lines))
2578         (lines (count-lines (point-min) (point-max))))
2579     (if (and (> lines mime-edit-message-max-length)
2580              mime-edit-split-message)
2581         (mime-edit-split-and-send cmd lines mime-edit-message-max-length))))
2582
2583
2584 ;;; @ preview message
2585 ;;;
2586
2587 (defvar mime-edit-buffer nil) ; buffer local variable
2588 (defvar mime-edit-temp-message-buffer nil) ; buffer local variable
2589
2590 (defun mime-edit-preview-message ()
2591   "preview editing MIME message."
2592   (interactive)
2593   (let* ((str (buffer-string))
2594          (separator mail-header-separator)
2595          (the-buf (current-buffer))
2596          (buf-name (buffer-name))
2597          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2598          (buf (get-buffer temp-buf-name))
2599          (pgp-processing mime-edit-pgp-processing))
2600     (if buf
2601         (progn
2602           (switch-to-buffer buf)
2603           (erase-buffer))
2604       (setq buf (get-buffer-create temp-buf-name))
2605       (switch-to-buffer buf))
2606     (insert str)
2607     (setq major-mode 'mime-temp-message-mode)
2608     (make-local-variable 'mail-header-separator)
2609     (setq mail-header-separator separator)
2610     (make-local-variable 'mime-edit-buffer)
2611     (setq mime-edit-buffer the-buf)
2612     (setq mime-edit-pgp-processing pgp-processing)
2613
2614     (run-hooks 'mime-edit-translate-hook)
2615     (mime-edit-translate-buffer)
2616     (goto-char (point-min))
2617     (if (re-search-forward
2618          (concat "^" (regexp-quote separator) "$"))
2619         (replace-match ""))
2620     (mime-view-buffer)
2621     (make-local-variable 'mime-edit-temp-message-buffer)
2622     (setq mime-edit-temp-message-buffer buf)))
2623
2624 (defun mime-edit-quitting-method ()
2625   "Quitting method for mime-view."
2626   (let* ((temp mime-edit-temp-message-buffer)
2627          buf)
2628     (mime-preview-kill-buffer)
2629     (set-buffer temp)
2630     (setq buf mime-edit-buffer)
2631     (kill-buffer temp)
2632     (switch-to-buffer buf)))
2633
2634 (set-alist 'mime-preview-quitting-method-alist
2635            'mime-temp-message-mode
2636            #'mime-edit-quitting-method)
2637
2638
2639 ;;; @ edit again
2640 ;;;
2641
2642 (defvar mime-edit-again-ignored-field-regexp
2643   (concat "^\\(" "Content-.*\\|Mime-Version"
2644           (if mime-edit-insert-user-agent-field "\\|User-Agent")
2645           "\\):")
2646   "Regexp for deleted header fields when `mime-edit-again' is called.")
2647
2648 (defsubst eliminate-top-spaces (string)
2649   "Eliminate top sequence of space or tab in STRING."
2650   (if (string-match "^[ \t]+" string)
2651       (substring string (match-end 0))
2652     string))
2653
2654 (defun mime-edit-decode-multipart-in-buffer (content-type not-decode-text)
2655   (let* ((subtype
2656           (or
2657            (cdr (assoc (mime-content-type-parameter content-type "protocol")
2658                        '(("application/pgp-encrypted" . pgp-encrypted)
2659                          ("application/pgp-signature" . pgp-signed))))
2660            (mime-content-type-subtype content-type)))
2661          (boundary (mime-content-type-parameter content-type "boundary"))
2662          (boundary-pat (concat "\n--" (regexp-quote boundary) "[ \t]*\n")))
2663     (re-search-forward boundary-pat nil t)
2664     (let ((bb (match-beginning 0)) eb tag)
2665       (setq tag (format "\n--<<%s>>-{\n" subtype))
2666       (goto-char bb)
2667       (insert tag)
2668       (setq bb (+ bb (length tag)))
2669       (re-search-forward
2670        (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2671        nil t)
2672       (setq eb (match-beginning 0))
2673       (replace-match (format "--}-<<%s>>\n" subtype))
2674       (save-restriction
2675         (narrow-to-region bb eb)
2676         (goto-char (point-min))
2677         (while (re-search-forward boundary-pat nil t)
2678           (let ((beg (match-beginning 0))
2679                 end)
2680             (delete-region beg (match-end 0))
2681             (save-excursion
2682               (if (re-search-forward boundary-pat nil t)
2683                   (setq end (match-beginning 0))
2684                 (setq end (point-max)))
2685               (save-restriction
2686                 (narrow-to-region beg end)
2687                 (cond
2688                  ((eq subtype 'pgp-encrypted)
2689                   (when (progn
2690                            (goto-char (point-min))
2691                            (re-search-forward "^-+BEGIN PGP MESSAGE-+$"
2692                                               nil t))
2693                     (insert (epg-decrypt-string
2694                              (epg-make-context)
2695                              (buffer-substring (match-beginning 0)
2696                                                (point-max))))
2697                     (delete-region (point)(point-max))
2698                     (mime-edit-decode-message-in-buffer 
2699                      nil not-decode-text)
2700                     (delete-region (goto-char (point-min))
2701                                    (if (search-forward "\n\n" nil t)
2702                                        (match-end 0)
2703                                      (point-min)))
2704                     (goto-char (point-max))))
2705                  (t 
2706                   (mime-edit-decode-message-in-buffer
2707                    (if (eq subtype 'digest)
2708                        (eval-when-compile
2709                          (make-mime-content-type 'message 'rfc822)))
2710                    not-decode-text)
2711                   (goto-char (point-max))))))))))
2712     (goto-char (point-min))
2713     (or (= (point-min) 1)
2714         (delete-region (point-min)
2715                        (if (search-forward "\n\n" nil t)
2716                            (match-end 0)
2717                          (point-min))))))
2718
2719 (defun mime-edit-decode-single-part-in-buffer
2720   (content-type not-decode-text &optional content-disposition)
2721   (let* ((type (mime-content-type-primary-type content-type))
2722          (subtype (mime-content-type-subtype content-type))
2723          (ctype (format "%s/%s" type subtype))
2724          charset
2725          (pstr (let ((bytes (+ 14 (length ctype))))
2726                  (mapconcat (function
2727                              (lambda (attr)
2728                                (if (string= (car attr) "charset")
2729                                    (progn
2730                                      (setq charset (cdr attr))
2731                                      "")
2732                                  (let* ((str (concat (car attr)
2733                                                      "=" (cdr attr)))
2734                                         (bs (length str)))
2735                                    (setq bytes (+ bytes bs 2))
2736                                    (if (< bytes 76)
2737                                        (concat "; " str)
2738                                      (setq bytes (+ bs 1))
2739                                      (concat ";\n " str)
2740                                      )))))
2741                             (mime-content-type-parameters content-type) "")))
2742          encoding
2743          encoded
2744          (limit (save-excursion
2745                   (if (search-forward "\n\n" nil t)
2746                       (1- (point)))))
2747          (disposition-type
2748           (mime-content-disposition-type content-disposition))
2749          (disposition-str
2750           (if disposition-type
2751               (let ((bytes (+ 21 (length (format "%s" disposition-type)))))
2752                 (mapconcat (function
2753                             (lambda (attr)
2754                               (let* ((str (concat
2755                                            (car attr)
2756                                            "="
2757                                            (if (string-equal "filename"
2758                                                              (car attr))
2759                                                (std11-wrap-as-quoted-string
2760                                                 (cdr attr))
2761                                              (cdr attr))))
2762                                      (bs (length str)))
2763                                 (setq bytes (+ bytes bs 2))
2764                                 (if (< bytes 76)
2765                                     (concat "; " str)
2766                                   (setq bytes (+ bs 1))
2767                                   (concat ";\n " str)
2768                                   ))))
2769                            (mime-content-disposition-parameters
2770                             content-disposition)
2771                            "")))))
2772     (if disposition-type
2773         (setq pstr (format "%s\nContent-Disposition: %s%s"
2774                            pstr disposition-type disposition-str)))
2775     (save-excursion
2776       (if (re-search-forward
2777            "^Content-Transfer-Encoding:" limit t)
2778           (let ((beg (match-beginning 0))
2779                 (hbeg (match-end 0))
2780                 (end (std11-field-end limit)))
2781             (setq encoding
2782                   (downcase
2783                    (eliminate-top-spaces
2784                     (std11-unfold-string
2785                      (buffer-substring hbeg end)))))
2786             (if (or charset (eq type 'text))
2787                 (progn
2788                   (delete-region beg (1+ end))
2789                   (goto-char (point-min))
2790                   (if (search-forward "\n\n" nil t)
2791                       (progn
2792                         (mime-decode-region
2793                          (match-end 0)(point-max) encoding)
2794                         (setq encoded t
2795                               encoding nil))))))))
2796     (if (and (eq type 'text)
2797              (or encoded (not not-decode-text)))
2798         (progn
2799           (save-excursion
2800             (goto-char (point-min))
2801             (while (re-search-forward "\r\n" nil t)
2802               (replace-match "\n")))
2803           (decode-mime-charset-region (point-min)(point-max)
2804                                       (or charset default-mime-charset))))
2805     (let ((he (if (re-search-forward "^$" nil t)
2806                   (match-end 0)
2807                 (point-min))))
2808       (if (and (eq type 'text)
2809                (eq subtype 'x-rot13-47-48))
2810           (mule-caesar-region he (point-max)))
2811       (if (= (point-min) 1)
2812           (progn
2813             (goto-char he)
2814             (insert
2815              (concat "\n"
2816                      (mime-create-tag
2817                       (format "%s/%s%s" type subtype pstr)
2818                       encoding))))
2819         (delete-region (point-min) he)
2820         (insert
2821          (mime-create-tag (format "%s/%s%s" type subtype pstr)
2822                           encoding))))))
2823
2824 ;;;###autoload
2825 (defun mime-edit-decode-message-in-buffer (&optional default-content-type
2826                                                      not-decode-text)
2827   (save-excursion
2828     (goto-char (point-min))
2829     (let ((ctl (or (mime-read-Content-Type)
2830                    default-content-type)))
2831       (if ctl
2832           (let ((type (mime-content-type-primary-type ctl)))
2833             (cond
2834              ((and (eq type 'application)
2835                    (eq (mime-content-type-subtype ctl) 'pgp-signature))
2836               (delete-region (point-min)(point-max)))
2837              ((eq type 'multipart)
2838               (mime-edit-decode-multipart-in-buffer ctl not-decode-text))
2839              (t
2840               (mime-edit-decode-single-part-in-buffer
2841                ctl not-decode-text (mime-read-Content-Disposition)))))
2842         (or not-decode-text
2843             (decode-mime-charset-region (point-min) (point-max)
2844                                         default-mime-charset)))
2845       (if (= (point-min) 1)
2846           (progn
2847             (save-restriction
2848               (std11-narrow-to-header)
2849               (goto-char (point-min))
2850               (while (re-search-forward
2851                       mime-edit-again-ignored-field-regexp nil t)
2852                 (delete-region (match-beginning 0) (1+ (std11-field-end)))))
2853             (mime-decode-header-in-buffer (not not-decode-text)))))))
2854
2855 ;;;###autoload
2856 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2857   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2858 Content-Type and Content-Transfer-Encoding header fields will be
2859 converted to MIME-Edit tags."
2860   (interactive)
2861   (goto-char (point-min))
2862   (if (search-forward
2863        (concat "\n" (regexp-quote mail-header-separator) "\n")
2864        nil t)
2865       (replace-match "\n\n"))
2866   (mime-edit-decode-message-in-buffer nil not-decode-text)
2867   (goto-char (point-min))
2868   (or no-separator
2869       (and (re-search-forward "^$")
2870            (replace-match mail-header-separator)))
2871   (or not-turn-on
2872       (turn-on-mime-edit)))
2873
2874
2875 ;;; @ end
2876 ;;;
2877
2878 (provide 'mime-edit)
2879
2880 (run-hooks 'mime-edit-load-hook)
2881
2882 ;;; mime-edit.el ends here