(mm-charset-synonym-alist): Map "unicode" to
[gnus] / lisp / mm-util.el
1 ;;; mm-util.el --- Utility functions for Mule and low level things
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
3 ;;   Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (require 'mail-prsvr)
30
31 (eval-and-compile
32   (mapcar
33    (lambda (elem)
34      (let ((nfunc (intern (format "mm-%s" (car elem)))))
35        (if (fboundp (car elem))
36            (defalias nfunc (car elem))
37          (defalias nfunc (cdr elem)))))
38    '((decode-coding-string . (lambda (s a) s))
39      (encode-coding-string . (lambda (s a) s))
40      (encode-coding-region . ignore)
41      (coding-system-list . ignore)
42      (decode-coding-region . ignore)
43      (char-int . identity)
44      (coding-system-equal . equal)
45      (annotationp . ignore)
46      (set-buffer-file-coding-system . ignore)
47      (read-charset
48       . (lambda (prompt)
49           "Return a charset."
50           (intern
51            (completing-read
52             prompt
53             (mapcar (lambda (e) (list (symbol-name (car e))))
54                     mm-mime-mule-charset-alist)
55             nil t))))
56      (subst-char-in-string
57       . (lambda (from to string &optional inplace) ;; stolen (and renamed) from nnheader.el
58           "Replace characters in STRING from FROM to TO.
59           Unless optional argument INPLACE is non-nil, return a new string."
60           (let ((string (if inplace string (copy-sequence string)))
61                 (len (length string))
62                 (idx 0))
63             ;; Replace all occurrences of FROM with TO.
64             (while (< idx len)
65               (when (= (aref string idx) from)
66                 (aset string idx to))
67               (setq idx (1+ idx)))
68             string)))
69      (replace-in-string
70       . (lambda (string regexp rep &optional literal)
71           "See `replace-regexp-in-string', only the order of args differs."
72           (replace-regexp-in-string regexp rep string nil literal)))
73      (string-as-unibyte . identity)
74      (string-make-unibyte . identity)
75      (string-as-multibyte . identity)
76      (multibyte-string-p . ignore)
77      ;; It is not a MIME function, but some MIME functions use it.
78      (make-temp-file . (lambda (prefix &optional dir-flag)
79                          (let ((file (expand-file-name
80                                       (make-temp-name prefix)
81                                       (if (fboundp 'temp-directory)
82                                           (temp-directory)
83                                         temporary-file-directory))))
84                            (if dir-flag
85                                (make-directory file))
86                            file)))
87      (insert-byte . insert-char)
88      (multibyte-char-to-unibyte . identity))))
89
90 (eval-and-compile
91   (defalias 'mm-char-or-char-int-p
92     (cond
93      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
94      ((fboundp 'char-valid-p) 'char-valid-p)
95      (t 'identity))))
96
97 ;; Fixme:  This seems always to be used to read a MIME charset, so it
98 ;; should be re-named and fixed (in Emacs) to offer completion only on
99 ;; proper charset names (base coding systems which have a
100 ;; mime-charset defined).  XEmacs doesn't believe in mime-charset;
101 ;; test with
102 ;;   `(or (coding-system-get 'iso-8859-1 'mime-charset)
103 ;;        (coding-system-get 'iso-8859-1 :mime-charset))'
104 ;; Actually, there should be an `mm-coding-system-mime-charset'.
105 (eval-and-compile
106   (defalias 'mm-read-coding-system
107     (cond
108      ((fboundp 'read-coding-system)
109       (if (and (featurep 'xemacs)
110                (<= (string-to-number emacs-version) 21.1))
111           (lambda (prompt &optional default-coding-system)
112             (read-coding-system prompt))
113         'read-coding-system))
114      (t (lambda (prompt &optional default-coding-system)
115           "Prompt the user for a coding system."
116           (completing-read
117            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
118                           mm-mime-mule-charset-alist)))))))
119
120 (defvar mm-coding-system-list nil)
121 (defun mm-get-coding-system-list ()
122   "Get the coding system list."
123   (or mm-coding-system-list
124       (setq mm-coding-system-list (mm-coding-system-list))))
125
126 (defun mm-coding-system-p (cs)
127   "Return non-nil if CS is a symbol naming a coding system.
128 In XEmacs, also return non-nil if CS is a coding system object.
129 If CS is available, return CS itself in Emacs, and return a coding
130 system object in XEmacs."
131   (if (fboundp 'find-coding-system)
132       (find-coding-system cs)
133     (if (fboundp 'coding-system-p)
134         (when (coding-system-p cs)
135           cs)
136       ;; Is this branch ever actually useful?
137       (car (memq cs (mm-get-coding-system-list))))))
138
139 (defvar mm-charset-synonym-alist
140   `(
141     ;; Not in XEmacs, but it's not a proper MIME charset anyhow.
142     ,@(unless (mm-coding-system-p 'x-ctext)
143        '((x-ctext . ctext)))
144     ;; ISO-8859-15 is very similar to ISO-8859-1.  But it's _different_!
145     ,@(unless (mm-coding-system-p 'iso-8859-15)
146        '((iso-8859-15 . iso-8859-1)))
147     ;; BIG-5HKSCS is similar to, but different than, BIG-5.
148     ,@(unless (mm-coding-system-p 'big5-hkscs)
149         '((big5-hkscs . big5)))
150     ;; Windows-1252 is actually a superset of Latin-1.  See also
151     ;; `gnus-article-dumbquotes-map'.
152     ,@(unless (mm-coding-system-p 'windows-1252)
153        (if (mm-coding-system-p 'cp1252)
154            '((windows-1252 . cp1252))
155          '((windows-1252 . iso-8859-1))))
156     ;; Windows-1250 is a variant of Latin-2 heavily used by Microsoft
157     ;; Outlook users in Czech republic. Use this to allow reading of their
158     ;; e-mails. cp1250 should be defined by M-x codepage-setup.
159     ,@(if (and (not (mm-coding-system-p 'windows-1250))
160                (mm-coding-system-p 'cp1250))
161           '((windows-1250 . cp1250)))
162     ;; A Microsoft misunderstanding.
163     ,@(if (and (not (mm-coding-system-p 'unicode))
164                (mm-coding-system-p 'utf-16-le))
165           '((unicode . utf-16-le)))
166     ;; A Microsoft misunderstanding.
167     ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
168         (if (mm-coding-system-p 'cp949)
169             '((ks_c_5601-1987 . cp949))
170           '((ks_c_5601-1987 . euc-kr))))
171     )
172   "A mapping from invalid charset names to the real charset names.")
173
174 (defvar mm-binary-coding-system
175   (cond
176    ((mm-coding-system-p 'binary) 'binary)
177    ((mm-coding-system-p 'no-conversion) 'no-conversion)
178    (t nil))
179   "100% binary coding system.")
180
181 (defvar mm-text-coding-system
182   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
183           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
184         (and (mm-coding-system-p 'raw-text) 'raw-text))
185       mm-binary-coding-system)
186   "Text-safe coding system (For removing ^M).")
187
188 (defvar mm-text-coding-system-for-write nil
189   "Text coding system for write.")
190
191 (defvar mm-auto-save-coding-system
192   (cond
193    ((mm-coding-system-p 'utf-8-emacs)   ; Mule 7
194     (if (memq system-type '(windows-nt ms-dos ms-windows))
195         (if (mm-coding-system-p 'utf-8-emacs-dos)
196             'utf-8-emacs-dos mm-binary-coding-system)
197       'utf-8-emacs))
198    ((mm-coding-system-p 'emacs-mule)
199     (if (memq system-type '(windows-nt ms-dos ms-windows))
200         (if (mm-coding-system-p 'emacs-mule-dos)
201             'emacs-mule-dos mm-binary-coding-system)
202       'emacs-mule))
203    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
204    (t mm-binary-coding-system))
205   "Coding system of auto save file.")
206
207 (defvar mm-universal-coding-system mm-auto-save-coding-system
208   "The universal coding system.")
209
210 ;; Fixme: some of the cars here aren't valid MIME charsets.  That
211 ;; should only matter with XEmacs, though.
212 (defvar mm-mime-mule-charset-alist
213   `((us-ascii ascii)
214     (iso-8859-1 latin-iso8859-1)
215     (iso-8859-2 latin-iso8859-2)
216     (iso-8859-3 latin-iso8859-3)
217     (iso-8859-4 latin-iso8859-4)
218     (iso-8859-5 cyrillic-iso8859-5)
219     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
220     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
221     ;; charset is koi8-r, not iso-8859-5.
222     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
223     (iso-8859-6 arabic-iso8859-6)
224     (iso-8859-7 greek-iso8859-7)
225     (iso-8859-8 hebrew-iso8859-8)
226     (iso-8859-9 latin-iso8859-9)
227     (iso-8859-14 latin-iso8859-14)
228     (iso-8859-15 latin-iso8859-15)
229     (viscii vietnamese-viscii-lower)
230     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
231     (euc-kr korean-ksc5601)
232     (gb2312 chinese-gb2312)
233     (big5 chinese-big5-1 chinese-big5-2)
234     (tibetan tibetan)
235     (thai-tis620 thai-tis620)
236     (windows-1251 cyrillic-iso8859-5)
237     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
238     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
239                    latin-jisx0201 japanese-jisx0208-1978
240                    chinese-gb2312 japanese-jisx0208
241                    korean-ksc5601 japanese-jisx0212)
242     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
243                     latin-jisx0201 japanese-jisx0208-1978
244                     chinese-gb2312 japanese-jisx0208
245                     korean-ksc5601 japanese-jisx0212
246                     chinese-cns11643-1 chinese-cns11643-2)
247     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
248                     cyrillic-iso8859-5 greek-iso8859-7
249                     latin-jisx0201 japanese-jisx0208-1978
250                     chinese-gb2312 japanese-jisx0208
251                     korean-ksc5601 japanese-jisx0212
252                     chinese-cns11643-1 chinese-cns11643-2
253                     chinese-cns11643-3 chinese-cns11643-4
254                     chinese-cns11643-5 chinese-cns11643-6
255                     chinese-cns11643-7)
256     (iso-2022-jp-3 latin-jisx0201 japanese-jisx0208-1978 japanese-jisx0208
257                    japanese-jisx0213-1 japanese-jisx0213-2)
258     (shift_jis latin-jisx0201 katakana-jisx0201 japanese-jisx0208)
259     ,(if (or (not (fboundp 'charsetp)) ;; non-Mule case
260              (charsetp 'unicode-a)
261              (not (mm-coding-system-p 'mule-utf-8)))
262          '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e)
263        ;; If we have utf-8 we're in Mule 5+.
264        (append '(utf-8)
265                (delete 'ascii
266                        (coding-system-get 'mule-utf-8 'safe-charsets)))))
267   "Alist of MIME-charset/MULE-charsets.")
268
269 (defun mm-enrich-utf-8-by-mule-ucs ()
270   "Make the `utf-8' MIME charset usable by the Mule-UCS package.
271 This function will run when the `un-define' module is loaded under
272 XEmacs, and fill the `utf-8' entry in `mm-mime-mule-charset-alist'
273 with Mule charsets.  It is completely useless for Emacs."
274   (unless (cdr (delete '(mm-enrich-utf-8-by-mule-ucs)
275                        (assoc "un-define" after-load-alist)))
276     (setq after-load-alist
277           (delete '("un-define") after-load-alist)))
278   (when (boundp 'unicode-basic-translation-charset-order-list)
279     (condition-case nil
280         (let ((val (delq
281                     'ascii
282                     (copy-sequence
283                      (symbol-value
284                       'unicode-basic-translation-charset-order-list))))
285               (elem (assq 'utf-8 mm-mime-mule-charset-alist)))
286           (if elem
287               (setcdr elem val)
288             (setq mm-mime-mule-charset-alist
289                   (nconc mm-mime-mule-charset-alist
290                          (list (cons 'utf-8 val))))))
291       (error))))
292
293 ;; Correct by construction, but should be unnecessary for Emacs:
294 (if (featurep 'xemacs)
295     (eval-after-load "un-define" '(mm-enrich-utf-8-by-mule-ucs))
296   (when (and (fboundp 'coding-system-list)
297              (fboundp 'sort-coding-systems))
298     (let ((css (sort-coding-systems (coding-system-list 'base-only)))
299           cs mime mule alist)
300       (while css
301         (setq cs (pop css)
302               mime (or (coding-system-get cs :mime-charset) ; Emacs 22
303                        (coding-system-get cs 'mime-charset)))
304         (when (and mime
305                    (not (eq t (setq mule
306                                     (coding-system-get cs 'safe-charsets))))
307                    (not (assq mime alist)))
308           (push (cons mime (delq 'ascii mule)) alist)))
309       (setq mm-mime-mule-charset-alist (nreverse alist)))))
310
311 (defvar mm-hack-charsets '(iso-8859-15 iso-2022-jp-2)
312   "A list of special charsets.
313 Valid elements include:
314 `iso-8859-15'    convert ISO-8859-1, -9 to ISO-8859-15 if ISO-8859-15 exists.
315 `iso-2022-jp-2'  convert ISO-2022-jp to ISO-2022-jp-2 if ISO-2022-jp-2 exists."
316 )
317
318 (defvar mm-iso-8859-15-compatible
319   '((iso-8859-1 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")
320     (iso-8859-9 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xD0\xDD\xDE\xF0\xFD\xFE"))
321   "ISO-8859-15 exchangeable coding systems and inconvertible characters.")
322
323 (defvar mm-iso-8859-x-to-15-table
324   (and (fboundp 'coding-system-p)
325        (mm-coding-system-p 'iso-8859-15)
326        (mapcar
327         (lambda (cs)
328           (if (mm-coding-system-p (car cs))
329               (let ((c (string-to-char
330                         (decode-coding-string "\341" (car cs)))))
331                 (cons (char-charset c)
332                       (cons
333                        (- (string-to-char
334                            (decode-coding-string "\341" 'iso-8859-15)) c)
335                        (string-to-list (decode-coding-string (car (cdr cs))
336                                                              (car cs))))))
337             '(gnus-charset 0)))
338         mm-iso-8859-15-compatible))
339   "A table of the difference character between ISO-8859-X and ISO-8859-15.")
340
341 (defcustom mm-coding-system-priorities
342   (if (boundp 'current-language-environment)
343       (let ((lang (symbol-value 'current-language-environment)))
344         (cond ((string= lang "Japanese")
345                ;; Japanese users may prefer iso-2022-jp to shift_jis.
346                '(iso-2022-jp iso-2022-jp-2 shift_jis iso-8859-1 utf-8)))))
347   "Preferred coding systems for encoding outgoing messages.
348
349 More than one suitable coding system may be found for some text.
350 By default, the coding system with the highest priority is used
351 to encode outgoing messages (see `sort-coding-systems').  If this
352 variable is set, it overrides the default priority."
353   :version "21.2"
354   :type '(repeat (symbol :tag "Coding system"))
355   :group 'mime)
356
357 ;; ??
358 (defvar mm-use-find-coding-systems-region
359   (fboundp 'find-coding-systems-region)
360   "Use `find-coding-systems-region' to find proper coding systems.
361
362 Setting it to nil is useful on Emacsen supporting Unicode if sending
363 mail with multiple parts is preferred to sending a Unicode one.")
364
365 ;;; Internal variables:
366
367 ;;; Functions:
368
369 (defun mm-mule-charset-to-mime-charset (charset)
370   "Return the MIME charset corresponding to the given Mule CHARSET."
371   (if (and (fboundp 'find-coding-systems-for-charsets)
372            (fboundp 'sort-coding-systems))
373       (let ((css (sort (sort-coding-systems
374                         (find-coding-systems-for-charsets (list charset)))
375                        'mm-sort-coding-systems-predicate))
376             cs mime)
377         (while (and (not mime)
378                     css)
379           (when (setq cs (pop css))
380             (setq mime (or (coding-system-get cs :mime-charset)
381                            (coding-system-get cs 'mime-charset)))))
382         mime)
383     (let ((alist (mapcar (lambda (cs)
384                            (assq cs mm-mime-mule-charset-alist))
385                          (sort (mapcar 'car mm-mime-mule-charset-alist)
386                                'mm-sort-coding-systems-predicate)))
387           out)
388       (while alist
389         (when (memq charset (cdar alist))
390           (setq out (caar alist)
391                 alist nil))
392         (pop alist))
393       out)))
394
395 (defun mm-charset-to-coding-system (charset &optional lbt)
396   "Return coding-system corresponding to CHARSET.
397 CHARSET is a symbol naming a MIME charset.
398 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
399 used as the line break code type of the coding system."
400   (when (stringp charset)
401     (setq charset (intern (downcase charset))))
402   (when lbt
403     (setq charset (intern (format "%s-%s" charset lbt))))
404   (cond
405    ((null charset)
406     charset)
407    ;; Running in a non-MULE environment.
408    ((or (null (mm-get-coding-system-list))
409         (not (fboundp 'coding-system-get)))
410     charset)
411    ;; ascii
412    ((eq charset 'us-ascii)
413     'ascii)
414    ;; Check to see whether we can handle this charset.  (This depends
415    ;; on there being some coding system matching each `mime-charset'
416    ;; property defined, as there should be.)
417    ((and (mm-coding-system-p charset)
418 ;;; Doing this would potentially weed out incorrect charsets.
419 ;;;      charset
420 ;;;      (eq charset (coding-system-get charset 'mime-charset))
421          )
422     charset)
423    ;; Translate invalid charsets.
424    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
425       (and cs (mm-coding-system-p cs) cs)))
426    ;; Last resort: search the coding system list for entries which
427    ;; have the right mime-charset in case the canonical name isn't
428    ;; defined (though it should be).
429    ((let (cs)
430       ;; mm-get-coding-system-list returns a list of cs without lbt.
431       ;; Do we need -lbt?
432       (dolist (c (mm-get-coding-system-list))
433         (if (and (null cs)
434                  (eq charset (or (coding-system-get c :mime-charset)
435                                  (coding-system-get c 'mime-charset))))
436             (setq cs c)))
437       cs))))
438
439 (eval-and-compile
440   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
441                              (boundp 'default-enable-multibyte-characters)
442                              default-enable-multibyte-characters
443                              (fboundp 'set-buffer-multibyte))
444     "True in Emacs with Mule.")
445
446   (if mm-emacs-mule
447       (defun mm-enable-multibyte ()
448         "Set the multibyte flag of the current buffer.
449 Only do this if the default value of `enable-multibyte-characters' is
450 non-nil.  This is a no-op in XEmacs."
451         (set-buffer-multibyte 'to))
452     (defalias 'mm-enable-multibyte 'ignore))
453
454   (if mm-emacs-mule
455       (defun mm-disable-multibyte ()
456         "Unset the multibyte flag of in the current buffer.
457 This is a no-op in XEmacs."
458         (set-buffer-multibyte nil))
459     (defalias 'mm-disable-multibyte 'ignore)))
460
461 (defun mm-preferred-coding-system (charset)
462   ;; A typo in some Emacs versions.
463   (or (get-charset-property charset 'preferred-coding-system)
464       (get-charset-property charset 'prefered-coding-system)))
465
466 ;; Mule charsets shouldn't be used.
467 (defsubst mm-guess-charset ()
468   "Guess Mule charset from the language environment."
469   (or
470    mail-parse-mule-charset ;; cached mule-charset
471    (progn
472      (setq mail-parse-mule-charset
473            (and (boundp 'current-language-environment)
474                 (car (last
475                       (assq 'charset
476                             (assoc current-language-environment
477                                    language-info-alist))))))
478      (if (or (not mail-parse-mule-charset)
479              (eq mail-parse-mule-charset 'ascii))
480          (setq mail-parse-mule-charset
481                (or (car (last (assq mail-parse-charset
482                                     mm-mime-mule-charset-alist)))
483                    ;; default
484                    'latin-iso8859-1)))
485      mail-parse-mule-charset)))
486
487 (defun mm-charset-after (&optional pos)
488   "Return charset of a character in current buffer at position POS.
489 If POS is nil, it defauls to the current point.
490 If POS is out of range, the value is nil.
491 If the charset is `composition', return the actual one."
492   (let ((char (char-after pos)) charset)
493     (if (< (mm-char-int char) 128)
494         (setq charset 'ascii)
495       ;; charset-after is fake in some Emacsen.
496       (setq charset (and (fboundp 'char-charset) (char-charset char)))
497       (if (eq charset 'composition)     ; Mule 4
498           (let ((p (or pos (point))))
499             (cadr (find-charset-region p (1+ p))))
500         (if (and charset (not (memq charset '(ascii eight-bit-control
501                                                     eight-bit-graphic))))
502             charset
503           (mm-guess-charset))))))
504
505 (defun mm-mime-charset (charset)
506   "Return the MIME charset corresponding to the given Mule CHARSET."
507   (if (eq charset 'unknown)
508       (error "The message contains non-printable characters, please use attachment"))
509   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
510       ;; This exists in Emacs 20.
511       (or
512        (and (mm-preferred-coding-system charset)
513             (or (coding-system-get
514                  (mm-preferred-coding-system charset) :mime-charset)
515                 (coding-system-get
516                  (mm-preferred-coding-system charset) 'mime-charset)))
517        (and (eq charset 'ascii)
518             'us-ascii)
519        (mm-preferred-coding-system charset)
520        (mm-mule-charset-to-mime-charset charset))
521     ;; This is for XEmacs.
522     (mm-mule-charset-to-mime-charset charset)))
523
524 (defun mm-delete-duplicates (list)
525   "Simple substitute for CL `delete-duplicates', testing with `equal'."
526   (let (result head)
527     (while list
528       (setq head (car list))
529       (setq list (delete head list))
530       (setq result (cons head result)))
531     (nreverse result)))
532
533 ;; Fixme:  This is used in places when it should be testing the
534 ;; default multibyteness.  See mm-default-multibyte-p.
535 (eval-and-compile
536   (if (and (not (featurep 'xemacs))
537            (boundp 'enable-multibyte-characters))
538       (defun mm-multibyte-p ()
539         "Non-nil if multibyte is enabled in the current buffer."
540         enable-multibyte-characters)
541     (defun mm-multibyte-p () (featurep 'mule))))
542
543 (defun mm-default-multibyte-p ()
544   "Return non-nil if the session is multibyte.
545 This affects whether coding conversion should be attempted generally."
546   (if (featurep 'mule)
547       (if (boundp 'default-enable-multibyte-characters)
548           default-enable-multibyte-characters
549         t)))
550
551 (defun mm-iso-8859-x-to-15-region (&optional b e)
552   (if (fboundp 'char-charset)
553       (let (charset item c inconvertible)
554         (save-restriction
555           (if e (narrow-to-region b e))
556           (goto-char (point-min))
557           (skip-chars-forward "\0-\177")
558           (while (not (eobp))
559             (cond
560              ((not (setq item (assq (char-charset (setq c (char-after)))
561                                     mm-iso-8859-x-to-15-table)))
562               (forward-char))
563              ((memq c (cdr (cdr item)))
564               (setq inconvertible t)
565               (forward-char))
566              (t
567               (insert-before-markers (prog1 (+ c (car (cdr item)))
568                                        (delete-char 1)))))
569             (skip-chars-forward "\0-\177")))
570         (not inconvertible))))
571
572 (defun mm-sort-coding-systems-predicate (a b)
573   (let ((priorities
574          (mapcar (lambda (cs)
575                    ;; Note: invalid entries are dropped silently
576                    (and (setq cs (mm-coding-system-p cs))
577                         (coding-system-base cs)))
578                  mm-coding-system-priorities)))
579     (and (setq a (mm-coding-system-p a))
580          (if (setq b (mm-coding-system-p b))
581              (> (length (memq (coding-system-base a) priorities))
582                 (length (memq (coding-system-base b) priorities)))
583            t))))
584
585 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
586   "Return the MIME charsets needed to encode the region between B and E.
587 nil means ASCII, a single-element list represents an appropriate MIME
588 charset, and a longer list means no appropriate charset."
589   (let (charsets)
590     ;; The return possibilities of this function are a mess...
591     (or (and (mm-multibyte-p)
592              mm-use-find-coding-systems-region
593              ;; Find the mime-charset of the most preferred coding
594              ;; system that has one.
595              (let ((systems (find-coding-systems-region b e)))
596                (when mm-coding-system-priorities
597                  (setq systems
598                        (sort systems 'mm-sort-coding-systems-predicate)))
599                (setq systems (delq 'compound-text systems))
600                (unless (equal systems '(undecided))
601                  (while systems
602                    (let* ((head (pop systems))
603                           (cs (or (coding-system-get head :mime-charset)
604                                   (coding-system-get head 'mime-charset))))
605                      ;; The mime-charset (`x-ctext') of
606                      ;; `compound-text' is not in the IANA list.  We
607                      ;; shouldn't normally use anything here with a
608                      ;; mime-charset having an `x-' prefix.
609                      ;; Fixme:  Allow this to be overridden, since
610                      ;; there is existing use of x-ctext.
611                      ;; Also people apparently need the coding system
612                      ;; `iso-2022-jp-3' (which Mule-UCS defines with
613                      ;; mime-charset, though it's not valid).
614                      (if (and cs
615                               (not (string-match "^[Xx]-" (symbol-name cs)))
616                               ;; UTF-16 of any variety is invalid for
617                               ;; text parts and, unfortunately, has
618                               ;; mime-charset defined both in Mule-UCS
619                               ;; and versions of Emacs.  (The name
620                               ;; might be `mule-utf-16...'  or
621                               ;; `utf-16...'.)
622                               (not (string-match "utf-16" (symbol-name cs))))
623                          (setq systems nil
624                                charsets (list cs))))))
625                charsets))
626         ;; Otherwise we're not multibyte, we're XEmacs, or a single
627         ;; coding system won't cover it.
628         (setq charsets
629               (mm-delete-duplicates
630                (mapcar 'mm-mime-charset
631                        (delq 'ascii
632                              (mm-find-charset-region b e))))))
633     (if (and (> (length charsets) 1)
634              (memq 'iso-8859-15 charsets)
635              (memq 'iso-8859-15 hack-charsets)
636              (save-excursion (mm-iso-8859-x-to-15-region b e)))
637         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
638                 mm-iso-8859-15-compatible))
639     (if (and (memq 'iso-2022-jp-2 charsets)
640              (memq 'iso-2022-jp-2 hack-charsets))
641         (setq charsets (delq 'iso-2022-jp charsets)))
642     charsets))
643
644 (defmacro mm-with-unibyte-buffer (&rest forms)
645   "Create a temporary buffer, and evaluate FORMS there like `progn'.
646 Use unibyte mode for this."
647   `(let (default-enable-multibyte-characters)
648      (with-temp-buffer ,@forms)))
649 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
650 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
651
652 (defmacro mm-with-multibyte-buffer (&rest forms)
653   "Create a temporary buffer, and evaluate FORMS there like `progn'.
654 Use multibyte mode for this."
655   `(let ((default-enable-multibyte-characters t))
656      (with-temp-buffer ,@forms)))
657 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
658 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
659
660 (defmacro mm-with-unibyte-current-buffer (&rest forms)
661   "Evaluate FORMS with current buffer temporarily made unibyte.
662 Also bind `default-enable-multibyte-characters' to nil.
663 Equivalent to `progn' in XEmacs"
664   (let ((multibyte (make-symbol "multibyte"))
665         (buffer (make-symbol "buffer")))
666     `(if mm-emacs-mule
667          (let ((,multibyte enable-multibyte-characters)
668                (,buffer (current-buffer)))
669            (unwind-protect
670                (let (default-enable-multibyte-characters)
671                  (set-buffer-multibyte nil)
672                  ,@forms)
673              (set-buffer ,buffer)
674              (set-buffer-multibyte ,multibyte)))
675        (let (default-enable-multibyte-characters)
676          ,@forms))))
677 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
678 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
679
680 (defmacro mm-with-unibyte (&rest forms)
681   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
682   `(let (default-enable-multibyte-characters)
683      ,@forms))
684 (put 'mm-with-unibyte 'lisp-indent-function 0)
685 (put 'mm-with-unibyte 'edebug-form-spec '(body))
686
687 (defmacro mm-with-multibyte (&rest forms)
688   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
689   `(let ((default-enable-multibyte-characters t))
690      ,@forms))
691 (put 'mm-with-multibyte 'lisp-indent-function 0)
692 (put 'mm-with-multibyte 'edebug-form-spec '(body))
693
694 (defun mm-find-charset-region (b e)
695   "Return a list of Emacs charsets in the region B to E."
696   (cond
697    ((and (mm-multibyte-p)
698          (fboundp 'find-charset-region))
699     ;; Remove composition since the base charsets have been included.
700     ;; Remove eight-bit-*, treat them as ascii.
701     (let ((css (find-charset-region b e)))
702       (mapcar (lambda (cs) (setq css (delq cs css)))
703               '(composition eight-bit-control eight-bit-graphic
704                             control-1))
705       css))
706    (t
707     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
708     (save-excursion
709       (save-restriction
710         (narrow-to-region b e)
711         (goto-char (point-min))
712         (skip-chars-forward "\0-\177")
713         (if (eobp)
714             '(ascii)
715           (let (charset)
716             (setq charset
717                   (and (boundp 'current-language-environment)
718                        (car (last (assq 'charset
719                                         (assoc current-language-environment
720                                                language-info-alist))))))
721             (if (eq charset 'ascii) (setq charset nil))
722             (or charset
723                 (setq charset
724                       (car (last (assq mail-parse-charset
725                                        mm-mime-mule-charset-alist)))))
726             (list 'ascii (or charset 'latin-iso8859-1)))))))))
727
728 (defun mm-auto-mode-alist ()
729   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
730   (let ((alist auto-mode-alist)
731         out)
732     (while alist
733       (when (listp (cdar alist))
734         (push (car alist) out))
735       (pop alist))
736     (nreverse out)))
737
738 (defvar mm-inhibit-file-name-handlers
739   '(jka-compr-handler image-file-handler)
740   "A list of handlers doing (un)compression (etc) thingies.")
741
742 (defun mm-insert-file-contents (filename &optional visit beg end replace
743                                          inhibit)
744   "Like `insert-file-contents', but only reads in the file.
745 A buffer may be modified in several ways after reading into the buffer due
746 to advanced Emacs features, such as file-name-handlers, format decoding,
747 `find-file-hooks', etc.
748 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
749   This function ensures that none of these modifications will take place."
750   (let ((format-alist nil)
751         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
752         (default-major-mode 'fundamental-mode)
753         (enable-local-variables nil)
754         (after-insert-file-functions nil)
755         (enable-local-eval nil)
756         (find-file-hooks nil)
757         (inhibit-file-name-operation (if inhibit
758                                          'insert-file-contents
759                                        inhibit-file-name-operation))
760         (inhibit-file-name-handlers
761          (if inhibit
762              (append mm-inhibit-file-name-handlers
763                      inhibit-file-name-handlers)
764            inhibit-file-name-handlers)))
765     (insert-file-contents filename visit beg end replace)))
766
767 (defun mm-append-to-file (start end filename &optional codesys inhibit)
768   "Append the contents of the region to the end of file FILENAME.
769 When called from a function, expects three arguments,
770 START, END and FILENAME.  START and END are buffer positions
771 saying what text to write.
772 Optional fourth argument specifies the coding system to use when
773 encoding the file.
774 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
775   (let ((coding-system-for-write
776          (or codesys mm-text-coding-system-for-write
777              mm-text-coding-system))
778         (inhibit-file-name-operation (if inhibit
779                                          'append-to-file
780                                        inhibit-file-name-operation))
781         (inhibit-file-name-handlers
782          (if inhibit
783              (append mm-inhibit-file-name-handlers
784                      inhibit-file-name-handlers)
785            inhibit-file-name-handlers)))
786     (write-region start end filename t 'no-message)
787     (message "Appended to %s" filename)))
788
789 (defun mm-write-region (start end filename &optional append visit lockname
790                               coding-system inhibit)
791
792   "Like `write-region'.
793 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
794   (let ((coding-system-for-write
795          (or coding-system mm-text-coding-system-for-write
796              mm-text-coding-system))
797         (inhibit-file-name-operation (if inhibit
798                                          'write-region
799                                        inhibit-file-name-operation))
800         (inhibit-file-name-handlers
801          (if inhibit
802              (append mm-inhibit-file-name-handlers
803                      inhibit-file-name-handlers)
804            inhibit-file-name-handlers)))
805     (write-region start end filename append visit lockname)))
806
807 (defun mm-image-load-path (&optional package)
808   (let (dir result)
809     (dolist (path load-path (nreverse result))
810       (when (and path
811                  (file-directory-p
812                   (setq dir (concat (file-name-directory
813                                      (directory-file-name path))
814                                     "etc/" (or package "gnus/")))))
815         (push dir result))
816       (push path result))))
817
818 ;; Fixme: This doesn't look useful where it's used.
819 (if (fboundp 'detect-coding-region)
820     (defun mm-detect-coding-region (start end)
821       "Like `detect-coding-region' except returning the best one."
822       (let ((coding-systems
823              (detect-coding-region (point) (point-max))))
824         (or (car-safe coding-systems)
825             coding-systems)))
826   (defun mm-detect-coding-region (start end)
827     (let ((point (point)))
828       (goto-char start)
829       (skip-chars-forward "\0-\177" end)
830       (prog1
831           (if (eq (point) end) 'ascii (mm-guess-charset))
832         (goto-char point)))))
833
834 (if (fboundp 'coding-system-get)
835     (defun mm-detect-mime-charset-region (start end)
836       "Detect MIME charset of the text in the region between START and END."
837       (let ((cs (mm-detect-coding-region start end)))
838         (coding-system-get cs 'mime-charset)))
839   (defun mm-detect-mime-charset-region (start end)
840     "Detect MIME charset of the text in the region between START and END."
841     (let ((cs (mm-detect-coding-region start end)))
842       cs)))
843
844
845 (provide 'mm-util)
846
847 ;;; arch-tag: 94dc5388-825d-4fd1-bfa5-2100aa351238
848 ;;; mm-util.el ends here