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