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