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