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