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