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