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