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