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