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