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