Synch with the semi-1_14 branch.
[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" "msword" 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$\\|\\.jpeg$"
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 nil
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                            ;; `xemacs-extra-name' has appeared in the
649                            ;; development version of XEmacs 21.5-b8.
650                            (if (and (boundp 'xemacs-extra-name)
651                                     (symbol-value 'xemacs-extra-name))
652                                (concat " " (symbol-value 'xemacs-extra-name))
653                              "")
654                            " ("
655                            system-configuration ")")
656                         " (" emacs-version ")"))
657             (let ((ver (if (string-match "\\.[0-9]+$" emacs-version)
658                            (substring emacs-version 0 (match-beginning 0))
659                          emacs-version)))
660               (if (featurep 'mule)
661                   (if (boundp 'enable-multibyte-characters)
662                       (concat "Emacs/" ver
663                               " (" system-configuration ")"
664                               (if enable-multibyte-characters
665                                   (concat " MULE/" mule-version)
666                                 " (with unibyte mode)")
667                               (if (featurep 'meadow)
668                                   (let ((mver (Meadow-version)))
669                                     (if (string-match "^Meadow-" mver)
670                                         (concat " Meadow/"
671                                                 (substring mver
672                                                            (match-end 0)))))))
673                     (concat "MULE/" mule-version
674                             " (based on Emacs " ver ")"))
675                 (concat "Emacs/" ver " (" system-configuration ")")))))
676   "Body of User-Agent field.
677 If variable `mime-edit-insert-user-agent-field' is not nil, it is
678 inserted into message header.")
679
680 \f
681 ;;; @ constants
682 ;;;
683
684 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
685   "Specify MIME tspecials.
686 Tspecials means any character that matches with it in header must be quoted.")
687
688 (defconst mime-edit-mime-version-value
689 ;  (concat "1.0 (generated by " mime-edit-version ")")
690   "1.0"
691   "MIME version number.")
692
693 ;;; @ keymap and menu
694 ;;;
695
696 (defvar mime-edit-mode-flag nil)
697 (make-variable-buffer-local 'mime-edit-mode-flag)
698
699 (defvar mime-edit-mode-entity-prefix "\C-c\C-x"
700   "Keymap prefix for MIME-Edit mode commands to insert entity or set status.")
701 (defvar mime-edit-mode-entity-map (make-sparse-keymap)
702   "Keymap for MIME-Edit mode commands to insert entity or set status.")
703
704 (define-key mime-edit-mode-entity-map "\C-t" 'mime-edit-insert-text)
705 (define-key mime-edit-mode-entity-map "\C-i" 'mime-edit-insert-file)
706 (define-key mime-edit-mode-entity-map "i"    'mime-edit-insert-text-file)
707 (define-key mime-edit-mode-entity-map "\C-e" 'mime-edit-insert-external)
708 (define-key mime-edit-mode-entity-map "\C-v" 'mime-edit-insert-voice)
709 (define-key mime-edit-mode-entity-map "\C-y" 'mime-edit-insert-message)
710 (define-key mime-edit-mode-entity-map "\C-m" 'mime-edit-insert-mail)
711 (define-key mime-edit-mode-entity-map "\C-w" 'mime-edit-insert-signature)
712 (define-key mime-edit-mode-entity-map "\C-s" 'mime-edit-insert-signature)
713 (define-key mime-edit-mode-entity-map "\C-k" 'mime-edit-insert-key)
714 (define-key mime-edit-mode-entity-map "t"    'mime-edit-insert-tag)
715
716 (define-key mime-edit-mode-entity-map "7" 'mime-edit-set-transfer-level-7bit)
717 (define-key mime-edit-mode-entity-map "8" 'mime-edit-set-transfer-level-8bit)
718 (define-key mime-edit-mode-entity-map "/" 'mime-edit-set-split)
719 (define-key mime-edit-mode-entity-map "s" 'mime-edit-set-sign)
720 (define-key mime-edit-mode-entity-map "v" 'mime-edit-set-sign)
721 (define-key mime-edit-mode-entity-map "e" 'mime-edit-set-encrypt)
722 (define-key mime-edit-mode-entity-map "h" 'mime-edit-set-encrypt)
723 (define-key mime-edit-mode-entity-map "p" 'mime-edit-preview-message)
724 (define-key mime-edit-mode-entity-map "\C-z" 'mime-edit-exit)
725 (define-key mime-edit-mode-entity-map "?" 'mime-edit-help)
726
727 (defvar mime-edit-mode-enclosure-prefix "\C-c\C-m"
728   "Keymap prefix for MIME-Edit mode commands about enclosure.")
729 (defvar mime-edit-mode-enclosure-map (make-sparse-keymap)
730   "Keymap for MIME-Edit mode commands about enclosure.")
731
732 (define-key mime-edit-mode-enclosure-map
733   "\C-a" 'mime-edit-enclose-alternative-region)
734 (define-key mime-edit-mode-enclosure-map
735   "\C-p" 'mime-edit-enclose-parallel-region)
736 (define-key mime-edit-mode-enclosure-map
737   "\C-m" 'mime-edit-enclose-mixed-region)
738 (define-key mime-edit-mode-enclosure-map
739   "\C-d" 'mime-edit-enclose-digest-region)
740 (define-key mime-edit-mode-enclosure-map
741   "\C-s" 'mime-edit-enclose-pgp-signed-region)
742 (define-key mime-edit-mode-enclosure-map
743   "\C-e" 'mime-edit-enclose-pgp-encrypted-region)
744 (define-key mime-edit-mode-enclosure-map
745   "\C-q" 'mime-edit-enclose-quote-region)
746
747 (defvar mime-edit-mode-map (make-sparse-keymap)
748   "Keymap for MIME-Edit mode commands.")
749 (define-key mime-edit-mode-map
750   mime-edit-mode-entity-prefix mime-edit-mode-entity-map)
751 (define-key mime-edit-mode-map
752   mime-edit-mode-enclosure-prefix mime-edit-mode-enclosure-map)
753
754 (defconst mime-edit-menu-title "MIME-Edit")
755
756 (defconst mime-edit-menu-list
757   '((mime-help  "Describe MIME editor mode" mime-edit-help)
758     (file       "Insert File"           mime-edit-insert-file)
759     (external   "Insert External"       mime-edit-insert-external)
760     (voice      "Insert Voice"          mime-edit-insert-voice)
761     (message    "Insert Message"        mime-edit-insert-message)
762     (mail       "Insert Mail"           mime-edit-insert-mail)
763     (signature  "Insert Signature"      mime-edit-insert-signature)
764     (text       "Insert Text"           mime-edit-insert-text)
765     (tag        "Insert Tag"            mime-edit-insert-tag)
766     (alternative "Enclose as alternative"
767                  mime-edit-enclose-alternative-region)
768     (parallel   "Enclose as parallel"   mime-edit-enclose-parallel-region)
769     (mixed      "Enclose as serial"     mime-edit-enclose-mixed-region)
770     (digest     "Enclose as digest"     mime-edit-enclose-digest-region)
771     (signed     "Enclose as signed"     mime-edit-enclose-pgp-signed-region)
772     (encrypted  "Enclose as encrypted"  mime-edit-enclose-pgp-encrypted-region)
773     (quote      "Verbatim region"       mime-edit-enclose-quote-region)
774     (key        "Insert Public Key"     mime-edit-insert-key)
775     (split      "Set splitting"         mime-edit-set-split)
776     (sign       "PGP sign"              mime-edit-set-sign)
777     (encrypt    "PGP encrypt"           mime-edit-set-encrypt)
778     (preview    "Preview Message"       mime-edit-preview-message)
779     (level      "Toggle transfer-level" mime-edit-toggle-transfer-level))
780   "MIME-edit menubar entry.")
781
782 (static-if (featurep 'xemacs)
783        ;; modified by Pekka Marjola <pema@iki.fi>
784        ;;       1995/9/5 (c.f. [tm-en:69])
785     (progn
786       (defun mime-edit-define-menu-for-xemacs ()
787         "Define menu for XEmacs."
788         (cond ((featurep 'menubar)
789                (make-local-variable 'current-menubar)
790                (set-buffer-menubar current-menubar)
791                (add-submenu
792                 nil
793                 (cons mime-edit-menu-title
794                       (mapcar (function
795                                (lambda (item)
796                                  (vector (nth 1 item)(nth 2 item)
797                                          mime-edit-mode-flag)))
798                               mime-edit-menu-list))))))
799       ;; modified by Steven L. Baur <steve@miranova.com>
800       ;;        1995/12/6 (c.f. [tm-en:209])
801       (or (boundp 'mime-edit-popup-menu-for-xemacs)
802           (setq mime-edit-popup-menu-for-xemacs
803                 (append '("MIME Commands" "---")
804                         (mapcar (function (lambda (item)
805                                             (vector (nth 1 item)
806                                                     (nth 2 item)
807                                                     t)))
808                                 mime-edit-menu-list)))))
809       ;; Bogus check.  Nemacs is not supported.
810       ;;(>= emacs-major-version 19)
811   (define-key mime-edit-mode-map [menu-bar mime-edit]
812     (cons mime-edit-menu-title
813           (make-sparse-keymap mime-edit-menu-title)))
814   (mapcar (function
815            (lambda (item)
816              (define-key mime-edit-mode-map
817                (vector 'menu-bar 'mime-edit (car item))
818                (cons (nth 1 item)(nth 2 item)))))
819           (reverse mime-edit-menu-list)))
820
821 ;;; @ macros
822 ;;;
823
824 (defmacro mime-edit-insert-place (type-list &rest body)
825   `(save-excursion
826      (if (get-text-property (point) 'invisible)
827          (error "Can't split invisible region"))
828      (if (or (member (intern (concat (car ,type-list) "/" (cadr ,type-list)))
829                      mime-edit-attach-at-end-type)
830              (member (intern (car ,type-list))
831                      mime-edit-attach-at-end-type))
832          (goto-char (point-max)))
833      ,@ body))
834
835 (defmacro mime-edit-force-text-tag (regexp)
836   `(cond ((looking-at (concat "\n*\\(" ,regexp "\\)"))
837           (replace-match "\\1"))
838          ((not (eobp))
839           (insert (mime-make-text-tag) "\n"))))
840
841 ;;; @ functions
842 ;;;
843
844 (defvar mime-edit-touched-flag nil)
845
846 ;;;###autoload
847 (defun mime-edit-mode ()
848   "MIME minor mode for editing the tagged MIME message.
849
850 In this mode, basically, the message is composed in the tagged MIME
851 format. The message tag looks like:
852
853         --[[text/plain; charset=ISO-2022-JP][7bit]]
854
855 The tag specifies the MIME content type, subtype, optional parameters
856 and transfer encoding of the message following the tag.  Messages
857 without any tag are treated as `text/plain' by default.  Charset and
858 transfer encoding are automatically defined unless explicitly
859 specified.  Binary messages such as audio and image are usually
860 hidden.  The messages in the tagged MIME format are automatically
861 translated into a MIME compliant message when exiting this mode.
862
863 Available charsets depend on Emacs.
864
865 These charsets are available in all emacsen (with MULE):
866 US-ASCII, ISO-8859-* (except for ISO-8859-5), KOI8-R, ISO-2022-JP,
867 ISO-2022-JP-2, EUC-KR, CN-GB-2312, CN-BIG5 and ISO-2022-INT-1 are
868 available.
869
870 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in mule is expected to
871 be used to represent multilingual text in intermixed manner.  Any
872 languages that has no registered charset are represented as either
873 ISO-2022-JP-2 or ISO-2022-INT-1 in mule.
874
875 If you want to add more charsets in mule, please set variable
876 `charsets-mime-charset-alist'.  This variable must be alist of which
877 key is list of charset and value is symbol of MIME charset.  If name
878 of coding-system is different as MIME charset, please set variable
879 `mime-charset-coding-system-alist'.  This variable must be alist of
880 which key is MIME charset and value is coding-system.
881
882 Following commands are available in addition to major mode commands:
883
884 \[make single part\]
885 \\[mime-edit-insert-text]       insert a text message.
886 \\[mime-edit-insert-file]       insert a (binary) file.
887 \\[mime-eidt-insert-text-file]  insert a text file.
888 \\[mime-edit-insert-external]   insert a reference to external body.
889 \\[mime-edit-insert-voice]      insert a voice message.
890 \\[mime-edit-insert-message]    insert a mail or news message.
891 \\[mime-edit-insert-mail]       insert a mail message.
892 \\[mime-edit-insert-signature]  insert a signature file at end.
893 \\[mime-edit-insert-key]        insert PGP public key.
894 \\[mime-edit-insert-tag]        insert a new MIME tag.
895
896 \[make enclosure (maybe multipart)\]
897 \\[mime-edit-enclose-alternative-region]   enclose as multipart/alternative.
898 \\[mime-edit-enclose-parallel-region]      enclose as multipart/parallel.
899 \\[mime-edit-enclose-mixed-region]         enclose as multipart/mixed.
900 \\[mime-edit-enclose-digest-region]        enclose as multipart/digest.
901 \\[mime-edit-enclose-pgp-signed-region]    enclose as PGP signed.
902 \\[mime-edit-enclose-pgp-encrypted-region] enclose as PGP encrypted.
903 \\[mime-edit-enclose-quote-region]         enclose as verbose mode
904                                            (to avoid to expand tags)
905
906 \[other commands\]
907 \\[mime-edit-set-transfer-level-7bit]   set transfer-level as 7.
908 \\[mime-edit-set-transfer-level-8bit]   set transfer-level as 8.
909 \\[mime-edit-set-split]                 set message splitting mode.
910 \\[mime-edit-set-sign]                  set PGP-sign mode.
911 \\[mime-edit-set-encrypt]               set PGP-encryption mode.
912 \\[mime-edit-preview-message]           preview editing MIME message.
913 \\[mime-edit-exit]                      exit and translate into a MIME
914                                         compliant message.
915 \\[mime-edit-help]                      show this help.
916 \\[mime-edit-maybe-translate]           exit and translate if in MIME mode,
917                                         then split.
918
919 Additional commands are available in some major modes:
920 C-c C-c         exit, translate and run the original command.
921 C-c C-s         exit, translate and run the original command.
922
923 The following is a message example written in the tagged MIME format.
924 TABs at the beginning of the line are not a part of the message:
925
926         This is a conventional plain text.  It should be translated
927         into text/plain.
928         --[[text/plain]]
929         This is also a plain text.  But, it is explicitly specified as
930         is.
931         --[[text/plain; charset=ISO-8859-1]]
932         This is also a plain text.  But charset is specified as
933         iso-8859-1.
934
935         ¡Hola!  Buenos días.  ¿Cómo está usted?
936         --[[text/enriched]]
937         This is a <bold>enriched text</bold>.
938         --[[image/gif][base64]]...image encoded in base64 here...
939         --[[audio/basic][base64]]...audio encoded in base64 here...
940
941 User customizable variables (not all of them are documented):
942 mime-edit-mode-entity-prefix
943 mime-edit-mode-enclosure-prefix
944     Specifies a key prefix for MIME minor mode commands.
945
946  mime-ignore-preceding-spaces
947     Preceding white spaces in a message body are ignored if non-nil.
948
949  mime-ignore-trailing-spaces
950     Trailing white spaces in a message body are ignored if non-nil.
951
952  mime-auto-hide-body
953     Hide a non-textual body message encoded in base64 after insertion
954     if non-nil.
955
956  mime-transfer-level
957     A number of network transfer level.  It should be bigger than 7.
958     If you are in 8bit-through environment, please set to 8.
959
960  mime-edit-voice-recorder
961     Specifies a function to record and encode a voice message.
962     The function `mime-edit-voice-recorder-for-sun' is for Sun
963     SparcStations.
964
965  mime-edit-mode-hook
966     Turning on MIME mode calls the value of mime-edit-mode-hook, if
967     it is non-nil.
968
969  mime-edit-translate-hook
970     The value of mime-edit-translate-hook is called just before translating
971     the tagged MIME format into a MIME compliant message if it is
972     non-nil.  If the hook call the function mime-edit-insert-signature,
973     the signature file will be inserted automatically.
974
975  mime-edit-exit-hook
976     Turning off MIME mode calls the value of mime-edit-exit-hook, if it is
977     non-nil."
978   (interactive)
979   (if mime-edit-mode-flag
980       (mime-edit-exit)
981     (if mime-edit-touched-flag
982         (mime-edit-again)
983       (make-local-variable 'mime-edit-touched-flag)
984       (setq mime-edit-touched-flag t)
985       (turn-on-mime-edit))))
986
987
988 (static-if (featurep 'xemacs)
989     (add-minor-mode 'mime-edit-mode-flag
990                     '((" MIME-Edit "  mime-transfer-level-string))
991                     mime-edit-mode-map
992                     nil
993                     'mime-edit-mode)
994   (set-alist 'minor-mode-alist
995              'mime-edit-mode-flag
996              '((" MIME-Edit "  mime-transfer-level-string)))
997   (set-alist 'minor-mode-map-alist
998              'mime-edit-mode-flag
999              mime-edit-mode-map))
1000
1001
1002 ;;;###autoload
1003 (defun turn-on-mime-edit ()
1004   "Unconditionally turn on MIME-Edit mode."
1005   (interactive)
1006   (if mime-edit-mode-flag
1007       (error "You are already editing a MIME message")
1008     (setq mime-edit-mode-flag t)
1009
1010     ;; Set transfer level into mode line
1011     ;;
1012     (setq mime-transfer-level-string
1013           (mime-encoding-name mime-transfer-level 'not-omit))
1014     (force-mode-line-update)
1015
1016     ;; Define menu for XEmacs.
1017     (if (featurep 'xemacs)
1018         (mime-edit-define-menu-for-xemacs))
1019
1020     (enable-invisible)
1021
1022     ;; I don't care about saving these.
1023     (setq paragraph-start
1024           (regexp-or mime-edit-single-part-tag-regexp
1025                      paragraph-start))
1026     (setq paragraph-separate
1027           (regexp-or mime-edit-single-part-tag-regexp
1028                      paragraph-separate))
1029     (run-hooks 'mime-edit-mode-hook)
1030     (message
1031      (substitute-command-keys
1032       "Type \\[mime-edit-exit] to exit MIME mode, and type \\[mime-edit-help] to get help."))))
1033
1034 ;;;###autoload
1035 (defalias 'edit-mime 'turn-on-mime-edit) ; for convenience
1036
1037
1038 (defun mime-edit-exit (&optional nomime no-error)
1039   "Translate the tagged MIME message into a MIME compliant message.
1040 When NOMIME is nil, encode a message in the buffer into MIME.
1041 Otherwise, just returns to previous mode.  If NO-ERROR is non-nil,
1042 no errors will be signaled even if it is not MIME-Edit mode."
1043   (interactive "P")
1044   (if (not mime-edit-mode-flag)
1045       (if (null no-error)
1046           (error "You aren't editing a MIME message"))
1047     (if (not nomime)
1048         (progn
1049           (run-hooks 'mime-edit-translate-hook)
1050           (mime-edit-translate-buffer)))
1051     ;; Restore previous state.
1052     (setq mime-edit-mode-flag nil)
1053     (if (and (featurep 'xemacs)
1054              (featurep 'menubar))
1055         (delete-menu-item (list mime-edit-menu-title)))
1056     (disable-invisible)
1057     (set-buffer-modified-p (buffer-modified-p))
1058     (run-hooks 'mime-edit-exit-hook)
1059     (message "Exit MIME editor mode.")))
1060
1061 (defun mime-edit-maybe-translate ()
1062   (interactive)
1063   (mime-edit-exit nil t)
1064   (call-interactively 'mime-edit-maybe-split-and-send))
1065
1066 (defun mime-edit-help ()
1067   "Show help message about MIME mode."
1068   (interactive)
1069   (with-output-to-temp-buffer "*Help*"
1070     (princ "MIME editor mode:\n")
1071     (princ (documentation 'mime-edit-mode))
1072     (print-help-return-message)))
1073
1074 (defun mime-edit-insert-text (&optional subtype)
1075   "Insert a text message.
1076 Charset is automatically obtained from the `charsets-mime-charset-alist'.
1077 If optional argument SUBTYPE is not nil, text/SUBTYPE tag is inserted."
1078   (interactive)
1079   (let ((ret (mime-edit-insert-tag "text" subtype nil)))
1080     (when ret
1081       (if (looking-at mime-edit-single-part-tag-regexp)
1082           (progn
1083             ;; Make a space between the following message.
1084             (insert "\n")
1085             (forward-char -1)))
1086       (if (and (member (cadr ret) '("enriched"))
1087                (fboundp 'enriched-mode))
1088           (enriched-mode t)
1089         (if (boundp 'enriched-mode)
1090             (enriched-mode -1))))))
1091
1092 (defun mime-edit-insert-text-file (file &optional verbose)
1093   "Insert a text message from a FILE.
1094 Charset is automatically obtained from the `charsets-mime-charset-alist'.
1095 If optional argument SUBTYPE is not nil, text/SUBTYPE tag is inserted."
1096   (interactive "fInsert file as a MIME text: \nP")
1097   (let*  ((guess (mime-find-file-type file))
1098           (type "text")
1099           (subtype nil)
1100           (parameters (nth 2 guess))
1101 ;;        (encoding (nth 3 guess))
1102           (disposition-type (nth 4 guess))
1103           (disposition-params (nth 5 guess))
1104           string)
1105     (setq subtype (mime-prompt-for-subtype type subtype))
1106 ;;    (if (or (interactive-p) verbose)
1107 ;;      (setq encoding (mime-prompt-for-encoding encoding)))
1108     (if verbose
1109         (setq disposition-type (mime-prompt-for-disposition disposition-type)))
1110     (if (or (consp parameters) (stringp disposition-type))
1111         (let ((rest parameters) cell attribute value)
1112           (setq parameters "")
1113           (while rest
1114             (setq cell (car rest))
1115             (setq attribute (car cell))
1116             (setq value (cdr cell))
1117             (if (eq value 'file)
1118                 (setq value (std11-wrap-as-quoted-string
1119                              (file-name-nondirectory file))))
1120             (setq parameters (concat parameters "; " attribute "=" value))
1121             (setq rest (cdr rest)))
1122           (if disposition-type
1123               (progn
1124                 (setq parameters
1125                       (concat parameters "\n"
1126                               "Content-Disposition: " disposition-type))
1127                 (setq rest disposition-params)
1128                 (while rest
1129                   (setq cell (car rest))
1130                   (setq attribute (car cell))
1131                   (setq value (cdr cell))
1132                   (if (eq value 'file)
1133                       (setq value (std11-wrap-as-quoted-string
1134                                    (file-name-nondirectory file))))
1135                   (setq parameters
1136                         (concat parameters "; " attribute "=" value))
1137                   (setq rest (cdr rest)))))))
1138     (mime-edit-insert-place
1139      (list type subtype)
1140      (mime-edit-insert-tag type subtype parameters)
1141 ;;     (if (stringp encoding)
1142 ;;       (mime-edit-define-encoding encoding))
1143      (save-excursion
1144        (let ((ret (insert-file-contents file)))
1145          (forward-char (cadr ret))
1146          (mime-edit-force-text-tag mime-edit-single-part-regexp))))))
1147
1148 (defun mime-edit-guess-charset (file)
1149   (with-temp-buffer
1150     (let (candidates candidate eol eol-string)
1151       (set-buffer-multibyte nil)
1152       (insert-file-contents-as-binary file)
1153       (setq candidates (detect-coding-region (point-min) (point-max)))
1154       (setq candidate (if (listp candidates)
1155                           (car candidates)
1156                         candidates))
1157       (setq eol (coding-system-eol-type candidate))
1158       (cond ((eq eol
1159                  (static-if (featurep 'xemacs)
1160                      'lf
1161                    0))
1162              (setq eol-string "\n"))
1163             ((eq eol
1164                  (static-if (featurep 'xemacs)
1165                      'cr
1166                    2))
1167              (setq eol-string "\r")))
1168       (goto-char (point-min))
1169       (when eol-string
1170         (while (search-forward eol-string nil t)
1171           (replace-match "\r\n")))
1172       (static-if (featurep 'xemacs)
1173           (setq candidate (coding-system-name (coding-system-base candidate)))
1174         (setq candidate (coding-system-base candidate)))
1175       ;; #### FIXME
1176       (cond ((eq candidate 'undecided)
1177              (setq candidate "us-ascii"))
1178             ((eq candidate 'iso-2022-7bit)
1179              (setq candidate "iso-2022-jp"))
1180             (t
1181              (setq candidate
1182                    (symbol-name (coding-system-to-mime-charset candidate)))))
1183       (cons candidate (buffer-string)))))
1184
1185 (defun mime-edit-insert-file (file &optional verbose)
1186   "Insert a message from a FILE.
1187 If VERBOSE is non-nil, it will prompt for Content-Type,
1188 Content-Transfer-Encoding and Content-Disposition headers."
1189   (interactive "fInsert file as MIME message: \nP")
1190   (let*  ((guess (mime-find-file-type file))
1191           (type (nth 0 guess))
1192           (subtype (nth 1 guess))
1193           (parameters (nth 2 guess))
1194           (encoding (nth 3 guess))
1195           (disposition-type (nth 4 guess))
1196           (disposition-params (nth 5 guess))
1197           charset-and-string)
1198     (if verbose
1199         (setq type    (mime-prompt-for-type type)
1200               subtype (mime-prompt-for-subtype type subtype)))
1201     (if (or (interactive-p) verbose)
1202         (setq encoding (mime-prompt-for-encoding encoding)))
1203     (if verbose
1204         (setq disposition-type (mime-prompt-for-disposition disposition-type)))
1205     (if (or (consp parameters) (stringp disposition-type))
1206         (let ((rest parameters) cell attribute value)
1207           (setq parameters "")
1208           (when (string= type "text")
1209             (setq charset-and-string (mime-edit-guess-charset file))
1210             (setq parameters
1211                   (concat parameters "; charset="
1212                           (car charset-and-string))))
1213           (while rest
1214             (setq cell (car rest))
1215             (setq attribute (car cell))
1216             (setq value (cdr cell))
1217             (if (eq value 'file)
1218                 (setq value (std11-wrap-as-quoted-string
1219                              (file-name-nondirectory file))))
1220             (setq parameters (concat parameters "; " attribute "=" value))
1221             (setq rest (cdr rest)))
1222           (if disposition-type
1223               (progn
1224                 (setq parameters
1225                       (concat parameters "\n"
1226                               "Content-Disposition: " disposition-type))
1227                 (setq rest disposition-params)
1228                 (while rest
1229                   (setq cell (car rest))
1230                   (setq attribute (car cell))
1231                   (setq value (cdr cell))
1232                   (if (eq value 'file)
1233                       (setq value (std11-wrap-as-quoted-string
1234                                    (file-name-nondirectory file))))
1235                   (setq parameters
1236                         (concat parameters "; " attribute "=" value))
1237                   (setq rest (cdr rest)))))))
1238     (mime-edit-insert-place
1239      (list type subtype)
1240      (mime-edit-insert-tag type subtype parameters)
1241      (if charset-and-string
1242          (mime-edit-insert-binary-string (cdr charset-and-string) encoding)
1243        (mime-edit-insert-binary-file file encoding)))))
1244
1245 (defun mime-edit-insert-external ()
1246   "Insert a reference to external body."
1247   (interactive)
1248   (let* ((pritype (mime-prompt-for-type))
1249          (subtype (mime-prompt-for-subtype pritype))
1250          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
1251     (mime-edit-insert-place
1252      '("message" "external-body")
1253      (mime-edit-insert-tag "message" "external-body" nil ";\n\t")
1254       ;;(forward-char -1)
1255       ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
1256       ;;(forward-line 1)
1257       (and pritype
1258            subtype
1259            (insert "Content-Type: "
1260                    pritype "/" subtype (or parameters "") "\n"))
1261       (mime-edit-force-text-tag mime-edit-single-part-tag-regexp))))
1262
1263 (defun mime-edit-insert-voice ()
1264   "Insert a voice message."
1265   (interactive)
1266   (let ((encoding
1267          (completing-read
1268           "What transfer encoding: "
1269           (mime-encoding-alist) nil t nil)))
1270     (mime-edit-insert-place
1271      '("audio" "basic")
1272      (mime-edit-insert-tag "audio" "basic" nil)
1273      (mime-edit-define-encoding encoding)
1274      (save-restriction
1275        (narrow-to-region (1- (point))(point))
1276        (unwind-protect
1277            (funcall mime-edit-voice-recorder encoding)
1278          (progn
1279            (insert "\n")
1280            (invisible-region (point-min)(point-max))
1281            (goto-char (point-max))))))))
1282
1283 (defun mime-edit-insert-signature (&optional arg)
1284   "Insert a signature file."
1285   (interactive "P")
1286   (let ((signature-insert-hook
1287          (function
1288           (lambda ()
1289             (let ((items (mime-find-file-type signature-file-name)))
1290               (apply (function mime-edit-insert-tag)
1291                      (car items) (cadr items) (list (caddr items))))))))
1292     (insert-signature arg)))
1293
1294 \f
1295 ;; Insert a new tag around a point.
1296
1297 (defun mime-edit-insert-tag (&optional pritype subtype parameters delimiter)
1298   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
1299 If nothing is inserted, return nil."
1300   (interactive)
1301   (if (get-text-property (point) 'invisible)
1302       (error "Can't split invisible region"))
1303   (let ((p (point)))
1304     (mime-edit-goto-tag)
1305     (if (and (re-search-forward mime-edit-tag-regexp nil t)
1306              (< (match-beginning 0) p)
1307              (< p (match-end 0)))
1308         (goto-char (match-beginning 0))
1309       (goto-char p)))
1310   (let ((oldtag nil)
1311         (newtag nil)
1312         (current (point)))
1313     (setq pritype
1314           (or pritype
1315               (mime-prompt-for-type)))
1316     (setq subtype
1317           (or subtype
1318               (mime-prompt-for-subtype pritype)))
1319     (setq parameters
1320           (or parameters
1321               (mime-prompt-for-parameters pritype subtype delimiter)))
1322     ;; Make a new MIME tag.
1323     (setq newtag (mime-make-tag pritype subtype parameters))
1324     ;; Find an current MIME tag.
1325     (setq oldtag
1326           (save-excursion
1327             (if (mime-edit-goto-tag)
1328                 (buffer-substring (match-beginning 0) (match-end 0))
1329               ;; Assume content type is 'text/plan'.
1330               (mime-make-tag "text" "plain"))))
1331     ;; We are only interested in TEXT.
1332     (if (and oldtag
1333              (not (mime-test-content-type
1334                    (mime-edit-get-contype oldtag) "text")))
1335         (setq oldtag nil))
1336     ;; Make a new tag.
1337     (if (or (not oldtag)                ;Not text
1338             (or mime-ignore-same-text-tag
1339                 (not (string-equal oldtag newtag))))
1340         (progn
1341           ;; Mark the beginning of the tag for convenience.
1342           (push-mark (point) 'nomsg)
1343           (insert newtag "\n")
1344           (list pritype subtype parameters) ;New tag is created.
1345           )
1346       ;; Restore previous point.
1347       (goto-char current)
1348       nil                               ;Nothing is created.
1349       )))
1350
1351 ;; #### This should be merged into the function below but for now,
1352 ;; don't change APIs.
1353 (defun mime-edit-insert-binary-string (string &optional encoding)
1354   "Insert binary STRING at point.
1355 Optional argument ENCODING specifies an encoding method such as base64."
1356   (let* ((tagend (1- (point)))          ;End of the tag
1357          (hide-p (and mime-auto-hide-body
1358                       (stringp encoding)
1359                       (not
1360                        (let ((en (downcase encoding)))
1361                          (or (string-equal en "7bit")
1362                              (string-equal en "8bit")
1363                              (string-equal en "binary")))))))
1364     (save-restriction
1365       (narrow-to-region tagend (point))
1366       (insert
1367        (with-temp-buffer
1368          ;; #### @!#$%@!${$@}
1369          (set-buffer-multibyte nil)
1370          (insert string)
1371          ;; #### Why mime-encode-string doesn't exist?
1372          (mime-encode-region (point-min) (point-max)
1373                              (or encoding "7bit"))
1374          (buffer-string)))
1375       (if hide-p
1376           (progn
1377             (invisible-region (point-min) (point-max))
1378             (goto-char (point-max)))
1379         (goto-char (point-max))))
1380     (mime-edit-force-text-tag mime-edit-tag-regexp)
1381     ;; Define encoding even if it is 7bit.
1382     (if (stringp encoding)
1383         (save-excursion
1384           (goto-char tagend) ; Make sure which line the tag is on.
1385           (mime-edit-define-encoding encoding)))))
1386
1387 (defun mime-edit-insert-binary-file (file &optional encoding)
1388   "Insert binary FILE at point.
1389 Optional argument ENCODING specifies an encoding method such as base64."
1390   (let* ((tagend (1- (point)))          ;End of the tag
1391          (hide-p (and mime-auto-hide-body
1392                       (stringp encoding)
1393                       (not
1394                        (let ((en (downcase encoding)))
1395                          (or (string-equal en "7bit")
1396                              (string-equal en "8bit")
1397                              (string-equal en "binary")))))))
1398     (save-restriction
1399       (narrow-to-region tagend (point))
1400       (mime-insert-encoded-file file encoding)
1401       (if hide-p
1402           (progn
1403             (invisible-region (point-min) (point-max))
1404             (goto-char (point-max)))
1405         (goto-char (point-max))))
1406     (mime-edit-force-text-tag mime-edit-tag-regexp)
1407     ;; Define encoding even if it is 7bit.
1408     (if (stringp encoding)
1409         (save-excursion
1410           (goto-char tagend) ; Make sure which line the tag is on.
1411           (mime-edit-define-encoding encoding)))))
1412
1413 \f
1414 ;; Commands work on a current message flagment.
1415
1416 (defun mime-edit-goto-tag ()
1417   "Search for the beginning of the tagged MIME message."
1418   (let ((current (point)))
1419     (if (looking-at mime-edit-tag-regexp)
1420         t
1421       ;; At first, go to the end.
1422       (cond ((re-search-forward mime-edit-beginning-tag-regexp nil t)
1423              (goto-char (1- (match-beginning 0))) ;For multiline tag
1424              )
1425             (t
1426              (goto-char (point-max))))
1427       ;; Then search for the beginning.
1428       (re-search-backward mime-edit-end-tag-regexp nil t)
1429       (or (looking-at mime-edit-beginning-tag-regexp)
1430           ;; Restore previous point.
1431           (progn
1432             (goto-char current)
1433             nil)))))
1434
1435 (defun mime-edit-content-beginning ()
1436   "Return the point of the beginning of content."
1437   (save-excursion
1438     (let ((beg (save-excursion
1439                  (beginning-of-line) (point))))
1440       (if (mime-edit-goto-tag)
1441           (let ((top (point)))
1442             (goto-char (match-end 0))
1443             (if (and (= beg top)
1444                      (= (following-char) ?\^M))
1445                 (point)
1446               (forward-line 1)
1447               (point)))
1448         ;; Default text/plain tag.
1449         (goto-char (point-min))
1450         (re-search-forward
1451          (concat "\n" (regexp-quote mail-header-separator)
1452                  (if mime-ignore-preceding-spaces
1453                      "[ \t\n]*\n" "\n")) nil 'move)
1454         (point)))))
1455
1456 (defun mime-edit-content-end ()
1457   "Return the point of the end of content."
1458   (save-excursion
1459     (if (mime-edit-goto-tag)
1460         (progn
1461           (goto-char (match-end 0))
1462           (if (invisible-p (point))
1463               (next-visible-point (point))
1464             ;; Move to the end of this text.
1465             (if (re-search-forward mime-edit-tag-regexp nil 'move)
1466                 ;; Don't forget a multiline tag.
1467                 (goto-char (match-beginning 0)))
1468             (point)))
1469       ;; Assume the message begins with text/plain.
1470       (goto-char (mime-edit-content-beginning))
1471       (if (re-search-forward mime-edit-tag-regexp nil 'move)
1472           ;; Don't forget a multiline tag.
1473           (goto-char (match-beginning 0)))
1474       (point))))
1475
1476 (defun mime-edit-define-charset (charset)
1477   "Set charset of current tag to CHARSET."
1478   (save-excursion
1479     (if (mime-edit-goto-tag)
1480         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1481           (delete-region (match-beginning 0) (match-end 0))
1482           (insert
1483            (mime-create-tag
1484             (mime-edit-set-parameter
1485              (mime-edit-get-contype tag)
1486              "charset"
1487              (let ((comment (get charset 'mime-charset-comment)))
1488                (if comment
1489                    (concat (upcase (symbol-name charset)) " (" comment ")")
1490                  (upcase (symbol-name charset)))))
1491             (mime-edit-get-encoding tag)))))))
1492
1493 (defun mime-edit-define-encoding (encoding)
1494   "Set encoding of current tag to ENCODING."
1495   (save-excursion
1496     (if (mime-edit-goto-tag)
1497         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1498           (delete-region (match-beginning 0) (match-end 0))
1499           (insert (mime-create-tag (mime-edit-get-contype tag) encoding))))))
1500
1501 (defun mime-edit-choose-charset ()
1502   "Choose charset of a text following current point."
1503   (detect-mime-charset-region (point) (mime-edit-content-end)))
1504
1505 (defun mime-make-text-tag (&optional subtype)
1506   "Make a tag for a text after current point.
1507 Subtype of text type can be specified by an optional argument SUBTYPE.
1508 Otherwise, it is obtained from `mime-content-types'."
1509   (let* ((pritype "text")
1510          (subtype (or subtype
1511                       (car (car (cdr (assoc pritype mime-content-types)))))))
1512     ;; Charset should be defined later.
1513     (mime-make-tag pritype subtype)))
1514
1515 \f
1516 ;; Tag handling functions
1517
1518 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1519   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1520   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1521                            (or parameters ""))
1522                    encoding))
1523
1524 (defun mime-create-tag (contype &optional encoding)
1525   "Make a tag with CONTENT-TYPE and optional ENCODING."
1526   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1527           contype encoding))
1528
1529 (defun mime-edit-get-contype (tag)
1530   "Return Content-Type (including parameters) of TAG."
1531   (and (stringp tag)
1532        (or (string-match mime-edit-single-part-tag-regexp tag)
1533            (string-match mime-edit-multipart-beginning-regexp tag)
1534            (string-match mime-edit-multipart-end-regexp tag))
1535        (substring tag (match-beginning 1) (match-end 1))))
1536
1537 (defun mime-edit-get-encoding (tag)
1538   "Return encoding of TAG."
1539   (and (stringp tag)
1540        (string-match mime-edit-single-part-tag-regexp tag)
1541        (match-beginning 3)
1542        (not (= (match-beginning 3) (match-end 3)))
1543        (substring tag (match-beginning 3) (match-end 3))))
1544
1545 (defun mime-get-parameter (contype parameter)
1546   "For given CONTYPE return value for PARAMETER.
1547 Nil if no such parameter."
1548   (if (string-match
1549        (concat
1550         ";[ \t\n]*"
1551         (regexp-quote parameter)
1552         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1553        contype)
1554       (substring contype (match-beginning 1) (match-end 1))
1555     nil                                 ;No such parameter
1556     ))
1557
1558 (defun mime-edit-set-parameter (contype parameter value)
1559   "For given CONTYPE set PARAMETER to VALUE."
1560   (let (ctype opt-fields)
1561     (if (string-match "\n[^ \t\n\r]+:" contype)
1562         (setq ctype (substring contype 0 (match-beginning 0))
1563               opt-fields (substring contype (match-beginning 0)))
1564       (setq ctype contype))
1565     (if (string-match
1566          (concat
1567           ";[ \t\n]*\\("
1568           (regexp-quote parameter)
1569           "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1570          ctype)
1571         ;; Change value
1572         (concat (substring ctype 0 (match-beginning 1))
1573                 parameter "=" value
1574                 (substring contype (match-end 1)))
1575       ;; This field makes two CDP header when charset parameter is present.
1576 ;;              opt-fields)
1577       (concat ctype "; " parameter "=" value opt-fields))))
1578
1579 (defun mime-strip-parameters (contype)
1580   "Return primary content-type and subtype without parameters for CONTYPE."
1581   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1582       (substring contype (match-beginning 1) (match-end 1)) nil))
1583
1584 (defun mime-test-content-type (contype type &optional subtype)
1585   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1586   (and (stringp contype)
1587        (stringp type)
1588        (string-match
1589         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1590         (downcase contype))))
1591
1592 \f
1593 ;; Basic functions
1594
1595 (defun mime-find-file-type (file)
1596   "Guess Content-Type, subtype, and parameters from FILE."
1597   (let ((guess nil)
1598         (guesses mime-file-types))
1599     (while (and (not guess) guesses)
1600       (if (string-match (car (car guesses)) file)
1601           (setq guess (cdr (car guesses))))
1602       (setq guesses (cdr guesses)))
1603     guess))
1604
1605 (defun mime-prompt-for-type (&optional default)
1606   "Ask for Content-type."
1607   (let ((type ""))
1608     ;; Repeat until primary content type is specified.
1609     (while (string-equal type "")
1610       (setq type
1611             (completing-read "What content type: "
1612                              mime-content-types
1613                              nil
1614                              'require-match ;Type must be specified.
1615                              default))
1616       (if (string-equal type "")
1617           (progn
1618             (message "Content type is required.")
1619             (beep)
1620             (sit-for 1))))
1621     type))
1622
1623 (defun mime-prompt-for-subtype (type &optional default)
1624   "Ask for subtype of media-type TYPE."
1625   (let ((subtypes (cdr (assoc type mime-content-types))))
1626     (or (and default
1627              (assoc default subtypes))
1628         (setq default (car (car subtypes)))))
1629   (let* ((answer
1630           (completing-read
1631            (if default
1632                (concat
1633                 "What content subtype: (default " default ") ")
1634              "What content subtype: ")
1635            (cdr (assoc type mime-content-types))
1636            nil
1637            'require-match               ;Subtype must be specified.
1638            nil)))
1639     (if (string-equal answer "") default answer)))
1640
1641 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1642   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1643 Optional DELIMITER specifies parameter delimiter (';' by default)."
1644   (let* ((delimiter (or delimiter "; "))
1645          (parameters
1646           (mapconcat
1647            (function identity)
1648            (delq nil
1649                  (mime-prompt-for-parameters-1
1650                   (cdr (assoc subtype
1651                               (cdr (assoc pritype mime-content-types))))))
1652            delimiter)))
1653     (if (and (stringp parameters)
1654              (not (string-equal parameters "")))
1655         (concat delimiter parameters)
1656       ""                                ;"" if no parameters
1657       )))
1658
1659 (defun mime-prompt-for-parameters-1 (optlist)
1660   (apply (function append)
1661          (mapcar (function mime-prompt-for-parameter) optlist)))
1662
1663 (defun mime-prompt-for-parameter (parameter)
1664   "Ask for PARAMETER.
1665 Parameter must be '(PROMPT CHOICE1 (CHOICE2...))."
1666   (let* ((prompt (car parameter))
1667          (choices (mapcar (function
1668                            (lambda (e)
1669                              (if (consp e) e (list e))))
1670                           (cdr parameter)))
1671          (default (car (car choices)))
1672          (answer nil))
1673     (if choices
1674         (progn
1675           (setq answer
1676                 (completing-read
1677                  (concat "What " prompt
1678                          ": (default "
1679                          (if (string-equal default "") "\"\"" default)
1680                          ") ")
1681                  choices nil nil ""))
1682           ;; If nothing is selected, use default.
1683           (if (string-equal answer "")
1684               (setq answer default)))
1685       (setq answer
1686             (read-string (concat "What " prompt ": "))))
1687     (cons (if (and answer
1688                    (not (string-equal answer "")))
1689               (concat prompt "="
1690                       ;; Note: control characters ignored!
1691                       (if (string-match mime-tspecials-regexp answer)
1692                           (concat "\"" answer "\"") answer)))
1693           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))))
1694
1695 (defun mime-prompt-for-encoding (default)
1696   "Ask for Content-Transfer-Encoding."
1697   (let (encoding)
1698     (while (string=
1699             (setq encoding
1700                   (completing-read
1701                    "What transfer encoding: "
1702                    (mime-encoding-alist) nil t default))
1703             ""))
1704     encoding))
1705
1706 (defun mime-prompt-for-disposition (default)
1707   "Prompt Content-Disposition"
1708   (completing-read (concat "What disposition type (default "
1709                            default "): ")
1710                            mime-content-disposition-types
1711                            nil t nil nil
1712                            default))
1713
1714 \f
1715 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1716 ;;;
1717
1718 (defvar mime-edit-translate-buffer-hook
1719   '(mime-edit-pgp-enclose-buffer
1720     mime-edit-translate-body
1721     mime-edit-translate-header))
1722
1723 (defun mime-edit-translate-header ()
1724   "Encode the message header into network representation."
1725   (eword-encode-header 'code-conversion)
1726   (run-hooks 'mime-edit-translate-header-hook))
1727
1728 (defun mime-edit-translate-buffer ()
1729   "Encode the tagged MIME message in current buffer in MIME compliant message."
1730   (interactive)
1731   (undo-boundary)
1732   (if (catch 'mime-edit-error
1733         (save-excursion
1734           (run-hooks 'mime-edit-translate-buffer-hook)))
1735       (progn
1736         (undo)
1737         (error "Translation error!"))))
1738
1739 (defun mime-edit-find-inmost ()
1740   (goto-char (point-min))
1741   (if (re-search-forward mime-edit-multipart-beginning-regexp nil t)
1742       (let ((bb (match-beginning 0))
1743             (be (match-end 0))
1744             (type (buffer-substring (match-beginning 1)(match-end 1)))
1745             end-exp eb)
1746         (setq end-exp (format "--}-<<%s>>\n" type))
1747         (widen)
1748         (if (re-search-forward end-exp nil t)
1749             (setq eb (match-beginning 0))
1750           (setq eb (point-max)))
1751         (narrow-to-region be eb)
1752         (goto-char be)
1753         (if (re-search-forward mime-edit-multipart-beginning-regexp nil t)
1754             (progn
1755               (narrow-to-region (match-beginning 0)(point-max))
1756               (mime-edit-find-inmost))
1757           (widen)
1758           (list type bb be eb)))))
1759
1760 (defun mime-edit-process-multipart-1 (boundary)
1761   (let ((ret (mime-edit-find-inmost)))
1762     (if ret
1763         (let ((type (car ret))
1764               (bb (nth 1 ret))(be (nth 2 ret))
1765               (eb (nth 3 ret)))
1766           (narrow-to-region bb eb)
1767           (delete-region bb be)
1768           (setq bb (point-min))
1769           (setq eb (point-max))
1770           (widen)
1771           (goto-char eb)
1772           (if (looking-at mime-edit-multipart-end-regexp)
1773               (let ((beg (match-beginning 0))
1774                     (end (match-end 0)))
1775                 (delete-region beg end)
1776                 (mime-edit-force-text-tag mime-edit-beginning-tag-regexp)))
1777           (cond ((string-equal type "quote")
1778                  (mime-edit-enquote-region bb eb))
1779                 ((string-equal type "pgp-signed")
1780                  (mime-edit-sign-pgp-mime bb eb boundary))
1781                 ((string-equal type "pgp-encrypted")
1782                  (mime-edit-encrypt-pgp-mime bb eb boundary))
1783                 ((string-equal type "kazu-signed")
1784                  (mime-edit-sign-pgp-kazu bb eb boundary))
1785                 ((string-equal type "kazu-encrypted")
1786                  (mime-edit-encrypt-pgp-kazu bb eb boundary))
1787                 ((string-equal type "smime-signed")
1788                  (mime-edit-sign-smime bb eb boundary))
1789                 ((string-equal type "smime-encrypted")
1790                  (mime-edit-encrypt-smime bb eb boundary))
1791                 (t
1792                  (setq boundary
1793                        (nth 2 (mime-edit-translate-region bb eb
1794                                                             boundary t)))
1795                  (goto-char bb)
1796                  (insert
1797                   (format "--[[multipart/%s;
1798  boundary=\"%s\"][7bit]]\n"
1799                           type boundary))))
1800           boundary))))
1801
1802 (defun mime-edit-enquote-region (beg end)
1803   (save-excursion
1804     (save-restriction
1805       (narrow-to-region beg end)
1806       (goto-char beg)
1807       (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1808         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1809           (replace-match (concat "- " (substring tag 1))))))))
1810
1811 (defun mime-edit-dequote-region (beg end)
1812   (save-excursion
1813     (save-restriction
1814       (narrow-to-region beg end)
1815       (goto-char beg)
1816       (while (re-search-forward
1817               mime-edit-quoted-single-part-tag-regexp nil t)
1818         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1819           (replace-match (concat "-" (substring tag 2))))))))
1820
1821 (defvar mime-edit-pgp-user-id nil)
1822
1823 (defun mime-edit-sign-pgp-mime (beg end boundary)
1824   (save-excursion
1825     (save-restriction
1826       (let* ((from (std11-field-body "From" mail-header-separator))
1827              (ret (progn
1828                     (narrow-to-region beg end)
1829                     (mime-edit-translate-region beg end boundary)))
1830              (ctype    (car ret))
1831              (encoding (nth 1 ret))
1832              (pgp-boundary (concat "pgp-sign-" boundary))
1833              micalg)
1834         (goto-char beg)
1835         (insert (format "Content-Type: %s\n" ctype))
1836         (if encoding
1837             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1838         (insert "\n")
1839         (or (let ((pgg-default-user-id
1840                    (or mime-edit-pgp-user-id
1841                        (if from
1842                            (nth 1 (std11-extract-address-components from))
1843                          pgg-default-user-id))))
1844               (pgg-sign-region (point-min)(point-max)))
1845             (throw 'mime-edit-error 'pgp-error))
1846         (setq micalg
1847               (cdr (assq 'hash-algorithm
1848                          (cdar (with-current-buffer pgg-output-buffer
1849                                  (pgg-parse-armor-region
1850                                   (point-min)(point-max))))))
1851               micalg
1852               (if micalg
1853                   (concat "; micalg=pgp-" (downcase (symbol-name micalg)))
1854                 ""))
1855         (goto-char beg)
1856         (insert (format "--[[multipart/signed;
1857  boundary=\"%s\"%s;
1858  protocol=\"application/pgp-signature\"][7bit]]
1859 --%s
1860 " pgp-boundary micalg pgp-boundary))
1861         (goto-char (point-max))
1862         (insert (format "\n--%s
1863 Content-Type: application/pgp-signature
1864 Content-Transfer-Encoding: 7bit
1865
1866 " pgp-boundary))
1867         (insert-buffer-substring pgg-output-buffer)
1868         (goto-char (point-max))
1869         (insert (format "\n--%s--\n" pgp-boundary))))))
1870
1871 (defvar mime-edit-encrypt-recipient-fields-list '("To" "cc"))
1872
1873 (defun mime-edit-make-encrypt-recipient-header ()
1874   (let* ((names mime-edit-encrypt-recipient-fields-list)
1875          (values
1876           (std11-field-bodies (cons "From" names)
1877                               nil mail-header-separator))
1878          (from (prog1
1879                    (car values)
1880                  (setq values (cdr values))))
1881          (header (and (stringp from)
1882                       (if (string-equal from "")
1883                           ""
1884                         (format "From: %s\n" from))))
1885          recipients)
1886     (while (and names values)
1887       (let ((name (car names))
1888             (value (car values)))
1889         (and (stringp value)
1890              (or (string-equal value "")
1891                  (progn
1892                    (setq header (concat header name ": " value "\n")
1893                          recipients (if recipients
1894                                         (concat recipients " ," value)
1895                                       value))))))
1896       (setq names (cdr names)
1897             values (cdr values)))
1898     (vector from recipients header)))
1899
1900 (defun mime-edit-encrypt-pgp-mime (beg end boundary)
1901   (save-excursion
1902     (save-restriction
1903       (let (from recipients header)
1904         (let ((ret (mime-edit-make-encrypt-recipient-header)))
1905           (setq from (aref ret 0)
1906                 recipients (aref ret 1)
1907                 header (aref ret 2)))
1908         (narrow-to-region beg end)
1909         (let* ((ret
1910                 (mime-edit-translate-region beg end boundary))
1911                (ctype    (car ret))
1912                (encoding (nth 1 ret))
1913                (pgp-boundary (concat "pgp-" boundary)))
1914           (goto-char beg)
1915           (insert header)
1916           (insert (format "Content-Type: %s\n" ctype))
1917           (if encoding
1918               (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1919           (insert "\n")
1920           (eword-encode-header)
1921           (or (let ((pgg-default-user-id
1922                      (or mime-edit-pgp-user-id
1923                          (if from
1924                              (nth 1 (std11-extract-address-components from))
1925                            pgg-default-user-id))))
1926                 (pgg-encrypt-region
1927                  (point-min) (point-max)
1928                  (mapcar (lambda (recipient)
1929                            (nth 1 (std11-extract-address-components
1930                                    recipient)))
1931                          (split-string recipients
1932                                        "\\([ \t\n]*,[ \t\n]*\\)+"))))
1933               (throw 'mime-edit-error 'pgp-error))
1934           (delete-region (point-min)(point-max))
1935           (goto-char beg)
1936           (insert (format "--[[multipart/encrypted;
1937  boundary=\"%s\";
1938  protocol=\"application/pgp-encrypted\"][7bit]]
1939 --%s
1940 Content-Type: application/pgp-encrypted
1941
1942 --%s
1943 Content-Type: application/octet-stream
1944 Content-Transfer-Encoding: 7bit
1945
1946 " pgp-boundary pgp-boundary pgp-boundary))
1947           (insert-buffer-substring pgg-output-buffer)
1948           (goto-char (point-max))
1949           (insert (format "\n--%s--\n" pgp-boundary)))))))
1950
1951 (defun mime-edit-sign-pgp-kazu (beg end boundary)
1952   (save-excursion
1953     (save-restriction
1954       (narrow-to-region beg end)
1955       (let* ((ret
1956               (mime-edit-translate-region beg end boundary))
1957              (ctype    (car ret))
1958              (encoding (nth 1 ret)))
1959         (goto-char beg)
1960         (insert (format "Content-Type: %s\n" ctype))
1961         (if encoding
1962             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1963         (insert "\n")
1964         (or (pgg-sign-region beg (point-max) 'clearsign)
1965             (throw 'mime-edit-error 'pgp-error))
1966         (goto-char beg)
1967         (insert
1968          "--[[application/pgp; format=mime][7bit]]\n")
1969         ))))
1970
1971 (defun mime-edit-encrypt-pgp-kazu (beg end boundary)
1972   (save-excursion
1973     (let (recipients header)
1974       (let ((ret (mime-edit-make-encrypt-recipient-header)))
1975         (setq recipients (aref ret 1)
1976               header (aref ret 2)))
1977       (save-restriction
1978         (narrow-to-region beg end)
1979         (let* ((ret
1980                 (mime-edit-translate-region beg end boundary))
1981                (ctype    (car ret))
1982                (encoding (nth 1 ret)))
1983           (goto-char beg)
1984           (insert header)
1985           (insert (format "Content-Type: %s\n" ctype))
1986           (if encoding
1987               (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
1988           (insert "\n")
1989           (or (pgg-encrypt-region beg (point-max) recipients)
1990               (throw 'mime-edit-error 'pgp-error))
1991           (goto-char beg)
1992           (insert
1993            "--[[application/pgp; format=mime][7bit]]\n")
1994           )))))
1995
1996 (defun mime-edit-sign-smime (beg end boundary)
1997   (save-excursion
1998     (save-restriction
1999       (let* ((ret (progn
2000                     (narrow-to-region beg end)
2001                     (mime-edit-translate-region beg end boundary)))
2002              (ctype    (car ret))
2003              (encoding (nth 1 ret))
2004              (smime-boundary (concat "smime-sign-" boundary)))
2005         (goto-char beg)
2006         (insert (format "Content-Type: %s\n" ctype))
2007         (if encoding
2008             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
2009         (insert "\n")
2010         (let (buffer-undo-list)
2011           (goto-char (point-min))
2012           (while (progn (end-of-line) (not (eobp)))
2013             (insert "\r")
2014             (forward-line 1))
2015           (or (prog1 (smime-sign-region (point-min)(point-max))
2016                 (push nil buffer-undo-list)
2017                 (ignore-errors (undo)))
2018               (throw 'mime-edit-error 'pgp-error)))
2019         (goto-char beg)
2020         (insert (format "--[[multipart/signed;
2021  boundary=\"%s\"; micalg=sha1;
2022  protocol=\"application/pkcs7-signature\"][7bit]]
2023 --%s
2024 " smime-boundary smime-boundary))
2025         (goto-char (point-max))
2026         (insert (format "\n--%s
2027 Content-Type: application/pkcs7-signature; name=\"smime.p7s\"
2028 Content-Transfer-Encoding: base64
2029 Content-Disposition: attachment; filename=\"smime.p7s\"
2030 Content-Description: S/MIME Cryptographic Signature
2031
2032 "  smime-boundary))
2033         (insert-buffer-substring smime-output-buffer)
2034         (goto-char (point-max))
2035         (insert (format "\n--%s--\n" smime-boundary))))))
2036
2037 (defun mime-edit-encrypt-smime (beg end boundary)
2038   (save-excursion
2039     (save-restriction
2040       (let* ((ret (progn
2041                     (narrow-to-region beg end)
2042                     (mime-edit-translate-region beg end boundary)))
2043              (ctype    (car ret))
2044              (encoding (nth 1 ret)))
2045         (goto-char beg)
2046         (insert (format "Content-Type: %s\n" ctype))
2047         (if encoding
2048             (insert (format "Content-Transfer-Encoding: %s\n" encoding)))
2049         (insert "\n")
2050         (goto-char (point-min))
2051         (while (progn (end-of-line) (not (eobp)))
2052           (insert "\r")
2053           (forward-line 1))
2054         (or (smime-encrypt-region (point-min)(point-max))
2055             (throw 'mime-edit-error 'pgp-error))
2056         (delete-region (point-min)(point-max))
2057         (insert "--[[application/pkcs7-mime; name=\"smime.p7m\"
2058 Content-Disposition: attachment; filename=\"smime.p7m\"
2059 Content-Description: S/MIME Encrypted Message][base64]]\n")
2060         (insert-buffer-substring smime-output-buffer)))))
2061
2062 (defsubst replace-space-with-underline (str)
2063   (mapconcat (function
2064               (lambda (arg)
2065                 (char-to-string
2066                  (if (eq arg ?\ )
2067                      ?_
2068                    arg)))) str ""))
2069
2070 (defun mime-edit-make-boundary ()
2071   (concat mime-multipart-boundary "_"
2072           (replace-space-with-underline (current-time-string))))
2073
2074 (defun mime-edit-translate-body ()
2075   "Encode the tagged MIME body in current buffer in MIME compliant message."
2076   (interactive)
2077   (save-excursion
2078     (let ((boundary (mime-edit-make-boundary))
2079           (i 1)
2080           ret)
2081       (while (mime-edit-process-multipart-1
2082               (format "%s-%d" boundary i))
2083         (setq i (1+ i)))
2084       (save-restriction
2085         ;; We are interested in message body.
2086         (let* ((beg
2087                 (progn
2088                   (goto-char (point-min))
2089                   (re-search-forward
2090                    (concat "\n" (regexp-quote mail-header-separator)
2091                            (if mime-ignore-preceding-spaces
2092                                "[ \t\n]*\n" "\n")) nil 'move)
2093                   (point)))
2094                (end
2095                 (progn
2096                   (goto-char (point-max))
2097                   (and mime-ignore-trailing-spaces
2098                        (re-search-backward "[^ \t\n]\n" beg t)
2099                        (forward-char 1))
2100                   (point))))
2101           (setq ret (mime-edit-translate-region
2102                      beg end
2103                      (format "%s-%d" boundary i)))))
2104       (mime-edit-dequote-region (point-min)(point-max))
2105       (let ((contype (car ret))         ;Content-Type
2106             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
2107             )
2108         ;; Insert User-Agent field
2109         (and mime-edit-insert-user-agent-field
2110              (or (mail-position-on-field "User-Agent")
2111                  (insert mime-edit-user-agent-value)))
2112         ;; Make primary MIME headers.
2113         (or (mail-position-on-field "MIME-Version")
2114             (insert mime-edit-mime-version-value))
2115         ;; Remove old Content-Type and other fields.
2116         (save-restriction
2117           (goto-char (point-min))
2118           (search-forward (concat "\n" mail-header-separator "\n") nil t)
2119           (narrow-to-region (point-min) (point))
2120           (goto-char (point-min))
2121           (mime-delete-field "Content-Type")
2122           (mime-delete-field "Content-Transfer-Encoding"))
2123         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
2124         (mail-position-on-field "Content-Type")
2125         (insert contype)
2126         (if encoding
2127             (progn
2128               (mail-position-on-field "Content-Transfer-Encoding")
2129               (insert encoding)))))))
2130
2131 (defun mime-edit-translate-single-part-tag (boundary &optional prefix)
2132   "Translate single-part-tag to MIME header."
2133   (if (re-search-forward mime-edit-single-part-tag-regexp nil t)
2134       (let* ((beg (match-beginning 0))
2135              (end (match-end 0))
2136              (tag (buffer-substring beg end)))
2137         (delete-region beg end)
2138         (let ((contype (mime-edit-get-contype tag))
2139               (encoding (mime-edit-get-encoding tag)))
2140           (insert (concat prefix "--" boundary "\n"))
2141           (save-restriction
2142             (narrow-to-region (point)(point))
2143             (insert "Content-Type: " contype "\n")
2144             (if encoding
2145                 (insert "Content-Transfer-Encoding: " encoding "\n"))
2146             (eword-encode-header))
2147           (cons (and contype
2148                      (downcase contype))
2149                 (and encoding
2150                      (downcase encoding)))))))
2151
2152 (defun mime-edit-translate-region (beg end &optional boundary multipart)
2153   (or boundary
2154       (setq boundary (mime-edit-make-boundary)))
2155   (save-excursion
2156     (save-restriction
2157       (narrow-to-region beg end)
2158       (let ((tag nil)                   ;MIME tag
2159             (contype nil)               ;Content-Type
2160             (encoding nil)              ;Content-Transfer-Encoding
2161             (nparts 0))                 ;Number of body parts
2162         ;; Normalize the body part by inserting appropriate message
2163         ;; tags for every message contents.
2164         (mime-edit-normalize-body)
2165         ;; Counting the number of Content-Type.
2166         (goto-char (point-min))
2167         (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
2168           (setq nparts (1+ nparts)))
2169         ;; Begin translation.
2170         (cond
2171          ((and (<= nparts 1)(not multipart))
2172           ;; It's a singular message.
2173           (goto-char (point-min))
2174           (while (re-search-forward
2175                   mime-edit-single-part-tag-regexp nil t)
2176             (setq tag
2177                   (buffer-substring (match-beginning 0) (match-end 0)))
2178             (delete-region (match-beginning 0) (1+ (match-end 0)))
2179             (setq contype (mime-edit-get-contype tag))
2180             (setq encoding (mime-edit-get-encoding tag))))
2181          (t
2182           ;; It's a multipart message.
2183           (goto-char (point-min))
2184           (let ((prio mime-content-transfer-encoding-priority-list)
2185                 part-info nprio)
2186             (when (setq part-info
2187                         (mime-edit-translate-single-part-tag boundary))
2188               (and (setq nprio (member (cdr part-info) prio))
2189                    (setq prio nprio))
2190               (while (setq part-info
2191                            (mime-edit-translate-single-part-tag boundary "\n"))
2192                 (and (setq nprio (member (cdr part-info) prio))
2193                      (setq prio nprio))))
2194             ;; Define Content-Type as "multipart/mixed".
2195             (setq contype
2196                   (concat "multipart/mixed;\n boundary=\"" boundary "\""))
2197             (setq encoding (car prio))
2198             ;; Insert the trailer.
2199             (goto-char (point-max))
2200             (insert "\n--" boundary "--\n"))))
2201          (list contype encoding boundary nparts)))))
2202
2203 (defun mime-edit-normalize-body ()
2204   "Normalize the body part by inserting appropriate message tags."
2205   ;; Insert the first MIME tags if necessary.
2206   (goto-char (point-min))
2207   (if (not (looking-at mime-edit-single-part-tag-regexp))
2208       (insert (mime-make-text-tag) "\n"))
2209   ;; Check each tag, and add new tag or correct it if necessary.
2210   (goto-char (point-min))
2211   (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
2212     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
2213            (contype (mime-edit-get-contype tag))
2214            (charset (mime-get-parameter contype "charset"))
2215            (encoding (mime-edit-get-encoding tag)))
2216       ;; Remove extra whitespaces after the tag.
2217       (if (looking-at "[ \t]+$")
2218           (delete-region (match-beginning 0) (match-end 0)))
2219       (let ((beg (point))
2220             (end (mime-edit-content-end)))
2221         (if (= end (point-max))
2222             nil
2223           (goto-char end)
2224           (mime-edit-force-text-tag mime-edit-beginning-tag-regexp))
2225         (visible-region beg end)
2226         (goto-char beg))
2227       (cond
2228        ((mime-test-content-type contype "message")
2229         ;; Content-type "message" should be sent as is.
2230         (forward-line 1))
2231        ((mime-test-content-type contype "text")
2232         ;; Define charset for text if necessary.
2233         (setq charset (if charset
2234                           (intern (downcase charset))
2235                         (mime-edit-choose-charset)))
2236         (mime-edit-define-charset charset)
2237         (cond ((string-equal contype "text/x-rot13-47-48")
2238                (save-excursion
2239                  (forward-line)
2240                  (mule-caesar-region (point) (mime-edit-content-end))))
2241               ((string-equal contype "text/enriched")
2242                (save-excursion
2243                  (let ((beg (progn
2244                               (forward-line)
2245                               (point)))
2246                        (end (mime-edit-content-end)))
2247                    ;; Patch for hard newlines
2248                    ;; (save-excursion
2249                    ;;   (goto-char beg)
2250                    ;;   (while (search-forward "\n" end t)
2251                    ;;     (put-text-property (match-beginning 0)
2252                    ;;                        (point)
2253                    ;;                        'hard t)))
2254                    ;; End patch for hard newlines
2255                    (enriched-encode beg end nil)
2256                    (goto-char beg)
2257                    (if (search-forward "\n\n")
2258                        (delete-region beg (match-end 0)))))))
2259         ;; Point is now on current tag.
2260         ;; Define encoding and encode text if necessary.
2261         (or encoding    ;Encoding is not specified.
2262             (let* ((encoding
2263                     (let (bits conv)
2264                       (let ((ret (cdr (assq charset mime-charset-type-list))))
2265                         (if ret
2266                             (setq bits (car ret)
2267                                   conv (nth 1 ret))
2268                           (setq bits 8
2269                                 conv "quoted-printable")))
2270                       (if (<= bits mime-transfer-level)
2271                           (mime-encoding-name bits)
2272                         conv)))
2273                    (beg (mime-edit-content-beginning)))
2274               (encode-mime-charset-region beg (mime-edit-content-end)
2275                                           charset)
2276               ;; Protect "From " in beginning of line
2277               (save-restriction
2278                 (narrow-to-region beg (mime-edit-content-end))
2279                 (goto-char beg)
2280                 (let (case-fold-search)
2281                   (if (re-search-forward "^From " nil t)
2282                       (unless encoding
2283                         (if (memq charset '(iso-2022-jp
2284                                             iso-2022-jp-2
2285                                             iso-2022-int-1
2286                                             x-ctext))
2287                             (while (progn
2288                                      (replace-match "\e(BFrom ")
2289                                      (re-search-forward "^From " nil t)))
2290                           (setq encoding "quoted-printable"))))))
2291               ;; canonicalize line break code
2292               (or (member encoding '(nil "7bit" "8bit" "quoted-printable"))
2293                   (save-restriction
2294                     (narrow-to-region beg (mime-edit-content-end))
2295                     (goto-char beg)
2296                     (while (re-search-forward "\\(\\=\\|[^\r]\\)\n" nil t)
2297                       (replace-match "\\1\r\n"))))
2298               (goto-char beg)
2299               (mime-encode-region beg (mime-edit-content-end)
2300                                   (or encoding "7bit"))
2301               (mime-edit-define-encoding encoding)))
2302         (goto-char (mime-edit-content-end)))
2303        ((null encoding)         ;Encoding is not specified.
2304         ;; Application, image, audio, video, and any other
2305         ;; unknown content-type without encoding should be
2306         ;; encoded.
2307         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2308                (beg (mime-edit-content-beginning))
2309                (end (mime-edit-content-end)))
2310           (mime-encode-region beg end encoding)
2311           (mime-edit-define-encoding encoding))
2312         (forward-line 1))))))
2313
2314 (defun mime-delete-field (field)
2315   "Delete header FIELD."
2316   (let ((regexp (format "^%s:[ \t]*" field)))
2317     (goto-char (point-min))
2318     (while (re-search-forward regexp nil t)
2319       (delete-region (match-beginning 0)
2320                      (1+ (std11-field-end))))))
2321
2322 \f
2323 ;;;
2324 ;;; Platform dependent functions
2325 ;;;
2326
2327 ;; Sun implementations
2328
2329 (defun mime-edit-voice-recorder-for-sun (encoding)
2330   "Record voice in a buffer using Sun audio device,
2331 and insert data encoded as ENCODING."
2332   (message "Start the recording on %s.  Type C-g to finish the recording..."
2333            (system-name))
2334   (mime-insert-encoded-file "/dev/audio" encoding))
2335
2336 \f
2337 ;;; @ Other useful commands.
2338 ;;;
2339
2340 ;; Message forwarding commands as content-type "message/rfc822".
2341
2342 (defun mime-edit-insert-message (&optional message)
2343   (interactive)
2344   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2345     (if (and inserter (fboundp inserter))
2346         (progn
2347           (mime-edit-insert-place
2348            '("message" "rfc822")
2349            (mime-edit-insert-tag "message" "rfc822")
2350            (funcall inserter message)))
2351       (message "Sorry, I don't have message inserter for your MUA."))))
2352
2353 (defun mime-edit-insert-mail (&optional message)
2354   (interactive)
2355   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2356     (if (and inserter (fboundp inserter))
2357         (progn
2358           (mime-edit-insert-place
2359            '("message" "rfc822")
2360            (mime-edit-insert-tag "message" "rfc822")
2361            (funcall inserter message)))
2362       (message "Sorry, I don't have mail inserter for your MUA."))))
2363
2364 (defun mime-edit-inserted-message-filter ()
2365   (save-excursion
2366     (save-restriction
2367       (let ((header-start (point))
2368             (case-fold-search t)
2369             beg end)
2370         ;; for Emacs 18
2371         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2372         (if (re-search-forward "^$" (mark t))
2373             (narrow-to-region header-start (match-beginning 0)))
2374         (goto-char header-start)
2375         (while (and (re-search-forward
2376                      (concat "^"
2377                              (apply (function regexp-or)
2378                                     mime-edit-yank-ignored-field-list)
2379                              ":") nil t)
2380                     (setq beg (match-beginning 0))
2381                     (setq end (1+ (std11-field-end))))
2382           (delete-region beg end))))))
2383
2384
2385 ;;; @ multipart enclosure
2386 ;;;
2387
2388 (defun mime-edit-enclose-region-internal (type beg end)
2389   (save-excursion
2390     (goto-char beg)
2391     (save-restriction
2392       (narrow-to-region beg end)
2393       (insert (format "--<<%s>>-{\n" type))
2394       (goto-char (point-max))
2395       (insert (format "--}-<<%s>>\n" type))
2396       (goto-char (point-max)))
2397     (mime-edit-force-text-tag mime-edit-beginning-tag-regexp)))
2398
2399 (defun mime-edit-enclose-quote-region (beg end)
2400   (interactive "*r")
2401   (mime-edit-enclose-region-internal 'quote beg end))
2402
2403 (defun mime-edit-enclose-mixed-region (beg end)
2404   (interactive "*r")
2405   (mime-edit-enclose-region-internal 'mixed beg end))
2406
2407 (defun mime-edit-enclose-parallel-region (beg end)
2408   (interactive "*r")
2409   (mime-edit-enclose-region-internal 'parallel beg end))
2410
2411 (defun mime-edit-enclose-digest-region (beg end)
2412   (interactive "*r")
2413   (mime-edit-enclose-region-internal 'digest beg end))
2414
2415 (defun mime-edit-enclose-alternative-region (beg end)
2416   (interactive "*r")
2417   (mime-edit-enclose-region-internal 'alternative beg end))
2418
2419 (defun mime-edit-enclose-pgp-signed-region (beg end)
2420   (interactive "*r")
2421   (mime-edit-enclose-region-internal 'pgp-signed beg end))
2422
2423 (defun mime-edit-enclose-pgp-encrypted-region (beg end)
2424   (interactive "*r")
2425   (mime-edit-enclose-region-internal 'pgp-encrypted beg end))
2426
2427 (defun mime-edit-enclose-kazu-signed-region (beg end)
2428   (interactive "*r")
2429   (mime-edit-enclose-region-internal 'kazu-signed beg end))
2430
2431 (defun mime-edit-enclose-kazu-encrypted-region (beg end)
2432   (interactive "*r")
2433   (mime-edit-enclose-region-internal 'kazu-encrypted beg end))
2434
2435 (defun mime-edit-enclose-smime-signed-region (beg end)
2436   (interactive "*r")
2437   (mime-edit-enclose-region-internal 'smime-signed beg end))
2438
2439 (defun mime-edit-enclose-smime-encrypted-region (beg end)
2440   (interactive "*r")
2441   (mime-edit-enclose-region-internal 'smime-encrypted beg end))
2442
2443 (defun mime-edit-insert-key (&optional arg)
2444   "Insert a pgp public key."
2445   (interactive "P")
2446   (mime-edit-insert-tag "application" "pgp-keys")
2447   (mime-edit-define-encoding "7bit")
2448   (pgg-insert-key)
2449   (mime-edit-force-text-tag mime-edit-single-part-tag-regexp))
2450
2451
2452 ;;; @ flag setting
2453 ;;;
2454
2455 (defun mime-edit-set-split (arg)
2456   (interactive
2457    (list
2458     (y-or-n-p "Do you want to enable split? ")))
2459   (setq mime-edit-split-message arg)
2460   (if arg
2461       (message "This message is enabled to split.")
2462     (message "This message is not enabled to split.")))
2463
2464 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2465   "Toggle transfer-level is 7bit or 8bit through.
2466
2467 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2468   (interactive)
2469   (if (numberp transfer-level)
2470       (setq mime-transfer-level transfer-level)
2471     (if (< mime-transfer-level 8)
2472         (setq mime-transfer-level 8)
2473       (setq mime-transfer-level 7)))
2474   (message (format "Current transfer-level is %d bit"
2475                    mime-transfer-level))
2476   (setq mime-transfer-level-string
2477         (mime-encoding-name mime-transfer-level 'not-omit))
2478   (force-mode-line-update))
2479
2480 (defun mime-edit-set-transfer-level-7bit ()
2481   (interactive)
2482   (mime-edit-toggle-transfer-level 7))
2483
2484 (defun mime-edit-set-transfer-level-8bit ()
2485   (interactive)
2486   (mime-edit-toggle-transfer-level 8))
2487
2488
2489 ;;; @ pgp
2490 ;;;
2491
2492 (defvar mime-edit-pgp-processing nil)
2493 (make-variable-buffer-local 'mime-edit-pgp-processing)
2494
2495 (defun mime-edit-set-sign (arg)
2496   (interactive
2497    (list
2498     (y-or-n-p "Do you want to sign? ")))
2499   (if arg
2500       (progn
2501         (or (memq 'sign mime-edit-pgp-processing)
2502             (setq mime-edit-pgp-processing
2503                   (nconc mime-edit-pgp-processing
2504                          (copy-sequence '(sign)))))
2505         (message "This message will be signed."))
2506     (setq mime-edit-pgp-processing
2507           (delq 'sign mime-edit-pgp-processing))
2508     (message "This message will not be signed.")))
2509
2510 (defun mime-edit-set-encrypt (arg)
2511   (interactive
2512    (list
2513     (y-or-n-p "Do you want to encrypt? ")))
2514   (if arg
2515       (progn
2516         (or (memq 'encrypt mime-edit-pgp-processing)
2517             (setq mime-edit-pgp-processing
2518                   (nconc mime-edit-pgp-processing
2519                          (copy-sequence '(encrypt)))))
2520         (message "This message will be encrypt."))
2521     (setq mime-edit-pgp-processing
2522           (delq 'encrypt mime-edit-pgp-processing))
2523     (message "This message will not be encrypt.")))
2524
2525 (defun mime-edit-pgp-enclose-buffer ()
2526   (let ((beg (save-excursion
2527                (goto-char (point-min))
2528                (if (search-forward (concat "\n" mail-header-separator "\n"))
2529                    (match-end 0)))))
2530     (if beg
2531         (dolist (pgp-processing mime-edit-pgp-processing)
2532           (case pgp-processing
2533             (sign
2534              (mime-edit-enclose-pgp-signed-region
2535               beg (point-max)))
2536             (encrypt
2537              (mime-edit-enclose-pgp-encrypted-region
2538               beg (point-max))))))))
2539
2540
2541 ;;; @ split
2542 ;;;
2543
2544 (defun mime-edit-insert-partial-header (fields subject
2545                                                id number total separator)
2546   (insert fields)
2547   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2548   (insert (format "Mime-Version: %s\n" mime-edit-mime-version-value))
2549   (insert (format "\
2550 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2551                   id number total separator)))
2552
2553 (defun mime-edit-split-and-send
2554   (&optional cmd lines mime-edit-message-max-length)
2555   (interactive)
2556   (or lines
2557       (setq lines
2558             (count-lines (point-min) (point-max))))
2559   (or mime-edit-message-max-length
2560       (setq mime-edit-message-max-length
2561             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2562                 mime-edit-message-default-max-lines)))
2563   (let* (
2564 ;;       (mime-edit-draft-file-name
2565 ;;        (or (buffer-file-name)
2566 ;;            (make-temp-name
2567 ;;             (expand-file-name "mime-draft" temporary-file-directory))))
2568          (separator mail-header-separator)
2569          (id (concat "\""
2570                      (replace-space-with-underline (current-time-string))
2571                      "@" (system-name) "\"")))
2572     (run-hooks 'mime-edit-before-split-hook)
2573     (let ((the-buf (current-buffer))
2574           (copy-buf (get-buffer-create " *Original Message*"))
2575           (header (std11-header-string-except
2576                    mime-edit-split-ignored-field-regexp separator))
2577           (subject (mail-fetch-field "subject"))
2578           (total (+ (/ lines mime-edit-message-max-length)
2579                     (if (> (mod lines mime-edit-message-max-length) 0)
2580                         1)))
2581           (command
2582            (or cmd
2583                (cdr
2584                 (assq major-mode
2585                       mime-edit-split-message-sender-alist))
2586                (function
2587                 (lambda ()
2588                   (interactive)
2589                   (error "Split sender is not specified for `%s'." major-mode)))))
2590           (mime-edit-partial-number 1)
2591           data)
2592       (save-excursion
2593         (set-buffer copy-buf)
2594         (erase-buffer)
2595         (insert-buffer the-buf)
2596         (save-restriction
2597           (if (re-search-forward
2598                (concat "^" (regexp-quote separator) "$") nil t)
2599               (let ((he (match-beginning 0)))
2600                 (replace-match "")
2601                 (narrow-to-region (point-min) he)))
2602           (goto-char (point-min))
2603           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2604             (delete-region (match-beginning 0)
2605                            (1+ (std11-field-end))))))
2606       (while (< mime-edit-partial-number total)
2607         (erase-buffer)
2608         (save-excursion
2609           (set-buffer copy-buf)
2610           (setq data (buffer-substring
2611                       (point-min)
2612                       (progn
2613                         (goto-line mime-edit-message-max-length)
2614                         (point))))
2615           (delete-region (point-min)(point)))
2616         (mime-edit-insert-partial-header
2617          header subject id mime-edit-partial-number total separator)
2618         (insert data)
2619         (save-excursion
2620           (message (format "Sending %d/%d..."
2621                            mime-edit-partial-number total))
2622           (call-interactively command)
2623           (message (format "Sending %d/%d...done"
2624                            mime-edit-partial-number total)))
2625         (setq mime-edit-partial-number
2626               (1+ mime-edit-partial-number)))
2627       (erase-buffer)
2628       (save-excursion
2629         (set-buffer copy-buf)
2630         (setq data (buffer-string))
2631         (erase-buffer))
2632       (mime-edit-insert-partial-header
2633        header subject id mime-edit-partial-number total separator)
2634       (insert data)
2635       (save-excursion
2636         (message (format "Sending %d/%d..."
2637                          mime-edit-partial-number total))
2638         (message (format "Sending %d/%d...done"
2639                          mime-edit-partial-number total))))))
2640
2641 (defun mime-edit-maybe-split-and-send (&optional cmd)
2642   (interactive)
2643   (run-hooks 'mime-edit-before-send-hook)
2644   (let ((mime-edit-message-max-length
2645          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2646              mime-edit-message-default-max-lines))
2647         (lines (count-lines (point-min) (point-max))))
2648     (if (and (> lines mime-edit-message-max-length)
2649              mime-edit-split-message)
2650         (mime-edit-split-and-send cmd lines mime-edit-message-max-length))))
2651
2652
2653 ;;; @ preview message
2654 ;;;
2655
2656 (defvar mime-edit-buffer nil) ; buffer local variable
2657 (defvar mime-edit-temp-message-buffer nil)
2658
2659 (defun mime-edit-preview-message ()
2660   "preview editing MIME message."
2661   (interactive)
2662   (let* ((str (buffer-string))
2663          (separator mail-header-separator)
2664          (the-buf (current-buffer))
2665          (buf-name (buffer-name))
2666          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2667          (buf (get-buffer temp-buf-name))
2668          (pgp-processing mime-edit-pgp-processing))
2669     (if buf
2670         (progn
2671           (switch-to-buffer buf)
2672           (erase-buffer))
2673       (setq buf (get-buffer-create temp-buf-name))
2674       (switch-to-buffer buf))
2675     (insert str)
2676     (setq major-mode 'mime-temp-message-mode)
2677     (make-local-variable 'mail-header-separator)
2678     (setq mail-header-separator separator)
2679     (make-local-variable 'mime-edit-buffer)
2680     (setq mime-edit-buffer the-buf)
2681     (setq mime-edit-pgp-processing pgp-processing)
2682
2683     (run-hooks 'mime-edit-translate-hook)
2684     (mime-edit-translate-buffer)
2685     (goto-char (point-min))
2686     (if (re-search-forward
2687          (concat "^" (regexp-quote separator) "$"))
2688         (replace-match ""))
2689     (mime-view-buffer)
2690     (make-local-variable 'mime-edit-temp-message-buffer)
2691     (setq mime-edit-temp-message-buffer buf)))
2692
2693 (defun mime-edit-quitting-method ()
2694   "Quitting method for mime-view."
2695   (let* ((temp mime-edit-temp-message-buffer)
2696          buf)
2697     (mime-preview-kill-buffer)
2698     (set-buffer temp)
2699     (setq buf mime-edit-buffer)
2700     (kill-buffer temp)
2701     (switch-to-buffer buf)))
2702
2703 (set-alist 'mime-preview-quitting-method-alist
2704            'mime-temp-message-mode
2705            #'mime-edit-quitting-method)
2706
2707
2708 ;;; @ edit again
2709 ;;;
2710
2711 (defvar mime-edit-again-ignored-field-regexp
2712   (concat "^\\(" "Content-.*\\|Mime-Version"
2713           (if mime-edit-insert-user-agent-field "\\|User-Agent")
2714           "\\):")
2715   "Regexp for deleted header fields when `mime-edit-again' is called.")
2716
2717 (defsubst eliminate-top-spaces (string)
2718   "Eliminate top sequence of space or tab in STRING."
2719   (if (string-match "^[ \t]+" string)
2720       (substring string (match-end 0))
2721     string))
2722
2723 (defun mime-edit-decode-multipart-in-buffer (content-type not-decode-text)
2724   (let* ((subtype
2725           (or
2726            (cdr (assoc (mime-content-type-parameter content-type "protocol")
2727                        '(("application/pgp-encrypted" . pgp-encrypted)
2728                          ("application/pgp-signature" . pgp-signed))))
2729            (mime-content-type-subtype content-type)))
2730          (boundary (mime-content-type-parameter content-type "boundary"))
2731          (boundary-pat (concat "\n--" (regexp-quote boundary) "[ \t]*\n")))
2732     (re-search-forward boundary-pat nil t)
2733     (let ((bb (match-beginning 0)) eb tag)
2734       (setq tag (format "\n--<<%s>>-{\n" subtype))
2735       (goto-char bb)
2736       (insert tag)
2737       (setq bb (+ bb (length tag)))
2738       (re-search-forward
2739        (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2740        nil t)
2741       (setq eb (match-beginning 0))
2742       (replace-match (format "--}-<<%s>>\n" subtype))
2743       (save-restriction
2744         (narrow-to-region bb eb)
2745         (goto-char (point-min))
2746         (while (re-search-forward boundary-pat nil t)
2747           (let ((beg (match-beginning 0))
2748                 end)
2749             (delete-region beg (match-end 0))
2750             (save-excursion
2751               (if (re-search-forward boundary-pat nil t)
2752                   (setq end (match-beginning 0))
2753                 (setq end (point-max)))
2754               (save-restriction
2755                 (narrow-to-region beg end)
2756                 (cond
2757                  ((eq subtype 'pgp-encrypted)
2758                   (when (and
2759                          (progn
2760                            (goto-char (point-min))
2761                            (re-search-forward "^-+BEGIN PGP MESSAGE-+$"
2762                                               nil t))
2763                          (prog1
2764                              (save-window-excursion
2765                                (pgg-decrypt-region (match-beginning 0)
2766                                                    (point-max)))
2767                            (delete-region (point-min)(point-max))))
2768                     (insert-buffer-substring pgg-output-buffer)
2769                     (mime-edit-decode-message-in-buffer
2770                      nil not-decode-text)
2771                     (delete-region (goto-char (point-min))
2772                                    (if (search-forward "\n\n" nil t)
2773                                        (match-end 0)
2774                                      (point-min)))
2775                     (goto-char (point-max))))
2776                  (t
2777                   (mime-edit-decode-message-in-buffer
2778                    (if (eq subtype 'digest)
2779                        (eval-when-compile
2780                          (make-mime-content-type 'message 'rfc822)))
2781                    not-decode-text)
2782                   (goto-char (point-max))))))))))
2783     (goto-char (point-min))
2784     (or (= (point-min) 1)
2785         (delete-region (point-min)
2786                        (if (search-forward "\n\n" nil t)
2787                            (match-end 0)
2788                          (point-min))))))
2789
2790 (defun mime-edit-decode-single-part-in-buffer
2791   (content-type not-decode-text &optional content-disposition)
2792   (let* ((type (mime-content-type-primary-type content-type))
2793          (subtype (mime-content-type-subtype content-type))
2794          (ctype (format "%s/%s" type subtype))
2795          charset
2796          (pstr (let ((bytes (+ 14 (length ctype))))
2797                  (mapconcat (function
2798                              (lambda (attr)
2799                                (if (string= (car attr) "charset")
2800                                    (progn
2801                                      (setq charset (cdr attr))
2802                                      "")
2803                                  (let* ((str (concat (car attr)
2804                                                      "=" (cdr attr)))
2805                                         (bs (length str)))
2806                                    (setq bytes (+ bytes bs 2))
2807                                    (if (< bytes 76)
2808                                        (concat "; " str)
2809                                      (setq bytes (+ bs 1))
2810                                      (concat ";\n " str)
2811                                      )))))
2812                             (mime-content-type-parameters content-type) "")))
2813          encoding
2814          encoded
2815          (limit (save-excursion
2816                   (if (search-forward "\n\n" nil t)
2817                       (1- (point)))))
2818          (disposition-type
2819           (mime-content-disposition-type content-disposition))
2820          (disposition-str
2821           (if disposition-type
2822               (let ((bytes (+ 21 (length (format "%s" disposition-type)))))
2823                 (mapconcat (function
2824                             (lambda (attr)
2825                               (let* ((str (concat
2826                                            (car attr)
2827                                            "="
2828                                            (if (string-equal "filename"
2829                                                              (car attr))
2830                                                (std11-wrap-as-quoted-string
2831                                                 (cdr attr))
2832                                              (cdr attr))))
2833                                      (bs (length str)))
2834                                 (setq bytes (+ bytes bs 2))
2835                                 (if (< bytes 76)
2836                                     (concat "; " str)
2837                                   (setq bytes (+ bs 1))
2838                                   (concat ";\n " str)
2839                                   ))))
2840                            (mime-content-disposition-parameters
2841                             content-disposition)
2842                            "")))))
2843     (if disposition-type
2844         (setq pstr (format "%s\nContent-Disposition: %s%s"
2845                            pstr disposition-type disposition-str)))
2846     (save-excursion
2847       (if (re-search-forward
2848            "^Content-Transfer-Encoding:" limit t)
2849           (let ((beg (match-beginning 0))
2850                 (hbeg (match-end 0))
2851                 (end (std11-field-end limit)))
2852             (setq encoding
2853                   (downcase
2854                    (eliminate-top-spaces
2855                     (std11-unfold-string
2856                      (buffer-substring hbeg end)))))
2857             (if (or charset (eq type 'text))
2858                 (progn
2859                   (delete-region beg (1+ end))
2860                   (goto-char (point-min))
2861                   (if (search-forward "\n\n" nil t)
2862                       (progn
2863                         (mime-decode-region
2864                          (match-end 0)(point-max) encoding)
2865                         (setq encoded t
2866                               encoding nil))))))))
2867     (if (and (eq type 'text)
2868              (or encoded (not not-decode-text)))
2869         (progn
2870           (save-excursion
2871             (goto-char (point-min))
2872             (while (re-search-forward "\r\n" nil t)
2873               (replace-match "\n")))
2874           (decode-mime-charset-region (point-min)(point-max)
2875                                       (or charset default-mime-charset))))
2876     (let ((he (if (re-search-forward "^$" nil t)
2877                   (match-end 0)
2878                 (point-min))))
2879       (if (and (eq type 'text)
2880                (eq subtype 'x-rot13-47-48))
2881           (mule-caesar-region he (point-max)))
2882       (if (= (point-min) 1)
2883           (progn
2884             (goto-char he)
2885             (insert
2886              (concat "\n"
2887                      (mime-create-tag
2888                       (format "%s/%s%s" type subtype pstr)
2889                       encoding))))
2890         (delete-region (point-min) he)
2891         (insert
2892          (mime-create-tag (format "%s/%s%s" type subtype pstr)
2893                           encoding))))))
2894
2895 ;;;###autoload
2896 (defun mime-edit-decode-message-in-buffer (&optional default-content-type
2897                                                      not-decode-text)
2898   (save-excursion
2899     (goto-char (point-min))
2900     (let ((ctl (or (mime-read-Content-Type)
2901                    default-content-type)))
2902       (if ctl
2903           (let ((type (mime-content-type-primary-type ctl)))
2904             (cond
2905              ((and (eq type 'application)
2906                    (eq (mime-content-type-subtype ctl) 'pgp-signature))
2907               (delete-region (point-min)(point-max)))
2908              ((eq type 'multipart)
2909               (mime-edit-decode-multipart-in-buffer ctl not-decode-text))
2910              (t
2911               (mime-edit-decode-single-part-in-buffer
2912                ctl not-decode-text (mime-read-Content-Disposition)))))
2913         (or not-decode-text
2914             (decode-mime-charset-region (point-min) (point-max)
2915                                         default-mime-charset)))
2916       (if (= (point-min) 1)
2917           (progn
2918             (save-restriction
2919               (std11-narrow-to-header)
2920               (goto-char (point-min))
2921               (while (re-search-forward
2922                       mime-edit-again-ignored-field-regexp nil t)
2923                 (delete-region (match-beginning 0) (1+ (std11-field-end)))))
2924             (mime-decode-header-in-buffer (not not-decode-text)))))))
2925
2926 ;;;###autoload
2927 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2928   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2929 Content-Type and Content-Transfer-Encoding header fields will be
2930 converted to MIME-Edit tags."
2931   (interactive)
2932   (goto-char (point-min))
2933   (if (search-forward
2934        (concat "\n" (regexp-quote mail-header-separator) "\n")
2935        nil t)
2936       (replace-match "\n\n"))
2937   (mime-edit-decode-message-in-buffer nil not-decode-text)
2938   (goto-char (point-min))
2939   (or no-separator
2940       (and (re-search-forward "^$")
2941            (replace-match mail-header-separator)))
2942   (or not-turn-on
2943       (turn-on-mime-edit)))
2944
2945
2946 ;;; @ end
2947 ;;;
2948
2949 (provide 'mime-edit)
2950
2951 (run-hooks 'mime-edit-load-hook)
2952
2953 ;;; mime-edit.el ends here