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