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