Synch to No Gnus 200409210948.
[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 may prefer iso-2022-jp to shift_jis.
349                '(iso-2022-jp iso-2022-jp-2 shift_jis iso-8859-1 utf-8)))))
350   "Preferred coding systems for encoding outgoing messages.
351
352 More than one suitable coding system may be found for some text.
353 By default, the coding system with the highest priority is used
354 to encode outgoing messages (see `sort-coding-systems').  If this
355 variable is set, it overrides the default priority."
356   :version "21.2"
357   :type '(repeat (symbol :tag "Coding system"))
358   :group 'mime)
359
360 ;; ??
361 (defvar mm-use-find-coding-systems-region
362   (fboundp 'find-coding-systems-region)
363   "Use `find-coding-systems-region' to find proper coding systems.
364
365 Setting it to nil is useful on Emacsen supporting Unicode if sending
366 mail with multiple parts is preferred to sending a Unicode one.")
367
368 ;;; Internal variables:
369
370 ;;; Functions:
371
372 (defun mm-mule-charset-to-mime-charset (charset)
373   "Return the MIME charset corresponding to the given Mule CHARSET."
374   (if (and (fboundp 'find-coding-systems-for-charsets)
375            (fboundp 'sort-coding-systems))
376       (let ((css (sort (sort-coding-systems
377                         (find-coding-systems-for-charsets (list charset)))
378                        'mm-sort-coding-systems-predicate))
379             cs mime)
380         (while (and (not mime)
381                     css)
382           (when (setq cs (pop css))
383             (setq mime (or (coding-system-get cs :mime-charset)
384                            (coding-system-get cs 'mime-charset)))))
385         mime)
386     (let ((alist (mapcar (lambda (cs)
387                            (assq cs mm-mime-mule-charset-alist))
388                          (sort (mapcar 'car mm-mime-mule-charset-alist)
389                                'mm-sort-coding-systems-predicate)))
390           out)
391       (while alist
392         (when (memq charset (cdar alist))
393           (setq out (caar alist)
394                 alist nil))
395         (pop alist))
396       out)))
397
398 (defun mm-charset-to-coding-system (charset &optional lbt)
399   "Return coding-system corresponding to CHARSET.
400 CHARSET is a symbol naming a MIME charset.
401 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
402 used as the line break code type of the coding system."
403   (when (stringp charset)
404     (setq charset (intern (downcase charset))))
405   (when lbt
406     (setq charset (intern (format "%s-%s" charset lbt))))
407   (cond
408    ((null charset)
409     charset)
410    ;; Running in a non-MULE environment.
411    ((or (null (mm-get-coding-system-list))
412         (not (fboundp 'coding-system-get)))
413     charset)
414    ;; ascii
415    ((eq charset 'us-ascii)
416     'ascii)
417    ;; Check to see whether we can handle this charset.  (This depends
418    ;; on there being some coding system matching each `mime-charset'
419    ;; property defined, as there should be.)
420    ((and (mm-coding-system-p charset)
421 ;;; Doing this would potentially weed out incorrect charsets.
422 ;;;      charset
423 ;;;      (eq charset (coding-system-get charset 'mime-charset))
424          )
425     charset)
426    ;; Translate invalid charsets.
427    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
428       (and cs (mm-coding-system-p cs) cs)))
429    ;; Last resort: search the coding system list for entries which
430    ;; have the right mime-charset in case the canonical name isn't
431    ;; defined (though it should be).
432    ((let (cs)
433       ;; mm-get-coding-system-list returns a list of cs without lbt.
434       ;; Do we need -lbt?
435       (dolist (c (mm-get-coding-system-list))
436         (if (and (null cs)
437                  (eq charset (or (coding-system-get c :mime-charset)
438                                  (coding-system-get c 'mime-charset))))
439             (setq cs c)))
440       cs))))
441
442 (eval-and-compile
443   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
444                              (boundp 'default-enable-multibyte-characters)
445                              default-enable-multibyte-characters
446                              (fboundp 'set-buffer-multibyte))
447     "True in Emacs with Mule.")
448
449   (if mm-emacs-mule
450       (defun mm-enable-multibyte ()
451         "Set the multibyte flag of the current buffer.
452 Only do this if the default value of `enable-multibyte-characters' is
453 non-nil.  This is a no-op in XEmacs."
454         (set-buffer-multibyte 'to))
455     (defalias 'mm-enable-multibyte 'ignore))
456
457   (if mm-emacs-mule
458       (defun mm-disable-multibyte ()
459         "Unset the multibyte flag of in the current buffer.
460 This is a no-op in XEmacs."
461         (set-buffer-multibyte nil))
462     (defalias 'mm-disable-multibyte 'ignore)))
463
464 (defun mm-preferred-coding-system (charset)
465   ;; A typo in some Emacs versions.
466   (or (get-charset-property charset 'preferred-coding-system)
467       (get-charset-property charset 'prefered-coding-system)))
468
469 ;; Mule charsets shouldn't be used.
470 (defsubst mm-guess-charset ()
471   "Guess Mule charset from the language environment."
472   (or
473    mail-parse-mule-charset ;; cached mule-charset
474    (progn
475      (setq mail-parse-mule-charset
476            (and (boundp 'current-language-environment)
477                 (car (last
478                       (assq 'charset
479                             (assoc current-language-environment
480                                    language-info-alist))))))
481      (if (or (not mail-parse-mule-charset)
482              (eq mail-parse-mule-charset 'ascii))
483          (setq mail-parse-mule-charset
484                (or (car (last (assq mail-parse-charset
485                                     mm-mime-mule-charset-alist)))
486                    ;; default
487                    'latin-iso8859-1)))
488      mail-parse-mule-charset)))
489
490 (defun mm-charset-after (&optional pos)
491   "Return charset of a character in current buffer at position POS.
492 If POS is nil, it defauls to the current point.
493 If POS is out of range, the value is nil.
494 If the charset is `composition', return the actual one."
495   (let ((char (char-after pos)) charset)
496     (if (< (mm-char-int char) 128)
497         (setq charset 'ascii)
498       ;; charset-after is fake in some Emacsen.
499       (setq charset (and (fboundp 'char-charset) (char-charset char)))
500       (if (eq charset 'composition)     ; Mule 4
501           (let ((p (or pos (point))))
502             (cadr (find-charset-region p (1+ p))))
503         (if (and charset (not (memq charset '(ascii eight-bit-control
504                                                     eight-bit-graphic))))
505             charset
506           (mm-guess-charset))))))
507
508 (defun mm-mime-charset (charset)
509   "Return the MIME charset corresponding to the given Mule CHARSET."
510   (if (eq charset 'unknown)
511       (error "The message contains non-printable characters, please use attachment"))
512   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
513       ;; This exists in Emacs 20.
514       (or
515        (and (mm-preferred-coding-system charset)
516             (or (coding-system-get
517                  (mm-preferred-coding-system charset) :mime-charset)
518                 (coding-system-get
519                  (mm-preferred-coding-system charset) 'mime-charset)))
520        (and (eq charset 'ascii)
521             'us-ascii)
522        (mm-preferred-coding-system charset)
523        (mm-mule-charset-to-mime-charset charset))
524     ;; This is for XEmacs.
525     (mm-mule-charset-to-mime-charset charset)))
526
527 (defun mm-delete-duplicates (list)
528   "Simple substitute for CL `delete-duplicates', testing with `equal'."
529   (let (result head)
530     (while list
531       (setq head (car list))
532       (setq list (delete head list))
533       (setq result (cons head result)))
534     (nreverse result)))
535
536 ;; Fixme:  This is used in places when it should be testing the
537 ;; default multibyteness.  See mm-default-multibyte-p.
538 (eval-and-compile
539   (if (and (not (featurep 'xemacs))
540            (boundp 'enable-multibyte-characters))
541       (defun mm-multibyte-p ()
542         "Non-nil if multibyte is enabled in the current buffer."
543         enable-multibyte-characters)
544     (defun mm-multibyte-p () (featurep 'mule))))
545
546 (defun mm-default-multibyte-p ()
547   "Return non-nil if the session is multibyte.
548 This affects whether coding conversion should be attempted generally."
549   (if (featurep 'mule)
550       (if (boundp 'default-enable-multibyte-characters)
551           default-enable-multibyte-characters
552         t)))
553
554 (defun mm-iso-8859-x-to-15-region (&optional b e)
555   (if (fboundp 'char-charset)
556       (let (charset item c inconvertible)
557         (save-restriction
558           (if e (narrow-to-region b e))
559           (goto-char (point-min))
560           (skip-chars-forward "\0-\177")
561           (while (not (eobp))
562             (cond
563              ((not (setq item (assq (char-charset (setq c (char-after)))
564                                     mm-iso-8859-x-to-15-table)))
565               (forward-char))
566              ((memq c (cdr (cdr item)))
567               (setq inconvertible t)
568               (forward-char))
569              (t
570               (insert-before-markers (prog1 (+ c (car (cdr item)))
571                                        (delete-char 1)))))
572             (skip-chars-forward "\0-\177")))
573         (not inconvertible))))
574
575 (defun mm-sort-coding-systems-predicate (a b)
576   (let ((priorities
577          (mapcar (lambda (cs)
578                    ;; Note: invalid entries are dropped silently
579                    (and (setq cs (mm-coding-system-p cs))
580                         (coding-system-base cs)))
581                  mm-coding-system-priorities)))
582     (and (setq a (mm-coding-system-p a))
583          (if (setq b (mm-coding-system-p b))
584              (> (length (memq (coding-system-base a) priorities))
585                 (length (memq (coding-system-base b) priorities)))
586            t))))
587
588 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
589   "Return the MIME charsets needed to encode the region between B and E.
590 nil means ASCII, a single-element list represents an appropriate MIME
591 charset, and a longer list means no appropriate charset."
592   (let (charsets)
593     ;; The return possibilities of this function are a mess...
594     (or (and (mm-multibyte-p)
595              mm-use-find-coding-systems-region
596              ;; Find the mime-charset of the most preferred coding
597              ;; system that has one.
598              (let ((systems (find-coding-systems-region b e)))
599                (when mm-coding-system-priorities
600                  (setq systems
601                        (sort systems 'mm-sort-coding-systems-predicate)))
602                (setq systems (delq 'compound-text systems))
603                (unless (equal systems '(undecided))
604                  (while systems
605                    (let* ((head (pop systems))
606                           (cs (or (coding-system-get head :mime-charset)
607                                   (coding-system-get head 'mime-charset))))
608                      ;; The mime-charset (`x-ctext') of
609                      ;; `compound-text' is not in the IANA list.  We
610                      ;; shouldn't normally use anything here with a
611                      ;; mime-charset having an `x-' prefix.
612                      ;; Fixme:  Allow this to be overridden, since
613                      ;; there is existing use of x-ctext.
614                      ;; Also people apparently need the coding system
615                      ;; `iso-2022-jp-3' (which Mule-UCS defines with
616                      ;; mime-charset, though it's not valid).
617                      (if (and cs
618                               (not (string-match "^[Xx]-" (symbol-name cs)))
619                               ;; UTF-16 of any variety is invalid for
620                               ;; text parts and, unfortunately, has
621                               ;; mime-charset defined both in Mule-UCS
622                               ;; and versions of Emacs.  (The name
623                               ;; might be `mule-utf-16...'  or
624                               ;; `utf-16...'.)
625                               (not (string-match "utf-16" (symbol-name cs))))
626                          (setq systems nil
627                                charsets (list cs))))))
628                charsets))
629         ;; Otherwise we're not multibyte, we're XEmacs, or a single
630         ;; coding system won't cover it.
631         (setq charsets
632               (mm-delete-duplicates
633                (mapcar 'mm-mime-charset
634                        (delq 'ascii
635                              (mm-find-charset-region b e))))))
636     (if (and (> (length charsets) 1)
637              (memq 'iso-8859-15 charsets)
638              (memq 'iso-8859-15 hack-charsets)
639              (save-excursion (mm-iso-8859-x-to-15-region b e)))
640         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
641                 mm-iso-8859-15-compatible))
642     (if (and (memq 'iso-2022-jp-2 charsets)
643              (memq 'iso-2022-jp-2 hack-charsets))
644         (setq charsets (delq 'iso-2022-jp charsets)))
645     charsets))
646
647 (defmacro mm-with-unibyte-buffer (&rest forms)
648   "Create a temporary buffer, and evaluate FORMS there like `progn'.
649 Use unibyte mode for this."
650   `(let (default-enable-multibyte-characters)
651      (with-temp-buffer ,@forms)))
652 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
653 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
654
655 (defmacro mm-with-multibyte-buffer (&rest forms)
656   "Create a temporary buffer, and evaluate FORMS there like `progn'.
657 Use multibyte mode for this."
658   `(let ((default-enable-multibyte-characters t))
659      (with-temp-buffer ,@forms)))
660 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
661 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
662
663 (defmacro mm-with-unibyte-current-buffer (&rest forms)
664   "Evaluate FORMS with current buffer temporarily made unibyte.
665 Also bind `default-enable-multibyte-characters' to nil.
666 Equivalent to `progn' in XEmacs"
667   (let ((multibyte (make-symbol "multibyte"))
668         (buffer (make-symbol "buffer")))
669     `(if mm-emacs-mule
670          (let ((,multibyte enable-multibyte-characters)
671                (,buffer (current-buffer)))
672            (unwind-protect
673                (let (default-enable-multibyte-characters)
674                  (set-buffer-multibyte nil)
675                  ,@forms)
676              (set-buffer ,buffer)
677              (set-buffer-multibyte ,multibyte)))
678        (let (default-enable-multibyte-characters)
679          ,@forms))))
680 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
681 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
682
683 (defmacro mm-with-unibyte (&rest forms)
684   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
685   `(let (default-enable-multibyte-characters)
686      ,@forms))
687 (put 'mm-with-unibyte 'lisp-indent-function 0)
688 (put 'mm-with-unibyte 'edebug-form-spec '(body))
689
690 (defmacro mm-with-multibyte (&rest forms)
691   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
692   `(let ((default-enable-multibyte-characters t))
693      ,@forms))
694 (put 'mm-with-multibyte 'lisp-indent-function 0)
695 (put 'mm-with-multibyte 'edebug-form-spec '(body))
696
697 (defun mm-find-charset-region (b e)
698   "Return a list of Emacs charsets in the region B to E."
699   (cond
700    ((and (mm-multibyte-p)
701          (fboundp 'find-charset-region))
702     ;; Remove composition since the base charsets have been included.
703     ;; Remove eight-bit-*, treat them as ascii.
704     (let ((css (find-charset-region b e)))
705       (mapcar (lambda (cs) (setq css (delq cs css)))
706               '(composition eight-bit-control eight-bit-graphic
707                             control-1))
708       css))
709    (t
710     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
711     (save-excursion
712       (save-restriction
713         (narrow-to-region b e)
714         (goto-char (point-min))
715         (skip-chars-forward "\0-\177")
716         (if (eobp)
717             '(ascii)
718           (let (charset)
719             (setq charset
720                   (and (boundp 'current-language-environment)
721                        (car (last (assq 'charset
722                                         (assoc current-language-environment
723                                                language-info-alist))))))
724             (if (eq charset 'ascii) (setq charset nil))
725             (or charset
726                 (setq charset
727                       (car (last (assq mail-parse-charset
728                                        mm-mime-mule-charset-alist)))))
729             (list 'ascii (or charset 'latin-iso8859-1)))))))))
730
731 (defun mm-auto-mode-alist ()
732   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
733   (let ((alist auto-mode-alist)
734         out)
735     (while alist
736       (when (listp (cdar alist))
737         (push (car alist) out))
738       (pop alist))
739     (nreverse out)))
740
741 (defvar mm-inhibit-file-name-handlers
742   '(jka-compr-handler image-file-handler)
743   "A list of handlers doing (un)compression (etc) thingies.")
744
745 (defun mm-insert-file-contents (filename &optional visit beg end replace
746                                          inhibit)
747   "Like `insert-file-contents', but only reads in the file.
748 A buffer may be modified in several ways after reading into the buffer due
749 to advanced Emacs features, such as file-name-handlers, format decoding,
750 `find-file-hooks', etc.
751 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
752   This function ensures that none of these modifications will take place."
753   (let ((format-alist nil)
754         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
755         (default-major-mode 'fundamental-mode)
756         (enable-local-variables nil)
757         (after-insert-file-functions nil)
758         (enable-local-eval nil)
759         (find-file-hooks nil)
760         (inhibit-file-name-operation (if inhibit
761                                          'insert-file-contents
762                                        inhibit-file-name-operation))
763         (inhibit-file-name-handlers
764          (if inhibit
765              (append mm-inhibit-file-name-handlers
766                      inhibit-file-name-handlers)
767            inhibit-file-name-handlers)))
768     (insert-file-contents filename visit beg end replace)))
769
770 (defun mm-append-to-file (start end filename &optional codesys inhibit)
771   "Append the contents of the region to the end of file FILENAME.
772 When called from a function, expects three arguments,
773 START, END and FILENAME.  START and END are buffer positions
774 saying what text to write.
775 Optional fourth argument specifies the coding system to use when
776 encoding the file.
777 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
778   (let ((coding-system-for-write
779          (or codesys mm-text-coding-system-for-write
780              mm-text-coding-system))
781         (inhibit-file-name-operation (if inhibit
782                                          'append-to-file
783                                        inhibit-file-name-operation))
784         (inhibit-file-name-handlers
785          (if inhibit
786              (append mm-inhibit-file-name-handlers
787                      inhibit-file-name-handlers)
788            inhibit-file-name-handlers)))
789     (write-region start end filename t 'no-message)
790     (message "Appended to %s" filename)))
791
792 (defun mm-write-region (start end filename &optional append visit lockname
793                               coding-system inhibit)
794
795   "Like `write-region'.
796 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
797   (let ((coding-system-for-write
798          (or coding-system mm-text-coding-system-for-write
799              mm-text-coding-system))
800         (inhibit-file-name-operation (if inhibit
801                                          'write-region
802                                        inhibit-file-name-operation))
803         (inhibit-file-name-handlers
804          (if inhibit
805              (append mm-inhibit-file-name-handlers
806                      inhibit-file-name-handlers)
807            inhibit-file-name-handlers)))
808     (write-region start end filename append visit lockname)))
809
810 (defun mm-image-load-path (&optional package)
811   (let (dir result)
812     (dolist (path load-path (nreverse result))
813       (when (and path
814                  (file-directory-p
815                   (setq dir (concat (file-name-directory
816                                      (directory-file-name path))
817                                     "etc/" (or package "gnus/")))))
818         (push dir result))
819       (push path result))))
820
821 ;; Fixme: This doesn't look useful where it's used.
822 (if (fboundp 'detect-coding-region)
823     (defun mm-detect-coding-region (start end)
824       "Like `detect-coding-region' except returning the best one."
825       (let ((coding-systems
826              (detect-coding-region (point) (point-max))))
827         (or (car-safe coding-systems)
828             coding-systems)))
829   (defun mm-detect-coding-region (start end)
830     (let ((point (point)))
831       (goto-char start)
832       (skip-chars-forward "\0-\177" end)
833       (prog1
834           (if (eq (point) end) 'ascii (mm-guess-charset))
835         (goto-char point)))))
836
837 (if (fboundp 'coding-system-get)
838     (defun mm-detect-mime-charset-region (start end)
839       "Detect MIME charset of the text in the region between START and END."
840       (let ((cs (mm-detect-coding-region start end)))
841         (coding-system-get cs 'mime-charset)))
842   (defun mm-detect-mime-charset-region (start end)
843     "Detect MIME charset of the text in the region between START and END."
844     (let ((cs (mm-detect-coding-region start end)))
845       cs)))
846
847
848 (provide 'mm-util)
849
850 ;;; mm-util.el ends here