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