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