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