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