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