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