(mm-with-unibyte-current-buffer): Add note.
[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 Emacs 23."
903   (let ((multibyte (make-symbol "multibyte"))
904         (buffer (make-symbol "buffer")))
905     `(if mm-emacs-mule
906          (let ((,multibyte enable-multibyte-characters)
907                (,buffer (current-buffer)))
908            (unwind-protect
909                (let (default-enable-multibyte-characters)
910                  (set-buffer-multibyte nil)
911                  ,@forms)
912              (set-buffer ,buffer)
913              (set-buffer-multibyte ,multibyte)))
914        (let (default-enable-multibyte-characters)
915          ,@forms))))
916 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
917 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
918
919 (defmacro mm-with-unibyte (&rest forms)
920   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
921   `(let (default-enable-multibyte-characters)
922      ,@forms))
923 (put 'mm-with-unibyte 'lisp-indent-function 0)
924 (put 'mm-with-unibyte 'edebug-form-spec '(body))
925
926 (defmacro mm-with-multibyte (&rest forms)
927   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
928   `(let ((default-enable-multibyte-characters t))
929      ,@forms))
930 (put 'mm-with-multibyte 'lisp-indent-function 0)
931 (put 'mm-with-multibyte 'edebug-form-spec '(body))
932
933 (defun mm-find-charset-region (b e)
934   "Return a list of Emacs charsets in the region B to E."
935   (cond
936    ((and (mm-multibyte-p)
937          (fboundp 'find-charset-region))
938     ;; Remove composition since the base charsets have been included.
939     ;; Remove eight-bit-*, treat them as ascii.
940     (let ((css (find-charset-region b e)))
941       (mapcar (lambda (cs) (setq css (delq cs css)))
942               '(composition eight-bit-control eight-bit-graphic
943                             control-1))
944       css))
945    (t
946     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
947     (save-excursion
948       (save-restriction
949         (narrow-to-region b e)
950         (goto-char (point-min))
951         (skip-chars-forward "\0-\177")
952         (if (eobp)
953             '(ascii)
954           (let (charset)
955             (setq charset
956                   (and (boundp 'current-language-environment)
957                        (car (last (assq 'charset
958                                         (assoc current-language-environment
959                                                language-info-alist))))))
960             (if (eq charset 'ascii) (setq charset nil))
961             (or charset
962                 (setq charset
963                       (car (last (assq mail-parse-charset
964                                        mm-mime-mule-charset-alist)))))
965             (list 'ascii (or charset 'latin-iso8859-1)))))))))
966
967 (defun mm-auto-mode-alist ()
968   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
969   (let ((alist auto-mode-alist)
970         out)
971     (while alist
972       (when (listp (cdar alist))
973         (push (car alist) out))
974       (pop alist))
975     (nreverse out)))
976
977 (defvar mm-inhibit-file-name-handlers
978   '(jka-compr-handler image-file-handler)
979   "A list of handlers doing (un)compression (etc) thingies.")
980
981 (defun mm-insert-file-contents (filename &optional visit beg end replace
982                                          inhibit)
983   "Like `insert-file-contents', but only reads in the file.
984 A buffer may be modified in several ways after reading into the buffer due
985 to advanced Emacs features, such as file-name-handlers, format decoding,
986 `find-file-hooks', etc.
987 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
988   This function ensures that none of these modifications will take place."
989   (let* ((format-alist nil)
990          (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
991          (default-major-mode 'fundamental-mode)
992          (enable-local-variables nil)
993          (after-insert-file-functions nil)
994          (enable-local-eval nil)
995          (inhibit-file-name-operation (if inhibit
996                                           'insert-file-contents
997                                         inhibit-file-name-operation))
998          (inhibit-file-name-handlers
999           (if inhibit
1000               (append mm-inhibit-file-name-handlers
1001                       inhibit-file-name-handlers)
1002             inhibit-file-name-handlers))
1003          (ffh (if (boundp 'find-file-hook)
1004                   'find-file-hook
1005                 'find-file-hooks))
1006          (val (symbol-value ffh)))
1007     (set ffh nil)
1008     (unwind-protect
1009         (insert-file-contents filename visit beg end replace)
1010       (set ffh val))))
1011
1012 (defun mm-append-to-file (start end filename &optional codesys inhibit)
1013   "Append the contents of the region to the end of file FILENAME.
1014 When called from a function, expects three arguments,
1015 START, END and FILENAME.  START and END are buffer positions
1016 saying what text to write.
1017 Optional fourth argument specifies the coding system to use when
1018 encoding the file.
1019 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1020   (let ((coding-system-for-write
1021          (or codesys mm-text-coding-system-for-write
1022              mm-text-coding-system))
1023         (inhibit-file-name-operation (if inhibit
1024                                          'append-to-file
1025                                        inhibit-file-name-operation))
1026         (inhibit-file-name-handlers
1027          (if inhibit
1028              (append mm-inhibit-file-name-handlers
1029                      inhibit-file-name-handlers)
1030            inhibit-file-name-handlers)))
1031     (write-region start end filename t 'no-message)
1032     (message "Appended to %s" filename)))
1033
1034 (defun mm-write-region (start end filename &optional append visit lockname
1035                               coding-system inhibit)
1036
1037   "Like `write-region'.
1038 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1039   (let ((coding-system-for-write
1040          (or coding-system mm-text-coding-system-for-write
1041              mm-text-coding-system))
1042         (inhibit-file-name-operation (if inhibit
1043                                          'write-region
1044                                        inhibit-file-name-operation))
1045         (inhibit-file-name-handlers
1046          (if inhibit
1047              (append mm-inhibit-file-name-handlers
1048                      inhibit-file-name-handlers)
1049            inhibit-file-name-handlers)))
1050     (write-region start end filename append visit lockname)))
1051
1052 ;; It is not a MIME function, but some MIME functions use it.
1053 (if (and (fboundp 'make-temp-file)
1054          (ignore-errors
1055            (let ((def (symbol-function 'make-temp-file)))
1056              (and (byte-code-function-p def)
1057                   (setq def (if (fboundp 'compiled-function-arglist)
1058                                 ;; XEmacs
1059                                 (eval (list 'compiled-function-arglist def))
1060                               (aref def 0)))
1061                   (>= (length def) 4)
1062                   (eq (nth 3 def) 'suffix)))))
1063     (defalias 'mm-make-temp-file 'make-temp-file)
1064   ;; Stolen (and modified for XEmacs) from Emacs 22.
1065   (defun mm-make-temp-file (prefix &optional dir-flag suffix)
1066     "Create a temporary file.
1067 The returned file name (created by appending some random characters at the end
1068 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1069 is guaranteed to point to a newly created empty file.
1070 You can then use `write-region' to write new data into the file.
1071
1072 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1073
1074 If SUFFIX is non-nil, add that at the end of the file name."
1075     (let ((umask (default-file-modes))
1076           file)
1077       (unwind-protect
1078           (progn
1079             ;; Create temp files with strict access rights.  It's easy to
1080             ;; loosen them later, whereas it's impossible to close the
1081             ;; time-window of loose permissions otherwise.
1082             (set-default-file-modes 448)
1083             (while (condition-case err
1084                        (progn
1085                          (setq file
1086                                (make-temp-name
1087                                 (expand-file-name
1088                                  prefix
1089                                  (if (fboundp 'temp-directory)
1090                                      ;; XEmacs
1091                                      (temp-directory)
1092                                    temporary-file-directory))))
1093                          (if suffix
1094                              (setq file (concat file suffix)))
1095                          (if dir-flag
1096                              (make-directory file)
1097                            (if (featurep 'xemacs)
1098                                ;; NOTE: This is unsafe if XEmacs users
1099                                ;; don't use a secure temp directory.
1100                                (if (file-exists-p file)
1101                                    (signal 'file-already-exists
1102                                            (list "File exists" file))
1103                                  (write-region "" nil file nil 'silent))
1104                              (write-region "" nil file nil 'silent
1105                                            nil 'excl)))
1106                          nil)
1107                      (file-already-exists t)
1108                      ;; The XEmacs version of `make-directory' issues
1109                      ;; `file-error'.
1110                      (file-error (or (and (featurep 'xemacs)
1111                                           (file-exists-p file))
1112                                      (signal (car err) (cdr err)))))
1113               ;; the file was somehow created by someone else between
1114               ;; `make-temp-name' and `write-region', let's try again.
1115               nil)
1116             file)
1117         ;; Reset the umask.
1118         (set-default-file-modes umask)))))
1119
1120 (defun mm-image-load-path (&optional package)
1121   (let (dir result)
1122     (dolist (path load-path (nreverse result))
1123       (when (and path
1124                  (file-directory-p
1125                   (setq dir (concat (file-name-directory
1126                                      (directory-file-name path))
1127                                     "etc/images/" (or package "gnus/")))))
1128         (push dir result))
1129       (push path result))))
1130
1131 ;; Fixme: This doesn't look useful where it's used.
1132 (if (fboundp 'detect-coding-region)
1133     (defun mm-detect-coding-region (start end)
1134       "Like `detect-coding-region' except returning the best one."
1135       (let ((coding-systems
1136              (detect-coding-region start end)))
1137         (or (car-safe coding-systems)
1138             coding-systems)))
1139   (defun mm-detect-coding-region (start end)
1140     (let ((point (point)))
1141       (goto-char start)
1142       (skip-chars-forward "\0-\177" end)
1143       (prog1
1144           (if (eq (point) end) 'ascii (mm-guess-charset))
1145         (goto-char point)))))
1146
1147 (if (fboundp 'coding-system-get)
1148     (defun mm-detect-mime-charset-region (start end)
1149       "Detect MIME charset of the text in the region between START and END."
1150       (let ((cs (mm-detect-coding-region start end)))
1151         (or (coding-system-get cs :mime-charset)
1152             (coding-system-get cs 'mime-charset))))
1153   (defun mm-detect-mime-charset-region (start end)
1154     "Detect MIME charset of the text in the region between START and END."
1155     (let ((cs (mm-detect-coding-region start end)))
1156       cs)))
1157
1158 (eval-when-compile
1159   (unless (fboundp 'coding-system-to-mime-charset)
1160     (defalias 'coding-system-to-mime-charset 'ignore)))
1161
1162 (defun mm-coding-system-to-mime-charset (coding-system)
1163   "Return the MIME charset corresponding to CODING-SYSTEM.
1164 To make this function work with XEmacs, the APEL package is required."
1165   (when coding-system
1166     (or (and (fboundp 'coding-system-get)
1167              (or (coding-system-get coding-system :mime-charset)
1168                  (coding-system-get coding-system 'mime-charset)))
1169         (and (featurep 'xemacs)
1170              (or (and (fboundp 'coding-system-to-mime-charset)
1171                       (not (eq (symbol-function 'coding-system-to-mime-charset)
1172                                'ignore)))
1173                  (and (condition-case nil
1174                           (require 'mcharset)
1175                         (error nil))
1176                       (fboundp 'coding-system-to-mime-charset)))
1177              (coding-system-to-mime-charset coding-system)))))
1178
1179 (eval-when-compile
1180   (require 'jka-compr))
1181
1182 (defun mm-decompress-buffer (filename &optional inplace force)
1183   "Decompress buffer's contents, depending on jka-compr.
1184 Only when FORCE is t or `auto-compression-mode' is enabled and FILENAME
1185 agrees with `jka-compr-compression-info-list', decompression is done.
1186 Signal an error if FORCE is neither nil nor t and compressed data are
1187 not decompressed because `auto-compression-mode' is disabled.
1188 If INPLACE is nil, return decompressed data or nil without modifying
1189 the buffer.  Otherwise, replace the buffer's contents with the
1190 decompressed data.  The buffer's multibyteness must be turned off."
1191   (when (and filename
1192              (if force
1193                  (prog1 t (require 'jka-compr))
1194                (and (fboundp 'jka-compr-installed-p)
1195                     (jka-compr-installed-p))))
1196     (let ((info (jka-compr-get-compression-info filename)))
1197       (when info
1198         (unless (or (memq force (list nil t))
1199                     (jka-compr-installed-p))
1200           (error ""))
1201         (let ((prog (jka-compr-info-uncompress-program info))
1202               (args (jka-compr-info-uncompress-args info))
1203               (msg (format "%s %s..."
1204                            (jka-compr-info-uncompress-message info)
1205                            filename))
1206               (err-file (jka-compr-make-temp-name))
1207               (cur (current-buffer))
1208               (coding-system-for-read mm-binary-coding-system)
1209               (coding-system-for-write mm-binary-coding-system)
1210               retval err-msg)
1211           (message "%s" msg)
1212           (with-temp-buffer
1213             (insert-buffer-substring cur)
1214             (condition-case err
1215                 (progn
1216                   (unless (memq (apply 'call-process-region
1217                                        (point-min) (point-max)
1218                                        prog t (list t err-file) nil args)
1219                                 jka-compr-acceptable-retval-list)
1220                     (erase-buffer)
1221                     (insert (mapconcat
1222                              'identity
1223                              (delete "" (split-string
1224                                          (prog2
1225                                              (insert-file-contents err-file)
1226                                              (buffer-string)
1227                                            (erase-buffer))))
1228                              " ")
1229                             "\n")
1230                     (setq err-msg
1231                           (format "Error while executing \"%s %s < %s\""
1232                                   prog (mapconcat 'identity args " ")
1233                                   filename)))
1234                   (setq retval (buffer-string)))
1235               (error
1236                (setq err-msg (error-message-string err)))))
1237           (when (file-exists-p err-file)
1238             (ignore-errors (jka-compr-delete-temp-file err-file)))
1239           (when inplace
1240             (unless err-msg
1241               (delete-region (point-min) (point-max))
1242               (insert retval))
1243             (setq retval nil))
1244           (message "%s" (or err-msg (concat msg "done")))
1245           retval)))))
1246
1247 (eval-when-compile
1248   (unless (fboundp 'coding-system-name)
1249     (defalias 'coding-system-name 'ignore))
1250   (unless (fboundp 'find-file-coding-system-for-read-from-filename)
1251     (defalias 'find-file-coding-system-for-read-from-filename 'ignore))
1252   (unless (fboundp 'find-operation-coding-system)
1253     (defalias 'find-operation-coding-system 'ignore)))
1254
1255 (defun mm-find-buffer-file-coding-system (&optional filename)
1256   "Find coding system used to decode the contents of the current buffer.
1257 This function looks for the coding system magic cookie or examines the
1258 coding system specified by `file-coding-system-alist' being associated
1259 with FILENAME which defaults to `buffer-file-name'.  Data compressed by
1260 gzip, bzip2, etc. are allowed."
1261   (unless filename
1262     (setq filename buffer-file-name))
1263   (save-excursion
1264     (let ((decomp (unless ;; No worth to examine charset of tar files.
1265                       (and filename
1266                            (string-match
1267                             "\\.\\(?:tar\\.[^.]+\\|tbz\\|tgz\\)\\'"
1268                             filename))
1269                     (mm-decompress-buffer filename nil t))))
1270       (when decomp
1271         (set-buffer (let (default-enable-multibyte-characters)
1272                       (generate-new-buffer " *temp*")))
1273         (insert decomp)
1274         (setq filename (file-name-sans-extension filename)))
1275       (goto-char (point-min))
1276       (prog1
1277           (cond
1278            ((boundp 'set-auto-coding-function) ;; Emacs
1279             (if filename
1280                 (or (funcall (symbol-value 'set-auto-coding-function)
1281                              filename (- (point-max) (point-min)))
1282                     (car (find-operation-coding-system 'insert-file-contents
1283                                                        filename)))
1284               (let (auto-coding-alist)
1285                 (condition-case nil
1286                     (funcall (symbol-value 'set-auto-coding-function)
1287                              nil (- (point-max) (point-min)))
1288                   (error nil)))))
1289            ((featurep 'file-coding) ;; XEmacs
1290             (let ((case-fold-search t)
1291                   (end (point-at-eol))
1292                   codesys start)
1293               (or
1294                (and (re-search-forward "-\\*-+[\t ]*" end t)
1295                     (progn
1296                       (setq start (match-end 0))
1297                       (re-search-forward "[\t ]*-+\\*-" end t))
1298                     (progn
1299                       (setq end (match-beginning 0))
1300                       (goto-char start)
1301                       (or (looking-at "coding:[\t ]*\\([^\t ;]+\\)")
1302                           (re-search-forward
1303                            "[\t ;]+coding:[\t ]*\\([^\t ;]+\\)"
1304                            end t)))
1305                     (find-coding-system (setq codesys
1306                                               (intern (match-string 1))))
1307                     codesys)
1308                (and (re-search-forward "^[\t ]*;+[\t ]*Local[\t ]+Variables:"
1309                                        nil t)
1310                     (progn
1311                       (setq start (match-end 0))
1312                       (re-search-forward "^[\t ]*;+[\t ]*End:" nil t))
1313                     (progn
1314                       (setq end (match-beginning 0))
1315                       (goto-char start)
1316                       (re-search-forward
1317                        "^[\t ]*;+[\t ]*coding:[\t ]*\\([^\t\n\r ]+\\)"
1318                        end t))
1319                     (find-coding-system (setq codesys
1320                                               (intern (match-string 1))))
1321                     codesys)
1322                (and (progn
1323                       (goto-char (point-min))
1324                       (setq case-fold-search nil)
1325                       (re-search-forward "^;;;coding system: "
1326                                          ;;(+ (point-min) 3000) t))
1327                                          nil t))
1328                     (looking-at "[^\t\n\r ]+")
1329                     (find-coding-system
1330                      (setq codesys (intern (match-string 0))))
1331                     codesys)
1332                (and filename
1333                     (setq codesys
1334                           (find-file-coding-system-for-read-from-filename
1335                            filename))
1336                     (coding-system-name (coding-system-base codesys)))))))
1337         (when decomp
1338           (kill-buffer (current-buffer)))))))
1339
1340 (provide 'mm-util)
1341
1342 ;; arch-tag: 94dc5388-825d-4fd1-bfa5-2100aa351238
1343 ;;; mm-util.el ends here