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