tm 7.22.
[elisp/tm.git] / tm-edit.el
1 ;;;
2 ;;; tm-edit.el --- Simple MIME Composer for GNU Emacs
3 ;;;
4
5 ;; Copyright (C) 1993 UMEDA Masanobu
6 ;; Copyright (C) 1994,1995 MORIOKA Tomohiko
7
8 ;; Author: UMEDA Masanobu <umerin@mse.kyutech.ac.jp>
9 ;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
10 ;; Keywords: mail, news, MIME, multimedia, multilingual
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU 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
26 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
27
28 ;;; Commentary:
29
30 ;; This is an Emacs minor mode for editing Internet multimedia
31 ;; messages formatted in MIME (RFC 1521 and RFC 1522). All messages in
32 ;; this mode are composed in the tagged MIME format, that are
33 ;; described in the following examples. The messages composed in the
34 ;; tagged MIME format are automatically translated into a MIME
35 ;; compliant message when exiting the mode.
36
37 ;; Mule (a multilingual extension to Emacs 18 and 19) has a capability
38 ;; of handling multilingual text in limited ISO-2022 manner that is
39 ;; based on early experiences in Japanese Internet community and
40 ;; resulted in RFC 1468 (ISO-2022-JP charset for MIME). In order to
41 ;; enable multilingual capability in single text message in MIME,
42 ;; charset of multilingual text written in Mule is declared as either
43 ;; `ISO-2022-JP-2' [RFC 1554] or `ISO-2022-INT-1'. Mule is required
44 ;; for reading the such messages.
45
46 ;; This MIME composer can work with Mail mode, mh-e letter Mode, and
47 ;; News mode.  First of all, you need the following autoload
48 ;; definition to load mime/editor-mode automatically:
49 ;;
50 ;; (autoload 'mime/editor-mode "tm-edit"
51 ;;      "Minor mode for editing MIME message." t)
52 ;;
53 ;; In case of Mail mode (includes VM mode), you need the following
54 ;; hook definition:
55 ;;
56 ;; (add-hook 'mail-mode-hook 'mime/editor-mode)
57 ;; (add-hook 'mail-send-hook 'mime-editor/maybe-translate)
58 ;;
59 ;; In case of MH-E, you need the following hook definition:
60 ;;
61 ;; (add-hook 'mh-letter-mode-hook
62 ;;           (function
63 ;;            (lambda ()
64 ;;              (mime/editor-mode)
65 ;;              (make-local-variable 'mail-header-separator)
66 ;;              (setq mail-header-separator "--------")
67 ;;              ))))
68 ;; (add-hook 'mh-before-send-letter-hook 'mime-editor/maybe-translate)
69 ;;
70 ;; In case of News mode, you need the following hook definition:
71 ;;
72 ;; (add-hook 'news-reply-mode-hook 'mime/editor-mode)
73 ;; (add-hook 'news-inews-hook 'mime-editor/maybe-translate)
74 ;;
75 ;; In case of Emacs 19, it is possible to emphasize the message tags
76 ;; using font-lock mode as follows:
77 ;;
78 ;; (add-hook 'mime/editor-mode-hook
79 ;;           (function
80 ;;            (lambda ()
81 ;;              (font-lock-mode 1)
82 ;;              (setq font-lock-keywords (list mime-editor/tag-regexp))
83 ;;              ))))
84
85 ;; The message tag looks like:
86 ;;
87 ;;      --[[TYPE/SUBTYPE;PARAMETERS][ENCODING]]
88 ;;
89 ;; The tagged MIME message examples:
90 ;;
91 ;; This is a conventional plain text.  It should be translated into
92 ;; text/plain.
93 ;; 
94 ;;--[[text/plain]]
95 ;; This is also a plain text.  But, it is explicitly specified as is.
96 ;;
97 ;;--[[text/plain; charset=ISO-2022-JP]]
98 ;; \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9%H$G$9\e(B.
99 ;;
100 ;;--[[text/richtext]]
101 ;; <center>This is a richtext.</center>
102 ;;
103 ;;--[[image/gif][base64]]^M...image encoded in base64 comes here...
104 ;;
105 ;;--[[audio/basic][base64]]^M...audio encoded in base64 comes here...
106
107 ;; LCD Archive Entry:
108 ;; mime|Masanobu UMEDA|umerin@mse.kyutech.ac.jp|
109 ;; Simple MIME Composer|
110 ;; $Date: 1995/11/03 08:32:03 $|$Revision: 7.15 $|~/misc/mime.el.Z|
111
112 ;;; Code:
113
114 (require 'sendmail)
115 (require 'mail-utils)
116 (require 'mel)
117 (require 'tl-822)
118 (require 'tl-list)
119 (require 'tm-view)
120 (require 'tm-ew-e)
121 (require 'signature)
122
123
124 ;;; @ version
125 ;;;
126
127 (defconst mime-editor/RCS-ID
128   "$Id: tm-edit.el,v 7.15 1995/11/03 08:32:03 morioka Exp morioka $")
129
130 (defconst mime-editor/version (get-version-string mime-editor/RCS-ID))
131
132
133 ;;; @ variables
134 ;;;
135
136 (defvar mime-prefix "\C-c\C-x"
137   "*Keymap prefix for MIME commands.")
138
139 (defvar mime-signature-file "~/.signature.rtf"
140   "*Signature file to be included as a part of a multipart message.")
141
142 (defvar mime-ignore-preceding-spaces nil
143   "*Ignore preceding white spaces if non-nil.")
144
145 (defvar mime-ignore-trailing-spaces nil
146   "*Ignore trailing white spaces if non-nil.")
147
148 (defvar mime-ignore-same-text-tag t
149   "*Ignore preceding text content-type tag that is same with new one.
150 If non-nil, the text tag is not inserted unless something different.")
151
152 (defvar mime-auto-hide-body t
153   "*Hide non-textual body encoded in base64 after insertion if non-nil.")
154
155 (defvar mime-body-charset-chooser
156   (cond ((boundp 'NEMACS)
157          (function mime-body-charset-chooser-for-nemacs))
158         ((featurep 'mule)
159          (function mime-body-charset-chooser-for-mule))
160         ((string-match "^19\\." emacs-version)
161          (function mime-body-charset-chooser-for-emacs19))
162         (t                              ;ASCII only emacs
163          (function mime-body-charset-chooser-for-emacs18)))
164   "*Function to identify charset and encoding of a text in a given region.
165 The value is a form of (CHARSET . ENCODING), where ENCODING must be a
166 full name, such as base64.")
167
168 (defvar mime-string-encoder
169   (cond ((boundp 'NEMACS)
170          (function mime-string-encoder-for-nemacs))
171         ((featurep 'mule)
172          (function mime-string-encoder-for-mule))
173         ((string-match "^19\\." emacs-version)
174          (function mime-string-encoder-for-emacs19))
175         (t                              ;ASCII only emacs
176          (function mime-string-encoder-for-emacs18)))
177   "*Function to encode a string for given encoding method.
178 The method is a form of (CHARSET . ENCODING).")
179
180 (defvar mime-voice-recorder
181   (function mime-voice-recorder-for-sun)
182   "*Function to record a voice message and return a buffer that contains it.")
183
184 (defvar mime/editor-mode-hook nil
185   "*Hook called when enter MIME mode.")
186
187 (defvar mime-editor/translate-hook nil
188   "*Hook called before translating into a MIME compliant message.
189 To insert a signature file specified by mime-signature-file
190 (`.signature.rtf' by default) automatically, call the function
191 `mime-editor/insert-signature' from this hook.")
192
193 (defvar mime-editor/exit-hook nil
194   "*Hook called when exit MIME mode.")
195
196 (defvar mime-content-types
197   '(("text"
198      ;; Charset parameter need not to be specified, since it is
199      ;; defined automatically while translation.
200      ("plain"
201       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
202       )
203      ("richtext"
204       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
205       )
206      ("enriched"
207       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
208       )
209      ("x-latex"
210       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
211       )
212      ("html"
213       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
214       )
215      ("x-rot13-47")
216      )
217     ("message"
218      ("external-body"
219       ("access-type"
220        ("anon-ftp"
221         ("site" "ftp.jaist.ac.jp" "wnoc-fuk.wide.ad.jp" "nic.karrn.ad.jp")
222         ("directory" "/pub/GNU/elisp/mime")
223         ("name")
224         ("mode" "binary" "ascii"))
225        ("ftp" ("site") ("directory") ("name") ("mode" "binary" "ascii"))
226        ("tftp"        ("site") ("name"))
227        ("afs"         ("site") ("name"))
228        ("local-file"  ("site") ("name"))
229        ("mail-server" ("server" "ftpmail@nic.karrn.ad.jp"))
230        ))
231      ("rfc822")
232      )
233     ("application"
234      ("octet-stream"
235       ("name")
236       ("type" "" "tar" "shar")
237       ("conversions"))
238      ("postscript")
239      ("x-kiss" ("x-cnf")))
240     ("image"
241      ("gif")
242      ("jpeg")
243      ("tiff")
244      ("x-pic")
245      ("x-xwd")
246      ("x-xbm")
247      )
248     ("audio" ("basic"))
249     ("video" ("mpeg"))
250     )
251   "*Alist of content-type, subtype, parameters and its values.")
252
253 (defvar mime-file-types
254   '(("\\.rtf$"
255      "text"     "richtext"      nil     nil)
256     ("\\.html$"
257      "text"     "html"          nil     nil)
258     ("\\.ps$"
259      "application" "postscript" nil     "quoted-printable")
260     ("\\.gif$"
261      "image"    "gif"           nil     "base64"
262      (("Content-Description" . file))
263      )
264     ("\\.jpg$"
265      "image"    "jpeg"          nil     "base64")
266     ("\\.xwd$"
267      "image"    "x-xwd"         nil     "base64")
268     ("\\.xbm$"
269      "image"    "x-xbm"         nil     "base64")
270     ("\\.pic$"
271      "image"    "x-pic"         nil     "base64"
272      (("Content-Description" . file))
273      )
274     ("\\.tiff$"
275      "image"    "tiff"          nil     "base64")
276     ("\\.au$"
277      "audio"    "basic"         nil     "base64")
278     ("\\.mpg$"
279      "video"    "mpeg"          nil     "base64")
280     ("\\.el$"
281      "application" "octet-stream" (("name" . file)
282                                    ("type" . "emacs-lisp")) "7bit")
283     ("\\.lsp$"
284      "application" "octet-stream" (("name" . file)
285                                    ("type" . "common-lisp")) "7bit")
286     ("\\.tar.gz$"
287      "application" "octet-stream" (("name" . file)
288                                    ("type" . "tar")
289                                    ("conversions" . "gzip")) nil)
290     ("\\.diff$"
291      "application" "octet-stream" (("name" . file)
292                                    ("type" . "patch")) nil)
293     ("\\.signature"
294      "text"     "plain"         nil     nil)
295     (".*"       nil             nil     nil     nil)
296     )
297   "*Alist of file name, types, parameters, and default encoding.
298 If encoding is nil, it is determined from its contents.")
299
300 (defvar mime-editor/split-message t)
301
302 (defvar mime-editor/message-default-max-length 1000)
303
304 (defvar mime-editor/message-max-length-alist
305   '((news-reply-mode . 500)))
306
307 (defconst mime-editor/message-nuke-headers
308   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\)")
309
310 (defvar mime-editor/blind-fields-regexp "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)")
311
312 (defvar mime-editor/message-default-sender-alist
313   '((mail-mode . mail-send-and-exit)
314     (mh-letter-mode . mh-send-letter)
315     (news-reply-mode . gnus-inews-news)
316     ))
317
318 (defvar mime-editor/message-sender-alist
319   '((mail-mode
320      . (lambda ()
321          (interactive)
322          (sendmail-send-it)
323          ))
324     (mh-letter-mode
325      . (lambda (&optional arg)
326          (interactive "P")
327          (write-region (point-min) (point-max)
328                        mime-editor/draft-file-name nil 'no-message)
329          (cond (arg
330                 (pop-to-buffer "MH mail delivery")
331                 (erase-buffer)
332                 (mh-exec-cmd-output mh-send-prog t "-watch" "-nopush"
333                                     "-nodraftfolder"
334                                     mh-send-args mime-editor/draft-file-name)
335                 (goto-char (point-max)) ; show the interesting part
336                 (recenter -1)
337                 (sit-for 1))
338                (t
339                 (apply 'mh-exec-cmd-quiet t mh-send-prog 
340                        (mh-list-to-string
341                         (list "-nopush" "-nodraftfolder"
342                               "-noverbose" "-nowatch"
343                               mh-send-args mime-editor/draft-file-name)))))
344          ))
345     ))
346
347 (defvar mime-editor/window-config-alist
348   '((mail-mode       . nil)
349     (mh-letter-mode  . mh-previous-window-config)
350     (news-reply-mode . (cond ((boundp 'gnus-winconf-post-news)
351                               (prog1
352                                   gnus-winconf-post-news
353                                 (setq gnus-winconf-post-news nil)
354                                 ))
355                              ((boundp 'gnus-prev-winconf)
356                               (prog1
357                                   gnus-prev-winconf
358                                 (setq gnus-prev-winconf nil)
359                                 ))
360                              ))
361     ))
362
363 (defvar mime-editor/news-reply-mode-server-running nil)
364
365 (defvar mime-editor/message-before-send-hook-alist
366   '((mh-letter-mode . mh-before-send-letter-hook)))
367
368 (defvar mime-editor/message-after-send-hook-alist
369   '((mh-letter-mode
370      . (lambda ()
371          (if mh-annotate-char
372              (mh-annotate-msg mh-sent-from-msg
373                               mh-sent-from-folder
374                               mh-annotate-char
375                               "-component" mh-annotate-field
376                               "-text"
377                               (format "\"%s %s\""
378                                       (mh-get-field "To:")
379                                       (mh-get-field "Cc:"))))))
380     ))
381
382 (defvar mime-editor/message-inserter-alist nil)
383
384 (defvar mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
385   "*Specify MIME tspecials.
386 Tspecials means any character that matches with it in header must be quoted.")
387
388 (defconst mime-editor/single-part-tag-regexp
389   "^--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
390   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
391
392 (defconst mime-editor/multipart-beginning-regexp "^--<<\\([^<>]+\\)>>-{\n")
393
394 (defconst mime-editor/multipart-end-regexp "^--}-<<\\([^<>]+\\)>>\n")
395
396 (defconst mime-editor/beginning-tag-regexp
397   (regexp-or mime-editor/single-part-tag-regexp
398              mime-editor/multipart-beginning-regexp))
399
400 (defconst mime-editor/end-tag-regexp
401   (regexp-or mime-editor/single-part-tag-regexp
402              mime-editor/multipart-end-regexp))
403
404 (defconst mime-editor/tag-regexp
405   (regexp-or mime-editor/single-part-tag-regexp
406              mime-editor/multipart-beginning-regexp
407              mime-editor/multipart-end-regexp))
408
409 (defvar mime-tag-format "--[[%s]]"
410   "*Control-string making a MIME tag.")
411
412 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
413   "*Control-string making a MIME tag with encoding.")
414
415 (defvar mime-multipart-boundary "Multipart"
416   "*Boundary of a multipart message.")
417
418
419 ;;; @@ buffer local variables
420 ;;;
421
422 (defvar mime/editor-mode-old-local-map nil)
423 (defvar mime/editor-mode-old-selective-display nil)
424 (defvar mime/editing-buffer nil)
425
426 \f
427 ;;; @ constants
428 ;;;
429
430 (defconst mime-editor/mime-version-value
431   (format "1.0 (generated by tm-edit %s)" mime-editor/version)
432   "MIME version number.")
433
434 (defvar mime/editor-mode-flag nil)
435 (make-variable-buffer-local 'mime/editor-mode-flag)
436
437 (set-alist 'minor-mode-alist 'mime/editor-mode-flag '(" MIME-Edit"))
438
439 (defun mime-editor/define-keymap (keymap)
440   "Add mime-editor commands to KEYMAP."
441   (if (not (keymapp keymap))
442       nil
443     (define-key keymap "\C-t" 'mime-editor/insert-text)
444     (define-key keymap "\C-i" 'mime-editor/insert-file)
445     (define-key keymap "\C-e" 'mime-editor/insert-external)
446     (define-key keymap "\C-v" 'mime-editor/insert-voice)
447     (define-key keymap "\C-y" 'mime-editor/insert-message)
448     (define-key keymap "\C-w" 'mime-editor/insert-signature)
449     (define-key keymap "\C-s" 'mime-editor/insert-signature)
450     (define-key keymap "\C-m" 'mime-editor/insert-tag)
451     (define-key keymap "a"    'mime-editor/enclose-alternative-region)
452     (define-key keymap "p"    'mime-editor/enclose-parallel-region)
453     (define-key keymap "m"    'mime-editor/enclose-mixed-region)
454     (define-key keymap "d"    'mime-editor/enclose-digest-region)
455     (define-key keymap "\C-p" 'mime-editor/preview-message)
456     (define-key keymap "\C-z" 'mime-editor/exit)
457     (define-key keymap "?"    'mime-editor/help)
458     ))
459
460 (defconst mime-editor/menu-title "MIME-Edit")
461
462 (defconst mime-editor/menu-list
463   '((mime-help  "Describe MIME Mode"    mime-editor/help)
464     (file       "Insert File"           mime-editor/insert-file)
465     (external   "Insert External"       mime-editor/insert-external)
466     (voice      "Insert Voice"          mime-editor/insert-voice)
467     (mail       "Insert Mail"           mime-editor/insert-message)
468     (signature  "Insert Signature"      mime-editor/insert-signature)
469     (text       "Insert Text"           mime-editor/insert-text)
470     (tag        "Insert Tag"            mime-editor/insert-tag)
471     (alternative "Enclose as alternative"
472                  mime-editor/enclose-alternative-region)
473     (parallel   "Enclose as parallel"   mime-editor/enclose-parallel-region)
474     (mixed      "Enclose as serial"     mime-editor/enclose-mixed-region)
475     (digest     "Enclose as digest"     mime-editor/enclose-digest-region)
476     (preview    "Preview Message"       mime-editor/preview-message)
477     )
478   "MIME-edit menubar entry.")
479
480 (defun mime-editor/define-menu-for-emacs19 ()
481   "Define menu for Emacs 19."
482   (define-key (current-local-map) [menu-bar mime-edit]
483     (cons mime-editor/menu-title
484           (make-sparse-keymap mime-editor/menu-title)))
485   (mapcar (function
486            (lambda (item)
487              (define-key (current-local-map)
488                (vector 'menu-bar 'mime-edit (car item))
489                (cons (nth 1 item)(nth 2 item))
490                )
491              ))
492           (reverse mime-editor/menu-list)
493           ))
494
495 ;;; modified by Pekka Marjola <pema@niksula.hut.fi>
496 ;;;     1995/9/5 (c.f. [tm-eng:69])
497 (defun mime-editor/define-menu-for-xemacs ()
498   "Define menu for Emacs 19."
499   (cond ((featurep 'menubar)
500          (make-local-variable 'current-menubar)
501          (set-buffer-menubar current-menubar)
502          (add-submenu nil
503                       (cons mime-editor/menu-title
504                             (mapcar (function
505                                      (lambda (item)
506                                        (vector (nth 1 item)(nth 2 item)
507                                                mime/editor-mode-flag)
508                                        ))
509                                     mime-editor/menu-list)))
510          )))
511 ;;; end
512
513 ;;;###autoload
514 (defun mime/editor-mode ()
515   "MIME minor mode for editing the tagged MIME message.
516
517 In this mode, basically, the message is composed in the tagged MIME
518 format.  The message tag looks like:
519
520         `--[[text/plain; charset=ISO-2022-JP][7bit]]'.
521
522 The tag specifies the MIME content type, subtype, optional parameters
523 and transfer encoding of the message following the tag.  Messages
524 without any tag are treated as `text/plain' by default.  Charset and
525 transfer encoding are automatically defined unless explicitly
526 specified.  Binary messages such as audio and image are usually hidden
527 using selective-display facility.  The messages in the tagged MIME
528 format are automatically translated into a MIME compliant message when
529 exiting this mode.
530
531 Available charsets depend on Emacs version being used.  The following
532 lists the available charsets of each emacs.
533
534 Emacs18:        US-ASCII is only available.
535 NEmacs:         US-ASCII and ISO-2022-JP are available.
536 Emacs19:        US-ASCII and ISO-8859-1 are available.
537 Mule:           US-ASCII, ISO-8859-* (except for ISO-8859-6),
538                 ISO-2022-JP, ISO-2022-JP-2 and ISO-2022-INT-1 are available.
539
540 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in Mule is expected to
541 be used to represent multilingual text in intermixed manner.  Any
542 languages that has no registered charset are represented as either
543 ISO-2022-JP-2 or ISO-2022-INT-1 in Mule.
544
545 Following commands are available in addition to major mode commands:
546 \\[mime-editor/insert-text]     insert a text message.
547 \\[mime-editor/insert-file]     insert a (binary) file.
548 \\[mime-editor/insert-external] insert a reference to external body.
549 \\[mime-editor/insert-voice]    insert a voice message.
550 \\[mime-editor/insert-message]  insert a mail or news message.
551 \\[mime-editor/insert-signature]        insert a signature file at end.
552 \\[mime-editor/insert-tag]      insert a new MIME tag.
553 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
554 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
555 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
556 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
557 \\[mime-editor/preview-message] preview editing MIME message.
558 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
559 \\[mime-editor/maybe-translate] exit, translate and run the original command.
560 \\[mime-editor/help]    show this help.
561
562 Additional commands are available in some major modes:
563 C-c C-c         exit, translate and run the original command.
564 C-c C-s         exit, translate and run the original command.
565
566 The following is a message example written in the tagged MIME format.
567 TABs at the beginning of the line are not a part of the message:
568
569         This is a conventional plain text.  It should be translated
570         into text/plain.
571         --[[text/plain]]
572         This is also a plain text.  But, it is explicitly specified as
573         is.
574         --[[text/plain; charset=ISO-2022-JP]]
575         \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9\e(B
576         \e$B%H$G$9\e(B.
577         --[[text/richtext]]
578         <center>This is a richtext.</center>
579         --[[image/gif][base64]]^M...image encoded in base64 here...
580         --[[audio/basic][base64]]^M...audio encoded in base64 here...
581
582 User customizable variables (not documented all of them):
583  mime-prefix
584     Specifies a key prefix for MIME minor mode commands.
585
586  mime-signature-file
587     Specifies a signature file to be included as part of a multipart
588     message.
589
590  mime-ignore-preceding-spaces
591     Preceding white spaces in a message body are ignored if non-nil.
592
593  mime-ignore-trailing-spaces
594     Trailing white spaces in a message body are ignored if non-nil.
595
596  mime-auto-fill-header
597     Fill header fields that contain encoded-words if non-nil.
598
599  mime-auto-hide-body
600     Hide a non-textual body message encoded in base64 after insertion
601     if non-nil.
602
603  mime-body-charset-chooser
604     Specifies a function to identify charset and encoding of a text in
605     a given region.  The value is a form of (CHARSET . ENCODING),
606     where ENCODING must be a full name, such as base64.
607
608  mime-string-encoder
609     Specifies a function to encode a string for given encoding method.
610     The method is a form of (CHARSET . ENCODING).
611
612  mime-voice-recorder
613     Specifies a function to record a voice message and return a buffer
614     that contains it.  The function mime-voice-recorder-for-sun is for
615     Sun SparcStations.
616
617  mime/editor-mode-hook
618     Turning on MIME mode calls the value of mime/editor-mode-hook, if
619     it is non-nil.
620
621  mime-editor/translate-hook
622     The value of mime-editor/translate-hook is called just before translating
623     the tagged MIME format into a MIME compliant message if it is
624     non-nil.  If the hook call the function mime-editor/insert-signature,
625     the signature file will be inserted automatically.
626
627  mime-editor/exit-hook
628     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
629     non-nil."
630   (interactive)
631   (if mime/editor-mode-flag
632       (error "You are already editing a MIME message.")
633     (setq mime/editor-mode-flag t)
634     ;; Remember old key bindings.
635     (make-local-variable 'mime/editor-mode-old-local-map)
636     (setq mime/editor-mode-old-local-map (current-local-map))
637     ;; Add MIME commands to current local map.
638     (use-local-map (copy-keymap (current-local-map)))
639     (if (not (lookup-key (current-local-map) mime-prefix))
640         (define-key (current-local-map) mime-prefix (make-sparse-keymap)))
641     (mime-editor/define-keymap (lookup-key (current-local-map) mime-prefix))
642     
643     ;; Define menu.  Menus for other emacs implementations are
644     ;; welcome.
645     ;;  modified by Pekka Marjola <pema@niksula.hut.fi>
646     ;;          1995/9/5 (c.f. [tm-eng:69])
647     (cond ((string-match "XEmacs\\|Lucid" emacs-version)
648            (mime-editor/define-menu-for-xemacs))
649           ((string-match "^19\\." emacs-version)
650            (mime-editor/define-menu-for-emacs19)
651            ))
652     ;; end
653     
654     ;; Remember old selective-display.
655     (make-local-variable 'mime/editor-mode-old-selective-display)
656     (setq mime/editor-mode-old-selective-display selective-display)
657     (setq selective-display t)
658     ;; I don't care about saving these.
659     (setq paragraph-start
660           (concat mime-editor/single-part-tag-regexp "\\|" paragraph-start))
661     (setq paragraph-separate
662           (concat mime-editor/single-part-tag-regexp "\\|" paragraph-separate))
663     (run-hooks 'mime/editor-mode-hook)
664     (message
665      (substitute-command-keys
666       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
667     ))
668
669 ;;;###autoload
670 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
671 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
672
673 (defun mime-editor/exit (&optional nomime no-error)
674   "Translate the tagged MIME message into a MIME compliant message.
675 With no argument encode a message in the buffer into MIME, otherwise
676 just return to previous mode."
677   (interactive "P")
678   (if (not mime/editor-mode-flag)
679       (if (null no-error)
680           (error "You aren't editing a MIME message.")
681         )
682     (if (not nomime)
683         (progn
684           (run-hooks 'mime-editor/translate-hook)
685           (mime-editor/translate-buffer)))
686     ;; Restore previous state.
687     (setq mime/editor-mode-flag nil)
688     (use-local-map mime/editor-mode-old-local-map)
689     
690     ;; modified by Pekka Marjola <pema@niksula.hut.fi>
691     ;;  1995/9/5 (c.f. [tm-eng:69])
692     (if (string-match "XEmacs\\|Lucid" emacs-version)
693         (progn
694           (delete-menu-item (list mime-editor/menu-title))
695                                         ; should rather be const
696           ;; (while mime-editor/xemacs-old-bindings
697           ;;   (eval (pop mime-editor/xemacs-old-bindings)))
698           (local-unset-key mime-prefix)))
699     ;; end
700     
701     (setq selective-display mime/editor-mode-old-selective-display)
702     (set-buffer-modified-p (buffer-modified-p))
703     (run-hooks 'mime-editor/exit-hook)
704     (message "Exit MIME editor mode.")
705     ))
706
707 (defun mime-editor/maybe-translate ()
708   (interactive)
709   (mime-editor/exit nil t)
710   (call-interactively 'mime-editor/split-and-send)
711   )
712
713 (defun mime-editor/help ()
714   "Show help message about MIME mode."
715   (interactive)
716   (with-output-to-temp-buffer "*Help*"
717     (princ "MIME editor mode:\n")
718     (princ (documentation 'mime/editor-mode))
719     (print-help-return-message)))
720
721 (defun mime-editor/insert-text ()
722   "Insert a text message.
723 Charset is automatically obtained from the mime-body-charset-chooser."
724   (interactive)
725   (if (and (mime-editor/insert-tag "text" nil nil)
726            (looking-at mime-editor/single-part-tag-regexp))
727       (progn
728         ;; Make a space between the following message.
729         (insert "\n")
730         (forward-char -1)
731         )))
732
733 (defun mime-editor/insert-file (file)
734   "Insert a message from a file."
735   (interactive "fInsert file as MIME message: ")
736   (let*  ((guess (mime-find-file-type file))
737           (pritype (nth 0 guess))
738           (subtype (nth 1 guess))
739           (parameters (nth 2 guess))
740           (default (nth 3 guess))       ;Guess encoding from its file name.
741           (fields (nth 4 guess))
742           (encoding
743            (if (not (interactive-p))
744                default
745              (completing-read
746               (concat "What transfer encoding"
747                       (if default
748                           (concat " (default "
749                                   (if (string-equal default "")
750                                       "\"\""
751                                     default)
752                                   ")"
753                                   ))
754                       ": ")
755               mime-encoding-method-alist nil t nil))))
756     (if (string-equal encoding "")
757         (setq encoding default))
758     (if (or (consp parameters) (consp fields))
759         (let ((rest parameters) cell attribute value)
760           (setq parameters "")
761           (while rest
762             (setq cell (car rest))
763             (setq attribute (car cell))
764             (setq value (cdr cell))
765             (if (eq value 'file)
766                 (setq value (file-name-nondirectory file))
767               )
768             (setq parameters (concat parameters "; " attribute "=" value))
769             (setq rest (cdr rest))
770             )
771           (setq rest fields)
772           (while rest
773             (setq cell (car rest))
774             (setq attribute (car cell))
775             (setq value (cdr cell))
776             (if (eq value 'file)
777                 (setq value (file-name-nondirectory file))
778               )
779             (setq parameters (concat parameters "\n" attribute ": " value))
780             (setq rest (cdr rest))
781             )
782           ))
783     (mime-editor/insert-tag pritype subtype parameters)
784     (mime-editor/insert-binary-file file encoding)
785     ))
786
787 (defun mime-editor/insert-external ()
788   "Insert a reference to external body."
789   (interactive)
790   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
791   ;;(forward-char -1)
792   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
793   ;;(forward-line 1)
794   (let* ((pritype (mime-prompt-for-type))
795          (subtype (mime-prompt-for-subtype pritype))
796          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
797     (and pritype
798          subtype
799          (insert "Content-Type: "
800                  pritype "/" subtype (or parameters "") "\n")))
801   (if (and (not (eobp))
802            (not (looking-at mime-editor/single-part-tag-regexp)))
803       (insert (mime-make-text-tag) "\n")))
804
805 (defun mime-editor/insert-voice ()
806   "Insert a voice message."
807   (interactive)
808   (mime-editor/insert-tag "audio" "basic" nil)
809   (let ((buffer (funcall mime-voice-recorder)))
810     (unwind-protect
811         (mime-editor/insert-binary-buffer buffer "base64")
812       (kill-buffer buffer)
813       )))
814
815 (defun mime-editor/insert-signature ()
816   "Insert a signature file specified by mime-signature-file."
817   (interactive)
818   (save-restriction
819     (apply (function mime-editor/insert-tag)
820            (prog1
821                (mime-find-file-type (insert-signature))
822              (narrow-to-region (point-min)(point))
823              ))
824     ))
825 \f
826 ;; Insert a new tag around a point.
827
828 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
829   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
830 If nothing is inserted, return nil."
831   (interactive)
832   (let ((oldtag nil)
833         (newtag nil)
834         (current (point)))
835     (setq pritype
836           (or pritype
837               (mime-prompt-for-type)))
838     (setq subtype
839           (or subtype
840               (mime-prompt-for-subtype pritype)))
841     (setq parameters
842           (or parameters
843               (mime-prompt-for-parameters pritype subtype delimiter)))
844     ;; Make a new MIME tag.
845     (setq newtag (mime-make-tag pritype subtype parameters))
846     ;; Find an current MIME tag.
847     (setq oldtag
848           (save-excursion
849             (if (mime-editor/goto-tag)
850                 (buffer-substring (match-beginning 0) (match-end 0))
851               ;; Assume content type is 'text/plan'.
852               (mime-make-tag "text" "plain")
853               )))
854     ;; We are only interested in TEXT.
855     (if (and oldtag
856              (not (mime-test-content-type
857                    (mime-editor/get-contype oldtag) "text")))
858         (setq oldtag nil))
859     (beginning-of-line)
860     (cond ((and oldtag                  ;Text
861                 (not (eobp))
862                 (save-excursion
863                   (forward-line -1)
864                   (looking-at mime-editor/beginning-tag-regexp)
865                   )
866                 (or mime-ignore-same-text-tag
867                     (not (string-equal oldtag newtag))))
868            ;; If point is at the next of current tag, move to the
869            ;; beginning of the tag to disable insertion of extra tag.
870            (forward-line -1))
871           ((and oldtag                  ;Text
872                 (not (eobp))
873                 (not (looking-at mime-editor/tag-regexp))
874                 (or mime-ignore-same-text-tag
875                     (not (string-equal oldtag newtag))))
876            ;; Copy current tag to break a text into two.
877            (save-excursion
878              (insert oldtag "\n")))
879           ((and (null oldtag)           ;Not text
880                 (not (looking-at mime-editor/tag-regexp)))
881            ;; Adjust insertion point.  In the middle of text, it is
882            ;; okay to break the text into two.  However, it should not
883            ;; be broken into two, if otherwise.
884            (goto-char (mime-editor/content-end))
885            (if (eolp)
886                (forward-line 1))
887            (if (not (bolp))
888                (insert "\n"))
889            ))
890     ;; Make a new tag.
891     (if (or (not oldtag)                ;Not text
892             (or mime-ignore-same-text-tag
893                 (not (string-equal oldtag newtag))))
894         (progn
895           ;; Mark the beginning of the tag for convenience.
896           (push-mark (point) 'nomsg)
897           (insert newtag "\n")
898           (list pritype subtype parameters) ;New tag is created.
899           )
900       ;; Restore previous point.
901       (goto-char current)
902       nil                               ;Nothing is created.
903       )
904     ))
905
906 ;; Insert the binary content after MIME tag.
907 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
908 ;;      for x-uue
909 (defun mime-editor/insert-binary-file (file &optional encoding)
910   "Insert binary FILE at point.
911 Optional argument ENCODING specifies an encoding method such as base64."
912   (let ((tmpbuf (get-buffer-create " *MIME insert*")))
913     (save-excursion
914       (set-buffer tmpbuf)
915       (erase-buffer)
916       (let ((mc-flag nil)               ;Mule
917             (file-coding-system-for-read
918              (if (featurep 'mule) *noconv*))
919             (kanji-flag nil)            ;NEmacs
920             (emx-binary-mode t)         ;Stop CRLF to LF conversion in OS/2
921             )
922         (let (jka-compr-compression-info-list
923               jam-zcat-filename-list)
924           (insert-file-contents file))))
925     (prog1
926         (if (and (stringp encoding)
927                  (string-equal (downcase encoding) "x-uue"))
928             (progn
929               (require 'mel-u)
930               (let ((uuencode-external-encoder
931                      (cons (car uuencode-external-encoder)
932                            (list (file-name-nondirectory file))
933                            )))
934                 (mime-editor/insert-binary-buffer tmpbuf encoding)
935                 ))
936           (mime-editor/insert-binary-buffer tmpbuf encoding))
937       (kill-buffer tmpbuf))))
938
939 ;; Insert the binary content after MIME tag.
940 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
941 ;;      for x-uue
942 (defun mime-editor/insert-binary-buffer (buffer &optional encoding)
943   "Insert binary BUFFER at point.
944 Optional argument ENCODING specifies an encoding method such as base64."
945   (let* ((tagend (1- (point)))          ;End of the tag
946          (hide-p (and mime-auto-hide-body
947                       (stringp encoding)
948                       (let ((en (downcase encoding)))
949                         (or (string-equal en "base64")
950                             (string-equal en "x-uue")
951                             ))))
952          )
953     (save-restriction
954       (narrow-to-region (1- (point)) (point))
955       (let ((start (point))
956             (emx-binary-mode t))        ;Stop LF to CRLF conversion in OS/2
957         (insert-buffer-substring buffer)
958         ;; Encode binary message if necessary.
959         (if encoding
960             (mime-encode-region encoding start (point-max))))
961       (if hide-p
962           (progn
963             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
964             (goto-char (point-max)))
965         ))
966     ;; Define encoding even if it is 7bit.
967     (if (stringp encoding)
968         (save-excursion
969           (goto-char tagend)            ;Make sure which line the tag is on.
970           (mime-editor/define-encoding encoding)))
971     ))
972
973 \f
974 ;; Commands work on a current message flagment.
975
976 (defun mime-editor/goto-tag ()
977   "Search for the beginning of the tagged MIME message."
978   (let ((current (point)) multipart)
979     (if (looking-at mime-editor/tag-regexp)
980         t
981       ;; At first, go to the end.
982       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
983              (goto-char (match-beginning 0)) ;For multiline tag
984              (forward-line -1)
985              (end-of-line)
986              )
987             (t
988              (goto-char (point-max))
989              ))
990       ;; Then search for the beginning. 
991       (re-search-backward mime-editor/end-tag-regexp nil t)
992       (beginning-of-line)
993       (or (looking-at mime-editor/beginning-tag-regexp)
994           ;; Restore previous point.
995           (progn
996             (goto-char current)
997             nil
998             ))
999       )))
1000
1001 (defun mime-editor/content-beginning ()
1002   "Return the point of the beginning of content."
1003   (save-excursion
1004     (let ((beg (save-excursion
1005                  (beginning-of-line) (point))))
1006       (if (mime-editor/goto-tag)
1007           (let ((top (point)))
1008             (goto-char (match-end 0))
1009             (if (and (= beg top)
1010                      (= (following-char) ?\^M))
1011                 (point)
1012               (forward-line 1)
1013               (point)))
1014         ;; Default text/plain tag.
1015         (goto-char (point-min))
1016         (re-search-forward
1017          (concat "\n" (regexp-quote mail-header-separator)
1018                  (if mime-ignore-preceding-spaces
1019                      "[ \t\n]*\n" "\n")) nil 'move)
1020         (point))
1021       )))
1022
1023 (defun mime-editor/content-end ()
1024   "Return the point of the end of content."
1025   (save-excursion
1026     (let ((beg (save-excursion
1027                  (beginning-of-line) (point))))
1028       (if (mime-editor/goto-tag)
1029           (let ((top (point)))
1030             (goto-char (match-end 0))
1031             (if (and (= beg top)        ;Must be on the same line.
1032                      (= (following-char) ?\^M))
1033                 (progn
1034                   (end-of-line)
1035                   (point))
1036               ;; Move to the end of this text.
1037               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1038                   ;; Don't forget a multiline tag.
1039                   (goto-char (match-beginning 0)))
1040               (point)
1041               ))
1042         ;; Assume the message begins with text/plain.
1043         (goto-char (mime-editor/content-beginning))
1044         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1045             ;; Don't forget a multiline tag.
1046             (goto-char (match-beginning 0)))
1047         (point))
1048       )))
1049
1050 (defun mime-editor/define-charset (charset)
1051   "Set charset of current tag to CHARSET."
1052   (save-excursion
1053     (if (mime-editor/goto-tag)
1054         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1055           (delete-region (match-beginning 0) (match-end 0))
1056           (insert
1057            (mime-create-tag (mime-set-parameter
1058                              (mime-editor/get-contype tag) "charset" charset)
1059                             (mime-editor/get-encoding tag))))
1060       )))
1061
1062 (defun mime-editor/define-encoding (encoding)
1063   "Set encoding of current tag to ENCODING."
1064   (save-excursion
1065     (if (mime-editor/goto-tag)
1066         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1067           (delete-region (match-beginning 0) (match-end 0))
1068           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1069       )))
1070
1071 (defun mime-editor/choose-charset ()
1072   "Choose charset of a text following current point."
1073   (save-excursion
1074     (let* ((beg (point))
1075            (end (mime-editor/content-end)))
1076       (car (funcall mime-body-charset-chooser beg end)))))
1077
1078 (defun mime-editor/choose-encoding ()
1079   "Choose encoding of a text following current point."
1080   (save-excursion
1081     (let* ((beg (point))
1082            (end (mime-editor/content-end)))
1083       (cdr (funcall mime-body-charset-chooser beg end)))))
1084
1085 (defun mime-make-text-tag (&optional subtype)
1086   "Make a tag for a text after current point.
1087 Subtype of text type can be specified by an optional argument SUBTYPE.
1088 Otherwise, it is obtained from mime-content-types."
1089   (let* ((pritype "text")
1090          (subtype (or subtype
1091                       (car (car (cdr (assoc pritype mime-content-types)))))))
1092     ;; Charset should be defined later.
1093     (mime-make-tag pritype subtype)))
1094
1095 \f
1096 ;; Tag handling functions
1097
1098 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1099   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1100   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1101                            (or parameters ""))
1102                    encoding))
1103
1104 (defun mime-create-tag (contype &optional encoding)
1105   "Make a tag with CONTENT-TYPE and optional ENCODING."
1106   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1107           contype encoding))
1108
1109 (defun mime-editor/get-contype (tag)
1110   "Return Content-Type (including parameters) of TAG."
1111   (and (stringp tag)
1112        (or (string-match mime-editor/single-part-tag-regexp tag)
1113            (string-match mime-editor/multipart-beginning-regexp tag)
1114            (string-match mime-editor/multipart-end-regexp tag)
1115            )
1116        (substring tag (match-beginning 1) (match-end 1))
1117        ))
1118
1119 (defun mime-editor/get-encoding (tag)
1120   "Return encoding of TAG."
1121   (and (stringp tag)
1122        (string-match mime-editor/single-part-tag-regexp tag)
1123        (match-beginning 3)
1124        (not (= (match-beginning 3) (match-end 3)))
1125        (substring tag (match-beginning 3) (match-end 3))))
1126
1127 (defun mime-get-parameter (contype parameter)
1128   "For given CONTYPE return value for PARAMETER.
1129 Nil if no such parameter."
1130   (if (string-match
1131        (concat
1132         ";[ \t\n]*"
1133         (regexp-quote parameter)
1134         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1135        contype)
1136       (substring contype (match-beginning 1) (match-end 1))
1137     nil                                 ;No such parameter
1138     ))
1139
1140 (defun mime-set-parameter (contype parameter value)
1141   "For given CONTYPE set PARAMETER to VALUE."
1142   (if (string-match
1143        (concat
1144         ";[ \t\n]*\\("
1145         (regexp-quote parameter)
1146         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1147        contype)
1148       ;; Change value
1149       (concat (substring contype 0 (match-beginning 1))
1150               parameter "=" value
1151               (substring contype (match-end 1)))
1152     (concat contype "; " parameter "=" value)))
1153
1154 (defun mime-strip-parameters (contype)
1155   "Return primary content-type and subtype without parameters for CONTYPE."
1156   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1157       (substring contype (match-beginning 1) (match-end 1)) nil))
1158
1159 (defun mime-test-content-type (contype type &optional subtype)
1160   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1161   (and (stringp contype)
1162        (stringp type)
1163        (string-match
1164         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1165         (downcase contype))))
1166
1167 \f
1168 ;; Basic functions
1169
1170 (defun mime-find-file-type (file)
1171   "Guess Content-Type, subtype, and parameters from FILE."
1172   (let ((guess nil)
1173         (guesses mime-file-types))
1174     (while (and (not guess) guesses)
1175       (if (string-match (car (car guesses)) file)
1176           (setq guess (cdr (car guesses))))
1177       (setq guesses (cdr guesses)))
1178     guess
1179     ))
1180
1181 (defun mime-prompt-for-type ()
1182   "Ask for Content-type."
1183   (let ((type ""))
1184     ;; Repeat until primary content type is specified.
1185     (while (string-equal type "")
1186       (setq type
1187             (completing-read "What content type: "
1188                              mime-content-types
1189                              nil
1190                              'require-match ;Type must be specified.
1191                              nil
1192                              ))
1193       (if (string-equal type "")
1194           (progn
1195             (message "Content type is required.")
1196             (beep)
1197             (sit-for 1)
1198             ))
1199       )
1200     type
1201     ))
1202
1203 (defun mime-prompt-for-subtype (pritype)
1204   "Ask for Content-type subtype of Content-Type PRITYPE."
1205   (let* ((default (car (car (cdr (assoc pritype mime-content-types)))))
1206          (answer
1207           (completing-read
1208            (if default
1209                (concat
1210                 "What content subtype: (default " default ") ")
1211              "What content subtype: ")
1212            (cdr (assoc pritype mime-content-types))
1213            nil
1214            'require-match               ;Subtype must be specified.
1215            nil
1216            )))
1217     (if (string-equal answer "") default answer)))
1218
1219 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1220   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1221 Optional DELIMITER specifies parameter delimiter (';' by default)."
1222   (let* ((delimiter (or delimiter "; "))
1223          (parameters
1224           (mapconcat
1225            (function identity)
1226            (delq nil
1227                  (mime-prompt-for-parameters-1
1228                   (cdr (assoc subtype
1229                               (cdr (assoc pritype mime-content-types))))))
1230            delimiter
1231            )))
1232     (if (and (stringp parameters)
1233              (not (string-equal parameters "")))
1234         (concat delimiter parameters)
1235       ""                                ;"" if no parameters
1236       )))
1237
1238 (defun mime-prompt-for-parameters-1 (optlist)
1239   (apply (function append)
1240          (mapcar (function mime-prompt-for-parameter) optlist)))
1241
1242 (defun mime-prompt-for-parameter (parameter)
1243   "Ask for PARAMETER.
1244 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1245   (let* ((prompt (car parameter))
1246          (choices (mapcar (function
1247                            (lambda (e)
1248                              (if (consp e) e (list e))))
1249                           (cdr parameter)))
1250          (default (car (car choices)))
1251          (answer nil))
1252     (if choices
1253         (progn
1254           (setq answer
1255                 (completing-read
1256                  (concat "What " prompt
1257                          ": (default "
1258                          (if (string-equal default "") "\"\"" default)
1259                          ") ")
1260                  choices nil nil ""))
1261           ;; If nothing is selected, use default.
1262           (if (string-equal answer "")
1263               (setq answer default)))
1264       (setq answer
1265             (read-string (concat "What " prompt ": "))))
1266     (cons (if (and answer
1267                    (not (string-equal answer "")))
1268               (concat prompt "="
1269                       ;; Note: control characters ignored!
1270                       (if (string-match mime-tspecials-regexp answer)
1271                           (concat "\"" answer "\"") answer)))
1272           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1273     ))
1274
1275 (defun mime-encode-string (encoding string)
1276   "Using ENCODING encode a STRING.
1277 If the STRING is too long, the encoded string may be broken into
1278 several lines."
1279   (save-excursion
1280     (set-buffer (get-buffer-create " *MIME encoding*"))
1281     (erase-buffer)
1282     (insert string)
1283     (mime-encode-region encoding (point-min) (point-max))
1284     (prog1
1285         (buffer-substring (point-min) (point-max))
1286       (kill-buffer (current-buffer)))))
1287
1288 (defun mime-decode-string (encoding string)
1289   "Using ENCODING decode a STRING."
1290   (save-excursion
1291     (set-buffer (get-buffer-create " *MIME decoding*"))
1292     (erase-buffer)
1293     (insert string)
1294     (mime-decode-region encoding (point-min) (point-max))
1295     (prog1
1296         (buffer-substring (point-min) (point-max))
1297       (kill-buffer (current-buffer)))))
1298
1299 (defun mime-flag-region (from to flag)
1300   "Hides or shows lines from FROM to TO, according to FLAG.
1301 If FLAG is `\\n' (newline character) then text is shown,
1302 while if FLAG is `\\^M' (control-M) the text is hidden."
1303   (let ((buffer-read-only nil)          ;Okay even if write protected.
1304         (modp (buffer-modified-p)))
1305     (unwind-protect
1306         (subst-char-in-region from to
1307                               (if (= flag ?\n) ?\^M ?\n)
1308                               flag t)
1309       (set-buffer-modified-p modp))))
1310
1311 \f
1312 ;; Translate the tagged MIME messages into a MIME compliant message.
1313
1314 (defun mime-editor/translate-buffer ()
1315   "Encode the tagged MIME message in current buffer in MIME compliant message."
1316   (interactive)
1317   (mime/encode-message-header)
1318   (mime-editor/translate-body)
1319   )
1320
1321 (defun mime-editor/translate-body ()
1322   "Encode the tagged MIME body in current buffer in MIME compliant message."
1323   (interactive)
1324   (save-excursion
1325     (let ((boundary
1326            (concat mime-multipart-boundary " " (current-time-string)))
1327           (i 1)
1328           (time (current-time-string))
1329           ret)
1330       (while (mime-editor/process-multipart-1
1331               (format "%s %s-%d" mime-multipart-boundary time i))
1332         (setq i (1+ i))
1333         )
1334       (save-restriction
1335         ;; We are interested in message body.
1336         (let* ((beg
1337                 (progn
1338                   (goto-char (point-min))
1339                   (re-search-forward
1340                    (concat "\n" (regexp-quote mail-header-separator)
1341                            (if mime-ignore-preceding-spaces
1342                                "[ \t\n]*\n" "\n")) nil 'move)
1343                   (point)))
1344                (end
1345                 (progn
1346                   (goto-char (point-max))
1347                   (and mime-ignore-trailing-spaces
1348                        (re-search-backward "[^ \t\n]\n" beg t)
1349                        (forward-char 1))
1350                   (point))))
1351           (setq ret (mime-editor/translate-region
1352                      beg end
1353                      (format "%s %s-%d" mime-multipart-boundary time i)))
1354           ))
1355       (let ((contype (car ret))         ;Content-Type
1356             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1357             )
1358         ;; Make primary MIME headers.
1359         (or (mail-position-on-field "Mime-Version")
1360             (insert mime-editor/mime-version-value))
1361         ;; Remove old Content-Type and other fields.
1362         (save-restriction
1363           (goto-char (point-min))
1364           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1365           (narrow-to-region (point-min) (point))
1366           (goto-char (point-min))
1367           (mime-delete-field "Content-Type")
1368           (mime-delete-field "Content-Transfer-Encoding"))
1369         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1370         (mail-position-on-field "Content-Type")
1371         (insert contype)
1372         (if encoding
1373             (progn
1374               (mail-position-on-field "Content-Transfer-Encoding")
1375               (insert encoding)))
1376         ))))
1377
1378 (defun mime-editor/normalize-body ()
1379   "Normalize the body part by inserting appropriate message tags."
1380   ;; Insert the first MIME tags if necessary.
1381   (goto-char (point-min))
1382   (if (not (looking-at mime-editor/single-part-tag-regexp))
1383       (insert (mime-make-text-tag) "\n"))
1384   ;; Check each tag, and add new tag or correct it if necessary.
1385   (goto-char (point-min))
1386   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1387     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1388            (contype (mime-editor/get-contype tag))
1389            (charset (mime-get-parameter contype "charset"))
1390            (encoding (mime-editor/get-encoding tag)))
1391       ;; Remove extra whitespaces after the tag.
1392       (if (looking-at "[ \t]+$")
1393           (delete-region (match-beginning 0) (match-end 0)))
1394       (cond ((= (following-char) ?\^M)
1395              ;; It must be image, audio or video.
1396              (let ((beg (point))
1397                    (end (mime-editor/content-end)))
1398                ;; Insert explicit MIME tags after hidden messages.
1399                (forward-line 1)
1400                (if (and (not (eobp))
1401                         (not (looking-at mime-editor/single-part-tag-regexp)))
1402                    (progn
1403                      (insert (mime-make-text-tag) "\n")
1404                      (forward-line -1)  ;Process it again as text.
1405                      ))
1406                ;; Show a hidden message.  The point is not altered
1407                ;; after the conversion.
1408                (mime-flag-region beg end ?\n)))
1409             ((mime-test-content-type contype "message")
1410              ;; Content-type "message" should be sent as is.
1411              (forward-line 1))
1412             ((mime-test-content-type contype "text")
1413              ;; Define charset for text if necessary.
1414              (setq charset (or charset (mime-editor/choose-charset)))
1415              (mime-editor/define-charset charset)
1416              (if (string-equal contype "text/x-rot13-47")
1417                  (save-excursion
1418                    (forward-line)
1419                    (set-mark (point))
1420                    (goto-char (mime-editor/content-end))
1421                    (mime-editor/caesar-region)
1422                    ))
1423              ;; Point is now on current tag.
1424              ;; Define encoding and encode text if necessary.
1425              (if (null encoding)        ;Encoding is not specified.
1426                  (let* ((encoding (mime-editor/choose-encoding))
1427                         (beg (mime-editor/content-beginning))
1428                         (end (mime-editor/content-end))
1429                         (body (buffer-substring beg end))
1430                         (encoded (funcall mime-string-encoder
1431                                           (cons charset encoding) body)))
1432                    (if (not (string-equal body encoded))
1433                        (progn
1434                          (goto-char beg)
1435                          (delete-region beg end)
1436                          (insert encoded)
1437                          (goto-char beg)))
1438                    (mime-editor/define-encoding encoding)))
1439              (forward-line 1))
1440             ((null encoding)            ;Encoding is not specified.
1441              ;; Application, image, audio, video, and any other
1442              ;; unknown content-type without encoding should be
1443              ;; encoded.
1444              (let* ((encoding "base64") ;Encode in BASE64 by default.
1445                     (beg (mime-editor/content-beginning))
1446                     (end (mime-editor/content-end))
1447                     (body (buffer-substring beg end))
1448                     (encoded (funcall mime-string-encoder
1449                                       (cons nil encoding) body)))
1450                (if (not (string-equal body encoded))
1451                    (progn
1452                      (goto-char beg)
1453                      (delete-region beg end)
1454                      (insert encoded)
1455                      (goto-char beg)))
1456                (mime-editor/define-encoding encoding))
1457              (forward-line 1))
1458             )
1459       )))
1460
1461 (defun mime-delete-field (field)
1462   "Delete header FIELD."
1463   (let ((regexp (format "^%s:[ \t]*" field)))
1464     (goto-char (point-min))
1465     (while (re-search-forward regexp nil t)
1466       (delete-region (match-beginning 0)
1467                      (progn (forward-line 1) (point)))
1468       )))
1469
1470 \f
1471 ;;;
1472 ;;; Platform dependent functions
1473 ;;;
1474
1475 ;; Emacs 18 implementations
1476
1477 (defun mime-body-charset-chooser-for-emacs18 (begin end)
1478   "Return a cons of charset and encoding of a message in a given region.
1479 Encoding name must be a canonical name, such as `base64'."
1480   '("US-ASCII" . nil)                   ;Default charset of MIME.
1481   )
1482
1483 (defun mime-string-encoder-for-emacs18 (method string)
1484   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1485   (let ((charset (car method))
1486         (encoding (cdr method)))
1487     (cond ((stringp encoding)
1488            (mime-encode-string encoding string))
1489           ;; Return string without any encoding.
1490           (t string)
1491           )))
1492
1493 \f
1494 ;; Emacs 19 implementations
1495
1496 (defun mime-body-charset-chooser-for-emacs19 (begin end)
1497   "Return a cons of charset and encoding of a message in a given region.
1498 Encoding name must be a canonical name, such as `base64'.
1499 US-ASCII and ISO-8859-1 are supported on Emacs 19."
1500   (cond ((save-excursion
1501            (goto-char begin)
1502            (re-search-forward "[\200-\377]" end t))
1503          '("ISO-8859-1" . "quoted-printable"))
1504         (t
1505          '("US-ASCII" . nil))           ;Default charset of MIME.
1506         ))
1507
1508 (defun mime-string-encoder-for-emacs19 (method string)
1509   "For given METHOD that is a cons of charset and encoding, encode a STRING."
1510   (let ((charset (car method))
1511         (encoding (cdr method)))
1512     (cond ((stringp encoding)
1513            (mime-encode-string encoding string))
1514           ;; Return string without any encoding.
1515           (t string)
1516           )))
1517
1518 \f
1519 ;; NEmacs implementations
1520
1521 (defun mime-body-charset-chooser-for-nemacs (begin end)
1522   "Return a cons of charset and encoding of a message in a given region.
1523 Encoding name must be a canonical name, such as `base64'.
1524 US-ASCII and ISO-2022-JP are supported on NEmacs."
1525   (cond ((check-region-kanji-code begin end)
1526          ;; The following are safe encoding methods for use in
1527          ;; USENET News systems that strip off all ESCs.
1528          ;; '("ISO-2022-JP" . "quoted-printable")
1529          ;; '("ISO-2022-JP" . "base64")
1530          ;; The following expects transport systems are all MIME
1531          ;; compliants.  For instance, ESCs are never stripped off.
1532          '("ISO-2022-JP" . nil))
1533         (t
1534          '("US-ASCII" . nil))           ;Default charset of MIME.
1535         ))
1536
1537 (defun mime-string-encoder-for-nemacs (method string)
1538   "For given METHOD that is a cons of charset and encoding, encode a STRING.
1539 US-ASCII and ISO-2022-JP are supported on NEmacs."
1540   (let ((charset (car method))
1541         (encoding (cdr method)))
1542     (cond ((stringp encoding)
1543            (mime-encode-string encoding
1544                                ;; Convert internal (EUC) to JIS code.
1545                                (convert-string-kanji-code string 3 2)
1546                                ))
1547           ;; NEmacs can convert into ISO-2022-JP automatically,
1548           ;; but can do it myself as follows:
1549           ;;(t (convert-string-kanji-code string 3 2))
1550
1551           ;; Return string without any encoding.
1552           (t string)
1553           )))
1554
1555 \f
1556 ;; Mule implementations
1557 ;; Thanks to contributions by wkenji@flab.fujitsu.co.jp (Kenji
1558 ;; WAKAMIYA) and handa@etl.go.jp (Kenichi Handa).
1559
1560 (defun mime-body-charset-chooser-for-mule (begin end)
1561   "Return a cons of charset and encoding of a message in a given
1562 region.  Encoding name must be a canonical name, such as `base64'.
1563 US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1564 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1565 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual text
1566 in Mule."
1567   (let ((lclist (find-charset-region begin end)))
1568     (cond ((null lclist)
1569            '("US-ASCII" . nil))         ;Default charset of MIME.
1570           ;; Multilingual capability requred.
1571           ((and (> (length lclist) 1)
1572                 (boundp '*iso-2022-int-1*))
1573            '("ISO-2022-INT-1" . nil))
1574           ((> (length lclist) 1)
1575            '("ISO-2022-JP-2" . nil))
1576           ;; Simple charset.
1577           ((memq lc-ltn1 lclist)
1578            '("ISO-8859-1" . "quoted-printable"))
1579           ((memq lc-ltn2 lclist)
1580            '("ISO-8859-2" . "quoted-printable"))
1581           ((memq lc-ltn3 lclist)
1582            '("ISO-8859-3" . "quoted-printable"))
1583           ((memq lc-ltn4 lclist)
1584            '("ISO-8859-4" . "quoted-printable"))
1585           ((memq lc-crl lclist)
1586            '("ISO-8859-5" . "quoted-printable"))
1587           ;;((memq lc-arb lclist)
1588           ;; '("ISO-8859-6" . "quoted-printable"))
1589           ((memq lc-grk lclist)
1590            '("ISO-8859-7" . "quoted-printable"))
1591           ((memq lc-hbw lclist)
1592            '("ISO-8859-8" . "quoted-printable"))
1593           ((memq lc-ltn5 lclist)
1594            '("ISO-8859-9" . "quoted-printable"))
1595           ((memq lc-jp lclist)
1596            '("ISO-2022-JP" . nil))
1597           ;; Unknown charset.
1598           ((boundp '*iso-2022-int-1*)
1599            '("ISO-2022-INT-1" . nil))
1600           (t
1601            '("ISO-2022-JP-2" . nil))
1602           )))
1603
1604 (defun mime-string-encoder-for-mule (method string)
1605   "For given METHOD that is a cons of charset and encoding, encode a
1606 STRING.  US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
1607 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
1608 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual
1609 text."
1610   (let* ((charset (car method))
1611          (encoding (cdr method))
1612          (coding-system
1613           (cdr (assoc (and (stringp charset) (upcase charset))
1614                       '(("ISO-8859-1" . *ctext*)
1615                         ("ISO-8859-2" . *iso-8859-2*)
1616                         ("ISO-8859-3" . *iso-8859-3*)
1617                         ("ISO-8859-4" . *iso-8859-4*)
1618                         ("ISO-8859-5" . *iso-8859-5*)
1619                         ;;("ISO-8859-6" . *iso-8859-6*)
1620                         ("ISO-8859-7" . *iso-8859-7*)
1621                         ("ISO-8859-8" . *iso-8859-8*)
1622                         ("ISO-8859-9" . *iso-8859-9*)
1623                         ("ISO-2022-JP" . *junet*)
1624                         ("ISO-2022-JP-2" . *iso-2022-ss2-7*)
1625                         ("ISO-2022-INT-1" . *iso-2022-int-1*)
1626                         )))))
1627     ;; In bilingual environment it may be unnecessary to convert the
1628     ;; coding system of the string unless transfer encoding is
1629     ;; required since such conversion may be performed by mule
1630     ;; automatically.
1631     (if (not (null coding-system))
1632         (setq string (code-convert-string string *internal* coding-system)))
1633     (if (stringp encoding)
1634         (setq string (mime-encode-string encoding string)))
1635     string
1636     ))
1637
1638 \f
1639 ;; Sun implementations
1640
1641 (defun mime-voice-recorder-for-sun ()
1642   "Record voice in a buffer using Sun audio device, and return the buffer.
1643 If the environment variable AUDIOHOST is defined, its value is used as
1644 a recording host instead of local host."
1645   (let ((buffer (get-buffer-create " *MIME audio*"))
1646         (host (getenv "AUDIOHOST")))
1647     (message "Start the recording on %s.  Type C-g to finish the recording..."
1648              (or host (system-name)))
1649     (save-excursion
1650       (set-buffer buffer)
1651       (erase-buffer)
1652       (condition-case errorcode
1653           (let ((selective-display nil) ;Disable ^M to nl translation.
1654                 (mc-flag nil)           ;Mule
1655                 (kanji-flag nil))       ;NEmacs
1656             ;; If AUDIOHOST is defined, use the value as recording host.
1657             (cond ((not (null host))
1658                    ;; Disable automatic conversion of coding system if Mule.
1659                    (if (featurep 'mule)
1660                        (define-program-coding-system nil "rsh" *noconv*))
1661                    (call-process "rsh"
1662                                  nil
1663                                  buffer
1664                                  nil
1665                                  host
1666                                  "cat"
1667                                  "/dev/audio"
1668                                  ))
1669                   (t
1670                    ;; Disable automatic conversion of coding system if Mule.
1671                    (if (featurep 'mule)
1672                        (define-program-coding-system nil "cat" *noconv*))
1673                    (call-process "cat"
1674                                  "/dev/audio"
1675                                  buffer
1676                                  nil
1677                                  ))))
1678         (quit (message "Type C-g to finish recording... done.")
1679               buffer                    ;Return the buffer
1680               )))))
1681
1682 \f
1683 ;;; @ Other useful commands.
1684 ;;;
1685
1686 ;; Message forwarding commands as content-type "message/rfc822".
1687
1688 (defun mime-editor/insert-message (&optional message)
1689   (interactive)
1690   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1691     (if (and inserter (fboundp inserter))
1692         (progn
1693           (mime-editor/insert-tag "message" "rfc822")
1694           (funcall inserter message)
1695           )
1696       (message "Sorry, I don't have message inserter for your MUA.")
1697       )))
1698
1699 ;;; mime.el ends here
1700
1701 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1702   (if (null boundary)
1703       (setq boundary
1704             (concat mime-multipart-boundary " " (current-time-string)))
1705     )
1706   (save-excursion
1707     (save-restriction
1708       (narrow-to-region beg end)
1709       (let ((tag nil)                   ;MIME tag
1710             (contype nil)               ;Content-Type
1711             (encoding nil)              ;Content-Transfer-Encoding
1712             (nparts 0))                 ;Number of body parts
1713         ;; Normalize the body part by inserting appropriate message
1714         ;; tags for every message contents.
1715         (mime-editor/normalize-body)
1716         ;; Counting the number of Content-Type.
1717         (goto-char (point-min))
1718         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1719           (setq nparts (1+ nparts)))
1720         ;; Begin translation.
1721         (cond ((and (<= nparts 1)(not multipart))
1722                ;; It's a singular message.
1723                (goto-char (point-min))
1724                (while (re-search-forward
1725                        mime-editor/single-part-tag-regexp nil t)
1726                  (setq tag
1727                        (buffer-substring (match-beginning 0) (match-end 0)))
1728                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1729                  (setq contype (mime-editor/get-contype tag))
1730                  (setq encoding (mime-editor/get-encoding tag))
1731                  ))
1732               (t
1733                ;; It's a multipart message.
1734                (goto-char (point-min))
1735                (while (re-search-forward
1736                        mime-editor/single-part-tag-regexp nil t)
1737                  (setq tag
1738                        (buffer-substring (match-beginning 0) (match-end 0)))
1739                  (delete-region (match-beginning 0) (match-end 0))
1740                  (setq contype (mime-editor/get-contype tag))
1741                  (setq encoding (mime-editor/get-encoding tag))
1742                  (insert "--" boundary "\n")
1743                  (insert "Content-Type: " contype "\n")
1744                  (if encoding
1745                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1746                  )
1747                ;; Define Content-Type as "multipart/mixed".
1748                (setq contype
1749                      (concat "multipart/mixed; boundary=\"" boundary "\""))
1750                ;; Content-Transfer-Encoding must be "7bit".
1751                ;; The following encoding can be `nil', but is
1752                ;; specified as is since there is no way that a user
1753                ;; specifies it.
1754                (setq encoding "7bit")
1755                ;; Insert the trailer.
1756                (goto-char (point-max))
1757                (if (not (= (preceding-char) ?\n))
1758                    ;; Boundary must start with a newline.
1759                    (insert "\n"))
1760                (insert "--" boundary "--\n")))
1761         (list contype encoding boundary nparts)
1762         ))))
1763
1764
1765 (defun mime-editor/find-inmost ()
1766   (goto-char (point-min))
1767   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1768       (let ((bb (match-beginning 0))
1769             (be (match-end 0))
1770             (type (buffer-substring (match-beginning 1)(match-end 1)))
1771             end-exp eb ee)
1772         (setq end-exp (format "^--}-<<%s>>\n" type))
1773         (widen)
1774         (if (re-search-forward end-exp nil t)
1775             (progn
1776               (setq eb (match-beginning 0))
1777               (setq ee (match-end 0))
1778               )
1779           (setq eb (point-max))
1780           (setq ee (point-max))
1781           )
1782         (narrow-to-region be eb)
1783         (goto-char be)
1784         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1785             (let (ret)
1786               (narrow-to-region (match-beginning 0)(point-max))
1787               (mime-editor/find-inmost)
1788               )
1789           (widen)
1790           ;;(delete-region eb ee)
1791           (list type bb be eb)
1792           ))))
1793
1794 (defun mime-editor/process-multipart-1 (boundary)
1795   (let ((ret (mime-editor/find-inmost)))
1796     (if ret
1797         (let ((type (car ret))
1798               (bb (nth 1 ret))(be (nth 2 ret))
1799               (eb (nth 3 ret))
1800               )
1801           (narrow-to-region bb eb)
1802           (delete-region bb be)
1803           (setq bb (point-min))
1804           (setq eb (point-max))
1805           (widen)
1806           (goto-char eb)
1807           (if (looking-at mime-editor/multipart-end-regexp)
1808               (let ((beg (match-beginning 0))
1809                     (end (match-end 0))
1810                     )
1811                 (delete-region beg end)
1812                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1813                          (not (eobp)))
1814                     (insert (concat (mime-make-text-tag) "\n"))
1815                   )))
1816           (setq boundary
1817                 (nth 2 (mime-editor/translate-region bb eb
1818                                                      boundary t)))
1819           (goto-char bb)
1820           (insert
1821            (format "--[[multipart/%s; boundary=\"%s\"][7bit]]\n"
1822                    type boundary))
1823           boundary))))
1824
1825
1826 ;;; caesar-region written by phr@prep.ai.mit.edu  Nov 86
1827 ;;; modified by tower@prep Nov 86
1828 ;;; gnus-caesar-region
1829 ;;; Modified by umerin@flab.flab.Fujitsu.JUNET for ROT47.
1830
1831 (defun mime-editor/caesar-region (&optional n)
1832   "Caesar rotation of region by N, default 13, for decrypting netnews.
1833 ROT47 will be performed for Japanese text in any case."
1834   (interactive (if current-prefix-arg   ; Was there a prefix arg?
1835                    (list (prefix-numeric-value current-prefix-arg))
1836                  (list nil)))
1837   (cond ((not (numberp n)) (setq n 13))
1838         (t (setq n (mod n 26))))        ;canonicalize N
1839   (if (not (zerop n))           ; no action needed for a rot of 0
1840       (progn
1841         (if (or (not (boundp 'caesar-translate-table))
1842                 (/= (aref caesar-translate-table ?a) (+ ?a n)))
1843             (let ((i 0) (lower "abcdefghijklmnopqrstuvwxyz") upper)
1844               (message "Building caesar-translate-table...")
1845               (setq caesar-translate-table (make-vector 256 0))
1846               (while (< i 256)
1847                 (aset caesar-translate-table i i)
1848                 (setq i (1+ i)))
1849               (setq lower (concat lower lower) upper (upcase lower) i 0)
1850               (while (< i 26)
1851                 (aset caesar-translate-table (+ ?a i) (aref lower (+ i n)))
1852                 (aset caesar-translate-table (+ ?A i) (aref upper (+ i n)))
1853                 (setq i (1+ i)))
1854               ;; ROT47 for Japanese text.
1855               ;; Thanks to ichikawa@flab.fujitsu.junet.
1856               (setq i 161)
1857               (let ((t1 (logior ?O 128))
1858                     (t2 (logior ?! 128))
1859                     (t3 (logior ?~ 128)))
1860                 (while (< i 256)
1861                   (aset caesar-translate-table i
1862                         (let ((v (aref caesar-translate-table i)))
1863                           (if (<= v t1) (if (< v t2) v (+ v 47))
1864                             (if (<= v t3) (- v 47) v))))
1865                   (setq i (1+ i))))
1866               (message "Building caesar-translate-table...done")))
1867         (let ((from (region-beginning))
1868               (to (region-end))
1869               (i 0) str len)
1870           (setq str (buffer-substring from to))
1871           (setq len (length str))
1872           (while (< i len)
1873             (aset str i (aref caesar-translate-table (aref str i)))
1874             (setq i (1+ i)))
1875           (goto-char from)
1876           (delete-region from to)
1877           (insert str)))))
1878
1879
1880 ;;; @ multipart enclosure
1881 ;;;
1882
1883 (defun mime-editor/enclose-region (type beg end)
1884   (save-excursion
1885     (goto-char beg)
1886     (let ((f (bolp)))
1887       (save-restriction
1888         (narrow-to-region beg end)
1889         (goto-char beg)
1890         (if (not f)
1891             (insert "\n")
1892           )
1893         (insert (format "--<<%s>>-{\n" type))
1894         (goto-char (point-max))
1895         (setq f (bolp))
1896         (if (not f)
1897             (insert (format "\n--}-<<%s>>" type))
1898           (insert (format "--}-<<%s>>\n" type))
1899           )
1900         (goto-char (point-max))
1901         )
1902       (if (not (eobp))
1903           (progn
1904             (if (not f)
1905                 (if (not (eolp))
1906                     (insert "\n")
1907                   (forward-char)
1908                   )
1909               )
1910             (if (not (looking-at mime-editor/single-part-tag-regexp))
1911                 (insert (mime-make-text-tag) "\n")
1912               )
1913             )
1914         (if (not f)
1915             (insert "\n")
1916           ))
1917       )))
1918
1919 (defun mime-editor/enclose-mixed-region (beg end)
1920   (interactive "*r")
1921   (mime-editor/enclose-region "mixed" beg end)
1922   )
1923
1924 (defun mime-editor/enclose-parallel-region (beg end)
1925   (interactive "*r")
1926   (mime-editor/enclose-region "parallel" beg end)
1927   )
1928
1929 (defun mime-editor/enclose-digest-region (beg end)
1930   (interactive "*r")
1931   (mime-editor/enclose-region "digest" beg end)
1932   )
1933
1934 (defun mime-editor/enclose-alternative-region (beg end)
1935   (interactive "*r")
1936   (mime-editor/enclose-region "alternative" beg end)
1937   )
1938
1939
1940 ;;; @ split
1941 ;;;
1942
1943 (defun mime-editor/insert-partial-header (fields subject id number total separator)
1944   (insert fields)
1945   (insert (format "Subject: %s (%d/%d)\n" subject number total))
1946   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
1947                   mime-editor/version))
1948   (insert (format "\
1949 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
1950                   id number total separator))
1951   )
1952
1953 (defun mime-editor/split-and-send (&optional cmd)
1954   (interactive)
1955   (let ((mime-editor/message-max-length
1956          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
1957              mime-editor/message-default-max-length))
1958         (lines (count-lines (point-min) (point-max)))
1959         )
1960     (if (and (> lines mime-editor/message-max-length) mime-editor/split-message)
1961         (let* ((mime-editor/draft-file-name 
1962                 (or (buffer-file-name)
1963                     (make-temp-name
1964                      (expand-file-name "tm-draft" mime/tmp-dir))))
1965                (separator mail-header-separator)
1966                (config
1967                 (eval (cdr (assq major-mode mime-editor/window-config-alist))))
1968                (id (concat "\""
1969                            (replace-space-with-underline (current-time-string))
1970                            "@" (system-name) "\"")))
1971           (run-hooks 'mime-editor/before-split-hook)
1972           (let* ((header (rfc822/get-header-string-except
1973                           mime-editor/message-nuke-headers separator))
1974                  (subject (mail-fetch-field "subject"))
1975                  (total (+ (/ lines mime-editor/message-max-length)
1976                            (if (> (mod lines mime-editor/message-max-length) 0)
1977                                1)))
1978                  (the-buf (current-buffer))
1979                  (buf (get-buffer "*tmp-send*"))
1980                  (command
1981                   (or cmd
1982                       (cdr (assq major-mode
1983                                  mime-editor/message-sender-alist))
1984                       (cdr (assq major-mode
1985                                  mime-editor/message-default-sender-alist))))
1986                  data)
1987             (goto-char (point-min))
1988             (if (re-search-forward (concat "^" (regexp-quote separator) "$")
1989                                    nil t)
1990                 (replace-match "")
1991               )
1992             (if buf
1993                 (progn
1994                   (switch-to-buffer buf)
1995                   (erase-buffer)
1996                   (switch-to-buffer the-buf)
1997                   )
1998               (setq buf (get-buffer-create "*tmp-send*"))
1999               )
2000             (switch-to-buffer buf)
2001             (make-variable-buffer-local 'mail-header-separator)
2002             (setq mail-header-separator separator)
2003             (switch-to-buffer the-buf)
2004             (goto-char (point-min))
2005             (re-search-forward "^$" nil t)
2006             (let ((mime-editor/partial-number 1))
2007               (setq data (buffer-substring
2008                           (point-min)
2009                           (progn
2010                             (goto-line mime-editor/message-max-length)
2011                             (point))
2012                           ))
2013               (delete-region (point-min)(point))
2014               (switch-to-buffer buf)
2015               (mime-editor/insert-partial-header header subject
2016                                              id mime-editor/partial-number total
2017                                              separator)
2018               (insert data)
2019               (save-excursion
2020                 (save-restriction
2021                   (goto-char (point-min))
2022                   (search-forward (concat "\n" mail-header-separator "\n"))
2023                   (narrow-to-region
2024                    (match-end 0)
2025                    (if (re-search-forward "^$" nil t)
2026                        (match-beginning 0)
2027                      (point-max)
2028                      ))
2029                   (goto-char (point-min))
2030                   (while (re-search-forward mime-editor/blind-fields-regexp nil t)
2031                     (delete-region (match-beginning 0)
2032                                    (let ((e (rfc822/field-end)))
2033                                      (if (< e (point-max))
2034                                          (1+ e)
2035                                        e)))
2036                     )
2037                   ))
2038               (save-excursion
2039                 (message (format "Sending %d/%d..."
2040                                  mime-editor/partial-number total))
2041                 (call-interactively command)
2042                 (message (format "Sending %d/%d... done"
2043                                  mime-editor/partial-number total))
2044                 )
2045               (erase-buffer)
2046               (switch-to-buffer the-buf)
2047               (setq mime-editor/partial-number 2)
2048               (while (< mime-editor/partial-number total)
2049                 (setq data (buffer-substring
2050                             (point-min)
2051                             (progn
2052                               (goto-line mime-editor/message-max-length)
2053                               (point))
2054                             ))
2055                 (delete-region (point-min)(point))
2056                 (switch-to-buffer buf)
2057                 (mime-editor/insert-partial-header header subject
2058                                                id mime-editor/partial-number total
2059                                                separator)
2060                 (insert data)
2061                 (save-excursion
2062                   (message (format "Sending %d/%d..."
2063                                    mime-editor/partial-number total))
2064                   (call-interactively command)
2065                   (message (format "Sending %d/%d... done"
2066                                    mime-editor/partial-number total))
2067                   )
2068                 (erase-buffer)
2069                 (switch-to-buffer the-buf)
2070                 (setq mime-editor/partial-number (1+ mime-editor/partial-number))
2071                 )
2072               (goto-char (point-min))
2073               (mime-editor/insert-partial-header header subject
2074                                              id mime-editor/partial-number total
2075                                              separator)
2076               (message (format "Sending %d/%d..."
2077                                mime-editor/partial-number total))
2078               ))))))
2079
2080
2081 ;;; @ preview message
2082 ;;;
2083
2084 (defun mime-editor/preview-message ()
2085   "preview editing MIME message. [tm-edit.el]"
2086   (interactive)
2087   (let* ((str (buffer-string))
2088          (separator mail-header-separator)
2089          (the-buf (current-buffer))
2090          (buf-name (buffer-name))
2091          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2092          (buf (get-buffer temp-buf-name))
2093          )
2094     (if buf
2095         (progn
2096           (switch-to-buffer buf)
2097           (erase-buffer)
2098           )
2099       (setq buf (get-buffer-create temp-buf-name))
2100       (switch-to-buffer buf)
2101       )
2102     (insert str)
2103     (setq major-mode 'mime/temporary-message-mode)
2104     (make-local-variable 'mail-header-separator)
2105     (setq mail-header-separator separator)
2106     (make-local-variable 'mime/editing-buffer)
2107     (setq mime/editing-buffer the-buf)
2108     
2109     (run-hooks 'mime-editor/translate-hook)
2110     (mime-editor/translate-buffer)
2111     (goto-char (point-min))
2112     (if (re-search-forward
2113          (concat "^" (regexp-quote separator) "$"))
2114         (replace-match "")
2115       )
2116     (mime/viewer-mode)
2117     ))
2118
2119 (defun mime-editor/quitting-method ()
2120   (let ((temp mime::preview/article-buffer)
2121         buf)
2122     (mime-viewer/kill-buffer)
2123     (set-buffer temp)
2124     (setq buf mime/editing-buffer)
2125     (kill-buffer temp)
2126     (switch-to-buffer buf)
2127     ))
2128
2129 (set-alist 'mime-viewer/quitting-method-alist
2130            'mime/temporary-message-mode
2131            (function mime-editor/quitting-method)
2132            )
2133
2134
2135 ;;; @ draft preview
2136 ;;; 
2137 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2138 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2139
2140 (defvar mime-editor/draft-header-separator-alist
2141   '((news-reply-mode . mail-header-separator)
2142     (mh-letter-mode . mail-header-separator)
2143     ))
2144
2145 (defvar mime::article/draft-header-separator nil)
2146
2147 (defun mime-editor/draft-preview ()
2148   (interactive)
2149   (let ((sep (assoc-value major-mode mime-editor/draft-header-separator-alist)))
2150     (or (stringp sep) (setq sep (eval sep)))
2151     (make-variable-buffer-local 'mime::article/draft-header-separator)
2152     (goto-char (point-min))
2153     (re-search-forward
2154      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2155     (setq mime::article/draft-header-separator
2156           (buffer-substring (match-beginning 0) (match-end 0)))
2157     (replace-match "")
2158     (mime/viewer-mode (current-buffer))
2159     (pop-to-buffer (current-buffer))
2160     ))
2161
2162 (defun mime-viewer::quitting-method/draft-preview ()
2163   (let ((mother mime/mother-buffer))
2164     (save-excursion
2165       (switch-to-buffer mother)
2166       (goto-char (point-min))
2167       (if (and
2168            (re-search-forward
2169             (concat "^\\("
2170                     (regexp-quote mime::article/draft-header-separator)
2171                     "\\)?$") nil t)
2172            (bolp))
2173           (progn
2174             (insert mime::article/draft-header-separator)
2175             (set-buffer-modified-p (buffer-modified-p))
2176             )))
2177     (mime-viewer/kill-buffer)
2178     (pop-to-buffer mother)
2179     ))
2180
2181 (set-alist 'mime-viewer/quitting-method-alist
2182            'mh-letter-mode
2183            (function mime-viewer::quitting-method/draft-preview)
2184            )
2185
2186 (set-alist 'mime-viewer/quitting-method-alist
2187            'news-reply-mode
2188            (function mime-viewer::quitting-method/draft-preview)
2189            )
2190
2191
2192 ;;; @ etc
2193 ;;;
2194
2195 (defun rfc822/get-header-string-except (pat boundary)
2196   (let ((case-fold-search t))
2197     (save-excursion
2198       (save-restriction
2199         (narrow-to-region (goto-char (point-min))
2200                           (progn
2201                             (re-search-forward
2202                              (concat "^\\(" (regexp-quote boundary) "\\)?$")
2203                              nil t)
2204                             (match-beginning 0)
2205                             ))
2206         (goto-char (point-min))
2207         (let (field header)
2208           (while (re-search-forward rfc822/field-top-regexp nil t)
2209             (setq field (buffer-substring (match-beginning 0)
2210                                           (rfc822/field-end)
2211                                           ))
2212             (if (not (string-match pat field))
2213                 (setq header (concat header field "\n"))
2214               ))
2215           header)
2216         ))))
2217
2218 (defun replace-space-with-underline (str)
2219   (mapconcat (function
2220               (lambda (arg)
2221                 (char-to-string
2222                  (if (= arg 32)
2223                      ?_
2224                    arg)))) str "")
2225   )
2226
2227
2228 ;;; @ end
2229 ;;;
2230
2231 (provide 'tm-edit)
2232
2233 (run-hooks 'tm-edit-load-hook)