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