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