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