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