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