87653b7dadc77182dc86efdfe21da3275b38f121
[gnus] / lisp / mm-util.el
1 ;;; mm-util.el --- Utility functions for Mule and low level things
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30 (require 'mail-prsvr)
31
32 (eval-and-compile
33   (mapcar
34    (lambda (elem)
35      (let ((nfunc (intern (format "mm-%s" (car elem)))))
36        (if (fboundp (car elem))
37            (defalias nfunc (car elem))
38          (defalias nfunc (cdr elem)))))
39    '((decode-coding-string . (lambda (s a) s))
40      (encode-coding-string . (lambda (s a) s))
41      (encode-coding-region . ignore)
42      (coding-system-list . ignore)
43      (decode-coding-region . ignore)
44      (char-int . identity)
45      (coding-system-equal . equal)
46      (annotationp . ignore)
47      (set-buffer-file-coding-system . ignore)
48      (read-charset
49       . (lambda (prompt)
50           "Return a charset."
51           (intern
52            (completing-read
53             prompt
54             (mapcar (lambda (e) (list (symbol-name (car e))))
55                     mm-mime-mule-charset-alist)
56             nil t))))
57      (subst-char-in-string
58       . (lambda (from to string &optional inplace)
59           ;; stolen (and renamed) from nnheader.el
60           "Replace characters in STRING from FROM to TO.
61           Unless optional argument INPLACE is non-nil, return a new string."
62           (let ((string (if inplace string (copy-sequence string)))
63                 (len (length string))
64                 (idx 0))
65             ;; Replace all occurrences of FROM with TO.
66             (while (< idx len)
67               (when (= (aref string idx) from)
68                 (aset string idx to))
69               (setq idx (1+ idx)))
70             string)))
71      (replace-in-string
72       . (lambda (string regexp rep &optional literal)
73           "See `replace-regexp-in-string', only the order of args differs."
74           (replace-regexp-in-string regexp rep string nil literal)))
75      (string-as-unibyte . identity)
76      (string-make-unibyte . identity)
77      ;; string-as-multibyte often doesn't really do what you think it does.
78      ;; Example:
79      ;;    (aref (string-as-multibyte "\201") 0) -> 129 (aka ?\201)
80      ;;    (aref (string-as-multibyte "\300") 0) -> 192 (aka ?\300)
81      ;;    (aref (string-as-multibyte "\300\201") 0) -> 192 (aka ?\300)
82      ;;    (aref (string-as-multibyte "\300\201") 1) -> 129 (aka ?\201)
83      ;; but
84      ;;    (aref (string-as-multibyte "\201\300") 0) -> 2240
85      ;;    (aref (string-as-multibyte "\201\300") 1) -> <error>
86      ;; Better use string-to-multibyte or encode-coding-string.
87      ;; If you really need string-as-multibyte somewhere it's usually
88      ;; because you're using the internal emacs-mule representation (maybe
89      ;; because you're using string-as-unibyte somewhere), which is
90      ;; generally a problem in itself.
91      ;; Here is an approximate equivalence table to help think about it:
92      ;; (string-as-multibyte s)   ~= (decode-coding-string s 'emacs-mule)
93      ;; (string-to-multibyte s)   ~= (decode-coding-string s 'binary)
94      ;; (string-make-multibyte s) ~= (decode-coding-string s locale-coding-system)
95      (string-as-multibyte . identity)
96      (string-to-multibyte
97       . (lambda (string)
98           "Return a multibyte string with the same individual chars as string."
99           (mapconcat
100            (lambda (ch) (mm-string-as-multibyte (char-to-string ch)))
101            string "")))
102      (multibyte-string-p . ignore)
103      ;; It is not a MIME function, but some MIME functions use it.
104      (make-temp-file . (lambda (prefix &optional dir-flag)
105                          (let ((file (expand-file-name
106                                       (make-temp-name prefix)
107                                       (if (fboundp 'temp-directory)
108                                           (temp-directory)
109                                         temporary-file-directory))))
110                            (if dir-flag
111                                (make-directory file))
112                            file)))
113      (insert-byte . insert-char)
114      (multibyte-char-to-unibyte . identity))))
115
116 (eval-and-compile
117   (defalias 'mm-char-or-char-int-p
118     (cond
119      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
120      ((fboundp 'char-valid-p) 'char-valid-p)
121      (t 'identity))))
122
123 ;; Fixme:  This seems always to be used to read a MIME charset, so it
124 ;; should be re-named and fixed (in Emacs) to offer completion only on
125 ;; proper charset names (base coding systems which have a
126 ;; mime-charset defined).  XEmacs doesn't believe in mime-charset;
127 ;; test with
128 ;;   `(or (coding-system-get 'iso-8859-1 'mime-charset)
129 ;;        (coding-system-get 'iso-8859-1 :mime-charset))'
130 ;; Actually, there should be an `mm-coding-system-mime-charset'.
131 (eval-and-compile
132   (defalias 'mm-read-coding-system
133     (cond
134      ((fboundp 'read-coding-system)
135       (if (and (featurep 'xemacs)
136                (<= (string-to-number emacs-version) 21.1))
137           (lambda (prompt &optional default-coding-system)
138             (read-coding-system prompt))
139         'read-coding-system))
140      (t (lambda (prompt &optional default-coding-system)
141           "Prompt the user for a coding system."
142           (completing-read
143            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
144                           mm-mime-mule-charset-alist)))))))
145
146 (defvar mm-coding-system-list nil)
147 (defun mm-get-coding-system-list ()
148   "Get the coding system list."
149   (or mm-coding-system-list
150       (setq mm-coding-system-list (mm-coding-system-list))))
151
152 (defun mm-coding-system-p (cs)
153   "Return non-nil if CS is a symbol naming a coding system.
154 In XEmacs, also return non-nil if CS is a coding system object.
155 If CS is available, return CS itself in Emacs, and return a coding
156 system object in XEmacs."
157   (if (fboundp 'find-coding-system)
158       (and cs (find-coding-system cs))
159     (if (fboundp 'coding-system-p)
160         (when (coding-system-p cs)
161           cs)
162       ;; Is this branch ever actually useful?
163       (car (memq cs (mm-get-coding-system-list))))))
164
165 (defun mm-codepage-setup (number &optional alias)
166   "Create a coding system cpNUMBER.
167 The coding system is created using `codepage-setup'.  If ALIAS is
168 non-nil, an alias is created and added to
169 `mm-charset-synonym-alist'.  If ALIAS is a string, it's used as
170 the alias.  Else windows-NUMBER is used."
171   (interactive
172    (let ((completion-ignore-case t)
173          (candidates (cp-supported-codepages)))
174      (list (completing-read "Setup DOS Codepage: (default 437) " candidates
175                             nil t nil nil "437"))))
176   (when alias
177     (setq alias (if (stringp alias)
178                     (intern alias)
179                   (intern (format "windows-%s" number)))))
180   (let* ((cp (intern (format "cp%s" number))))
181     (unless (mm-coding-system-p cp)
182       (codepage-setup number))
183     (when (and alias
184                ;; Don't add alias if setup of cp failed.
185                (mm-coding-system-p cp))
186       (add-to-list 'mm-charset-synonym-alist (cons alias cp)))))
187
188 (defvar mm-charset-synonym-alist
189   `(
190     ;; Not in XEmacs, but it's not a proper MIME charset anyhow.
191     ,@(unless (mm-coding-system-p 'x-ctext)
192        '((x-ctext . ctext)))
193     ;; ISO-8859-15 is very similar to ISO-8859-1.  But it's _different_!
194     ,@(unless (mm-coding-system-p 'iso-8859-15)
195        '((iso-8859-15 . iso-8859-1)))
196     ;; BIG-5HKSCS is similar to, but different than, BIG-5.
197     ,@(unless (mm-coding-system-p 'big5-hkscs)
198         '((big5-hkscs . big5)))
199     ;; Windows-1252 is actually a superset of Latin-1.  See also
200     ;; `gnus-article-dumbquotes-map'.
201     ,@(unless (mm-coding-system-p 'windows-1252)
202        (if (mm-coding-system-p 'cp1252)
203            '((windows-1252 . cp1252))
204          '((windows-1252 . iso-8859-1))))
205     ;; Windows-1250 is a variant of Latin-2 heavily used by Microsoft
206     ;; Outlook users in Czech republic. Use this to allow reading of their
207     ;; e-mails. cp1250 should be defined by M-x codepage-setup.
208     ,@(if (and (not (mm-coding-system-p 'windows-1250))
209                (mm-coding-system-p 'cp1250))
210           '((windows-1250 . cp1250)))
211     ;; A Microsoft misunderstanding.
212     ,@(if (and (not (mm-coding-system-p 'unicode))
213                (mm-coding-system-p 'utf-16-le))
214           '((unicode . utf-16-le)))
215     ;; A Microsoft misunderstanding.
216     ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
217         (if (mm-coding-system-p 'cp949)
218             '((ks_c_5601-1987 . cp949))
219           '((ks_c_5601-1987 . euc-kr))))
220     )
221   "A mapping from unknown or invalid charset names to the real charset names.")
222
223 (defcustom mm-charset-override-alist
224   `((iso-8859-1 . windows-1252))
225   "A mapping from undesired charset names to their replacement.
226
227 You may add pair like (iso-8859-1 . windows-1252) here,
228 i.e. treat iso-8859-1 as windows-1252.  windows-1252 is a
229 superset of iso-8859-1."
230   :type '(list (set :inline t
231                     (const (iso-8859-1 . windows-1252))
232                     (const (undecided  . windows-1252)))
233                (repeat :inline t
234                        :tag "Other options"
235                        (cons (symbol :tag "From charset")
236                              (symbol :tag "To charset"))))
237   :version "23.0" ;; No Gnus
238   :group 'mime)
239
240 (defcustom mm-charset-eval-alist
241   (if (featurep 'xemacs)
242       nil ;; I don't know what would be useful for XEmacs.
243     '(;; Emacs 21 offers 1250 1251 1253 1257.  Emacs 22 provides autoloads for
244       ;; 1250-1258 (i.e. `mm-codepage-setup' does nothing).
245       (windows-1250 . (mm-codepage-setup 1250 t))
246       (windows-1251 . (mm-codepage-setup 1251 t))
247       (windows-1253 . (mm-codepage-setup 1253 t))
248       (windows-1257 . (mm-codepage-setup 1257 t))))
249   "An alist of (CHARSET . FORM) pairs.
250 If an article is encoded in an unknown CHARSET, FORM is
251 evaluated.  This allows to load additional libraries providing
252 charsets on demand.  If supported by your Emacs version, you
253 could use `autoload-coding-system' here."
254   :version "23.0" ;; No Gnus
255   :type '(list (set :inline t
256                     (const (windows-1250 . (mm-codepage-setup 1250 t)))
257                     (const (windows-1251 . (mm-codepage-setup 1251 t)))
258                     (const (windows-1253 . (mm-codepage-setup 1253 t)))
259                     (const (windows-1257 . (mm-codepage-setup 1257 t)))
260                     (const (cp850 . (mm-codepage-setup 850 nil))))
261                (repeat :inline t
262                        :tag "Other options"
263                        (cons (symbol :tag "charset")
264                              (symbol :tag "form"))))
265   :group 'mime)
266
267 (defvar mm-binary-coding-system
268   (cond
269    ((mm-coding-system-p 'binary) 'binary)
270    ((mm-coding-system-p 'no-conversion) 'no-conversion)
271    (t nil))
272   "100% binary coding system.")
273
274 (defvar mm-text-coding-system
275   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
276           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
277         (and (mm-coding-system-p 'raw-text) 'raw-text))
278       mm-binary-coding-system)
279   "Text-safe coding system (For removing ^M).")
280
281 (defvar mm-text-coding-system-for-write nil
282   "Text coding system for write.")
283
284 (defvar mm-auto-save-coding-system
285   (cond
286    ((mm-coding-system-p 'utf-8-emacs)   ; Mule 7
287     (if (memq system-type '(windows-nt ms-dos ms-windows))
288         (if (mm-coding-system-p 'utf-8-emacs-dos)
289             'utf-8-emacs-dos mm-binary-coding-system)
290       'utf-8-emacs))
291    ((mm-coding-system-p 'emacs-mule)
292     (if (memq system-type '(windows-nt ms-dos ms-windows))
293         (if (mm-coding-system-p 'emacs-mule-dos)
294             'emacs-mule-dos mm-binary-coding-system)
295       'emacs-mule))
296    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
297    (t mm-binary-coding-system))
298   "Coding system of auto save file.")
299
300 (defvar mm-universal-coding-system mm-auto-save-coding-system
301   "The universal coding system.")
302
303 ;; Fixme: some of the cars here aren't valid MIME charsets.  That
304 ;; should only matter with XEmacs, though.
305 (defvar mm-mime-mule-charset-alist
306   `((us-ascii ascii)
307     (iso-8859-1 latin-iso8859-1)
308     (iso-8859-2 latin-iso8859-2)
309     (iso-8859-3 latin-iso8859-3)
310     (iso-8859-4 latin-iso8859-4)
311     (iso-8859-5 cyrillic-iso8859-5)
312     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
313     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
314     ;; charset is koi8-r, not iso-8859-5.
315     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
316     (iso-8859-6 arabic-iso8859-6)
317     (iso-8859-7 greek-iso8859-7)
318     (iso-8859-8 hebrew-iso8859-8)
319     (iso-8859-9 latin-iso8859-9)
320     (iso-8859-14 latin-iso8859-14)
321     (iso-8859-15 latin-iso8859-15)
322     (viscii vietnamese-viscii-lower)
323     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
324     (euc-kr korean-ksc5601)
325     (gb2312 chinese-gb2312)
326     (big5 chinese-big5-1 chinese-big5-2)
327     (tibetan tibetan)
328     (thai-tis620 thai-tis620)
329     (windows-1251 cyrillic-iso8859-5)
330     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
331     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
332                    latin-jisx0201 japanese-jisx0208-1978
333                    chinese-gb2312 japanese-jisx0208
334                    korean-ksc5601 japanese-jisx0212)
335     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
336                     latin-jisx0201 japanese-jisx0208-1978
337                     chinese-gb2312 japanese-jisx0208
338                     korean-ksc5601 japanese-jisx0212
339                     chinese-cns11643-1 chinese-cns11643-2)
340     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
341                     cyrillic-iso8859-5 greek-iso8859-7
342                     latin-jisx0201 japanese-jisx0208-1978
343                     chinese-gb2312 japanese-jisx0208
344                     korean-ksc5601 japanese-jisx0212
345                     chinese-cns11643-1 chinese-cns11643-2
346                     chinese-cns11643-3 chinese-cns11643-4
347                     chinese-cns11643-5 chinese-cns11643-6
348                     chinese-cns11643-7)
349     (iso-2022-jp-3 latin-jisx0201 japanese-jisx0208-1978 japanese-jisx0208
350                    japanese-jisx0213-1 japanese-jisx0213-2)
351     (shift_jis latin-jisx0201 katakana-jisx0201 japanese-jisx0208)
352     ,(if (or (not (fboundp 'charsetp)) ;; non-Mule case
353              (charsetp 'unicode-a)
354              (not (mm-coding-system-p 'mule-utf-8)))
355          '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e)
356        ;; If we have utf-8 we're in Mule 5+.
357        (append '(utf-8)
358                (delete 'ascii
359                        (coding-system-get 'mule-utf-8 'safe-charsets)))))
360   "Alist of MIME-charset/MULE-charsets.")
361
362 (defun mm-enrich-utf-8-by-mule-ucs ()
363   "Make the `utf-8' MIME charset usable by the Mule-UCS package.
364 This function will run when the `un-define' module is loaded under
365 XEmacs, and fill the `utf-8' entry in `mm-mime-mule-charset-alist'
366 with Mule charsets.  It is completely useless for Emacs."
367   (unless (cdr (delete '(mm-enrich-utf-8-by-mule-ucs)
368                        (assoc "un-define" after-load-alist)))
369     (setq after-load-alist
370           (delete '("un-define") after-load-alist)))
371   (when (boundp 'unicode-basic-translation-charset-order-list)
372     (condition-case nil
373         (let ((val (delq
374                     'ascii
375                     (copy-sequence
376                      (symbol-value
377                       'unicode-basic-translation-charset-order-list))))
378               (elem (assq 'utf-8 mm-mime-mule-charset-alist)))
379           (if elem
380               (setcdr elem val)
381             (setq mm-mime-mule-charset-alist
382                   (nconc mm-mime-mule-charset-alist
383                          (list (cons 'utf-8 val))))))
384       (error))))
385
386 ;; Correct by construction, but should be unnecessary for Emacs:
387 (if (featurep 'xemacs)
388     (eval-after-load "un-define" '(mm-enrich-utf-8-by-mule-ucs))
389   (when (and (fboundp 'coding-system-list)
390              (fboundp 'sort-coding-systems))
391     (let ((css (sort-coding-systems (coding-system-list 'base-only)))
392           cs mime mule alist)
393       (while css
394         (setq cs (pop css)
395               mime (or (coding-system-get cs :mime-charset) ; Emacs 22
396                        (coding-system-get cs 'mime-charset)))
397         (when (and mime
398                    (not (eq t (setq mule
399                                     (coding-system-get cs 'safe-charsets))))
400                    (not (assq mime alist)))
401           (push (cons mime (delq 'ascii mule)) alist)))
402       (setq mm-mime-mule-charset-alist (nreverse alist)))))
403
404 (defvar mm-hack-charsets '(iso-8859-15 iso-2022-jp-2)
405   "A list of special charsets.
406 Valid elements include:
407 `iso-8859-15'    convert ISO-8859-1, -9 to ISO-8859-15 if ISO-8859-15 exists.
408 `iso-2022-jp-2'  convert ISO-2022-jp to ISO-2022-jp-2 if ISO-2022-jp-2 exists."
409 )
410
411 (defvar mm-iso-8859-15-compatible
412   '((iso-8859-1 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")
413     (iso-8859-9 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xD0\xDD\xDE\xF0\xFD\xFE"))
414   "ISO-8859-15 exchangeable coding systems and inconvertible characters.")
415
416 (defvar mm-iso-8859-x-to-15-table
417   (and (fboundp 'coding-system-p)
418        (mm-coding-system-p 'iso-8859-15)
419        (mapcar
420         (lambda (cs)
421           (if (mm-coding-system-p (car cs))
422               (let ((c (string-to-char
423                         (decode-coding-string "\341" (car cs)))))
424                 (cons (char-charset c)
425                       (cons
426                        (- (string-to-char
427                            (decode-coding-string "\341" 'iso-8859-15)) c)
428                        (string-to-list (decode-coding-string (car (cdr cs))
429                                                              (car cs))))))
430             '(gnus-charset 0)))
431         mm-iso-8859-15-compatible))
432   "A table of the difference character between ISO-8859-X and ISO-8859-15.")
433
434 (defcustom mm-coding-system-priorities
435   (if (boundp 'current-language-environment)
436       (let ((lang (symbol-value 'current-language-environment)))
437         (cond ((string= lang "Japanese")
438                ;; Japanese users prefer iso-2022-jp to euc-japan or
439                ;; shift_jis, however iso-8859-1 should be used when
440                ;; there are only ASCII text and Latin-1 characters.
441                '(iso-8859-1 iso-2022-jp iso-2022-jp-2 shift_jis utf-8)))))
442   "Preferred coding systems for encoding outgoing messages.
443
444 More than one suitable coding system may be found for some text.
445 By default, the coding system with the highest priority is used
446 to encode outgoing messages (see `sort-coding-systems').  If this
447 variable is set, it overrides the default priority."
448   :version "21.2"
449   :type '(repeat (symbol :tag "Coding system"))
450   :group 'mime)
451
452 ;; ??
453 (defvar mm-use-find-coding-systems-region
454   (fboundp 'find-coding-systems-region)
455   "Use `find-coding-systems-region' to find proper coding systems.
456
457 Setting it to nil is useful on Emacsen supporting Unicode if sending
458 mail with multiple parts is preferred to sending a Unicode one.")
459
460 ;;; Internal variables:
461
462 ;;; Functions:
463
464 (defun mm-mule-charset-to-mime-charset (charset)
465   "Return the MIME charset corresponding to the given Mule CHARSET."
466   (if (and (fboundp 'find-coding-systems-for-charsets)
467            (fboundp 'sort-coding-systems))
468       (let ((css (sort (sort-coding-systems
469                         (find-coding-systems-for-charsets (list charset)))
470                        'mm-sort-coding-systems-predicate))
471             cs mime)
472         (while (and (not mime)
473                     css)
474           (when (setq cs (pop css))
475             (setq mime (or (coding-system-get cs :mime-charset)
476                            (coding-system-get cs 'mime-charset)))))
477         mime)
478     (let ((alist (mapcar (lambda (cs)
479                            (assq cs mm-mime-mule-charset-alist))
480                          (sort (mapcar 'car mm-mime-mule-charset-alist)
481                                'mm-sort-coding-systems-predicate)))
482           out)
483       (while alist
484         (when (memq charset (cdar alist))
485           (setq out (caar alist)
486                 alist nil))
487         (pop alist))
488       out)))
489
490 (defun mm-charset-to-coding-system (charset &optional lbt
491                                             allow-override)
492   "Return coding-system corresponding to CHARSET.
493 CHARSET is a symbol naming a MIME charset.
494 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
495 used as the line break code type of the coding system.
496
497 If ALLOW-OVERRIDE is given, use `mm-charset-override-alist' to
498 map undesired charset names to their replacement.  This should
499 only be used for decoding, not for encoding."
500   ;; OVERRIDE is used (only) in `mm-decode-body'.
501   (when (stringp charset)
502     (setq charset (intern (downcase charset))))
503   (when lbt
504     (setq charset (intern (format "%s-%s" charset lbt))))
505   (cond
506    ((null charset)
507     charset)
508    ;; Running in a non-MULE environment.
509    ((or (null (mm-get-coding-system-list))
510         (not (fboundp 'coding-system-get)))
511     charset)
512    ;; Check override list quite early.  Should only used for decoding, not for
513    ;; encoding!
514    ((and allow-override
515          (let ((cs (cdr (assq charset mm-charset-override-alist))))
516            (and cs (mm-coding-system-p cs) cs))))
517    ;; ascii
518    ((eq charset 'us-ascii)
519     'ascii)
520    ;; Check to see whether we can handle this charset.  (This depends
521    ;; on there being some coding system matching each `mime-charset'
522    ;; property defined, as there should be.)
523    ((and (mm-coding-system-p charset)
524 ;;; Doing this would potentially weed out incorrect charsets.
525 ;;;      charset
526 ;;;      (eq charset (coding-system-get charset 'mime-charset))
527          )
528     charset)
529    ;; Eval expressions from `mm-charset-eval-alist'
530    ((let* ((el (assq charset mm-charset-eval-alist))
531            (cs (car el))
532            (form (cdr el)))
533       (and cs
534            form
535            (prog2
536                ;; Avoid errors...
537                (condition-case nil (eval form) (error nil))
538                ;; (message "Failed to eval `%s'" form))
539                (mm-coding-system-p cs)
540              (message "Added charset `%s' via `mm-charset-eval-alist'" cs))
541            cs)))
542    ;; Translate invalid charsets.
543    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
544       (and cs
545            (mm-coding-system-p cs)
546            ;; (message
547            ;;  "Using synonym `%s' from `mm-charset-synonym-alist' for `%s'"
548            ;;  cs charset)
549            cs)))
550    ;; Last resort: search the coding system list for entries which
551    ;; have the right mime-charset in case the canonical name isn't
552    ;; defined (though it should be).
553    ((let (cs)
554       ;; mm-get-coding-system-list returns a list of cs without lbt.
555       ;; Do we need -lbt?
556       (dolist (c (mm-get-coding-system-list))
557         (if (and (null cs)
558                  (eq charset (or (coding-system-get c :mime-charset)
559                                  (coding-system-get c 'mime-charset))))
560             (setq cs c)))
561       (unless cs
562         ;; Warn the user about unknown charset:
563         (if (fboundp 'gnus-message)
564             (gnus-message 7 "Unknown charset: %s" charset)
565           (message "Unknown charset: %s" charset)))
566       cs))))
567
568 (eval-and-compile
569   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
570                              (boundp 'default-enable-multibyte-characters)
571                              default-enable-multibyte-characters
572                              (fboundp 'set-buffer-multibyte))
573     "True in Emacs with Mule.")
574
575   (if mm-emacs-mule
576       (defun mm-enable-multibyte ()
577         "Set the multibyte flag of the current buffer.
578 Only do this if the default value of `enable-multibyte-characters' is
579 non-nil.  This is a no-op in XEmacs."
580         (set-buffer-multibyte 'to))
581     (defalias 'mm-enable-multibyte 'ignore))
582
583   (if mm-emacs-mule
584       (defun mm-disable-multibyte ()
585         "Unset the multibyte flag of in the current buffer.
586 This is a no-op in XEmacs."
587         (set-buffer-multibyte nil))
588     (defalias 'mm-disable-multibyte 'ignore)))
589
590 (defun mm-preferred-coding-system (charset)
591   ;; A typo in some Emacs versions.
592   (or (get-charset-property charset 'preferred-coding-system)
593       (get-charset-property charset 'prefered-coding-system)))
594
595 ;; Mule charsets shouldn't be used.
596 (defsubst mm-guess-charset ()
597   "Guess Mule charset from the language environment."
598   (or
599    mail-parse-mule-charset ;; cached mule-charset
600    (progn
601      (setq mail-parse-mule-charset
602            (and (boundp 'current-language-environment)
603                 (car (last
604                       (assq 'charset
605                             (assoc current-language-environment
606                                    language-info-alist))))))
607      (if (or (not mail-parse-mule-charset)
608              (eq mail-parse-mule-charset 'ascii))
609          (setq mail-parse-mule-charset
610                (or (car (last (assq mail-parse-charset
611                                     mm-mime-mule-charset-alist)))
612                    ;; default
613                    'latin-iso8859-1)))
614      mail-parse-mule-charset)))
615
616 (defun mm-charset-after (&optional pos)
617   "Return charset of a character in current buffer at position POS.
618 If POS is nil, it defauls to the current point.
619 If POS is out of range, the value is nil.
620 If the charset is `composition', return the actual one."
621   (let ((char (char-after pos)) charset)
622     (if (< (mm-char-int char) 128)
623         (setq charset 'ascii)
624       ;; charset-after is fake in some Emacsen.
625       (setq charset (and (fboundp 'char-charset) (char-charset char)))
626       (if (eq charset 'composition)     ; Mule 4
627           (let ((p (or pos (point))))
628             (cadr (find-charset-region p (1+ p))))
629         (if (and charset (not (memq charset '(ascii eight-bit-control
630                                                     eight-bit-graphic))))
631             charset
632           (mm-guess-charset))))))
633
634 (defun mm-mime-charset (charset)
635   "Return the MIME charset corresponding to the given Mule CHARSET."
636   (if (eq charset 'unknown)
637       (error "The message contains non-printable characters, please use attachment"))
638   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
639       ;; This exists in Emacs 20.
640       (or
641        (and (mm-preferred-coding-system charset)
642             (or (coding-system-get
643                  (mm-preferred-coding-system charset) :mime-charset)
644                 (coding-system-get
645                  (mm-preferred-coding-system charset) 'mime-charset)))
646        (and (eq charset 'ascii)
647             'us-ascii)
648        (mm-preferred-coding-system charset)
649        (mm-mule-charset-to-mime-charset charset))
650     ;; This is for XEmacs.
651     (mm-mule-charset-to-mime-charset charset)))
652
653 (if (fboundp 'delete-dups)
654     (defalias 'mm-delete-duplicates 'delete-dups)
655   (defun mm-delete-duplicates (list)
656     "Destructively remove `equal' duplicates from LIST.
657 Store the result in LIST and return it.  LIST must be a proper list.
658 Of several `equal' occurrences of an element in LIST, the first
659 one is kept.
660
661 This is a compatibility function for Emacsen without `delete-dups'."
662     ;; Code from `subr.el' in Emacs 22:
663     (let ((tail list))
664       (while tail
665         (setcdr tail (delete (car tail) (cdr tail)))
666         (setq tail (cdr tail))))
667     list))
668
669 ;; Fixme:  This is used in places when it should be testing the
670 ;; default multibyteness.  See mm-default-multibyte-p.
671 (eval-and-compile
672   (if (and (not (featurep 'xemacs))
673            (boundp 'enable-multibyte-characters))
674       (defun mm-multibyte-p ()
675         "Non-nil if multibyte is enabled in the current buffer."
676         enable-multibyte-characters)
677     (defun mm-multibyte-p () (featurep 'mule))))
678
679 (defun mm-default-multibyte-p ()
680   "Return non-nil if the session is multibyte.
681 This affects whether coding conversion should be attempted generally."
682   (if (featurep 'mule)
683       (if (boundp 'default-enable-multibyte-characters)
684           default-enable-multibyte-characters
685         t)))
686
687 (defun mm-iso-8859-x-to-15-region (&optional b e)
688   (if (fboundp 'char-charset)
689       (let (charset item c inconvertible)
690         (save-restriction
691           (if e (narrow-to-region b e))
692           (goto-char (point-min))
693           (skip-chars-forward "\0-\177")
694           (while (not (eobp))
695             (cond
696              ((not (setq item (assq (char-charset (setq c (char-after)))
697                                     mm-iso-8859-x-to-15-table)))
698               (forward-char))
699              ((memq c (cdr (cdr item)))
700               (setq inconvertible t)
701               (forward-char))
702              (t
703               (insert-before-markers (prog1 (+ c (car (cdr item)))
704                                        (delete-char 1)))))
705             (skip-chars-forward "\0-\177")))
706         (not inconvertible))))
707
708 (defun mm-sort-coding-systems-predicate (a b)
709   (let ((priorities
710          (mapcar (lambda (cs)
711                    ;; Note: invalid entries are dropped silently
712                    (and (setq cs (mm-coding-system-p cs))
713                         (coding-system-base cs)))
714                  mm-coding-system-priorities)))
715     (and (setq a (mm-coding-system-p a))
716          (if (setq b (mm-coding-system-p b))
717              (> (length (memq (coding-system-base a) priorities))
718                 (length (memq (coding-system-base b) priorities)))
719            t))))
720
721 (eval-when-compile
722   (autoload 'latin-unity-massage-name "latin-unity")
723   (autoload 'latin-unity-maybe-remap "latin-unity")
724   (autoload 'latin-unity-representations-feasible-region "latin-unity")
725   (autoload 'latin-unity-representations-present-region "latin-unity")
726   (defvar latin-unity-coding-systems)
727   (defvar latin-unity-ucs-list))
728
729 (defun mm-xemacs-find-mime-charset-1 (begin end)
730   "Determine which MIME charset to use to send region as message.
731 This uses the XEmacs-specific latin-unity package to better handle the
732 case where identical characters from diverse ISO-8859-? character sets
733 can be encoded using a single one of the corresponding coding systems.
734
735 It treats `mm-coding-system-priorities' as the list of preferred
736 coding systems; a useful example setting for this list in Western
737 Europe would be '(iso-8859-1 iso-8859-15 utf-8), which would default
738 to the very standard Latin 1 coding system, and only move to coding
739 systems that are less supported as is necessary to encode the
740 characters that exist in the buffer.
741
742 Latin Unity doesn't know about those non-ASCII Roman characters that
743 are available in various East Asian character sets.  As such, its
744 behavior if you have a JIS 0212 LATIN SMALL LETTER A WITH ACUTE in a
745 buffer and it can otherwise be encoded as Latin 1, won't be ideal.
746 But this is very much a corner case, so don't worry about it."
747   (let ((systems mm-coding-system-priorities) csets psets curset)
748
749     ;; Load the Latin Unity library, if available.
750     (when (and (not (featurep 'latin-unity)) (locate-library "latin-unity"))
751       (require 'latin-unity))
752
753     ;; Now, can we use it?
754     (if (featurep 'latin-unity)
755         (progn
756           (setq csets (latin-unity-representations-feasible-region begin end)
757                 psets (latin-unity-representations-present-region begin end))
758
759           (catch 'done
760
761             ;; Pass back the first coding system in the preferred list
762             ;; that can encode the whole region.
763             (dolist (curset systems)
764               (setq curset (latin-unity-massage-name 'buffer-default curset))
765
766               ;; If the coding system is a universal coding system, then
767               ;; it can certainly encode all the characters in the region.
768               (if (memq curset latin-unity-ucs-list)
769                   (throw 'done (list curset)))
770
771               ;; If a coding system isn't universal, and isn't in
772               ;; the list that latin unity knows about, we can't
773               ;; decide whether to use it here. Leave that until later
774               ;; in `mm-find-mime-charset-region' function, whence we
775               ;; have been called.
776               (unless (memq curset latin-unity-coding-systems)
777                 (throw 'done nil))
778
779               ;; Right, we know about this coding system, and it may
780               ;; conceivably be able to encode all the characters in
781               ;; the region.
782               (if (latin-unity-maybe-remap begin end curset csets psets t)
783                   (throw 'done (list curset))))
784
785             ;; Can't encode using anything from the
786             ;; `mm-coding-system-priorities' list.
787             ;; Leave `mm-find-mime-charset' to do most of the work.
788             nil))
789
790       ;; Right, latin unity isn't available; let `mm-find-charset-region'
791       ;; take its default action, which equally applies to GNU Emacs.
792       nil)))
793
794 (defmacro mm-xemacs-find-mime-charset (begin end)
795   (when (featurep 'xemacs)
796     `(and (featurep 'mule) (mm-xemacs-find-mime-charset-1 ,begin ,end))))
797
798 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
799   "Return the MIME charsets needed to encode the region between B and E.
800 nil means ASCII, a single-element list represents an appropriate MIME
801 charset, and a longer list means no appropriate charset."
802   (let (charsets)
803     ;; The return possibilities of this function are a mess...
804     (or (and (mm-multibyte-p)
805              mm-use-find-coding-systems-region
806              ;; Find the mime-charset of the most preferred coding
807              ;; system that has one.
808              (let ((systems (find-coding-systems-region b e)))
809                (when mm-coding-system-priorities
810                  (setq systems
811                        (sort systems 'mm-sort-coding-systems-predicate)))
812                (setq systems (delq 'compound-text systems))
813                (unless (equal systems '(undecided))
814                  (while systems
815                    (let* ((head (pop systems))
816                           (cs (or (coding-system-get head :mime-charset)
817                                   (coding-system-get head 'mime-charset))))
818                      ;; The mime-charset (`x-ctext') of
819                      ;; `compound-text' is not in the IANA list.  We
820                      ;; shouldn't normally use anything here with a
821                      ;; mime-charset having an `x-' prefix.
822                      ;; Fixme:  Allow this to be overridden, since
823                      ;; there is existing use of x-ctext.
824                      ;; Also people apparently need the coding system
825                      ;; `iso-2022-jp-3' (which Mule-UCS defines with
826                      ;; mime-charset, though it's not valid).
827                      (if (and cs
828                               (not (string-match "^[Xx]-" (symbol-name cs)))
829                               ;; UTF-16 of any variety is invalid for
830                               ;; text parts and, unfortunately, has
831                               ;; mime-charset defined both in Mule-UCS
832                               ;; and versions of Emacs.  (The name
833                               ;; might be `mule-utf-16...'  or
834                               ;; `utf-16...'.)
835                               (not (string-match "utf-16" (symbol-name cs))))
836                          (setq systems nil
837                                charsets (list cs))))))
838                charsets))
839         ;; If we're XEmacs, and some coding system is appropriate,
840         ;; mm-xemacs-find-mime-charset will return an appropriate list.
841         ;; Otherwise, we'll get nil, and the next setq will get invoked.
842         (setq charsets (mm-xemacs-find-mime-charset b e))
843
844         ;; We're not multibyte, or a single coding system won't cover it.
845         (setq charsets
846               (mm-delete-duplicates
847                (mapcar 'mm-mime-charset
848                        (delq 'ascii
849                              (mm-find-charset-region b e))))))
850     (if (and (> (length charsets) 1)
851              (memq 'iso-8859-15 charsets)
852              (memq 'iso-8859-15 hack-charsets)
853              (save-excursion (mm-iso-8859-x-to-15-region b e)))
854         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
855                 mm-iso-8859-15-compatible))
856     (if (and (memq 'iso-2022-jp-2 charsets)
857              (memq 'iso-2022-jp-2 hack-charsets))
858         (setq charsets (delq 'iso-2022-jp charsets)))
859     ;; Attempt to reduce the number of charsets if utf-8 is available.
860     (if (and (featurep 'xemacs)
861              (> (length charsets) 1)
862              (mm-coding-system-p 'utf-8))
863         (let ((mm-coding-system-priorities
864                (cons 'utf-8 mm-coding-system-priorities)))
865           (setq charsets
866                 (mm-delete-duplicates
867                  (mapcar 'mm-mime-charset
868                          (delq 'ascii
869                                (mm-find-charset-region b e)))))))
870     charsets))
871
872 (defmacro mm-with-unibyte-buffer (&rest forms)
873   "Create a temporary buffer, and evaluate FORMS there like `progn'.
874 Use unibyte mode for this."
875   `(let (default-enable-multibyte-characters)
876      (with-temp-buffer ,@forms)))
877 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
878 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
879
880 (defmacro mm-with-multibyte-buffer (&rest forms)
881   "Create a temporary buffer, and evaluate FORMS there like `progn'.
882 Use multibyte mode for this."
883   `(let ((default-enable-multibyte-characters t))
884      (with-temp-buffer ,@forms)))
885 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
886 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
887
888 (defmacro mm-with-unibyte-current-buffer (&rest forms)
889   "Evaluate FORMS with current buffer temporarily made unibyte.
890 Also bind `default-enable-multibyte-characters' to nil.
891 Equivalent to `progn' in XEmacs"
892   (let ((multibyte (make-symbol "multibyte"))
893         (buffer (make-symbol "buffer")))
894     `(if mm-emacs-mule
895          (let ((,multibyte enable-multibyte-characters)
896                (,buffer (current-buffer)))
897            (unwind-protect
898                (let (default-enable-multibyte-characters)
899                  (set-buffer-multibyte nil)
900                  ,@forms)
901              (set-buffer ,buffer)
902              (set-buffer-multibyte ,multibyte)))
903        (let (default-enable-multibyte-characters)
904          ,@forms))))
905 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
906 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
907
908 (defmacro mm-with-unibyte (&rest forms)
909   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
910   `(let (default-enable-multibyte-characters)
911      ,@forms))
912 (put 'mm-with-unibyte 'lisp-indent-function 0)
913 (put 'mm-with-unibyte 'edebug-form-spec '(body))
914
915 (defmacro mm-with-multibyte (&rest forms)
916   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
917   `(let ((default-enable-multibyte-characters t))
918      ,@forms))
919 (put 'mm-with-multibyte 'lisp-indent-function 0)
920 (put 'mm-with-multibyte 'edebug-form-spec '(body))
921
922 (defun mm-find-charset-region (b e)
923   "Return a list of Emacs charsets in the region B to E."
924   (cond
925    ((and (mm-multibyte-p)
926          (fboundp 'find-charset-region))
927     ;; Remove composition since the base charsets have been included.
928     ;; Remove eight-bit-*, treat them as ascii.
929     (let ((css (find-charset-region b e)))
930       (mapcar (lambda (cs) (setq css (delq cs css)))
931               '(composition eight-bit-control eight-bit-graphic
932                             control-1))
933       css))
934    (t
935     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
936     (save-excursion
937       (save-restriction
938         (narrow-to-region b e)
939         (goto-char (point-min))
940         (skip-chars-forward "\0-\177")
941         (if (eobp)
942             '(ascii)
943           (let (charset)
944             (setq charset
945                   (and (boundp 'current-language-environment)
946                        (car (last (assq 'charset
947                                         (assoc current-language-environment
948                                                language-info-alist))))))
949             (if (eq charset 'ascii) (setq charset nil))
950             (or charset
951                 (setq charset
952                       (car (last (assq mail-parse-charset
953                                        mm-mime-mule-charset-alist)))))
954             (list 'ascii (or charset 'latin-iso8859-1)))))))))
955
956 (defun mm-auto-mode-alist ()
957   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
958   (let ((alist auto-mode-alist)
959         out)
960     (while alist
961       (when (listp (cdar alist))
962         (push (car alist) out))
963       (pop alist))
964     (nreverse out)))
965
966 (defvar mm-inhibit-file-name-handlers
967   '(jka-compr-handler image-file-handler)
968   "A list of handlers doing (un)compression (etc) thingies.")
969
970 (defun mm-insert-file-contents (filename &optional visit beg end replace
971                                          inhibit)
972   "Like `insert-file-contents', but only reads in the file.
973 A buffer may be modified in several ways after reading into the buffer due
974 to advanced Emacs features, such as file-name-handlers, format decoding,
975 `find-file-hooks', etc.
976 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
977   This function ensures that none of these modifications will take place."
978   (let* ((format-alist nil)
979          (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
980          (default-major-mode 'fundamental-mode)
981          (enable-local-variables nil)
982          (after-insert-file-functions nil)
983          (enable-local-eval nil)
984          (inhibit-file-name-operation (if inhibit
985                                           'insert-file-contents
986                                         inhibit-file-name-operation))
987          (inhibit-file-name-handlers
988           (if inhibit
989               (append mm-inhibit-file-name-handlers
990                       inhibit-file-name-handlers)
991             inhibit-file-name-handlers))
992          (ffh (if (boundp 'find-file-hook)
993                   'find-file-hook
994                 'find-file-hooks))
995          (val (symbol-value ffh)))
996     (set ffh nil)
997     (unwind-protect
998         (insert-file-contents filename visit beg end replace)
999       (set ffh val))))
1000
1001 (defun mm-append-to-file (start end filename &optional codesys inhibit)
1002   "Append the contents of the region to the end of file FILENAME.
1003 When called from a function, expects three arguments,
1004 START, END and FILENAME.  START and END are buffer positions
1005 saying what text to write.
1006 Optional fourth argument specifies the coding system to use when
1007 encoding the file.
1008 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1009   (let ((coding-system-for-write
1010          (or codesys mm-text-coding-system-for-write
1011              mm-text-coding-system))
1012         (inhibit-file-name-operation (if inhibit
1013                                          'append-to-file
1014                                        inhibit-file-name-operation))
1015         (inhibit-file-name-handlers
1016          (if inhibit
1017              (append mm-inhibit-file-name-handlers
1018                      inhibit-file-name-handlers)
1019            inhibit-file-name-handlers)))
1020     (write-region start end filename t 'no-message)
1021     (message "Appended to %s" filename)))
1022
1023 (defun mm-write-region (start end filename &optional append visit lockname
1024                               coding-system inhibit)
1025
1026   "Like `write-region'.
1027 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1028   (let ((coding-system-for-write
1029          (or coding-system mm-text-coding-system-for-write
1030              mm-text-coding-system))
1031         (inhibit-file-name-operation (if inhibit
1032                                          'write-region
1033                                        inhibit-file-name-operation))
1034         (inhibit-file-name-handlers
1035          (if inhibit
1036              (append mm-inhibit-file-name-handlers
1037                      inhibit-file-name-handlers)
1038            inhibit-file-name-handlers)))
1039     (write-region start end filename append visit lockname)))
1040
1041 (defun mm-image-load-path (&optional package)
1042   (let (dir result)
1043     (dolist (path load-path (nreverse result))
1044       (when (and path
1045                  (file-directory-p
1046                   (setq dir (concat (file-name-directory
1047                                      (directory-file-name path))
1048                                     "etc/images/" (or package "gnus/")))))
1049         (push dir result))
1050       (push path result))))
1051
1052 ;; Fixme: This doesn't look useful where it's used.
1053 (if (fboundp 'detect-coding-region)
1054     (defun mm-detect-coding-region (start end)
1055       "Like `detect-coding-region' except returning the best one."
1056       (let ((coding-systems
1057              (detect-coding-region start end)))
1058         (or (car-safe coding-systems)
1059             coding-systems)))
1060   (defun mm-detect-coding-region (start end)
1061     (let ((point (point)))
1062       (goto-char start)
1063       (skip-chars-forward "\0-\177" end)
1064       (prog1
1065           (if (eq (point) end) 'ascii (mm-guess-charset))
1066         (goto-char point)))))
1067
1068 (if (fboundp 'coding-system-get)
1069     (defun mm-detect-mime-charset-region (start end)
1070       "Detect MIME charset of the text in the region between START and END."
1071       (let ((cs (mm-detect-coding-region start end)))
1072         (or (coding-system-get cs :mime-charset)
1073             (coding-system-get cs 'mime-charset))))
1074   (defun mm-detect-mime-charset-region (start end)
1075     "Detect MIME charset of the text in the region between START and END."
1076     (let ((cs (mm-detect-coding-region start end)))
1077       cs)))
1078
1079 (eval-when-compile
1080   (unless (fboundp 'coding-system-to-mime-charset)
1081     (defalias 'coding-system-to-mime-charset 'ignore)))
1082
1083 (defun mm-coding-system-to-mime-charset (coding-system)
1084   "Return the MIME charset corresponding to CODING-SYSTEM.
1085 To make this function work with XEmacs, the APEL package is required."
1086   (when coding-system
1087     (or (and (fboundp 'coding-system-get)
1088              (or (coding-system-get coding-system :mime-charset)
1089                  (coding-system-get coding-system 'mime-charset)))
1090         (and (featurep 'xemacs)
1091              (or (and (fboundp 'coding-system-to-mime-charset)
1092                       (not (eq (symbol-function 'coding-system-to-mime-charset)
1093                                'ignore)))
1094                  (and (condition-case nil
1095                           (require 'mcharset)
1096                         (error nil))
1097                       (fboundp 'coding-system-to-mime-charset)))
1098              (coding-system-to-mime-charset coding-system)))))
1099
1100 (eval-when-compile
1101   (require 'jka-compr))
1102
1103 (defun mm-decompress-buffer (filename &optional inplace force)
1104   "Decompress buffer's contents, depending on jka-compr.
1105 Only when FORCE is t or `auto-compression-mode' is enabled and FILENAME
1106 agrees with `jka-compr-compression-info-list', decompression is done.
1107 Signal an error if FORCE is neither nil nor t and compressed data are
1108 not decompressed because `auto-compression-mode' is disabled.
1109 If INPLACE is nil, return decompressed data or nil without modifying
1110 the buffer.  Otherwise, replace the buffer's contents with the
1111 decompressed data.  The buffer's multibyteness must be turned off."
1112   (when (and filename
1113              (if force
1114                  (prog1 t (require 'jka-compr))
1115                (and (fboundp 'jka-compr-installed-p)
1116                     (jka-compr-installed-p))))
1117     (let ((info (jka-compr-get-compression-info filename)))
1118       (when info
1119         (unless (or (memq force (list nil t))
1120                     (jka-compr-installed-p))
1121           (error ""))
1122         (let ((prog (jka-compr-info-uncompress-program info))
1123               (args (jka-compr-info-uncompress-args info))
1124               (msg (format "%s %s..."
1125                            (jka-compr-info-uncompress-message info)
1126                            filename))
1127               (err-file (jka-compr-make-temp-name))
1128               (cur (current-buffer))
1129               (coding-system-for-read mm-binary-coding-system)
1130               (coding-system-for-write mm-binary-coding-system)
1131               retval err-msg)
1132           (message "%s" msg)
1133           (with-temp-buffer
1134             (insert-buffer-substring cur)
1135             (condition-case err
1136                 (progn
1137                   (unless (memq (apply 'call-process-region
1138                                        (point-min) (point-max)
1139                                        prog t (list t err-file) nil args)
1140                                 jka-compr-acceptable-retval-list)
1141                     (erase-buffer)
1142                     (insert (mapconcat
1143                              'identity
1144                              (delete "" (split-string
1145                                          (prog2
1146                                              (insert-file-contents err-file)
1147                                              (buffer-string)
1148                                            (erase-buffer))))
1149                              " ")
1150                             "\n")
1151                     (setq err-msg
1152                           (format "Error while executing \"%s %s < %s\""
1153                                   prog (mapconcat 'identity args " ")
1154                                   filename)))
1155                   (setq retval (buffer-string)))
1156               (error
1157                (setq err-msg (error-message-string err)))))
1158           (when (file-exists-p err-file)
1159             (ignore-errors (jka-compr-delete-temp-file err-file)))
1160           (when inplace
1161             (unless err-msg
1162               (delete-region (point-min) (point-max))
1163               (insert retval))
1164             (setq retval nil))
1165           (message "%s" (or err-msg (concat msg "done")))
1166           retval)))))
1167
1168 (eval-when-compile
1169   (unless (fboundp 'coding-system-name)
1170     (defalias 'coding-system-name 'ignore))
1171   (unless (fboundp 'find-file-coding-system-for-read-from-filename)
1172     (defalias 'find-file-coding-system-for-read-from-filename 'ignore))
1173   (unless (fboundp 'find-operation-coding-system)
1174     (defalias 'find-operation-coding-system 'ignore)))
1175
1176 (defun mm-find-buffer-file-coding-system (&optional filename)
1177   "Find coding system used to decode the contents of the current buffer.
1178 This function looks for the coding system magic cookie or examines the
1179 coding system specified by `file-coding-system-alist' being associated
1180 with FILENAME which defaults to `buffer-file-name'.  Data compressed by
1181 gzip, bzip2, etc. are allowed."
1182   (unless filename
1183     (setq filename buffer-file-name))
1184   (save-excursion
1185     (let ((decomp (unless ;; No worth to examine charset of tar files.
1186                       (and filename
1187                            (string-match
1188                             "\\.\\(?:tar\\.[^.]+\\|tbz\\|tgz\\)\\'"
1189                             filename))
1190                     (mm-decompress-buffer filename nil t))))
1191       (when decomp
1192         (set-buffer (let (default-enable-multibyte-characters)
1193                       (generate-new-buffer " *temp*")))
1194         (insert decomp)
1195         (setq filename (file-name-sans-extension filename)))
1196       (goto-char (point-min))
1197       (prog1
1198           (cond
1199            ((boundp 'set-auto-coding-function) ;; Emacs
1200             (if filename
1201                 (or (funcall (symbol-value 'set-auto-coding-function)
1202                              filename (- (point-max) (point-min)))
1203                     (car (find-operation-coding-system 'insert-file-contents
1204                                                        filename)))
1205               (let (auto-coding-alist)
1206                 (condition-case nil
1207                     (funcall (symbol-value 'set-auto-coding-function)
1208                              nil (- (point-max) (point-min)))
1209                   (error nil)))))
1210            ((featurep 'file-coding) ;; XEmacs
1211             (let ((case-fold-search t)
1212                   (end (point-at-eol))
1213                   codesys start)
1214               (or
1215                (and (re-search-forward "-\\*-+[\t ]*" end t)
1216                     (progn
1217                       (setq start (match-end 0))
1218                       (re-search-forward "[\t ]*-+\\*-" end t))
1219                     (progn
1220                       (setq end (match-beginning 0))
1221                       (goto-char start)
1222                       (or (looking-at "coding:[\t ]*\\([^\t ;]+\\)")
1223                           (re-search-forward
1224                            "[\t ;]+coding:[\t ]*\\([^\t ;]+\\)"
1225                            end t)))
1226                     (find-coding-system (setq codesys
1227                                               (intern (match-string 1))))
1228                     codesys)
1229                (and (re-search-forward "^[\t ]*;+[\t ]*Local[\t ]+Variables:"
1230                                        nil t)
1231                     (progn
1232                       (setq start (match-end 0))
1233                       (re-search-forward "^[\t ]*;+[\t ]*End:" nil t))
1234                     (progn
1235                       (setq end (match-beginning 0))
1236                       (goto-char start)
1237                       (re-search-forward
1238                        "^[\t ]*;+[\t ]*coding:[\t ]*\\([^\t\n\r ]+\\)"
1239                        end t))
1240                     (find-coding-system (setq codesys
1241                                               (intern (match-string 1))))
1242                     codesys)
1243                (and (progn
1244                       (goto-char (point-min))
1245                       (setq case-fold-search nil)
1246                       (re-search-forward "^;;;coding system: "
1247                                          ;;(+ (point-min) 3000) t))
1248                                          nil t))
1249                     (looking-at "[^\t\n\r ]+")
1250                     (find-coding-system
1251                      (setq codesys (intern (match-string 0))))
1252                     codesys)
1253                (and filename
1254                     (setq codesys
1255                           (find-file-coding-system-for-read-from-filename
1256                            filename))
1257                     (coding-system-name (coding-system-base codesys)))))))
1258         (when decomp
1259           (kill-buffer (current-buffer)))))))
1260
1261 (provide 'mm-util)
1262
1263 ;; arch-tag: 94dc5388-825d-4fd1-bfa5-2100aa351238
1264 ;;; mm-util.el ends here