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