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