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