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