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