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