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