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