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