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