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