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