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