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