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