Synch to No Gnus 200405201115.
[elisp/gnus.git-] / 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
29   (require 'cl)
30   (require 'static))
31
32 (require 'mail-prsvr)
33
34 (eval-and-compile
35   (mapcar
36    (lambda (elem)
37      (let ((nfunc (intern (format "mm-%s" (car elem)))))
38        (if (fboundp (car elem))
39            (defalias nfunc (car elem))
40          (defalias nfunc (cdr elem)))))
41    '((decode-coding-string . (lambda (s a) s))
42      (encode-coding-string . (lambda (s a) s))
43      (encode-coding-region . ignore)
44      (coding-system-list . ignore)
45      (decode-coding-region . ignore)
46      (char-int . identity)
47      (coding-system-equal . equal)
48      (annotationp . ignore)
49      (set-buffer-file-coding-system . ignore)
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 &optional inplace) ;; stolen (and renamed) from nnheader.el
61           "Replace characters in STRING from FROM to TO.
62           Unless optional argument INPLACE is non-nil, return a new string."
63           (let ((string (if inplace string (copy-sequence string)))
64                 (len (length string))
65                 (idx 0))
66             ;; Replace all occurrences of FROM with TO.
67             (while (< idx len)
68               (when (= (aref string idx) from)
69                 (aset string idx to))
70               (setq idx (1+ idx)))
71             string)))
72      (replace-in-string
73       . (lambda (string regexp rep &optional literal)
74           "See `replace-regexp-in-string', only the order of args differs."
75           (replace-regexp-in-string regexp rep string nil literal)))
76      (string-as-unibyte . identity)
77      (string-make-unibyte . identity)
78      (string-as-multibyte . identity)
79      (multibyte-string-p . ignore)
80      ;; It is not a MIME function, but some MIME functions use it.
81      (make-temp-file . (lambda (prefix &optional dir-flag)
82                          (let ((file (expand-file-name
83                                       (make-temp-name prefix)
84                                       (if (fboundp 'temp-directory)
85                                           (temp-directory)
86                                         temporary-file-directory))))
87                            (if dir-flag
88                                (make-directory file))
89                            file)))
90      (insert-byte . insert-char)
91      (multibyte-char-to-unibyte . identity))))
92
93 (eval-and-compile
94   (defalias 'mm-char-or-char-int-p
95     (cond
96      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
97      ((fboundp 'char-valid-p) 'char-valid-p)
98      (t 'identity))))
99
100 ;; Fixme:  This seems always to be used to read a MIME charset, so it
101 ;; should be re-named and fixed (in Emacs) to offer completion only on
102 ;; proper charset names (base coding systems which have a
103 ;; mime-charset defined).  XEmacs doesn't believe in mime-charset;
104 ;; test with
105 ;;   `(or (coding-system-get 'iso-8859-1 'mime-charset)
106 ;;        (coding-system-get 'iso-8859-1 :mime-charset))'
107 ;; Actually, there should be an `mm-coding-system-mime-charset'.
108 (eval-and-compile
109   (defalias 'mm-read-coding-system
110     (cond
111      ((fboundp 'read-coding-system)
112       (if (and (featurep 'xemacs)
113                (<= (string-to-number emacs-version) 21.1))
114           (lambda (prompt &optional default-coding-system)
115             (read-coding-system prompt))
116         'read-coding-system))
117      (t (lambda (prompt &optional default-coding-system)
118           "Prompt the user for a coding system."
119           (completing-read
120            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
121                           mm-mime-mule-charset-alist)))))))
122
123 (defvar mm-coding-system-list nil)
124 (defun mm-get-coding-system-list ()
125   "Get the coding system list."
126   (or mm-coding-system-list
127       (setq mm-coding-system-list (mm-coding-system-list))))
128
129 (defun mm-coding-system-p (cs)
130   "Return non-nil if CS is a symbol naming a coding system.
131 In XEmacs, also return non-nil if CS is a coding system object."
132   (if (fboundp 'find-coding-system)
133       (find-coding-system cs)
134     (if (fboundp 'coding-system-p)
135         (coding-system-p cs)
136       ;; Is this branch ever actually useful?
137       (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     ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
164         (if (mm-coding-system-p 'cp949)
165             '((ks_c_5601-1987 . cp949))
166           '((ks_c_5601-1987 . euc-kr))))
167     )
168   "A mapping from invalid charset names to the real charset names.")
169
170 (defvar mm-binary-coding-system
171   (cond
172    ((mm-coding-system-p 'binary) 'binary)
173    ((mm-coding-system-p 'no-conversion) 'no-conversion)
174    (t nil))
175   "100% binary coding system.")
176
177 (defvar mm-text-coding-system
178   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
179           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
180         (and (mm-coding-system-p 'raw-text) 'raw-text))
181       mm-binary-coding-system)
182   "Text-safe coding system (For removing ^M).")
183
184 (defvar mm-text-coding-system-for-write nil
185   "Text coding system for write.")
186
187 (defvar mm-auto-save-coding-system
188   (cond
189    ((mm-coding-system-p 'utf-8-emacs)   ; Mule 7
190     (if (memq system-type '(windows-nt ms-dos ms-windows))
191         (if (mm-coding-system-p 'utf-8-emacs-dos)
192             'utf-8-emacs-dos mm-binary-coding-system)
193       'utf-8-emacs))
194    ((mm-coding-system-p 'emacs-mule)
195     (if (memq system-type '(windows-nt ms-dos ms-windows))
196         (if (mm-coding-system-p 'emacs-mule-dos)
197             'emacs-mule-dos mm-binary-coding-system)
198       'emacs-mule))
199    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
200    (t mm-binary-coding-system))
201   "Coding system of auto save file.")
202
203 (defvar mm-universal-coding-system mm-auto-save-coding-system
204   "The universal coding system.")
205
206 ;; Fixme: some of the cars here aren't valid MIME charsets.  That
207 ;; should only matter with XEmacs, though.
208 (defvar mm-mime-mule-charset-alist
209   `((us-ascii ascii)
210     (iso-8859-1 latin-iso8859-1)
211     (iso-8859-2 latin-iso8859-2)
212     (iso-8859-3 latin-iso8859-3)
213     (iso-8859-4 latin-iso8859-4)
214     (iso-8859-5 cyrillic-iso8859-5)
215     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
216     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
217     ;; charset is koi8-r, not iso-8859-5.
218     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
219     (iso-8859-6 arabic-iso8859-6)
220     (iso-8859-7 greek-iso8859-7)
221     (iso-8859-8 hebrew-iso8859-8)
222     (iso-8859-9 latin-iso8859-9)
223     (iso-8859-14 latin-iso8859-14)
224     (iso-8859-15 latin-iso8859-15)
225     (viscii vietnamese-viscii-lower)
226     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
227     (euc-kr korean-ksc5601)
228     (gb2312 chinese-gb2312)
229     (big5 chinese-big5-1 chinese-big5-2)
230     (tibetan tibetan)
231     (thai-tis620 thai-tis620)
232     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
233     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
234                    latin-jisx0201 japanese-jisx0208-1978
235                    chinese-gb2312 japanese-jisx0208
236                    korean-ksc5601 japanese-jisx0212
237                    katakana-jisx0201)
238     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
239                     latin-jisx0201 japanese-jisx0208-1978
240                     chinese-gb2312 japanese-jisx0208
241                     korean-ksc5601 japanese-jisx0212
242                     chinese-cns11643-1 chinese-cns11643-2)
243     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
244                     cyrillic-iso8859-5 greek-iso8859-7
245                     latin-jisx0201 japanese-jisx0208-1978
246                     chinese-gb2312 japanese-jisx0208
247                     korean-ksc5601 japanese-jisx0212
248                     chinese-cns11643-1 chinese-cns11643-2
249                     chinese-cns11643-3 chinese-cns11643-4
250                     chinese-cns11643-5 chinese-cns11643-6
251                     chinese-cns11643-7)
252     ,(if (or (not (fboundp 'charsetp)) ;; non-Mule case
253              (charsetp 'unicode-a)
254              (not (mm-coding-system-p 'mule-utf-8)))
255          '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e)
256        ;; If we have utf-8 we're in Mule 5+.
257        (append '(utf-8)
258                (delete 'ascii
259                        (coding-system-get 'mule-utf-8 'safe-charsets)))))
260   "Alist of MIME-charset/MULE-charsets.")
261
262 ;; Correct by construction, but should be unnecessary:
263 ;; XEmacs hates it.
264 (when (and (not (featurep 'xemacs))
265            (fboundp 'coding-system-list)
266            (fboundp 'sort-coding-systems))
267   (setq mm-mime-mule-charset-alist
268         (apply
269          'nconc
270          (mapcar
271           (lambda (cs)
272             (when (and (or (coding-system-get cs :mime-charset) ; Emacs 22
273                            (coding-system-get cs 'mime-charset))
274                        (not (eq t (coding-system-get cs 'safe-charsets))))
275               (list (cons (or (coding-system-get cs :mime-charset)
276                               (coding-system-get cs 'mime-charset))
277                           (delq 'ascii
278                                 (coding-system-get cs 'safe-charsets))))))
279           (sort-coding-systems (coding-system-list 'base-only))))))
280
281 (defvar mm-hack-charsets '(iso-8859-15 iso-2022-jp-2)
282   "A list of special charsets.
283 Valid elements include:
284 `iso-8859-15'    convert ISO-8859-1, -9 to ISO-8859-15 if ISO-8859-15 exists.
285 `iso-2022-jp-2'  convert ISO-2022-jp to ISO-2022-jp-2 if ISO-2022-jp-2 exists."
286 )
287
288 (defvar mm-iso-8859-15-compatible
289   '((iso-8859-1 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")
290     (iso-8859-9 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xD0\xDD\xDE\xF0\xFD\xFE"))
291   "ISO-8859-15 exchangeable coding systems and inconvertible characters.")
292
293 (defvar mm-iso-8859-x-to-15-table
294   (and (fboundp 'coding-system-p)
295        (mm-coding-system-p 'iso-8859-15)
296        (mapcar
297         (lambda (cs)
298           (if (mm-coding-system-p (car cs))
299               (let ((c (string-to-char
300                         (decode-coding-string "\341" (car cs)))))
301                 (cons (char-charset c)
302                       (cons
303                        (- (string-to-char
304                            (decode-coding-string "\341" 'iso-8859-15)) c)
305                        (string-to-list (decode-coding-string (car (cdr cs))
306                                                              (car cs))))))
307             '(gnus-charset 0)))
308         mm-iso-8859-15-compatible))
309   "A table of the difference character between ISO-8859-X and ISO-8859-15.")
310
311 (defcustom mm-coding-system-priorities
312   (if (boundp 'current-language-environment)
313       (let ((lang (symbol-value 'current-language-environment)))
314         (cond ((string= lang "Japanese")
315                ;; Japanese users may prefer iso-2022-jp to shift-jis.
316                '(iso-2022-jp iso-2022-jp-2 japanese-shift-jis
317                              iso-latin-1 utf-8)))))
318   "Preferred coding systems for encoding outgoing messages.
319
320 More than one suitable coding system may be found for some text.
321 By default, the coding system with the highest priority is used
322 to encode outgoing messages (see `sort-coding-systems').  If this
323 variable is set, it overrides the default priority."
324   :type '(repeat (symbol :tag "Coding system"))
325   :group 'mime)
326
327 ;; ??
328 (defvar mm-use-find-coding-systems-region
329   (fboundp 'find-coding-systems-region)
330   "Use `find-coding-systems-region' to find proper coding systems.
331
332 Setting it to nil is useful on Emacsen supporting Unicode if sending
333 mail with multiple parts is preferred to sending a Unicode one.")
334
335 ;;; Internal variables:
336
337 ;;; Functions:
338
339 (defun mm-mule-charset-to-mime-charset (charset)
340   "Return the MIME charset corresponding to the given Mule CHARSET."
341   (if (and (fboundp 'find-coding-systems-for-charsets)
342            (fboundp 'sort-coding-systems))
343       (let (mime)
344         (dolist (cs (sort-coding-systems
345                      (copy-sequence
346                       (find-coding-systems-for-charsets (list charset)))))
347           (unless mime
348             (when cs
349               (setq mime (or (coding-system-get cs :mime-charset)
350                              (coding-system-get cs 'mime-charset))))))
351         mime)
352     (let ((alist mm-mime-mule-charset-alist)
353           out)
354       (while alist
355         (when (memq charset (cdar alist))
356           (setq out (caar alist)
357                 alist nil))
358         (pop alist))
359       out)))
360
361 (defun mm-charset-to-coding-system (charset &optional lbt)
362   "Return coding-system corresponding to CHARSET.
363 CHARSET is a symbol naming a MIME charset.
364 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
365 used as the line break code type of the coding system."
366   (when (stringp charset)
367     (setq charset (intern (downcase charset))))
368   (when lbt
369     (setq charset (intern (format "%s-%s" charset lbt))))
370   (cond
371    ((null charset)
372     charset)
373    ;; Running in a non-MULE environment.
374    ((or (null (mm-get-coding-system-list))
375         (not (fboundp 'coding-system-get)))
376     charset)
377    ;; ascii
378    ((eq charset 'us-ascii)
379     'ascii)
380    ;; Check to see whether we can handle this charset.  (This depends
381    ;; on there being some coding system matching each `mime-charset'
382    ;; property defined, as there should be.)
383    ((and (mm-coding-system-p charset)
384 ;;; Doing this would potentially weed out incorrect charsets.
385 ;;;      charset
386 ;;;      (eq charset (coding-system-get charset 'mime-charset))
387          )
388     charset)
389    ;; Translate invalid charsets.
390    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
391       (and cs (mm-coding-system-p cs) cs)))
392    ;; Last resort: search the coding system list for entries which
393    ;; have the right mime-charset in case the canonical name isn't
394    ;; defined (though it should be).
395    ((let (cs)
396       ;; mm-get-coding-system-list returns a list of cs without lbt.
397       ;; Do we need -lbt?
398       (dolist (c (mm-get-coding-system-list))
399         (if (and (null cs)
400                  (eq charset (or (coding-system-get c :mime-charset)
401                                  (coding-system-get c 'mime-charset))))
402             (setq cs c)))
403       cs))))
404
405 (eval-and-compile
406   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
407                              (boundp 'default-enable-multibyte-characters)
408                              default-enable-multibyte-characters
409                              (fboundp 'set-buffer-multibyte))
410     "True in Emacs with Mule.")
411
412   (if mm-emacs-mule
413       (defun mm-enable-multibyte ()
414         "Set the multibyte flag of the current buffer.
415 Only do this if the default value of `enable-multibyte-characters' is
416 non-nil.  This is a no-op in XEmacs."
417         (set-buffer-multibyte 'to))
418     (defalias 'mm-enable-multibyte 'ignore))
419
420   (if mm-emacs-mule
421       (defun mm-disable-multibyte ()
422         "Unset the multibyte flag of in the current buffer.
423 This is a no-op in XEmacs."
424         (set-buffer-multibyte nil))
425     (defalias 'mm-disable-multibyte 'ignore)))
426
427 (defun mm-preferred-coding-system (charset)
428   ;; A typo in some Emacs versions.
429   (or (get-charset-property charset 'preferred-coding-system)
430       (get-charset-property charset 'prefered-coding-system)))
431
432 ;; Mule charsets shouldn't be used.
433 (defsubst mm-guess-charset ()
434   "Guess Mule charset from the language environment."
435   (or
436    mail-parse-mule-charset ;; cached mule-charset
437    (progn
438      (setq mail-parse-mule-charset
439            (and (boundp 'current-language-environment)
440                 (car (last
441                       (assq 'charset
442                             (assoc current-language-environment
443                                    language-info-alist))))))
444      (if (or (not mail-parse-mule-charset)
445              (eq mail-parse-mule-charset 'ascii))
446          (setq mail-parse-mule-charset
447                (or (car (last (assq mail-parse-charset
448                                     mm-mime-mule-charset-alist)))
449                    ;; default
450                    'latin-iso8859-1)))
451      mail-parse-mule-charset)))
452
453 (defun mm-charset-after (&optional pos)
454   "Return charset of a character in current buffer at position POS.
455 If POS is nil, it defauls to the current point.
456 If POS is out of range, the value is nil.
457 If the charset is `composition', return the actual one."
458   (let ((char (char-after pos)) charset)
459     (if (< (mm-char-int char) 128)
460         (setq charset 'ascii)
461       ;; charset-after is fake in some Emacsen.
462       (setq charset (and (fboundp 'char-charset) (char-charset char)))
463       (if (eq charset 'composition)     ; Mule 4
464           (let ((p (or pos (point))))
465             (cadr (find-charset-region p (1+ p))))
466         (if (and charset (not (memq charset '(ascii eight-bit-control
467                                                     eight-bit-graphic))))
468             charset
469           (mm-guess-charset))))))
470
471 (defun mm-mime-charset (charset)
472   "Return the MIME charset corresponding to the given Mule CHARSET."
473   (if (eq charset 'unknown)
474       (error "The message contains non-printable characters, please use attachment"))
475   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
476       ;; This exists in Emacs 20.
477       (or
478        (and (mm-preferred-coding-system charset)
479             (or (coding-system-get
480                  (mm-preferred-coding-system charset) :mime-charset)
481                 (coding-system-get
482                  (mm-preferred-coding-system charset) 'mime-charset)))
483        (and (eq charset 'ascii)
484             'us-ascii)
485        (mm-preferred-coding-system charset)
486        (mm-mule-charset-to-mime-charset charset))
487     ;; This is for XEmacs.
488     (mm-mule-charset-to-mime-charset charset)))
489
490 (defun mm-delete-duplicates (list)
491   "Simple substitute for CL `delete-duplicates', testing with `equal'."
492   (let (result head)
493     (while list
494       (setq head (car list))
495       (setq list (delete head list))
496       (setq result (cons head result)))
497     (nreverse result)))
498
499 ;; Fixme:  This is used in places when it should be testing the
500 ;; default multibyteness.  See mm-default-multibyte-p.
501 (eval-and-compile
502   (if (and (not (featurep 'xemacs))
503            (boundp 'enable-multibyte-characters))
504       (defun mm-multibyte-p ()
505         "Non-nil if multibyte is enabled in the current buffer."
506         enable-multibyte-characters)
507     (defun mm-multibyte-p () (featurep 'mule))))
508
509 (defun mm-default-multibyte-p ()
510   "Return non-nil if the session is multibyte.
511 This affects whether coding conversion should be attempted generally."
512   (if (featurep 'mule)
513       (if (boundp 'default-enable-multibyte-characters)
514           default-enable-multibyte-characters
515         t)))
516
517 (defun mm-iso-8859-x-to-15-region (&optional b e)
518   (if (fboundp 'char-charset)
519       (let (charset item c inconvertible)
520         (save-restriction
521           (if e (narrow-to-region b e))
522           (goto-char (point-min))
523           (skip-chars-forward "\0-\177")
524           (while (not (eobp))
525             (cond
526              ((not (setq item (assq (char-charset (setq c (char-after)))
527                                     mm-iso-8859-x-to-15-table)))
528               (forward-char))
529              ((memq c (cdr (cdr item)))
530               (setq inconvertible t)
531               (forward-char))
532              (t
533               (insert-before-markers (prog1 (+ c (car (cdr item)))
534                                        (delete-char 1)))))
535             (skip-chars-forward "\0-\177")))
536         (not inconvertible))))
537
538 (defun mm-sort-coding-systems-predicate (a b)
539   (let ((priorities
540          (mapcar (lambda (cs)
541                    ;; Note: invalid entries are dropped silently
542                    (and (coding-system-p cs)
543                         (coding-system-base cs)))
544                  mm-coding-system-priorities)))
545     (> (length (memq a priorities))
546        (length (memq b priorities)))))
547
548 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
549   "Return the MIME charsets needed to encode the region between B and E.
550 nil means ASCII, a single-element list represents an appropriate MIME
551 charset, and a longer list means no appropriate charset."
552   (let (charsets)
553     ;; The return possibilities of this function are a mess...
554     (or (and (mm-multibyte-p)
555              mm-use-find-coding-systems-region
556              ;; Find the mime-charset of the most preferred coding
557              ;; system that has one.
558              (let ((systems (find-coding-systems-region b e)))
559                (when mm-coding-system-priorities
560                  (setq systems
561                        (sort systems 'mm-sort-coding-systems-predicate)))
562                (setq systems (delq 'compound-text systems))
563                (unless (equal systems '(undecided))
564                  (while systems
565                    (let* ((head (pop systems))
566                           (cs (or (coding-system-get head :mime-charset)
567                                   (coding-system-get head 'mime-charset))))
568                      ;; The mime-charset (`x-ctext') of
569                      ;; `compound-text' is not in the IANA list.  We
570                      ;; shouldn't normally use anything here with a
571                      ;; mime-charset having an `x-' prefix.
572                      ;; Fixme:  Allow this to be overridden, since
573                      ;; there is existing use of x-ctext.
574                      ;; Also people apparently need the coding system
575                      ;; `iso-2022-jp-3' (which Mule-UCS defines with
576                      ;; mime-charset, though it's not valid).
577                      (if (and cs
578                               (not (string-match "^[Xx]-" (symbol-name cs)))
579                               ;; UTF-16 of any variety is invalid for
580                               ;; text parts and, unfortunately, has
581                               ;; mime-charset defined both in Mule-UCS
582                               ;; and versions of Emacs.  (The name
583                               ;; might be `mule-utf-16...'  or
584                               ;; `utf-16...'.)
585                               (not (string-match "utf-16" (symbol-name cs))))
586                          (setq systems nil
587                                charsets (list cs))))))
588                charsets))
589         ;; Otherwise we're not multibyte, we're XEmacs, or a single
590         ;; coding system won't cover it.
591         (setq charsets
592               (mm-delete-duplicates
593                (mapcar 'mm-mime-charset
594                        (delq 'ascii
595                              (mm-find-charset-region b e))))))
596     (if (and (> (length charsets) 1)
597              (memq 'iso-8859-15 charsets)
598              (memq 'iso-8859-15 hack-charsets)
599              (save-excursion (mm-iso-8859-x-to-15-region b e)))
600         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
601                 mm-iso-8859-15-compatible))
602     (if (and (memq 'iso-2022-jp-2 charsets)
603              (memq 'iso-2022-jp-2 hack-charsets))
604         (setq charsets (delq 'iso-2022-jp charsets)))
605     charsets))
606
607 (defmacro mm-with-unibyte-buffer (&rest forms)
608   "Create a temporary buffer, and evaluate FORMS there like `progn'.
609 Use unibyte mode for this."
610   `(let (default-enable-multibyte-characters)
611      (with-temp-buffer ,@forms)))
612 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
613 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
614
615 (defmacro mm-with-unibyte-current-buffer (&rest forms)
616   "Evaluate FORMS with current buffer temporarily made unibyte.
617 Also bind `default-enable-multibyte-characters' to nil.
618 Equivalent to `progn' in XEmacs"
619   (let ((multibyte (make-symbol "multibyte"))
620         (buffer (make-symbol "buffer")))
621     `(if mm-emacs-mule
622          (let ((,multibyte enable-multibyte-characters)
623                (,buffer (current-buffer)))
624            (unwind-protect
625                (let (default-enable-multibyte-characters)
626                  (set-buffer-multibyte nil)
627                  ,@forms)
628              (set-buffer ,buffer)
629              (set-buffer-multibyte ,multibyte)))
630        (let (default-enable-multibyte-characters)
631          ,@forms))))
632 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
633 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
634
635 (defmacro mm-with-unibyte (&rest forms)
636   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
637   `(let (default-enable-multibyte-characters)
638      ,@forms))
639 (put 'mm-with-unibyte 'lisp-indent-function 0)
640 (put 'mm-with-unibyte 'edebug-form-spec '(body))
641
642 (defmacro mm-with-multibyte (&rest forms)
643   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
644   `(let ((default-enable-multibyte-characters t))
645      ,@forms))
646 (put 'mm-with-multibyte 'lisp-indent-function 0)
647 (put 'mm-with-multibyte 'edebug-form-spec '(body))
648
649 (defun mm-find-charset-region (b e)
650   "Return a list of Emacs charsets in the region B to E."
651   (cond
652    ((and (mm-multibyte-p)
653          (fboundp 'find-charset-region))
654     ;; Remove composition since the base charsets have been included.
655     ;; Remove eight-bit-*, treat them as ascii.
656     (let ((css (find-charset-region b e)))
657       (mapcar (lambda (cs) (setq css (delq cs css)))
658               '(composition eight-bit-control eight-bit-graphic
659                             control-1))
660       css))
661    (t
662     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
663     (save-excursion
664       (save-restriction
665         (narrow-to-region b e)
666         (goto-char (point-min))
667         (skip-chars-forward "\0-\177")
668         (if (eobp)
669             '(ascii)
670           (let (charset)
671             (setq charset
672                   (and (boundp 'current-language-environment)
673                        (car (last (assq 'charset
674                                         (assoc current-language-environment
675                                                language-info-alist))))))
676             (if (eq charset 'ascii) (setq charset nil))
677             (or charset
678                 (setq charset
679                       (car (last (assq mail-parse-charset
680                                        mm-mime-mule-charset-alist)))))
681             (list 'ascii (or charset 'latin-iso8859-1)))))))))
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', 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     (write-region start end filename t 'no-message)
742     (message "Appended to %s" filename)))
743
744 (defun mm-write-region (start end filename &optional append visit lockname
745                               coding-system inhibit)
746
747   "Like `write-region'.
748 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
749   (let ((coding-system-for-write
750          (or coding-system mm-text-coding-system-for-write
751              mm-text-coding-system))
752         (inhibit-file-name-operation (if inhibit
753                                          'write-region
754                                        inhibit-file-name-operation))
755         (inhibit-file-name-handlers
756          (if inhibit
757              (append mm-inhibit-file-name-handlers
758                      inhibit-file-name-handlers)
759            inhibit-file-name-handlers)))
760     (write-region start end filename append visit lockname)))
761
762 (defun mm-image-load-path (&optional package)
763   (let (dir result)
764     (dolist (path load-path (nreverse result))
765       (when (and path
766                  (file-directory-p
767                   (setq dir (concat (file-name-directory
768                                      (directory-file-name path))
769                                     "etc/" (or package "gnus/")))))
770         (push dir result))
771       (push path result))))
772
773 ;; Fixme: This doesn't look useful where it's used.
774 (if (fboundp 'detect-coding-region)
775     (defun mm-detect-coding-region (start end)
776       "Like `detect-coding-region' except returning the best one."
777       (let ((coding-systems
778              (detect-coding-region (point) (point-max))))
779         (or (car-safe coding-systems)
780             coding-systems)))
781   (defun mm-detect-coding-region (start end)
782     (let ((point (point)))
783       (goto-char start)
784       (skip-chars-forward "\0-\177" end)
785       (prog1
786           (if (eq (point) end) 'ascii (mm-guess-charset))
787         (goto-char point)))))
788
789 (if (fboundp 'coding-system-get)
790     (defun mm-detect-mime-charset-region (start end)
791       "Detect MIME charset of the text in the region between START and END."
792       (let ((cs (mm-detect-coding-region start end)))
793         (coding-system-get cs 'mime-charset)))
794   (defun mm-detect-mime-charset-region (start end)
795     "Detect MIME charset of the text in the region between START and END."
796     (let ((cs (mm-detect-coding-region start end)))
797       cs)))
798
799
800 (provide 'mm-util)
801
802 ;;; mm-util.el ends here