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