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