(mime-edit-sign-pgp-elkins): Enclose PGP-processing by
[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.82 $
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.82 1997-05-27 03:26:23 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 (as-binary-process
1609              (funcall (pgp-function 'mime-sign)
1610                       (point-min)(point-max) nil nil pgp-boundary))
1611             (throw 'mime-edit-error 'pgp-error)
1612             )
1613         ))))
1614
1615 (defvar mime-edit-encrypt-recipient-fields-list '("To" "cc"))
1616
1617 (defun mime-edit-make-encrypt-recipient-header ()
1618   (let* ((names mime-edit-encrypt-recipient-fields-list)
1619          (values
1620           (std11-field-bodies (cons "From" names)
1621                               nil mail-header-separator))
1622          (from (prog1
1623                    (car values)
1624                  (setq values (cdr values))))
1625          (header (and (stringp from)
1626                       (if (string-equal from "")
1627                           ""
1628                         (format "From: %s\n" from)
1629                         )))
1630          recipients)
1631     (while (and names values)
1632       (let ((name (car names))
1633             (value (car values))
1634             )
1635         (and (stringp value)
1636              (or (string-equal value "")
1637                  (progn
1638                    (setq header (concat header name ": " value "\n")
1639                          recipients (if recipients
1640                                         (concat recipients " ," value)
1641                                       value))
1642                    ))))
1643       (setq names (cdr names)
1644             values (cdr values))
1645       )
1646     (vector from recipients header)
1647     ))
1648
1649 (defun mime-edit-encrypt-pgp-elkins (beg end boundary)
1650   (save-excursion
1651     (save-restriction
1652       (let (from recipients header)
1653         (let ((ret (mime-edit-make-encrypt-recipient-header)))
1654           (setq from (aref ret 0)
1655                 recipients (aref ret 1)
1656                 header (aref ret 2))
1657           )
1658         (narrow-to-region beg end)
1659         (let* ((ret
1660                 (mime-edit-translate-region beg end boundary))
1661                (ctype    (car ret))
1662                (encoding (nth 1 ret))
1663                (parts    (nth 3 ret))
1664                (pgp-boundary (concat "pgp-" boundary))
1665                )
1666           (goto-char beg)
1667           (insert header)
1668           (insert (format "Content-Type: %s\n" ctype))
1669           (if encoding
1670               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1671             )
1672           (insert "\n")
1673           (or (funcall (pgp-function 'encrypt)
1674                        recipients (point-min) (point-max) from)
1675               (throw 'mime-edit-error 'pgp-error)
1676               )
1677           (goto-char beg)
1678           (insert (format "--[[multipart/encrypted;
1679  boundary=\"%s\";
1680  protocol=\"application/pgp-encrypted\"][7bit]]
1681 --%s
1682 Content-Type: application/pgp-encrypted
1683
1684 --%s
1685 Content-Type: application/octet-stream
1686 Content-Transfer-Encoding: 7bit
1687
1688 " pgp-boundary pgp-boundary pgp-boundary))
1689           (goto-char (point-max))
1690           (insert (format "\n--%s--\n" pgp-boundary))
1691           )))))
1692
1693 (defun mime-edit-sign-pgp-kazu (beg end boundary)
1694   (save-excursion
1695     (save-restriction
1696       (narrow-to-region beg end)
1697       (let* ((ret
1698               (mime-edit-translate-region beg end boundary))
1699              (ctype    (car ret))
1700              (encoding (nth 1 ret))
1701              (parts    (nth 3 ret))
1702              )
1703         (goto-char beg)
1704         (insert (format "Content-Type: %s\n" ctype))
1705         (if encoding
1706             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1707           )
1708         (insert "\n")
1709         (or (as-binary-process
1710              (funcall (pgp-function 'traditional-sign)
1711                       beg (point-max)))
1712             (throw 'mime-edit-error 'pgp-error)
1713             )
1714         (goto-char beg)
1715         (insert
1716          "--[[application/pgp; format=mime][7bit]]\n")
1717         ))
1718     ))
1719
1720 (defun mime-edit-encrypt-pgp-kazu (beg end boundary)
1721   (save-excursion
1722     (let (from recipients header)
1723       (let ((ret (mime-edit-make-encrypt-recipient-header)))
1724         (setq from (aref ret 0)
1725               recipients (aref ret 1)
1726               header (aref ret 2))
1727         )
1728       (save-restriction
1729         (narrow-to-region beg end)
1730         (let* ((ret
1731                 (mime-edit-translate-region beg end boundary))
1732                (ctype    (car ret))
1733                (encoding (nth 1 ret))
1734                (parts    (nth 3 ret))
1735                )
1736           (goto-char beg)
1737           (insert header)
1738           (insert (format "Content-Type: %s\n" ctype))
1739           (if encoding
1740               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1741             )
1742           (insert "\n")
1743           (or (as-binary-process
1744                (funcall (pgp-function 'encrypt)
1745                         recipients beg (point-max) nil 'maybe)
1746                )
1747               (throw 'mime-edit-error 'pgp-error)
1748               )
1749           (goto-char beg)
1750           (insert
1751            "--[[application/pgp; format=mime][7bit]]\n")
1752           ))
1753       )))
1754
1755 (defsubst replace-space-with-underline (str)
1756   (mapconcat (function
1757               (lambda (arg)
1758                 (char-to-string
1759                  (if (eq arg ?\ )
1760                      ?_
1761                    arg)))) str "")
1762   )
1763
1764 (defun mime-edit-make-boundary ()
1765   (concat mime-multipart-boundary "_"
1766           (replace-space-with-underline (current-time-string))
1767           ))
1768
1769 (defun mime-edit-translate-body ()
1770   "Encode the tagged MIME body in current buffer in MIME compliant message."
1771   (interactive)
1772   (save-excursion
1773     (let ((boundary (mime-edit-make-boundary))
1774           (i 1)
1775           ret)
1776       (while (mime-edit-process-multipart-1
1777               (format "%s-%d" boundary i))
1778         (setq i (1+ i))
1779         )
1780       (save-restriction
1781         ;; We are interested in message body.
1782         (let* ((beg
1783                 (progn
1784                   (goto-char (point-min))
1785                   (re-search-forward
1786                    (concat "\n" (regexp-quote mail-header-separator)
1787                            (if mime-ignore-preceding-spaces
1788                                "[ \t\n]*\n" "\n")) nil 'move)
1789                   (point)))
1790                (end
1791                 (progn
1792                   (goto-char (point-max))
1793                   (and mime-ignore-trailing-spaces
1794                        (re-search-backward "[^ \t\n]\n" beg t)
1795                        (forward-char 1))
1796                   (point))))
1797           (setq ret (mime-edit-translate-region
1798                      beg end
1799                      (format "%s-%d" boundary i)))
1800           ))
1801       (mime-edit-dequote-region (point-min)(point-max))
1802       (let ((contype (car ret))         ;Content-Type
1803             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1804             )
1805         ;; Insert X-Emacs field
1806         (and mime-edit-insert-x-emacs-field
1807              (or (mail-position-on-field "X-Emacs")
1808                  (insert mime-edit-x-emacs-value)
1809                  ))
1810         ;; Make primary MIME headers.
1811         (or (mail-position-on-field "Mime-Version")
1812             (insert mime-edit-mime-version-value))
1813         ;; Remove old Content-Type and other fields.
1814         (save-restriction
1815           (goto-char (point-min))
1816           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1817           (narrow-to-region (point-min) (point))
1818           (goto-char (point-min))
1819           (mime-delete-field "Content-Type")
1820           (mime-delete-field "Content-Transfer-Encoding"))
1821         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1822         (mail-position-on-field "Content-Type")
1823         (insert contype)
1824         (if encoding
1825             (progn
1826               (mail-position-on-field "Content-Transfer-Encoding")
1827               (insert encoding)))
1828         ))))
1829
1830 (defun mime-edit-translate-single-part-tag (&optional prefix)
1831   "Translate single-part-tag to MIME header."
1832   (if (re-search-forward mime-edit-single-part-tag-regexp nil t)
1833       (let* ((beg (match-beginning 0))
1834              (end (match-end 0))
1835              (tag (buffer-substring beg end))
1836              )
1837         (delete-region beg end)
1838         (let ((contype (mime-edit-get-contype tag))
1839               (encoding (mime-edit-get-encoding tag))
1840               )
1841           (insert (concat prefix "--" boundary "\n"))
1842           (save-restriction
1843             (narrow-to-region (point)(point))
1844             (insert "Content-Type: " contype "\n")
1845             (if encoding
1846                 (insert "Content-Transfer-Encoding: " encoding "\n"))
1847             (eword-encode-header)
1848             ))
1849         t)))
1850
1851 (defun mime-edit-translate-region (beg end &optional boundary multipart)
1852   (or boundary
1853       (setq boundary (mime-edit-make-boundary))
1854       )
1855   (save-excursion
1856     (save-restriction
1857       (narrow-to-region beg end)
1858       (let ((tag nil)                   ;MIME tag
1859             (contype nil)               ;Content-Type
1860             (encoding nil)              ;Content-Transfer-Encoding
1861             (nparts 0))                 ;Number of body parts
1862         ;; Normalize the body part by inserting appropriate message
1863         ;; tags for every message contents.
1864         (mime-edit-normalize-body)
1865         ;; Counting the number of Content-Type.
1866         (goto-char (point-min))
1867         (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1868           (setq nparts (1+ nparts)))
1869         ;; Begin translation.
1870         (cond
1871          ((and (<= nparts 1)(not multipart))
1872           ;; It's a singular message.
1873           (goto-char (point-min))
1874           (while (re-search-forward
1875                   mime-edit-single-part-tag-regexp nil t)
1876             (setq tag
1877                   (buffer-substring (match-beginning 0) (match-end 0)))
1878             (delete-region (match-beginning 0) (1+ (match-end 0)))
1879             (setq contype (mime-edit-get-contype tag))
1880             (setq encoding (mime-edit-get-encoding tag))
1881             ))
1882          (t
1883           ;; It's a multipart message.
1884           (goto-char (point-min))
1885           (and (mime-edit-translate-single-part-tag)
1886                (while (mime-edit-translate-single-part-tag "\n"))
1887                )
1888           ;; Define Content-Type as "multipart/mixed".
1889           (setq contype
1890                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1891           ;; Content-Transfer-Encoding must be "7bit".
1892           ;; The following encoding can be `nil', but is
1893           ;; specified as is since there is no way that a user
1894           ;; specifies it.
1895           (setq encoding "7bit")
1896           ;; Insert the trailer.
1897           (goto-char (point-max))
1898           (insert "\n--" boundary "--\n")
1899           ))
1900         (list contype encoding boundary nparts)
1901         ))))
1902
1903 (defun mime-edit-normalize-body ()
1904   "Normalize the body part by inserting appropriate message tags."
1905   ;; Insert the first MIME tags if necessary.
1906   (goto-char (point-min))
1907   (if (not (looking-at mime-edit-single-part-tag-regexp))
1908       (insert (mime-make-text-tag) "\n"))
1909   ;; Check each tag, and add new tag or correct it if necessary.
1910   (goto-char (point-min))
1911   (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1912     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1913            (contype (mime-edit-get-contype tag))
1914            (charset (mime-get-parameter contype "charset"))
1915            (encoding (mime-edit-get-encoding tag)))
1916       ;; Remove extra whitespaces after the tag.
1917       (if (looking-at "[ \t]+$")
1918           (delete-region (match-beginning 0) (match-end 0)))
1919       (let ((beg (point))
1920             (end (mime-edit-content-end))
1921             )
1922         (if (= end (point-max))
1923             nil
1924           (goto-char end)
1925           (or (looking-at mime-edit-beginning-tag-regexp)
1926               (eobp)
1927               (insert (mime-make-text-tag) "\n")
1928               ))
1929         (visible-region beg end)
1930         (goto-char beg)
1931         )
1932       (cond
1933        ((mime-test-content-type contype "message")
1934         ;; Content-type "message" should be sent as is.
1935         (forward-line 1)
1936         )
1937        ((mime-test-content-type contype "text")
1938         ;; Define charset for text if necessary.
1939         (setq charset (if charset
1940                           (intern (downcase charset))
1941                         (mime-edit-choose-charset)))
1942         (mime-edit-define-charset charset)
1943         (cond ((string-equal contype "text/x-rot13-47-48")
1944                (save-excursion
1945                  (forward-line)
1946                  (mule-caesar-region (point) (mime-edit-content-end))
1947                  ))
1948               ((string-equal contype "text/enriched")
1949                (save-excursion
1950                  (let ((beg (progn
1951                               (forward-line)
1952                               (point)))
1953                        (end (mime-edit-content-end))
1954                        )
1955                    ;; Patch for hard newlines
1956                    ;; (save-excursion
1957                    ;;   (goto-char beg)
1958                    ;;   (while (search-forward "\n" end t)
1959                    ;;     (put-text-property (match-beginning 0)
1960                    ;;                        (point)
1961                    ;;                        'hard t)))
1962                    ;; End patch for hard newlines
1963                    (enriched-encode beg end)
1964                    (goto-char beg)
1965                    (if (search-forward "\n\n")
1966                        (delete-region beg (match-end 0))
1967                      )
1968                    ))))
1969         ;; Point is now on current tag.
1970         ;; Define encoding and encode text if necessary.
1971         (or encoding    ;Encoding is not specified.
1972             (let* ((encoding
1973                     (cdr
1974                      (assq charset
1975                            mime-edit-charset-default-encoding-alist)
1976                      ))
1977                    (beg (mime-edit-content-beginning))
1978                    )
1979               (encode-mime-charset-region beg (mime-edit-content-end)
1980                                           charset)
1981               (mime-encode-region beg (mime-edit-content-end) encoding)
1982               (mime-edit-define-encoding encoding)
1983               ))
1984         (goto-char (mime-edit-content-end))
1985         )
1986        ((null encoding)         ;Encoding is not specified.
1987         ;; Application, image, audio, video, and any other
1988         ;; unknown content-type without encoding should be
1989         ;; encoded.
1990         (let* ((encoding "base64")      ;Encode in BASE64 by default.
1991                (beg (mime-edit-content-beginning))
1992                (end (mime-edit-content-end))
1993                (body (buffer-substring beg end))
1994                )
1995           (mime-encode-region beg end encoding)
1996           (mime-edit-define-encoding encoding))
1997         (forward-line 1)
1998         ))
1999       )))
2000
2001 (defun mime-delete-field (field)
2002   "Delete header FIELD."
2003   (let ((regexp (format "^%s:[ \t]*" field)))
2004     (goto-char (point-min))
2005     (while (re-search-forward regexp nil t)
2006       (delete-region (match-beginning 0)
2007                      (progn (forward-line 1) (point)))
2008       )))
2009
2010 \f
2011 ;;;
2012 ;;; Platform dependent functions
2013 ;;;
2014
2015 ;; Sun implementations
2016
2017 (defun mime-edit-voice-recorder-for-sun (encoding)
2018   "Record voice in a buffer using Sun audio device,
2019 and insert data encoded as ENCODING. [mime-edit.el]"
2020   (message "Start the recording on %s.  Type C-g to finish the recording..."
2021            (system-name))
2022   (mime-insert-encoded-file "/dev/audio" encoding)
2023   )
2024
2025 \f
2026 ;;; @ Other useful commands.
2027 ;;;
2028
2029 ;; Message forwarding commands as content-type "message/rfc822".
2030
2031 (defun mime-edit-insert-message (&optional message)
2032   (interactive)
2033   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2034     (if (and inserter (fboundp inserter))
2035         (progn
2036           (mime-edit-insert-tag "message" "rfc822")
2037           (funcall inserter message)
2038           )
2039       (message "Sorry, I don't have message inserter for your MUA.")
2040       )))
2041
2042 (defun mime-edit-insert-mail (&optional message)
2043   (interactive)
2044   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2045     (if (and inserter (fboundp inserter))
2046         (progn
2047           (mime-edit-insert-tag "message" "rfc822")
2048           (funcall inserter message)
2049           )
2050       (message "Sorry, I don't have mail inserter for your MUA.")
2051       )))
2052
2053 (defun mime-edit-inserted-message-filter ()
2054   (save-excursion
2055     (save-restriction
2056       (let ((header-start (point))
2057             (case-fold-search t)
2058             beg end)
2059         ;; for Emacs 18
2060         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2061         (if (re-search-forward "^$" (mark t))
2062             (narrow-to-region header-start (match-beginning 0))
2063           )
2064         (goto-char header-start)
2065         (while (and (re-search-forward
2066                      mime-edit-yank-ignored-field-regexp nil t)
2067                     (setq beg (match-beginning 0))
2068                     (setq end (1+ (std11-field-end)))
2069                     )
2070           (delete-region beg end)
2071           )
2072         ))))
2073
2074
2075 ;;; @ multipart enclosure
2076 ;;;
2077
2078 (defun mime-edit-enclose-region (type beg end)
2079   (save-excursion
2080     (goto-char beg)
2081     (let ((current (point)))
2082       (save-restriction
2083         (narrow-to-region beg end)
2084         (insert (format "--<<%s>>-{\n" type))
2085         (goto-char (point-max))
2086         (insert (format "--}-<<%s>>\n" type))
2087         (goto-char (point-max))
2088         )
2089       (or (looking-at mime-edit-beginning-tag-regexp)
2090           (eobp)
2091           (insert (mime-make-text-tag) "\n")
2092           )
2093       )))
2094
2095 (defun mime-edit-enclose-quote-region (beg end)
2096   (interactive "*r")
2097   (mime-edit-enclose-region "quote" beg end)
2098   )
2099
2100 (defun mime-edit-enclose-mixed-region (beg end)
2101   (interactive "*r")
2102   (mime-edit-enclose-region "mixed" beg end)
2103   )
2104
2105 (defun mime-edit-enclose-parallel-region (beg end)
2106   (interactive "*r")
2107   (mime-edit-enclose-region "parallel" beg end)
2108   )
2109
2110 (defun mime-edit-enclose-digest-region (beg end)
2111   (interactive "*r")
2112   (mime-edit-enclose-region "digest" beg end)
2113   )
2114
2115 (defun mime-edit-enclose-alternative-region (beg end)
2116   (interactive "*r")
2117   (mime-edit-enclose-region "alternative" beg end)
2118   )
2119
2120 (defun mime-edit-enclose-signed-region (beg end)
2121   (interactive "*r")
2122   (if mime-edit-signing-type
2123       (mime-edit-enclose-region "signed" beg end)
2124     (message "Please specify signing type.")
2125     ))
2126
2127 (defun mime-edit-enclose-encrypted-region (beg end)
2128   (interactive "*r")
2129   (if mime-edit-signing-type
2130       (mime-edit-enclose-region "encrypted" beg end)
2131     (message "Please specify encrypting type.")
2132     ))
2133
2134 (defun mime-edit-insert-key (&optional arg)
2135   "Insert a pgp public key."
2136   (interactive "P")
2137   (mime-edit-insert-tag "application" "pgp-keys")
2138   (mime-edit-define-encoding "7bit")
2139   (funcall (pgp-function 'insert-key))
2140   )
2141
2142
2143 ;;; @ flag setting
2144 ;;;
2145
2146 (defun mime-edit-set-split (arg)
2147   (interactive
2148    (list
2149     (y-or-n-p "Do you want to enable split?")
2150     ))
2151   (setq mime-edit-split-message arg)
2152   (if arg
2153       (message "This message is enabled to split.")
2154     (message "This message is not enabled to split.")
2155     ))
2156
2157 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2158   "Toggle transfer-level is 7bit or 8bit through.
2159
2160 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2161   (interactive)
2162   (if (numberp transfer-level)
2163       (setq mime-transfer-level transfer-level)
2164     (if (< mime-transfer-level 8)
2165         (setq mime-transfer-level 8)
2166       (setq mime-transfer-level 7)
2167       ))
2168   (setq mime-edit-charset-default-encoding-alist
2169         (mime-make-charset-default-encoding-alist mime-transfer-level))
2170   (message (format "Current transfer-level is %d bit"
2171                    mime-transfer-level))
2172   (setq mime-transfer-level-string
2173         (mime-encoding-name mime-transfer-level 'not-omit))
2174   (force-mode-line-update)
2175   )
2176
2177 (defun mime-edit-set-transfer-level-7bit ()
2178   (interactive)
2179   (mime-edit-toggle-transfer-level 7)
2180   )
2181
2182 (defun mime-edit-set-transfer-level-8bit ()
2183   (interactive)
2184   (mime-edit-toggle-transfer-level 8)
2185   )
2186
2187
2188 ;;; @ pgp
2189 ;;;
2190
2191 (defun mime-edit-set-sign (arg)
2192   (interactive
2193    (list
2194     (y-or-n-p "Do you want to sign?")
2195     ))
2196   (if arg
2197       (if mime-edit-signing-type
2198           (progn
2199             (setq mime-edit-pgp-processing 'sign)
2200             (message "This message will be signed.")
2201             )
2202         (message "Please specify signing type.")
2203         )
2204     (if (eq mime-edit-pgp-processing 'sign)
2205         (setq mime-edit-pgp-processing nil)
2206       )
2207     (message "This message will not be signed.")
2208     ))
2209
2210 (defun mime-edit-set-encrypt (arg)
2211   (interactive
2212    (list
2213     (y-or-n-p "Do you want to encrypt?")
2214     ))
2215   (if arg
2216       (if mime-edit-encrypting-type
2217           (progn
2218             (setq mime-edit-pgp-processing 'encrypt)
2219             (message "This message will be encrypt.")
2220             )
2221         (message "Please specify encrypting type.")
2222         )
2223     (if (eq mime-edit-pgp-processing 'encrypt)
2224         (setq mime-edit-pgp-processing nil)
2225       )
2226     (message "This message will not be encrypt.")
2227     ))
2228
2229 (defvar mime-edit-pgp-processing nil)
2230 (make-variable-buffer-local 'mime-edit-pgp-processing)
2231
2232 (defun mime-edit-pgp-enclose-buffer ()
2233   (let ((beg (save-excursion
2234                (goto-char (point-min))
2235                (if (search-forward (concat "\n" mail-header-separator "\n"))
2236                    (match-end 0)
2237                  )))
2238         (end (point-max))
2239         )
2240     (if beg
2241         (cond ((eq mime-edit-pgp-processing 'sign)
2242                (mime-edit-enclose-signed-region beg end)
2243                )
2244               ((eq mime-edit-pgp-processing 'encrypt)
2245                (mime-edit-enclose-encrypted-region beg end)
2246                ))
2247       )))
2248
2249
2250 ;;; @ split
2251 ;;;
2252
2253 (defun mime-edit-insert-partial-header
2254   (fields subject id number total separator)
2255   (insert fields)
2256   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2257   (insert (format "Mime-Version: 1.0 (split by %s)\n"
2258                   mime-edit-version-name))
2259   (insert (format "\
2260 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2261                   id number total separator))
2262   )
2263
2264 (defun mime-edit-split-and-send
2265   (&optional cmd lines mime-edit-message-max-length)
2266   (interactive)
2267   (or lines
2268       (setq lines
2269             (count-lines (point-min) (point-max)))
2270       )
2271   (or mime-edit-message-max-length
2272       (setq mime-edit-message-max-length
2273             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2274                 mime-edit-message-default-max-lines))
2275       )
2276   (let* ((mime-edit-draft-file-name 
2277           (or (buffer-file-name)
2278               (make-temp-name
2279                (expand-file-name "mime-draft" mime-temp-directory))))
2280          (separator mail-header-separator)
2281          (id (concat "\""
2282                      (replace-space-with-underline (current-time-string))
2283                      "@" (system-name) "\"")))
2284     (run-hooks 'mime-edit-before-split-hook)
2285     (let ((the-buf (current-buffer))
2286           (copy-buf (get-buffer-create " *Original Message*"))
2287           (header (std11-header-string-except
2288                    mime-edit-split-ignored-field-regexp separator))
2289           (subject (mail-fetch-field "subject"))
2290           (total (+ (/ lines mime-edit-message-max-length)
2291                     (if (> (mod lines mime-edit-message-max-length) 0)
2292                         1)))
2293           (command
2294            (or cmd
2295                (cdr
2296                 (assq major-mode
2297                       mime-edit-split-message-sender-alist))
2298                (function
2299                 (lambda ()
2300                   (interactive)
2301                   (error "Split sender is not specified for `%s'." major-mode)
2302                   ))
2303                ))
2304           (mime-edit-partial-number 1)
2305           data)
2306       (save-excursion
2307         (set-buffer copy-buf)
2308         (erase-buffer)
2309         (insert-buffer the-buf)
2310         (save-restriction
2311           (if (re-search-forward
2312                (concat "^" (regexp-quote separator) "$") nil t)
2313               (let ((he (match-beginning 0)))
2314                 (replace-match "")
2315                 (narrow-to-region (point-min) he)
2316                 ))
2317           (goto-char (point-min))
2318           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2319             (delete-region (match-beginning 0)
2320                            (1+ (std11-field-end)))
2321             )))
2322       (while (< mime-edit-partial-number total)
2323         (erase-buffer)
2324         (save-excursion
2325           (set-buffer copy-buf)
2326           (setq data (buffer-substring
2327                       (point-min)
2328                       (progn
2329                         (goto-line mime-edit-message-max-length)
2330                         (point))
2331                       ))
2332           (delete-region (point-min)(point))
2333           )
2334         (mime-edit-insert-partial-header
2335          header subject id mime-edit-partial-number total separator)
2336         (insert data)
2337         (save-excursion
2338           (message (format "Sending %d/%d..."
2339                            mime-edit-partial-number total))
2340           (call-interactively command)
2341           (message (format "Sending %d/%d... done"
2342                            mime-edit-partial-number total))
2343           )
2344         (setq mime-edit-partial-number
2345               (1+ mime-edit-partial-number))
2346         )
2347       (erase-buffer)
2348       (save-excursion
2349         (set-buffer copy-buf)
2350         (setq data (buffer-string))
2351         (erase-buffer)
2352         )
2353       (mime-edit-insert-partial-header
2354        header subject id mime-edit-partial-number total separator)
2355       (insert data)
2356       (save-excursion
2357         (message (format "Sending %d/%d..."
2358                          mime-edit-partial-number total))
2359         (message (format "Sending %d/%d... done"
2360                          mime-edit-partial-number total))
2361         )
2362       )))
2363
2364 (defun mime-edit-maybe-split-and-send (&optional cmd)
2365   (interactive)
2366   (run-hooks 'mime-edit-before-send-hook)
2367   (let ((mime-edit-message-max-length
2368          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2369              mime-edit-message-default-max-lines))
2370         (lines (count-lines (point-min) (point-max)))
2371         )
2372     (if (and (> lines mime-edit-message-max-length)
2373              mime-edit-split-message)
2374         (mime-edit-split-and-send cmd lines mime-edit-message-max-length)
2375       )))
2376
2377
2378 ;;; @ preview message
2379 ;;;
2380
2381 (defvar mime-edit-buffer nil) ; buffer local variable
2382
2383 (defun mime-edit-preview-message ()
2384   "preview editing MIME message. [mime-edit.el]"
2385   (interactive)
2386   (let* ((str (buffer-string))
2387          (separator mail-header-separator)
2388          (the-buf (current-buffer))
2389          (buf-name (buffer-name))
2390          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2391          (buf (get-buffer temp-buf-name))
2392          )
2393     (if buf
2394         (progn
2395           (switch-to-buffer buf)
2396           (erase-buffer)
2397           )
2398       (setq buf (get-buffer-create temp-buf-name))
2399       (switch-to-buffer buf)
2400       )
2401     (insert str)
2402     (setq major-mode 'mime-temp-message-mode)
2403     (make-local-variable 'mail-header-separator)
2404     (setq mail-header-separator separator)
2405     (make-local-variable 'mime-edit-buffer)
2406     (setq mime-edit-buffer the-buf)
2407     
2408     (run-hooks 'mime-edit-translate-hook)
2409     (mime-edit-translate-buffer)
2410     (goto-char (point-min))
2411     (if (re-search-forward
2412          (concat "^" (regexp-quote separator) "$"))
2413         (replace-match "")
2414       )
2415     (mime-view-mode)
2416     ))
2417
2418 (defun mime-edit-quitting-method ()
2419   "Quitting method for mime-view."
2420   (let ((temp mime-raw-buffer)
2421         buf)
2422     (mime-view-kill-buffer)
2423     (set-buffer temp)
2424     (setq buf mime-edit-buffer)
2425     (kill-buffer temp)
2426     (switch-to-buffer buf)
2427     ))
2428
2429 (set-alist 'mime-view-quitting-method-alist
2430            'mime-temp-message-mode
2431            (function mime-edit-quitting-method)
2432            )
2433
2434
2435 ;;; @ edit again
2436 ;;;
2437
2438 (defvar mime-edit-again-ignored-field-regexp
2439   (concat "^\\(" "Content-.*\\|Mime-Version"
2440           (if mime-edit-insert-x-emacs-field "\\|X-Emacs")
2441           "\\):")
2442   "Regexp for deleted header fields when `mime-edit-again' is called.")
2443
2444 (defun mime-edit-decode-buffer (not-decode-text)
2445   (save-excursion
2446     (goto-char (point-min))
2447     (let ((ctl (mime/Content-Type)))
2448       (if ctl
2449           (let ((ctype (car ctl))
2450                 (params (cdr ctl))
2451                 type stype)
2452             (if (string-match "/" ctype)
2453                 (progn
2454                   (setq type (substring ctype 0 (match-beginning 0)))
2455                   (setq stype (substring ctype (match-end 0)))
2456                   )
2457               (setq type ctype)
2458               )
2459             (cond
2460              ((string= ctype "application/pgp-signature")
2461               (delete-region (point-min)(point-max))
2462               )
2463              ((string= type "multipart")
2464               (let* ((boundary (cdr (assoc "boundary" params)))
2465                      (boundary-pat
2466                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2467                      )
2468                 (re-search-forward boundary-pat nil t)
2469                 (let ((bb (match-beginning 0)) eb tag)
2470                   (setq tag (format "\n--<<%s>>-{\n" stype))
2471                   (goto-char bb)
2472                   (insert tag)
2473                   (setq bb (+ bb (length tag)))
2474                   (re-search-forward
2475                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2476                    nil t)
2477                   (setq eb (match-beginning 0))
2478                   (replace-match (format "--}-<<%s>>\n" stype))
2479                   (save-restriction
2480                     (narrow-to-region bb eb)
2481                     (goto-char (point-min))
2482                     (while (re-search-forward boundary-pat nil t)
2483                       (let ((beg (match-beginning 0))
2484                             end)
2485                         (delete-region beg (match-end 0))
2486                         (save-excursion
2487                           (if (re-search-forward boundary-pat nil t)
2488                               (setq end (match-beginning 0))
2489                             (setq end (point-max))
2490                             )
2491                           (save-restriction
2492                             (narrow-to-region beg end)
2493                             (mime-edit-decode-buffer not-decode-text)
2494                             (goto-char (point-max))
2495                             ))))
2496                     ))
2497                 (goto-char (point-min))
2498                 (or (= (point-min) 1)
2499                     (delete-region (point-min)
2500                                    (if (search-forward "\n\n" nil t)
2501                                        (match-end 0)
2502                                      (point-min)
2503                                      )))
2504                 ))
2505              (t
2506               (let* (charset
2507                      (pstr
2508                       (let ((bytes (+ 14 (length ctype))))
2509                         (mapconcat (function
2510                                     (lambda (attr)
2511                                       (if (string-equal (car attr) "charset")
2512                                           (progn
2513                                             (setq charset (cdr attr))
2514                                             "")
2515                                         (let* ((str
2516                                                 (concat (car attr)
2517                                                         "=" (cdr attr))
2518                                                 )
2519                                                (bs (length str))
2520                                                )
2521                                           (setq bytes (+ bytes bs 2))
2522                                           (if (< bytes 76)
2523                                               (concat "; " str)
2524                                             (setq bytes (+ bs 1))
2525                                             (concat ";\n " str)
2526                                             )
2527                                           ))))
2528                                    params "")))
2529                      encoding
2530                      encoded)
2531                 (save-excursion
2532                   (if (re-search-forward
2533                        "Content-Transfer-Encoding:" nil t)
2534                       (let ((beg (match-beginning 0))
2535                             (hbeg (match-end 0))
2536                             (end (std11-field-end)))
2537                         (setq encoding
2538                               (eliminate-top-spaces
2539                                (std11-unfold-string
2540                                 (buffer-substring hbeg end))))
2541                         (if (or charset (string-equal type "text"))
2542                             (progn
2543                               (delete-region beg (1+ end))
2544                               (goto-char (point-min))
2545                               (if (search-forward "\n\n" nil t)
2546                                   (progn
2547                                     (mime-decode-region
2548                                      (match-end 0)(point-max) encoding)
2549                                     (setq encoded t
2550                                           encoding nil)
2551                                     )))))))
2552                 (if (or encoded (not not-decode-text))
2553                     (decode-mime-charset-region
2554                      (point-min)(point-max)
2555                      (or charset default-mime-charset))
2556                   )
2557                 (let ((he
2558                        (if (re-search-forward "^$" nil t)
2559                            (match-end 0)
2560                          (point-min)
2561                          )))
2562                   (if (= (point-min) 1)
2563                       (progn
2564                         (goto-char he)
2565                         (insert
2566                          (concat "\n"
2567                                  (mime-create-tag
2568                                   (concat type "/" stype pstr) encoding)))
2569                         )
2570                     (delete-region (point-min) he)
2571                     (insert
2572                      (mime-create-tag
2573                       (concat type "/" stype pstr) encoding))
2574                     ))
2575                 ))))
2576         (or not-decode-text
2577             (decode-mime-charset-region (point-min) (point-max)
2578                                         default-mime-charset)
2579             )
2580         ))))
2581
2582 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2583   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2584 Content-Type and Content-Transfer-Encoding header fields will be
2585 converted to MIME-Edit tags."
2586   (interactive)
2587   (goto-char (point-min))
2588   (if (search-forward
2589        (concat "\n" (regexp-quote mail-header-separator) "\n")
2590        nil t)
2591       (replace-match "\n\n")
2592     )
2593   (mime-edit-decode-buffer not-decode-text)
2594   (goto-char (point-min))
2595   (save-restriction
2596     (std11-narrow-to-header)
2597     (goto-char (point-min))
2598     (while (re-search-forward mime-edit-again-ignored-field-regexp nil t)
2599       (delete-region (match-beginning 0) (1+ (std11-field-end)))
2600       ))
2601   (or no-separator
2602       (and (re-search-forward "^$")
2603            (replace-match mail-header-separator)
2604            ))
2605   (or not-turn-on
2606       (turn-on-mime-edit)
2607       ))
2608
2609
2610 ;;; @ end
2611 ;;;
2612
2613 (provide 'mime-edit)
2614
2615 (run-hooks 'mime-edit-load-hook)
2616
2617 ;;; mime-edit.el ends here