85dc2b385f2db46bd24364d2bfd5ad3dc8b0baea
[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    ((null (mm-get-coding-system-list))
348     charset)
349    ;; ascii
350    ((eq charset 'us-ascii)
351     'ascii)
352    ;; Check to see whether we can handle this charset.  (This depends
353    ;; on there being some coding system matching each `mime-charset'
354    ;; property defined, as there should be.)
355    ((and (mm-coding-system-p charset)
356 ;;; Doing this would potentially weed out incorrect charsets.
357 ;;;      charset
358 ;;;      (eq charset (coding-system-get charset 'mime-charset))
359          )
360     charset)
361    ;; Translate invalid charsets.
362    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
363       (and cs (mm-coding-system-p cs) cs)))
364    ;; Last resort: search the coding system list for entries which
365    ;; have the right mime-charset in case the canonical name isn't
366    ;; defined (though it should be).
367    ((let (cs)
368       ;; mm-get-coding-system-list returns a list of cs without lbt.
369       ;; Do we need -lbt?
370       (dolist (c (mm-get-coding-system-list))
371         (if (and (null cs)
372                  (eq charset (or (coding-system-get c :mime-charset)
373                                  (coding-system-get c 'mime-charset))))
374             (setq cs c)))
375       cs))))
376
377 (defsubst mm-replace-chars-in-string (string from to)
378   (mm-subst-char-in-string from to string))
379
380 (eval-and-compile
381   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
382                              (boundp 'default-enable-multibyte-characters)
383                              default-enable-multibyte-characters
384                              (fboundp 'set-buffer-multibyte))
385     "Emacs mule.")
386
387   (defvar mm-mule4-p (and mm-emacs-mule
388                           (fboundp 'charsetp)
389                           (not (charsetp 'eight-bit-control)))
390     "Mule version 4.")
391
392   (if mm-emacs-mule
393       (defun mm-enable-multibyte ()
394         "Set the multibyte flag of the current buffer.
395 Only do this if the default value of `enable-multibyte-characters' is
396 non-nil.  This is a no-op in XEmacs."
397         (set-buffer-multibyte t))
398     (defalias 'mm-enable-multibyte 'ignore))
399
400   (if mm-emacs-mule
401       (defun mm-disable-multibyte ()
402         "Unset the multibyte flag of in the current buffer.
403 This is a no-op in XEmacs."
404         (set-buffer-multibyte nil))
405     (defalias 'mm-disable-multibyte 'ignore))
406
407   (if mm-mule4-p
408       (defun mm-enable-multibyte-mule4  ()
409         "Enable multibyte in the current buffer.
410 Only used in Emacs Mule 4."
411         (set-buffer-multibyte t))
412     (defalias 'mm-enable-multibyte-mule4 'ignore))
413
414   (if mm-mule4-p
415       (defun mm-disable-multibyte-mule4 ()
416         "Disable multibyte in the current buffer.
417 Only used in Emacs Mule 4."
418         (set-buffer-multibyte nil))
419     (defalias 'mm-disable-multibyte-mule4 '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 (defsubst mm-guess-charset ()
427   "Guess Mule charset from the language environment."
428   (or
429    mail-parse-mule-charset ;; cached mule-charset
430    (progn
431      (setq mail-parse-mule-charset
432            (and (boundp 'current-language-environment)
433                 (car (last
434                       (assq 'charset
435                             (assoc current-language-environment
436                                    language-info-alist))))))
437      (if (or (not mail-parse-mule-charset)
438              (eq mail-parse-mule-charset 'ascii))
439          (setq mail-parse-mule-charset
440                (or (car (last (assq mail-parse-charset
441                                     mm-mime-mule-charset-alist)))
442                    ;; default
443                    'latin-iso8859-1)))
444      mail-parse-mule-charset)))
445
446 (defun mm-charset-after (&optional pos)
447   "Return charset of a character in current buffer at position POS.
448 If POS is nil, it defauls to the current point.
449 If POS is out of range, the value is nil.
450 If the charset is `composition', return the actual one."
451   (let ((char (char-after pos)) charset)
452     (if (< (mm-char-int char) 128)
453         (setq charset 'ascii)
454       ;; charset-after is fake in some Emacsen.
455       (setq charset (and (fboundp 'char-charset) (char-charset char)))
456       (if (eq charset 'composition)
457           (let ((p (or pos (point))))
458             (cadr (find-charset-region p (1+ p))))
459         (if (and charset (not (memq charset '(ascii eight-bit-control
460                                                     eight-bit-graphic))))
461             charset
462           (mm-guess-charset))))))
463
464 (defun mm-mime-charset (charset)
465   "Return the MIME charset corresponding to the given Mule CHARSET."
466   (if (eq charset 'unknown)
467       (error "The message contains non-printable characters, please use attachment"))
468   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
469       ;; This exists in Emacs 20.
470       (or
471        (and (mm-preferred-coding-system charset)
472             (or (coding-system-get
473                  (mm-preferred-coding-system charset) :mime-charset)
474                 (coding-system-get
475                  (mm-preferred-coding-system charset) 'mime-charset)))
476        (and (eq charset 'ascii)
477             'us-ascii)
478        (mm-preferred-coding-system charset)
479        (mm-mule-charset-to-mime-charset charset))
480     ;; This is for XEmacs.
481     (mm-mule-charset-to-mime-charset charset)))
482
483 (defun mm-delete-duplicates (list)
484   "Simple substitute for CL `delete-duplicates', testing with `equal'."
485   (let (result head)
486     (while list
487       (setq head (car list))
488       (setq list (delete head list))
489       (setq result (cons head result)))
490     (nreverse result)))
491
492 (if (and (not (featurep 'xemacs))
493          (boundp 'enable-multibyte-characters))
494     (defalias 'mm-multibyte-p
495       (lambda ()
496         "Say whether multibyte is enabled in the current buffer."
497         enable-multibyte-characters))
498   (defalias 'mm-multibyte-p (lambda () (featurep 'mule))))
499
500 (defun mm-iso-8859-x-to-15-region (&optional b e)
501   (if (fboundp 'char-charset)
502       (let (charset item c inconvertible)
503         (save-restriction
504           (if e (narrow-to-region b e))
505           (goto-char (point-min))
506           (skip-chars-forward "\0-\177")
507           (while (not (eobp))
508             (cond
509              ((not (setq item (assq (char-charset (setq c (char-after)))
510                                     mm-iso-8859-x-to-15-table)))
511               (forward-char))
512              ((memq c (cdr (cdr item)))
513               (setq inconvertible t)
514               (forward-char))
515              (t
516               (insert-before-markers (prog1 (+ c (car (cdr item)))
517                                        (delete-char 1)))))
518             (skip-chars-forward "\0-\177")))
519         (not inconvertible))))
520
521 (defun mm-sort-coding-systems-predicate (a b)
522   (let ((priorities
523          (mapcar (lambda (cs)
524                    ;; Note: invalid entries are dropped silently
525                    (and (coding-system-p cs)
526                         (coding-system-base cs)))
527                  mm-coding-system-priorities)))
528     (> (length (memq a priorities))
529        (length (memq b priorities)))))
530
531 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
532   "Return the MIME charsets needed to encode the region between B and E.
533 nil means ASCII, a single-element list represents an appropriate MIME
534 charset, and a longer list means no appropriate charset."
535   (let (charsets)
536     ;; The return possibilities of this function are a mess...
537     (or (and (mm-multibyte-p)
538              mm-use-find-coding-systems-region
539              ;; Find the mime-charset of the most preferred coding
540              ;; system that has one.
541              (let ((systems (find-coding-systems-region b e)))
542                (when mm-coding-system-priorities
543                  (setq systems
544                        (sort systems 'mm-sort-coding-systems-predicate)))
545                (setq systems (delq 'compound-text systems))
546                (unless (equal systems '(undecided))
547                  (while systems
548                    (let* ((head (pop systems))
549                           (cs (or (coding-system-get head :mime-charset)
550                                   (coding-system-get head 'mime-charset))))
551                      ;; The mime-charset (`x-ctext') of
552                      ;; `compound-text' is not in the IANA list.  We
553                      ;; shouldn't normally use anything here with a
554                      ;; mime-charset having an `x-' prefix.
555                      ;; Fixme:  allow this to be overridden, since
556                      ;; there is existing use of x-ctext.
557                      ;; Also people apparently need the coding system
558                      ;; `iso-2022-jp-3', which Mule-UCS defines.
559                      (if (and cs
560                               (not (string-match "^[Xx]-" (symbol-name cs))))
561                          (setq systems nil
562                                charsets (list cs))))))
563                charsets))
564         ;; Otherwise we're not multibyte, we're XEmacs or a single
565         ;; coding system won't cover it.
566         (setq charsets
567               (mm-delete-duplicates
568                (mapcar 'mm-mime-charset
569                        (delq 'ascii
570                              (mm-find-charset-region b e))))))
571     (if (and (> (length charsets) 1)
572              (memq 'iso-8859-15 charsets)
573              (memq 'iso-8859-15 hack-charsets)
574              (save-excursion (mm-iso-8859-x-to-15-region b e)))
575         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
576                 mm-iso-8859-15-compatible))
577     (if (and (memq 'iso-2022-jp-2 charsets)
578              (memq 'iso-2022-jp-2 hack-charsets))
579         (setq charsets (delq 'iso-2022-jp charsets)))
580     charsets))
581
582 (defmacro mm-with-unibyte-buffer (&rest forms)
583   "Create a temporary buffer, and evaluate FORMS there like `progn'.
584 Use unibyte mode for this."
585   `(let (default-enable-multibyte-characters)
586      (with-temp-buffer ,@forms)))
587 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
588 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
589
590 (defmacro mm-with-unibyte-current-buffer (&rest forms)
591   "Evaluate FORMS with current buffer temporarily made unibyte.
592 Also bind `default-enable-multibyte-characters' to nil.
593 Equivalent to `progn' in XEmacs"
594   (let ((multibyte (make-symbol "multibyte"))
595         (buffer (make-symbol "buffer")))
596     `(if mm-emacs-mule
597          (let ((,multibyte enable-multibyte-characters)
598                (,buffer (current-buffer)))
599            (unwind-protect
600                (let (default-enable-multibyte-characters)
601                  (set-buffer-multibyte nil)
602                  ,@forms)
603              (set-buffer ,buffer)
604              (set-buffer-multibyte ,multibyte)))
605        (let (default-enable-multibyte-characters)
606          ,@forms))))
607 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
608 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
609
610 (defmacro mm-with-unibyte-current-buffer-mule4 (&rest forms)
611   "Evaluate FORMS there like `progn' in current buffer.
612 Mule4 only."
613   (let ((multibyte (make-symbol "multibyte"))
614         (buffer (make-symbol "buffer")))
615     `(if mm-mule4-p
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-mule4 'lisp-indent-function 0)
627 (put 'mm-with-unibyte-current-buffer-mule4 '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 (static-if (fboundp 'shell-quote-argument)
671     (defalias 'mm-quote-arg 'shell-quote-argument)
672   (defun mm-quote-arg (arg)
673     "Return a version of ARG that is safe to evaluate in a shell."
674     (let ((pos 0) new-pos accum)
675       ;; *** bug: we don't handle newline characters properly
676       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
677         (push (substring arg pos new-pos) accum)
678         (push "\\" accum)
679         (push (list (aref arg new-pos)) accum)
680         (setq pos (1+ new-pos)))
681       (if (= pos 0)
682           arg
683         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
684
685 (defun mm-auto-mode-alist ()
686   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
687   (let ((alist auto-mode-alist)
688         out)
689     (while alist
690       (when (listp (cdar alist))
691         (push (car alist) out))
692       (pop alist))
693     (nreverse out)))
694
695 (defvar mm-inhibit-file-name-handlers
696   '(jka-compr-handler image-file-handler)
697   "A list of handlers doing (un)compression (etc) thingies.")
698
699 (defun mm-insert-file-contents (filename &optional visit beg end replace
700                                          inhibit)
701   "Like `insert-file-contents', q.v., but only reads in the file.
702 A buffer may be modified in several ways after reading into the buffer due
703 to advanced Emacs features, such as file-name-handlers, format decoding,
704 find-file-hooks, etc.
705 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
706   This function ensures that none of these modifications will take place."
707   (let ((format-alist nil)
708         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
709         (default-major-mode 'fundamental-mode)
710         (enable-local-variables nil)
711         (after-insert-file-functions nil)
712         (enable-local-eval nil)
713         (find-file-hooks nil)
714         (inhibit-file-name-operation (if inhibit
715                                          'insert-file-contents
716                                        inhibit-file-name-operation))
717         (inhibit-file-name-handlers
718          (if inhibit
719              (append mm-inhibit-file-name-handlers
720                      inhibit-file-name-handlers)
721            inhibit-file-name-handlers)))
722     (insert-file-contents filename visit beg end replace)))
723
724 (defun mm-append-to-file (start end filename &optional codesys inhibit)
725   "Append the contents of the region to the end of file FILENAME.
726 When called from a function, expects three arguments,
727 START, END and FILENAME.  START and END are buffer positions
728 saying what text to write.
729 Optional fourth argument specifies the coding system to use when
730 encoding the file.
731 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
732   (let ((coding-system-for-write
733          (or codesys mm-text-coding-system-for-write
734              mm-text-coding-system))
735         (inhibit-file-name-operation (if inhibit
736                                          'append-to-file
737                                        inhibit-file-name-operation))
738         (inhibit-file-name-handlers
739          (if inhibit
740              (append mm-inhibit-file-name-handlers
741                      inhibit-file-name-handlers)
742            inhibit-file-name-handlers)))
743     (append-to-file start end filename)))
744
745 (defun mm-write-region (start end filename &optional append visit lockname
746                               coding-system inhibit)
747
748   "Like `write-region'.
749 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
750   (let ((coding-system-for-write
751          (or coding-system mm-text-coding-system-for-write
752              mm-text-coding-system))
753         (inhibit-file-name-operation (if inhibit
754                                          'write-region
755                                        inhibit-file-name-operation))
756         (inhibit-file-name-handlers
757          (if inhibit
758              (append mm-inhibit-file-name-handlers
759                      inhibit-file-name-handlers)
760            inhibit-file-name-handlers)))
761     (write-region start end filename append visit lockname)))
762
763 (defun mm-image-load-path (&optional package)
764   (let (dir result)
765     (dolist (path load-path (nreverse result))
766       (if (file-directory-p
767            (setq dir (concat (file-name-directory
768                               (directory-file-name path))
769                              "etc/" (or package "gnus/"))))
770           (push dir result))
771       (push path result))))
772
773 (if (fboundp 'detect-coding-region)
774     (defun mm-detect-coding-region (start end)
775       "Like `detect-coding-region' except returning the best one."
776       (let ((coding-systems
777              (detect-coding-region (point) (point-max))))
778         (or (car-safe coding-systems)
779             coding-systems)))
780   (defun mm-detect-coding-region (start end)
781     (let ((point (point)))
782       (goto-char start)
783       (skip-chars-forward "\0-\177" end)
784       (prog1
785           (if (eq (point) end) 'ascii (mm-guess-charset))
786         (goto-char point)))))
787
788 (if (fboundp 'coding-system-get)
789     (defun mm-detect-mime-charset-region (start end)
790       "Detect MIME charset of the text in the region between START and END."
791       (let ((cs (mm-detect-coding-region start end)))
792         (coding-system-get cs 'mime-charset)))
793   (defun mm-detect-mime-charset-region (start end)
794     "Detect MIME charset of the text in the region between START and END."
795     (let ((cs (mm-detect-coding-region start end)))
796       cs)))
797
798 (defun mm-guess-mime-charset ()
799   "Guess the default MIME charset from the language environment."
800   (let ((language-info
801          (and (boundp 'current-language-environment)
802               (assoc current-language-environment
803                      language-info-alist)))
804         item)
805     (cond
806      ((null language-info)
807       'iso-8859-1)
808      ((setq item
809             (cadr
810              (or (assq 'coding-priority language-info)
811                  (assq 'coding-system language-info))))
812       (if (fboundp 'coding-system-get)
813           (or (coding-system-get item 'mime-charset)
814               item)
815         item))
816      ((setq item (car (last (assq 'charset language-info))))
817       (if (eq item 'ascii)
818           'iso-8859-1
819         (mm-mime-charset item)))
820      (t
821       'iso-8859-1))))
822
823 ;; It is not a MIME function, but some MIME functions use it.
824 (defalias 'mm-make-temp-file
825   (if (fboundp 'make-temp-file)
826       'make-temp-file
827     (lambda (prefix &optional dir-flag)
828       (let ((file (expand-file-name
829                    (make-temp-name prefix)
830                    (if (fboundp 'temp-directory)
831                        (temp-directory)
832                      temporary-file-directory))))
833         (if dir-flag
834             (make-directory file))
835         file))))
836
837 (provide 'mm-util)
838
839 ;;; mm-util.el ends here