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