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