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