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