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