Merge from trunk
[bpt/emacs.git] / lisp / gnus / mm-util.el
1 ;;; mm-util.el --- Utility functions for Mule and low level things
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;; 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 ;; For Emacs < 22.2.
28 (eval-and-compile
29 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
30
31 (eval-when-compile (require 'cl))
32 (require 'mail-prsvr)
33
34 (eval-and-compile
35 (if (featurep 'xemacs)
36 (unless (ignore-errors
37 (require 'timer-funcs))
38 (require 'timer))
39 (require 'timer)))
40
41 (defvar mm-mime-mule-charset-alist )
42
43 ;; Emulate functions that are not available in every (X)Emacs version.
44 ;; The name of a function is prefixed with mm-, like `mm-char-int' for
45 ;; `char-int' that is a native XEmacs function, not available in Emacs.
46 ;; Gnus programs all should use mm- functions, not the original ones.
47 (eval-and-compile
48 (mapc
49 (lambda (elem)
50 (let ((nfunc (intern (format "mm-%s" (car elem)))))
51 (if (fboundp (car elem))
52 (defalias nfunc (car elem))
53 (defalias nfunc (cdr elem)))))
54 `(;; `coding-system-list' is not available in XEmacs 21.4 built
55 ;; without the `file-coding' feature.
56 (coding-system-list . ignore)
57 ;; `char-int' is an XEmacs function, not available in Emacs.
58 (char-int . identity)
59 ;; `coding-system-equal' is an Emacs function, not available in XEmacs.
60 (coding-system-equal . equal)
61 ;; `annotationp' is an XEmacs function, not available in Emacs.
62 (annotationp . ignore)
63 ;; `set-buffer-file-coding-system' is not available in XEmacs 21.4
64 ;; built without the `file-coding' feature.
65 (set-buffer-file-coding-system . ignore)
66 ;; `read-charset' is an Emacs function, not available in XEmacs.
67 (read-charset
68 . ,(lambda (prompt)
69 "Return a charset."
70 (intern
71 (completing-read
72 prompt
73 (mapcar (lambda (e) (list (symbol-name (car e))))
74 mm-mime-mule-charset-alist)
75 nil t))))
76 ;; `subst-char-in-string' is not available in XEmacs 21.4.
77 (subst-char-in-string
78 . ,(lambda (from to string &optional inplace)
79 ;; stolen (and renamed) from nnheader.el
80 "Replace characters in STRING from FROM to TO.
81 Unless optional argument INPLACE is non-nil, return a new string."
82 (let ((string (if inplace string (copy-sequence string)))
83 (len (length string))
84 (idx 0))
85 ;; Replace all occurrences of FROM with TO.
86 (while (< idx len)
87 (when (= (aref string idx) from)
88 (aset string idx to))
89 (setq idx (1+ idx)))
90 string)))
91 ;; `replace-in-string' is an XEmacs function, not available in Emacs.
92 (replace-in-string
93 . ,(lambda (string regexp rep &optional literal)
94 "See `replace-regexp-in-string', only the order of args differs."
95 (replace-regexp-in-string regexp rep string nil literal)))
96 ;; `string-as-unibyte' is an Emacs function, not available in XEmacs.
97 (string-as-unibyte . identity)
98 ;; `string-make-unibyte' is an Emacs function, not available in XEmacs.
99 (string-make-unibyte . identity)
100 ;; string-as-multibyte often doesn't really do what you think it does.
101 ;; Example:
102 ;; (aref (string-as-multibyte "\201") 0) -> 129 (aka ?\201)
103 ;; (aref (string-as-multibyte "\300") 0) -> 192 (aka ?\300)
104 ;; (aref (string-as-multibyte "\300\201") 0) -> 192 (aka ?\300)
105 ;; (aref (string-as-multibyte "\300\201") 1) -> 129 (aka ?\201)
106 ;; but
107 ;; (aref (string-as-multibyte "\201\300") 0) -> 2240
108 ;; (aref (string-as-multibyte "\201\300") 1) -> <error>
109 ;; Better use string-to-multibyte or encode-coding-string.
110 ;; If you really need string-as-multibyte somewhere it's usually
111 ;; because you're using the internal emacs-mule representation (maybe
112 ;; because you're using string-as-unibyte somewhere), which is
113 ;; generally a problem in itself.
114 ;; Here is an approximate equivalence table to help think about it:
115 ;; (string-as-multibyte s) ~= (decode-coding-string s 'emacs-mule)
116 ;; (string-to-multibyte s) ~= (decode-coding-string s 'binary)
117 ;; (string-make-multibyte s) ~= (decode-coding-string s locale-coding-system)
118 ;; `string-as-multibyte' is an Emacs function, not available in XEmacs.
119 (string-as-multibyte . identity)
120 ;; `multibyte-string-p' is an Emacs function, not available in XEmacs.
121 (multibyte-string-p . ignore)
122 ;; `insert-byte' is available only in Emacs 23.1 or greater.
123 (insert-byte . insert-char)
124 ;; `multibyte-char-to-unibyte' is an Emacs function, not available
125 ;; in XEmacs.
126 (multibyte-char-to-unibyte . identity)
127 ;; `set-buffer-multibyte' is an Emacs function, not available in XEmacs.
128 (set-buffer-multibyte . ignore)
129 ;; `special-display-p' is an Emacs function, not available in XEmacs.
130 (special-display-p
131 . ,(lambda (buffer-name)
132 "Returns non-nil if a buffer named BUFFER-NAME gets a special frame."
133 (and special-display-function
134 (or (and (member buffer-name special-display-buffer-names) t)
135 (cdr (assoc buffer-name special-display-buffer-names))
136 (catch 'return
137 (dolist (elem special-display-regexps)
138 (and (stringp elem)
139 (string-match elem buffer-name)
140 (throw 'return t))
141 (and (consp elem)
142 (stringp (car elem))
143 (string-match (car elem) buffer-name)
144 (throw 'return (cdr elem)))))))))
145 ;; `substring-no-properties' is available only in Emacs 22.1 or greater.
146 (substring-no-properties
147 . ,(lambda (string &optional from to)
148 "Return a substring of STRING, without text properties.
149 It starts at index FROM and ending before TO.
150 TO may be nil or omitted; then the substring runs to the end of STRING.
151 If FROM is nil or omitted, the substring starts at the beginning of STRING.
152 If FROM or TO is negative, it counts from the end.
153
154 With one argument, just copy STRING without its properties."
155 (setq string (substring string (or from 0) to))
156 (set-text-properties 0 (length string) nil string)
157 string))
158 ;; `line-number-at-pos' is available only in Emacs 22.1 or greater
159 ;; and XEmacs 21.5.
160 (line-number-at-pos
161 . ,(lambda (&optional pos)
162 "Return (narrowed) buffer line number at position POS.
163 If POS is nil, use current buffer location.
164 Counting starts at (point-min), so the value refers
165 to the contents of the accessible portion of the buffer."
166 (let ((opoint (or pos (point))) start)
167 (save-excursion
168 (goto-char (point-min))
169 (setq start (point))
170 (goto-char opoint)
171 (forward-line 0)
172 (1+ (count-lines start (point))))))))))
173
174 ;; `decode-coding-string', `encode-coding-string', `decode-coding-region'
175 ;; and `encode-coding-region' are available in Emacs and XEmacs built with
176 ;; the `file-coding' feature, but the XEmacs versions treat nil, that is
177 ;; given as the `coding-system' argument, as the `binary' coding system.
178 (eval-and-compile
179 (if (featurep 'xemacs)
180 (if (featurep 'file-coding)
181 (progn
182 (defun mm-decode-coding-string (str coding-system)
183 (if coding-system
184 (decode-coding-string str coding-system)
185 str))
186 (defun mm-encode-coding-string (str coding-system)
187 (if coding-system
188 (encode-coding-string str coding-system)
189 str))
190 (defun mm-decode-coding-region (start end coding-system)
191 (if coding-system
192 (decode-coding-region start end coding-system)))
193 (defun mm-encode-coding-region (start end coding-system)
194 (if coding-system
195 (encode-coding-region start end coding-system))))
196 (defun mm-decode-coding-string (str coding-system) str)
197 (defun mm-encode-coding-string (str coding-system) str)
198 (defalias 'mm-decode-coding-region 'ignore)
199 (defalias 'mm-encode-coding-region 'ignore))
200 (defalias 'mm-decode-coding-string 'decode-coding-string)
201 (defalias 'mm-encode-coding-string 'encode-coding-string)
202 (defalias 'mm-decode-coding-region 'decode-coding-region)
203 (defalias 'mm-encode-coding-region 'encode-coding-region)))
204
205 ;; `string-to-multibyte' is available only in Emacs 22.1 or greater.
206 (defalias 'mm-string-to-multibyte
207 (cond
208 ((featurep 'xemacs)
209 'identity)
210 ((fboundp 'string-to-multibyte)
211 'string-to-multibyte)
212 (t
213 (lambda (string)
214 "Return a multibyte string with the same individual chars as STRING."
215 (mapconcat
216 (lambda (ch) (mm-string-as-multibyte (char-to-string ch)))
217 string "")))))
218
219 ;; `char-or-char-int-p' is an XEmacs function, not available in Emacs.
220 (eval-and-compile
221 (defalias 'mm-char-or-char-int-p
222 (cond
223 ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
224 ((fboundp 'char-valid-p) 'char-valid-p)
225 (t 'identity))))
226
227 ;; `ucs-to-char' is a function that Mule-UCS provides.
228 (if (featurep 'xemacs)
229 (cond ((and (fboundp 'unicode-to-char) ;; XEmacs 21.5.
230 (subrp (symbol-function 'unicode-to-char)))
231 (if (featurep 'mule)
232 (defalias 'mm-ucs-to-char 'unicode-to-char)
233 (defun mm-ucs-to-char (codepoint)
234 "Convert Unicode codepoint to character."
235 (or (unicode-to-char codepoint) ?#))))
236 ((featurep 'mule)
237 (defun mm-ucs-to-char (codepoint)
238 "Convert Unicode codepoint to character."
239 (if (fboundp 'ucs-to-char) ;; Mule-UCS is loaded.
240 (progn
241 (defalias 'mm-ucs-to-char
242 (lambda (codepoint)
243 "Convert Unicode codepoint to character."
244 (condition-case nil
245 (or (ucs-to-char codepoint) ?#)
246 (error ?#))))
247 (mm-ucs-to-char codepoint))
248 (condition-case nil
249 (or (int-to-char codepoint) ?#)
250 (error ?#)))))
251 (t
252 (defun mm-ucs-to-char (codepoint)
253 "Convert Unicode codepoint to character."
254 (condition-case nil
255 (or (int-to-char codepoint) ?#)
256 (error ?#)))))
257 (if (let ((char (make-char 'japanese-jisx0208 36 34)))
258 (eq char (decode-char 'ucs char)))
259 ;; Emacs 23.
260 (defalias 'mm-ucs-to-char 'identity)
261 (defun mm-ucs-to-char (codepoint)
262 "Convert Unicode codepoint to character."
263 (or (decode-char 'ucs codepoint) ?#))))
264
265 ;; Fixme: This seems always to be used to read a MIME charset, so it
266 ;; should be re-named and fixed (in Emacs) to offer completion only on
267 ;; proper charset names (base coding systems which have a
268 ;; mime-charset defined). XEmacs doesn't believe in mime-charset;
269 ;; test with
270 ;; `(or (coding-system-get 'iso-8859-1 'mime-charset)
271 ;; (coding-system-get 'iso-8859-1 :mime-charset))'
272 ;; Actually, there should be an `mm-coding-system-mime-charset'.
273 (eval-and-compile
274 (defalias 'mm-read-coding-system
275 (cond
276 ((fboundp 'read-coding-system)
277 (if (and (featurep 'xemacs)
278 (<= (string-to-number emacs-version) 21.1))
279 (lambda (prompt &optional default-coding-system)
280 (read-coding-system prompt))
281 'read-coding-system))
282 (t (lambda (prompt &optional default-coding-system)
283 "Prompt the user for a coding system."
284 (completing-read
285 prompt (mapcar (lambda (s) (list (symbol-name (car s))))
286 mm-mime-mule-charset-alist)))))))
287
288 (defvar mm-coding-system-list nil)
289 (defun mm-get-coding-system-list ()
290 "Get the coding system list."
291 (or mm-coding-system-list
292 (setq mm-coding-system-list (mm-coding-system-list))))
293
294 (defun mm-coding-system-p (cs)
295 "Return non-nil if CS is a symbol naming a coding system.
296 In XEmacs, also return non-nil if CS is a coding system object.
297 If CS is available, return CS itself in Emacs, and return a coding
298 system object in XEmacs."
299 (if (fboundp 'find-coding-system)
300 (and cs (find-coding-system cs))
301 (if (fboundp 'coding-system-p)
302 (when (coding-system-p cs)
303 cs)
304 ;; no-MULE XEmacs:
305 (car (memq cs (mm-get-coding-system-list))))))
306
307 (defun mm-codepage-setup (number &optional alias)
308 "Create a coding system cpNUMBER.
309 The coding system is created using `codepage-setup'. If ALIAS is
310 non-nil, an alias is created and added to
311 `mm-charset-synonym-alist'. If ALIAS is a string, it's used as
312 the alias. Else windows-NUMBER is used."
313 (interactive
314 (let ((completion-ignore-case t)
315 (candidates (if (fboundp 'cp-supported-codepages)
316 (cp-supported-codepages)
317 ;; Removed in Emacs 23 (unicode), so signal an error:
318 (error "`codepage-setup' not present in this Emacs version"))))
319 (list (completing-read "Setup DOS Codepage: (default 437) " candidates
320 nil t nil nil "437"))))
321 (when alias
322 (setq alias (if (stringp alias)
323 (intern alias)
324 (intern (format "windows-%s" number)))))
325 (let* ((cp (intern (format "cp%s" number))))
326 (unless (mm-coding-system-p cp)
327 (if (fboundp 'codepage-setup) ; silence compiler
328 (codepage-setup number)
329 (error "`codepage-setup' not present in this Emacs version")))
330 (when (and alias
331 ;; Don't add alias if setup of cp failed.
332 (mm-coding-system-p cp))
333 (add-to-list 'mm-charset-synonym-alist (cons alias cp)))))
334
335 (defvar mm-charset-synonym-alist
336 `(
337 ;; Not in XEmacs, but it's not a proper MIME charset anyhow.
338 ,@(unless (mm-coding-system-p 'x-ctext)
339 '((x-ctext . ctext)))
340 ;; ISO-8859-15 is very similar to ISO-8859-1. But it's _different_ in 8
341 ;; positions!
342 ,@(unless (mm-coding-system-p 'iso-8859-15)
343 '((iso-8859-15 . iso-8859-1)))
344 ;; BIG-5HKSCS is similar to, but different than, BIG-5.
345 ,@(unless (mm-coding-system-p 'big5-hkscs)
346 '((big5-hkscs . big5)))
347 ;; A Microsoft misunderstanding.
348 ,@(when (and (not (mm-coding-system-p 'unicode))
349 (mm-coding-system-p 'utf-16-le))
350 '((unicode . utf-16-le)))
351 ;; A Microsoft misunderstanding.
352 ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
353 (if (mm-coding-system-p 'cp949)
354 '((ks_c_5601-1987 . cp949))
355 '((ks_c_5601-1987 . euc-kr))))
356 ;; Windows-31J is Windows Codepage 932.
357 ,@(when (and (not (mm-coding-system-p 'windows-31j))
358 (mm-coding-system-p 'cp932))
359 '((windows-31j . cp932)))
360 ;; Charset name: GBK, Charset aliases: CP936, MS936, windows-936
361 ;; http://www.iana.org/assignments/charset-reg/GBK
362 ;; Emacs 22.1 has cp936, but not gbk, so we alias it:
363 ,@(when (and (not (mm-coding-system-p 'gbk))
364 (mm-coding-system-p 'cp936))
365 '((gbk . cp936)))
366 ;; UTF8 is a bogus name for UTF-8
367 ,@(when (and (not (mm-coding-system-p 'utf8))
368 (mm-coding-system-p 'utf-8))
369 '((utf8 . utf-8)))
370 ;; ISO8859-1 is a bogus name for ISO-8859-1
371 ,@(when (and (not (mm-coding-system-p 'iso8859-1))
372 (mm-coding-system-p 'iso-8859-1))
373 '((iso8859-1 . iso-8859-1)))
374 ;; ISO_8859-1 is a bogus name for ISO-8859-1
375 ,@(when (and (not (mm-coding-system-p 'iso_8859-1))
376 (mm-coding-system-p 'iso-8859-1))
377 '((iso_8859-1 . iso-8859-1)))
378 )
379 "A mapping from unknown or invalid charset names to the real charset names.
380
381 See `mm-codepage-iso-8859-list' and `mm-codepage-ibm-list'.")
382
383 (defcustom mm-codepage-iso-8859-list
384 (list 1250 ;; Windows-1250 is a variant of Latin-2 heavily used by Microsoft
385 ;; Outlook users in Czech republic. Use this to allow reading of
386 ;; their e-mails.
387 '(1252 . 1) ;; Windows-1252 is a superset of iso-8859-1 (West
388 ;; Europe). See also `gnus-article-dumbquotes-map'.
389 '(1254 . 9) ;; Windows-1254 is a superset of iso-8859-9 (Turkish).
390 '(1255 . 8));; Windows-1255 is a superset of iso-8859-8 (Hebrew).
391 "A list of Windows codepage numbers and iso-8859 charset numbers.
392
393 If an element is a number corresponding to a supported windows
394 codepage, appropriate entries to `mm-charset-synonym-alist' are
395 added by `mm-setup-codepage-iso-8859'. An element may also be a
396 cons cell where the car is a codepage number and the cdr is the
397 corresponding number of an iso-8859 charset."
398 :type '(list (set :inline t
399 (const 1250 :tag "Central and East European")
400 (const (1252 . 1) :tag "West European")
401 (const (1254 . 9) :tag "Turkish")
402 (const (1255 . 8) :tag "Hebrew"))
403 (repeat :inline t
404 :tag "Other options"
405 (choice
406 (integer :tag "Windows codepage number")
407 (cons (integer :tag "Windows codepage number")
408 (integer :tag "iso-8859 charset number")))))
409 :version "22.1" ;; Gnus 5.10.9
410 :group 'mime)
411
412 (defcustom mm-codepage-ibm-list
413 (list 437 ;; (US etc.)
414 860 ;; (Portugal)
415 861 ;; (Iceland)
416 862 ;; (Israel)
417 863 ;; (Canadian French)
418 865 ;; (Nordic)
419 852 ;;
420 850 ;; (Latin 1)
421 855 ;; (Cyrillic)
422 866 ;; (Cyrillic - Russian)
423 857 ;; (Turkish)
424 864 ;; (Arabic)
425 869 ;; (Greek)
426 874);; (Thai)
427 ;; In Emacs 23 (unicode), cp... and ibm... are aliases.
428 ;; Cf. http://thread.gmane.org/v9lkng5nwy.fsf@marauder.physik.uni-ulm.de
429 "List of IBM codepage numbers.
430
431 The codepage mappings slighly differ between IBM and other vendors.
432 See \"ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/IBM/README.TXT\".
433
434 If an element is a number corresponding to a supported windows
435 codepage, appropriate entries to `mm-charset-synonym-alist' are
436 added by `mm-setup-codepage-ibm'."
437 :type '(list (set :inline t
438 (const 437 :tag "US etc.")
439 (const 860 :tag "Portugal")
440 (const 861 :tag "Iceland")
441 (const 862 :tag "Israel")
442 (const 863 :tag "Canadian French")
443 (const 865 :tag "Nordic")
444 (const 852)
445 (const 850 :tag "Latin 1")
446 (const 855 :tag "Cyrillic")
447 (const 866 :tag "Cyrillic - Russian")
448 (const 857 :tag "Turkish")
449 (const 864 :tag "Arabic")
450 (const 869 :tag "Greek")
451 (const 874 :tag "Thai"))
452 (repeat :inline t
453 :tag "Other options"
454 (integer :tag "Codepage number")))
455 :version "22.1" ;; Gnus 5.10.9
456 :group 'mime)
457
458 (defun mm-setup-codepage-iso-8859 (&optional list)
459 "Add appropriate entries to `mm-charset-synonym-alist'.
460 Unless LIST is given, `mm-codepage-iso-8859-list' is used."
461 (unless list
462 (setq list mm-codepage-iso-8859-list))
463 (dolist (i list)
464 (let (cp windows iso)
465 (if (consp i)
466 (setq cp (intern (format "cp%d" (car i)))
467 windows (intern (format "windows-%d" (car i)))
468 iso (intern (format "iso-8859-%d" (cdr i))))
469 (setq cp (intern (format "cp%d" i))
470 windows (intern (format "windows-%d" i))))
471 (unless (mm-coding-system-p windows)
472 (if (mm-coding-system-p cp)
473 (add-to-list 'mm-charset-synonym-alist (cons windows cp))
474 (add-to-list 'mm-charset-synonym-alist (cons windows iso)))))))
475
476 (defun mm-setup-codepage-ibm (&optional list)
477 "Add appropriate entries to `mm-charset-synonym-alist'.
478 Unless LIST is given, `mm-codepage-ibm-list' is used."
479 (unless list
480 (setq list mm-codepage-ibm-list))
481 (dolist (number list)
482 (let ((ibm (intern (format "ibm%d" number)))
483 (cp (intern (format "cp%d" number))))
484 (when (and (not (mm-coding-system-p ibm))
485 (mm-coding-system-p cp))
486 (add-to-list 'mm-charset-synonym-alist (cons ibm cp))))))
487
488 ;; Initialize:
489 (mm-setup-codepage-iso-8859)
490 (mm-setup-codepage-ibm)
491
492 ;; Note: this has to be defined before `mm-charset-to-coding-system'.
493 (defcustom mm-charset-eval-alist
494 (if (featurep 'xemacs)
495 nil ;; I don't know what would be useful for XEmacs.
496 '(;; Emacs 22 provides autoloads for 1250-1258
497 ;; (i.e. `mm-codepage-setup' does nothing).
498 (windows-1250 . (mm-codepage-setup 1250 t))
499 (windows-1251 . (mm-codepage-setup 1251 t))
500 (windows-1253 . (mm-codepage-setup 1253 t))
501 (windows-1257 . (mm-codepage-setup 1257 t))))
502 "An alist of (CHARSET . FORM) pairs.
503 If an article is encoded in an unknown CHARSET, FORM is
504 evaluated. This allows to load additional libraries providing
505 charsets on demand. If supported by your Emacs version, you
506 could use `autoload-coding-system' here."
507 :version "22.1" ;; Gnus 5.10.9
508 :type '(list (set :inline t
509 (const (windows-1250 . (mm-codepage-setup 1250 t)))
510 (const (windows-1251 . (mm-codepage-setup 1251 t)))
511 (const (windows-1253 . (mm-codepage-setup 1253 t)))
512 (const (windows-1257 . (mm-codepage-setup 1257 t)))
513 (const (cp850 . (mm-codepage-setup 850 nil))))
514 (repeat :inline t
515 :tag "Other options"
516 (cons (symbol :tag "charset")
517 (symbol :tag "form"))))
518 :group 'mime)
519 (put 'mm-charset-eval-alist 'risky-local-variable t)
520
521 (defvar mm-charset-override-alist)
522
523 ;; Note: this function has to be defined before `mm-charset-override-alist'
524 ;; since it will use this function in order to determine its default value
525 ;; when loading mm-util.elc.
526 (defun mm-charset-to-coding-system (charset &optional lbt
527 allow-override silent)
528 "Return coding-system corresponding to CHARSET.
529 CHARSET is a symbol naming a MIME charset.
530 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
531 used as the line break code type of the coding system.
532
533 If ALLOW-OVERRIDE is given, use `mm-charset-override-alist' to
534 map undesired charset names to their replacement. This should
535 only be used for decoding, not for encoding.
536
537 A non-nil value of SILENT means don't issue a warning even if CHARSET
538 is not available."
539 ;; OVERRIDE is used (only) in `mm-decode-body' and `mm-decode-string'.
540 (when (stringp charset)
541 (setq charset (intern (downcase charset))))
542 (when lbt
543 (setq charset (intern (format "%s-%s" charset lbt))))
544 (cond
545 ((null charset)
546 charset)
547 ;; Running in a non-MULE environment.
548 ((or (null (mm-get-coding-system-list))
549 (not (fboundp 'coding-system-get)))
550 charset)
551 ;; Check override list quite early. Should only used for decoding, not for
552 ;; encoding!
553 ((and allow-override
554 (let ((cs (cdr (assq charset mm-charset-override-alist))))
555 (and cs (mm-coding-system-p cs) cs))))
556 ;; ascii
557 ((eq charset 'us-ascii)
558 'ascii)
559 ;; Check to see whether we can handle this charset. (This depends
560 ;; on there being some coding system matching each `mime-charset'
561 ;; property defined, as there should be.)
562 ((and (mm-coding-system-p charset)
563 ;;; Doing this would potentially weed out incorrect charsets.
564 ;;; charset
565 ;;; (eq charset (coding-system-get charset 'mime-charset))
566 )
567 charset)
568 ;; Use coding system Emacs knows.
569 ((and (fboundp 'coding-system-from-name)
570 (coding-system-from-name charset)))
571 ;; Eval expressions from `mm-charset-eval-alist'
572 ((let* ((el (assq charset mm-charset-eval-alist))
573 (cs (car el))
574 (form (cdr el)))
575 (and cs
576 form
577 (prog2
578 ;; Avoid errors...
579 (condition-case nil (eval form) (error nil))
580 ;; (message "Failed to eval `%s'" form))
581 (mm-coding-system-p cs)
582 (message "Added charset `%s' via `mm-charset-eval-alist'" cs))
583 cs)))
584 ;; Translate invalid charsets.
585 ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
586 (and cs
587 (mm-coding-system-p cs)
588 ;; (message
589 ;; "Using synonym `%s' from `mm-charset-synonym-alist' for `%s'"
590 ;; cs charset)
591 cs)))
592 ;; Last resort: search the coding system list for entries which
593 ;; have the right mime-charset in case the canonical name isn't
594 ;; defined (though it should be).
595 ((let (cs)
596 ;; mm-get-coding-system-list returns a list of cs without lbt.
597 ;; Do we need -lbt?
598 (dolist (c (mm-get-coding-system-list))
599 (if (and (null cs)
600 (eq charset (or (coding-system-get c :mime-charset)
601 (coding-system-get c 'mime-charset))))
602 (setq cs c)))
603 (unless (or silent cs)
604 ;; Warn the user about unknown charset:
605 (if (fboundp 'gnus-message)
606 (gnus-message 7 "Unknown charset: %s" charset)
607 (message "Unknown charset: %s" charset)))
608 cs))))
609
610 ;; Note: `mm-charset-to-coding-system' has to be defined before this.
611 (defcustom mm-charset-override-alist
612 ;; Note: pairs that cannot be used in the Emacs version currently running
613 ;; will be removed.
614 '((gb2312 . gbk)
615 (iso-8859-1 . windows-1252)
616 (iso-8859-8 . windows-1255)
617 (iso-8859-9 . windows-1254))
618 "A mapping from undesired charset names to their replacement.
619
620 You may add pairs like (iso-8859-1 . windows-1252) here,
621 i.e. treat iso-8859-1 as windows-1252. windows-1252 is a
622 superset of iso-8859-1."
623 :type
624 '(list
625 :convert-widget
626 (lambda (widget)
627 (let ((defaults
628 (delq nil
629 (mapcar (lambda (pair)
630 (if (mm-charset-to-coding-system (cdr pair)
631 nil nil t)
632 pair))
633 '((gb2312 . gbk)
634 (iso-8859-1 . windows-1252)
635 (iso-8859-8 . windows-1255)
636 (iso-8859-9 . windows-1254)
637 (undecided . windows-1252)))))
638 (val (copy-sequence (default-value 'mm-charset-override-alist)))
639 pair rest)
640 (while val
641 (push (if (and (prog1
642 (setq pair (assq (caar val) defaults))
643 (setq defaults (delq pair defaults)))
644 (equal (car val) pair))
645 `(const ,pair)
646 `(cons :format "%v"
647 (const :format "(%v" ,(caar val))
648 (symbol :size 3 :format " . %v)\n" ,(cdar val))))
649 rest)
650 (setq val (cdr val)))
651 (while defaults
652 (push `(const ,(pop defaults)) rest))
653 (widget-convert
654 'list
655 `(set :inline t :format "%v" ,@(nreverse rest))
656 `(repeat :inline t :tag "Other options"
657 (cons :format "%v"
658 (symbol :size 3 :format "(%v")
659 (symbol :size 3 :format " . %v)\n")))))))
660 ;; Remove pairs that cannot be used in the Emacs version currently
661 ;; running. Note that this section will be evaluated when loading
662 ;; mm-util.elc.
663 :set (lambda (symbol value)
664 (custom-set-default
665 symbol (delq nil
666 (mapcar (lambda (pair)
667 (if (mm-charset-to-coding-system (cdr pair)
668 nil nil t)
669 pair))
670 value))))
671 :version "22.1" ;; Gnus 5.10.9
672 :group 'mime)
673
674 (defvar mm-binary-coding-system
675 (cond
676 ((mm-coding-system-p 'binary) 'binary)
677 ((mm-coding-system-p 'no-conversion) 'no-conversion)
678 (t nil))
679 "100% binary coding system.")
680
681 (defvar mm-text-coding-system
682 (or (if (memq system-type '(windows-nt ms-dos))
683 (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
684 (and (mm-coding-system-p 'raw-text) 'raw-text))
685 mm-binary-coding-system)
686 "Text-safe coding system (For removing ^M).")
687
688 (defvar mm-text-coding-system-for-write nil
689 "Text coding system for write.")
690
691 (defvar mm-auto-save-coding-system
692 (cond
693 ((mm-coding-system-p 'utf-8-emacs) ; Mule 7
694 (if (memq system-type '(windows-nt ms-dos))
695 (if (mm-coding-system-p 'utf-8-emacs-dos)
696 'utf-8-emacs-dos mm-binary-coding-system)
697 'utf-8-emacs))
698 ((mm-coding-system-p 'emacs-mule)
699 (if (memq system-type '(windows-nt ms-dos))
700 (if (mm-coding-system-p 'emacs-mule-dos)
701 'emacs-mule-dos mm-binary-coding-system)
702 'emacs-mule))
703 ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
704 (t mm-binary-coding-system))
705 "Coding system of auto save file.")
706
707 (defvar mm-universal-coding-system mm-auto-save-coding-system
708 "The universal coding system.")
709
710 ;; Fixme: some of the cars here aren't valid MIME charsets. That
711 ;; should only matter with XEmacs, though.
712 (defvar mm-mime-mule-charset-alist
713 `((us-ascii ascii)
714 (iso-8859-1 latin-iso8859-1)
715 (iso-8859-2 latin-iso8859-2)
716 (iso-8859-3 latin-iso8859-3)
717 (iso-8859-4 latin-iso8859-4)
718 (iso-8859-5 cyrillic-iso8859-5)
719 ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
720 ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
721 ;; charset is koi8-r, not iso-8859-5.
722 (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
723 (iso-8859-6 arabic-iso8859-6)
724 (iso-8859-7 greek-iso8859-7)
725 (iso-8859-8 hebrew-iso8859-8)
726 (iso-8859-9 latin-iso8859-9)
727 (iso-8859-14 latin-iso8859-14)
728 (iso-8859-15 latin-iso8859-15)
729 (viscii vietnamese-viscii-lower)
730 (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
731 (euc-kr korean-ksc5601)
732 (gb2312 chinese-gb2312)
733 (gbk chinese-gbk)
734 (gb18030 gb18030-2-byte
735 gb18030-4-byte-bmp gb18030-4-byte-smp
736 gb18030-4-byte-ext-1 gb18030-4-byte-ext-2)
737 (big5 chinese-big5-1 chinese-big5-2)
738 (tibetan tibetan)
739 (thai-tis620 thai-tis620)
740 (windows-1251 cyrillic-iso8859-5)
741 (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
742 (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
743 latin-jisx0201 japanese-jisx0208-1978
744 chinese-gb2312 japanese-jisx0208
745 korean-ksc5601 japanese-jisx0212)
746 (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
747 latin-jisx0201 japanese-jisx0208-1978
748 chinese-gb2312 japanese-jisx0208
749 korean-ksc5601 japanese-jisx0212
750 chinese-cns11643-1 chinese-cns11643-2)
751 (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
752 cyrillic-iso8859-5 greek-iso8859-7
753 latin-jisx0201 japanese-jisx0208-1978
754 chinese-gb2312 japanese-jisx0208
755 korean-ksc5601 japanese-jisx0212
756 chinese-cns11643-1 chinese-cns11643-2
757 chinese-cns11643-3 chinese-cns11643-4
758 chinese-cns11643-5 chinese-cns11643-6
759 chinese-cns11643-7)
760 (iso-2022-jp-3 latin-jisx0201 japanese-jisx0208-1978 japanese-jisx0208
761 japanese-jisx0213-1 japanese-jisx0213-2)
762 (shift_jis latin-jisx0201 katakana-jisx0201 japanese-jisx0208)
763 ,(cond ((fboundp 'unicode-precedence-list)
764 (cons 'utf-8 (delq 'ascii (mapcar 'charset-name
765 (unicode-precedence-list)))))
766 ((or (not (fboundp 'charsetp)) ;; non-Mule case
767 (charsetp 'unicode-a)
768 (not (mm-coding-system-p 'mule-utf-8)))
769 '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e))
770 (t ;; If we have utf-8 we're in Mule 5+.
771 (append '(utf-8)
772 (delete 'ascii
773 (coding-system-get 'mule-utf-8 'safe-charsets))))))
774 "Alist of MIME-charset/MULE-charsets.")
775
776 (defun mm-enrich-utf-8-by-mule-ucs ()
777 "Make the `utf-8' MIME charset usable by the Mule-UCS package.
778 This function will run when the `un-define' module is loaded under
779 XEmacs, and fill the `utf-8' entry in `mm-mime-mule-charset-alist'
780 with Mule charsets. It is completely useless for Emacs."
781 (when (boundp 'unicode-basic-translation-charset-order-list)
782 (condition-case nil
783 (let ((val (delq
784 'ascii
785 (copy-sequence
786 (symbol-value
787 'unicode-basic-translation-charset-order-list))))
788 (elem (assq 'utf-8 mm-mime-mule-charset-alist)))
789 (if elem
790 (setcdr elem val)
791 (setq mm-mime-mule-charset-alist
792 (nconc mm-mime-mule-charset-alist
793 (list (cons 'utf-8 val))))))
794 (error))))
795
796 ;; Correct by construction, but should be unnecessary for Emacs:
797 (if (featurep 'xemacs)
798 (eval-after-load "un-define" '(mm-enrich-utf-8-by-mule-ucs))
799 (when (and (fboundp 'coding-system-list)
800 (fboundp 'sort-coding-systems))
801 (let ((css (sort-coding-systems (coding-system-list 'base-only)))
802 cs mime mule alist)
803 (while css
804 (setq cs (pop css)
805 mime (or (coding-system-get cs :mime-charset); Emacs 23 (unicode)
806 (coding-system-get cs 'mime-charset)))
807 (when (and mime
808 (not (eq t (setq mule
809 (coding-system-get cs 'safe-charsets))))
810 (not (assq mime alist)))
811 (push (cons mime (delq 'ascii mule)) alist)))
812 (setq mm-mime-mule-charset-alist (nreverse alist)))))
813
814 (defvar mm-hack-charsets '(iso-8859-15 iso-2022-jp-2)
815 "A list of special charsets.
816 Valid elements include:
817 `iso-8859-15' convert ISO-8859-1, -9 to ISO-8859-15 if ISO-8859-15 exists.
818 `iso-2022-jp-2' convert ISO-2022-jp to ISO-2022-jp-2 if ISO-2022-jp-2 exists."
819 )
820
821 (defvar mm-iso-8859-15-compatible
822 '((iso-8859-1 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")
823 (iso-8859-9 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xD0\xDD\xDE\xF0\xFD\xFE"))
824 "ISO-8859-15 exchangeable coding systems and inconvertible characters.")
825
826 (defvar mm-iso-8859-x-to-15-table
827 (and (fboundp 'coding-system-p)
828 (mm-coding-system-p 'iso-8859-15)
829 (mapcar
830 (lambda (cs)
831 (if (mm-coding-system-p (car cs))
832 (let ((c (string-to-char
833 (decode-coding-string "\341" (car cs)))))
834 (cons (char-charset c)
835 (cons
836 (- (string-to-char
837 (decode-coding-string "\341" 'iso-8859-15)) c)
838 (string-to-list (decode-coding-string (car (cdr cs))
839 (car cs))))))
840 '(gnus-charset 0)))
841 mm-iso-8859-15-compatible))
842 "A table of the difference character between ISO-8859-X and ISO-8859-15.")
843
844 (defcustom mm-coding-system-priorities
845 (let ((lang (if (boundp 'current-language-environment)
846 (symbol-value 'current-language-environment))))
847 (cond (;; XEmacs without Mule but with `file-coding'.
848 (not lang) nil)
849 ;; In XEmacs 21.5 it may be the one like "Japanese (UTF-8)".
850 ((string-match "\\`Japanese" lang)
851 ;; Japanese users prefer iso-2022-jp to euc-japan or
852 ;; shift_jis, however iso-8859-1 should be used when
853 ;; there are only ASCII text and Latin-1 characters.
854 '(iso-8859-1 iso-2022-jp iso-2022-jp-2 shift_jis utf-8))))
855 "Preferred coding systems for encoding outgoing messages.
856
857 More than one suitable coding system may be found for some text.
858 By default, the coding system with the highest priority is used
859 to encode outgoing messages (see `sort-coding-systems'). If this
860 variable is set, it overrides the default priority."
861 :version "21.2"
862 :type '(repeat (symbol :tag "Coding system"))
863 :group 'mime)
864
865 ;; ??
866 (defvar mm-use-find-coding-systems-region
867 (fboundp 'find-coding-systems-region)
868 "Use `find-coding-systems-region' to find proper coding systems.
869
870 Setting it to nil is useful on Emacsen supporting Unicode if sending
871 mail with multiple parts is preferred to sending a Unicode one.")
872
873 ;;; Internal variables:
874
875 ;;; Functions:
876
877 (defun mm-mule-charset-to-mime-charset (charset)
878 "Return the MIME charset corresponding to the given Mule CHARSET."
879 (if (and (fboundp 'find-coding-systems-for-charsets)
880 (fboundp 'sort-coding-systems))
881 (let ((css (sort (sort-coding-systems
882 (find-coding-systems-for-charsets (list charset)))
883 'mm-sort-coding-systems-predicate))
884 cs mime)
885 (while (and (not mime)
886 css)
887 (when (setq cs (pop css))
888 (setq mime (or (coding-system-get cs :mime-charset)
889 (coding-system-get cs 'mime-charset)))))
890 mime)
891 (let ((alist (mapcar (lambda (cs)
892 (assq cs mm-mime-mule-charset-alist))
893 (sort (mapcar 'car mm-mime-mule-charset-alist)
894 'mm-sort-coding-systems-predicate)))
895 out)
896 (while alist
897 (when (memq charset (cdar alist))
898 (setq out (caar alist)
899 alist nil))
900 (pop alist))
901 out)))
902
903 (eval-and-compile
904 (if (featurep 'xemacs)
905 (defalias 'mm-enable-multibyte 'ignore)
906 (defun mm-enable-multibyte ()
907 "Set the multibyte flag of the current buffer.
908 Only do this if the default value of `enable-multibyte-characters' is
909 non-nil. This is a no-op in XEmacs."
910 (set-buffer-multibyte t)))
911
912 (if (featurep 'xemacs)
913 (defalias 'mm-disable-multibyte 'ignore)
914 (defun mm-disable-multibyte ()
915 "Unset the multibyte flag of in the current buffer.
916 This is a no-op in XEmacs."
917 (set-buffer-multibyte nil))))
918
919 (defun mm-preferred-coding-system (charset)
920 ;; A typo in some Emacs versions.
921 (or (get-charset-property charset 'preferred-coding-system)
922 (get-charset-property charset 'prefered-coding-system)))
923
924 ;; Mule charsets shouldn't be used.
925 (defsubst mm-guess-charset ()
926 "Guess Mule charset from the language environment."
927 (or
928 mail-parse-mule-charset ;; cached mule-charset
929 (progn
930 (setq mail-parse-mule-charset
931 (and (boundp 'current-language-environment)
932 (car (last
933 (assq 'charset
934 (assoc current-language-environment
935 language-info-alist))))))
936 (if (or (not mail-parse-mule-charset)
937 (eq mail-parse-mule-charset 'ascii))
938 (setq mail-parse-mule-charset
939 (or (car (last (assq mail-parse-charset
940 mm-mime-mule-charset-alist)))
941 ;; default
942 'latin-iso8859-1)))
943 mail-parse-mule-charset)))
944
945 (defun mm-charset-after (&optional pos)
946 "Return charset of a character in current buffer at position POS.
947 If POS is nil, it defauls to the current point.
948 If POS is out of range, the value is nil.
949 If the charset is `composition', return the actual one."
950 (let ((char (char-after pos)) charset)
951 (if (< (mm-char-int char) 128)
952 (setq charset 'ascii)
953 ;; charset-after is fake in some Emacsen.
954 (setq charset (and (fboundp 'char-charset) (char-charset char)))
955 (if (eq charset 'composition) ; Mule 4
956 (let ((p (or pos (point))))
957 (cadr (find-charset-region p (1+ p))))
958 (if (and charset (not (memq charset '(ascii eight-bit-control
959 eight-bit-graphic))))
960 charset
961 (mm-guess-charset))))))
962
963 (defun mm-mime-charset (charset)
964 "Return the MIME charset corresponding to the given Mule CHARSET."
965 (if (eq charset 'unknown)
966 (error "The message contains non-printable characters, please use attachment"))
967 (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
968 (or
969 (and (mm-preferred-coding-system charset)
970 (or (coding-system-get
971 (mm-preferred-coding-system charset) :mime-charset)
972 (coding-system-get
973 (mm-preferred-coding-system charset) 'mime-charset)))
974 (and (eq charset 'ascii)
975 'us-ascii)
976 (mm-preferred-coding-system charset)
977 (mm-mule-charset-to-mime-charset charset))
978 ;; This is for XEmacs.
979 (mm-mule-charset-to-mime-charset charset)))
980
981 (if (fboundp 'delete-dups)
982 (defalias 'mm-delete-duplicates 'delete-dups)
983 (defun mm-delete-duplicates (list)
984 "Destructively remove `equal' duplicates from LIST.
985 Store the result in LIST and return it. LIST must be a proper list.
986 Of several `equal' occurrences of an element in LIST, the first
987 one is kept.
988
989 This is a compatibility function for Emacsen without `delete-dups'."
990 ;; Code from `subr.el' in Emacs 22:
991 (let ((tail list))
992 (while tail
993 (setcdr tail (delete (car tail) (cdr tail)))
994 (setq tail (cdr tail))))
995 list))
996
997 ;; Fixme: This is used in places when it should be testing the
998 ;; default multibyteness. See mm-default-multibyte-p.
999 (eval-and-compile
1000 (if (and (not (featurep 'xemacs))
1001 (boundp 'enable-multibyte-characters))
1002 (defun mm-multibyte-p ()
1003 "Non-nil if multibyte is enabled in the current buffer."
1004 enable-multibyte-characters)
1005 (defun mm-multibyte-p () (featurep 'mule))))
1006
1007 (defun mm-default-multibyte-p ()
1008 "Return non-nil if the session is multibyte.
1009 This affects whether coding conversion should be attempted generally."
1010 (if (featurep 'mule)
1011 (if (boundp 'enable-multibyte-characters)
1012 (default-value 'enable-multibyte-characters)
1013 t)))
1014
1015 (defun mm-iso-8859-x-to-15-region (&optional b e)
1016 (if (fboundp 'char-charset)
1017 (let (charset item c inconvertible)
1018 (save-restriction
1019 (if e (narrow-to-region b e))
1020 (goto-char (point-min))
1021 (skip-chars-forward "\0-\177")
1022 (while (not (eobp))
1023 (cond
1024 ((not (setq item (assq (char-charset (setq c (char-after)))
1025 mm-iso-8859-x-to-15-table)))
1026 (forward-char))
1027 ((memq c (cdr (cdr item)))
1028 (setq inconvertible t)
1029 (forward-char))
1030 (t
1031 (insert-before-markers (prog1 (+ c (car (cdr item)))
1032 (delete-char 1)))))
1033 (skip-chars-forward "\0-\177")))
1034 (not inconvertible))))
1035
1036 (defun mm-sort-coding-systems-predicate (a b)
1037 (let ((priorities
1038 (mapcar (lambda (cs)
1039 ;; Note: invalid entries are dropped silently
1040 (and (setq cs (mm-coding-system-p cs))
1041 (coding-system-base cs)))
1042 mm-coding-system-priorities)))
1043 (and (setq a (mm-coding-system-p a))
1044 (if (setq b (mm-coding-system-p b))
1045 (> (length (memq (coding-system-base a) priorities))
1046 (length (memq (coding-system-base b) priorities)))
1047 t))))
1048
1049 (eval-when-compile
1050 (autoload 'latin-unity-massage-name "latin-unity")
1051 (autoload 'latin-unity-maybe-remap "latin-unity")
1052 (autoload 'latin-unity-representations-feasible-region "latin-unity")
1053 (autoload 'latin-unity-representations-present-region "latin-unity"))
1054
1055 (defvar latin-unity-coding-systems)
1056 (defvar latin-unity-ucs-list)
1057
1058 (defun mm-xemacs-find-mime-charset-1 (begin end)
1059 "Determine which MIME charset to use to send region as message.
1060 This uses the XEmacs-specific latin-unity package to better handle the
1061 case where identical characters from diverse ISO-8859-? character sets
1062 can be encoded using a single one of the corresponding coding systems.
1063
1064 It treats `mm-coding-system-priorities' as the list of preferred
1065 coding systems; a useful example setting for this list in Western
1066 Europe would be '(iso-8859-1 iso-8859-15 utf-8), which would default
1067 to the very standard Latin 1 coding system, and only move to coding
1068 systems that are less supported as is necessary to encode the
1069 characters that exist in the buffer.
1070
1071 Latin Unity doesn't know about those non-ASCII Roman characters that
1072 are available in various East Asian character sets. As such, its
1073 behavior if you have a JIS 0212 LATIN SMALL LETTER A WITH ACUTE in a
1074 buffer and it can otherwise be encoded as Latin 1, won't be ideal.
1075 But this is very much a corner case, so don't worry about it."
1076 (let ((systems mm-coding-system-priorities) csets psets curset)
1077
1078 ;; Load the Latin Unity library, if available.
1079 (when (and (not (featurep 'latin-unity)) (locate-library "latin-unity"))
1080 (require 'latin-unity))
1081
1082 ;; Now, can we use it?
1083 (if (featurep 'latin-unity)
1084 (progn
1085 (setq csets (latin-unity-representations-feasible-region begin end)
1086 psets (latin-unity-representations-present-region begin end))
1087
1088 (catch 'done
1089
1090 ;; Pass back the first coding system in the preferred list
1091 ;; that can encode the whole region.
1092 (dolist (curset systems)
1093 (setq curset (latin-unity-massage-name 'buffer-default curset))
1094
1095 ;; If the coding system is a universal coding system, then
1096 ;; it can certainly encode all the characters in the region.
1097 (if (memq curset latin-unity-ucs-list)
1098 (throw 'done (list curset)))
1099
1100 ;; If a coding system isn't universal, and isn't in
1101 ;; the list that latin unity knows about, we can't
1102 ;; decide whether to use it here. Leave that until later
1103 ;; in `mm-find-mime-charset-region' function, whence we
1104 ;; have been called.
1105 (unless (memq curset latin-unity-coding-systems)
1106 (throw 'done nil))
1107
1108 ;; Right, we know about this coding system, and it may
1109 ;; conceivably be able to encode all the characters in
1110 ;; the region.
1111 (if (latin-unity-maybe-remap begin end curset csets psets t)
1112 (throw 'done (list curset))))
1113
1114 ;; Can't encode using anything from the
1115 ;; `mm-coding-system-priorities' list.
1116 ;; Leave `mm-find-mime-charset' to do most of the work.
1117 nil))
1118
1119 ;; Right, latin unity isn't available; let `mm-find-charset-region'
1120 ;; take its default action, which equally applies to GNU Emacs.
1121 nil)))
1122
1123 (defmacro mm-xemacs-find-mime-charset (begin end)
1124 (when (featurep 'xemacs)
1125 `(and (featurep 'mule) (mm-xemacs-find-mime-charset-1 ,begin ,end))))
1126
1127 (declare-function mm-delete-duplicates "mm-util" (list))
1128
1129 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
1130 "Return the MIME charsets needed to encode the region between B and E.
1131 nil means ASCII, a single-element list represents an appropriate MIME
1132 charset, and a longer list means no appropriate charset."
1133 (let (charsets)
1134 ;; The return possibilities of this function are a mess...
1135 (or (and (mm-multibyte-p)
1136 mm-use-find-coding-systems-region
1137 ;; Find the mime-charset of the most preferred coding
1138 ;; system that has one.
1139 (let ((systems (find-coding-systems-region b e)))
1140 (when mm-coding-system-priorities
1141 (setq systems
1142 (sort systems 'mm-sort-coding-systems-predicate)))
1143 (setq systems (delq 'compound-text systems))
1144 (unless (equal systems '(undecided))
1145 (while systems
1146 (let* ((head (pop systems))
1147 (cs (or (coding-system-get head :mime-charset)
1148 (coding-system-get head 'mime-charset))))
1149 ;; The mime-charset (`x-ctext') of
1150 ;; `compound-text' is not in the IANA list. We
1151 ;; shouldn't normally use anything here with a
1152 ;; mime-charset having an `x-' prefix.
1153 ;; Fixme: Allow this to be overridden, since
1154 ;; there is existing use of x-ctext.
1155 ;; Also people apparently need the coding system
1156 ;; `iso-2022-jp-3' (which Mule-UCS defines with
1157 ;; mime-charset, though it's not valid).
1158 (if (and cs
1159 (not (string-match "^[Xx]-" (symbol-name cs)))
1160 ;; UTF-16 of any variety is invalid for
1161 ;; text parts and, unfortunately, has
1162 ;; mime-charset defined both in Mule-UCS
1163 ;; and versions of Emacs. (The name
1164 ;; might be `mule-utf-16...' or
1165 ;; `utf-16...'.)
1166 (not (string-match "utf-16" (symbol-name cs))))
1167 (setq systems nil
1168 charsets (list cs))))))
1169 charsets))
1170 ;; If we're XEmacs, and some coding system is appropriate,
1171 ;; mm-xemacs-find-mime-charset will return an appropriate list.
1172 ;; Otherwise, we'll get nil, and the next setq will get invoked.
1173 (setq charsets (mm-xemacs-find-mime-charset b e))
1174
1175 ;; Fixme: won't work for unibyte Emacs 23:
1176
1177 ;; We're not multibyte, or a single coding system won't cover it.
1178 (setq charsets
1179 (mm-delete-duplicates
1180 (mapcar 'mm-mime-charset
1181 (delq 'ascii
1182 (mm-find-charset-region b e))))))
1183 (if (and (> (length charsets) 1)
1184 (memq 'iso-8859-15 charsets)
1185 (memq 'iso-8859-15 hack-charsets)
1186 (save-excursion (mm-iso-8859-x-to-15-region b e)))
1187 (dolist (x mm-iso-8859-15-compatible)
1188 (setq charsets (delq (car x) charsets))))
1189 (if (and (memq 'iso-2022-jp-2 charsets)
1190 (memq 'iso-2022-jp-2 hack-charsets))
1191 (setq charsets (delq 'iso-2022-jp charsets)))
1192 ;; Attempt to reduce the number of charsets if utf-8 is available.
1193 (if (and (featurep 'xemacs)
1194 (> (length charsets) 1)
1195 (mm-coding-system-p 'utf-8))
1196 (let ((mm-coding-system-priorities
1197 (cons 'utf-8 mm-coding-system-priorities)))
1198 (setq charsets
1199 (mm-delete-duplicates
1200 (mapcar 'mm-mime-charset
1201 (delq 'ascii
1202 (mm-find-charset-region b e)))))))
1203 charsets))
1204
1205 (defmacro mm-with-unibyte-buffer (&rest forms)
1206 "Create a temporary buffer, and evaluate FORMS there like `progn'.
1207 Use unibyte mode for this."
1208 `(with-temp-buffer
1209 (mm-disable-multibyte)
1210 ,@forms))
1211 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
1212 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
1213
1214 (defmacro mm-with-multibyte-buffer (&rest forms)
1215 "Create a temporary buffer, and evaluate FORMS there like `progn'.
1216 Use multibyte mode for this."
1217 `(with-temp-buffer
1218 (mm-enable-multibyte)
1219 ,@forms))
1220 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
1221 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
1222
1223 (defmacro mm-with-unibyte-current-buffer (&rest forms)
1224 "Evaluate FORMS with current buffer temporarily made unibyte.
1225 Equivalent to `progn' in XEmacs.
1226
1227 Note: We recommend not using this macro any more; there should be
1228 better ways to do a similar thing. The previous version of this macro
1229 bound the default value of `enable-multibyte-characters' to nil while
1230 evaluating FORMS but it is no longer done. So, some programs assuming
1231 it if any may malfunction."
1232 (if (featurep 'xemacs)
1233 `(progn ,@forms)
1234 (let ((multibyte (make-symbol "multibyte")))
1235 `(let ((,multibyte enable-multibyte-characters))
1236 (when ,multibyte
1237 (set-buffer-multibyte nil))
1238 (prog1
1239 (progn ,@forms)
1240 (when ,multibyte
1241 (set-buffer-multibyte t)))))))
1242 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
1243 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
1244
1245 (defun mm-find-charset-region (b e)
1246 "Return a list of Emacs charsets in the region B to E."
1247 (cond
1248 ((and (mm-multibyte-p)
1249 (fboundp 'find-charset-region))
1250 ;; Remove composition since the base charsets have been included.
1251 ;; Remove eight-bit-*, treat them as ascii.
1252 (let ((css (find-charset-region b e)))
1253 (dolist (cs
1254 '(composition eight-bit-control eight-bit-graphic control-1)
1255 css)
1256 (setq css (delq cs css)))))
1257 (t
1258 ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
1259 (save-excursion
1260 (save-restriction
1261 (narrow-to-region b e)
1262 (goto-char (point-min))
1263 (skip-chars-forward "\0-\177")
1264 (if (eobp)
1265 '(ascii)
1266 (let (charset)
1267 (setq charset
1268 (and (boundp 'current-language-environment)
1269 (car (last (assq 'charset
1270 (assoc current-language-environment
1271 language-info-alist))))))
1272 (if (eq charset 'ascii) (setq charset nil))
1273 (or charset
1274 (setq charset
1275 (car (last (assq mail-parse-charset
1276 mm-mime-mule-charset-alist)))))
1277 (list 'ascii (or charset 'latin-iso8859-1)))))))))
1278
1279 (defun mm-auto-mode-alist ()
1280 "Return an `auto-mode-alist' with only the .gz (etc) thingies."
1281 (let ((alist auto-mode-alist)
1282 out)
1283 (while alist
1284 (when (listp (cdar alist))
1285 (push (car alist) out))
1286 (pop alist))
1287 (nreverse out)))
1288
1289 (defvar mm-inhibit-file-name-handlers
1290 '(jka-compr-handler image-file-handler epa-file-handler)
1291 "A list of handlers doing (un)compression (etc) thingies.")
1292
1293 (defun mm-insert-file-contents (filename &optional visit beg end replace
1294 inhibit)
1295 "Like `insert-file-contents', but only reads in the file.
1296 A buffer may be modified in several ways after reading into the buffer due
1297 to advanced Emacs features, such as file-name-handlers, format decoding,
1298 `find-file-hooks', etc.
1299 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
1300 This function ensures that none of these modifications will take place."
1301 (letf* ((format-alist nil)
1302 (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
1303 ((default-value 'major-mode) 'fundamental-mode)
1304 (enable-local-variables nil)
1305 (after-insert-file-functions nil)
1306 (enable-local-eval nil)
1307 (inhibit-file-name-operation (if inhibit
1308 'insert-file-contents
1309 inhibit-file-name-operation))
1310 (inhibit-file-name-handlers
1311 (if inhibit
1312 (append mm-inhibit-file-name-handlers
1313 inhibit-file-name-handlers)
1314 inhibit-file-name-handlers))
1315 (ffh (if (boundp 'find-file-hook)
1316 'find-file-hook
1317 'find-file-hooks))
1318 (val (symbol-value ffh)))
1319 (set ffh nil)
1320 (unwind-protect
1321 (insert-file-contents filename visit beg end replace)
1322 (set ffh val))))
1323
1324 (defun mm-append-to-file (start end filename &optional codesys inhibit)
1325 "Append the contents of the region to the end of file FILENAME.
1326 When called from a function, expects three arguments,
1327 START, END and FILENAME. START and END are buffer positions
1328 saying what text to write.
1329 Optional fourth argument specifies the coding system to use when
1330 encoding the file.
1331 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1332 (let ((coding-system-for-write
1333 (or codesys mm-text-coding-system-for-write
1334 mm-text-coding-system))
1335 (inhibit-file-name-operation (if inhibit
1336 'append-to-file
1337 inhibit-file-name-operation))
1338 (inhibit-file-name-handlers
1339 (if inhibit
1340 (append mm-inhibit-file-name-handlers
1341 inhibit-file-name-handlers)
1342 inhibit-file-name-handlers)))
1343 (write-region start end filename t 'no-message)
1344 (message "Appended to %s" filename)))
1345
1346 (defun mm-write-region (start end filename &optional append visit lockname
1347 coding-system inhibit)
1348
1349 "Like `write-region'.
1350 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
1351 (let ((coding-system-for-write
1352 (or coding-system mm-text-coding-system-for-write
1353 mm-text-coding-system))
1354 (inhibit-file-name-operation (if inhibit
1355 'write-region
1356 inhibit-file-name-operation))
1357 (inhibit-file-name-handlers
1358 (if inhibit
1359 (append mm-inhibit-file-name-handlers
1360 inhibit-file-name-handlers)
1361 inhibit-file-name-handlers)))
1362 (write-region start end filename append visit lockname)))
1363
1364 (autoload 'gmm-write-region "gmm-utils")
1365
1366 ;; It is not a MIME function, but some MIME functions use it.
1367 (if (and (fboundp 'make-temp-file)
1368 (ignore-errors
1369 (let ((def (symbol-function 'make-temp-file)))
1370 (and (byte-code-function-p def)
1371 (setq def (if (fboundp 'compiled-function-arglist)
1372 ;; XEmacs
1373 (eval (list 'compiled-function-arglist def))
1374 (aref def 0)))
1375 (>= (length def) 4)
1376 (eq (nth 3 def) 'suffix)))))
1377 (defalias 'mm-make-temp-file 'make-temp-file)
1378 ;; Stolen (and modified for XEmacs) from Emacs 22.
1379 (defun mm-make-temp-file (prefix &optional dir-flag suffix)
1380 "Create a temporary file.
1381 The returned file name (created by appending some random characters at the end
1382 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1383 is guaranteed to point to a newly created empty file.
1384 You can then use `write-region' to write new data into the file.
1385
1386 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1387
1388 If SUFFIX is non-nil, add that at the end of the file name."
1389 (let ((umask (default-file-modes))
1390 file)
1391 (unwind-protect
1392 (progn
1393 ;; Create temp files with strict access rights. It's easy to
1394 ;; loosen them later, whereas it's impossible to close the
1395 ;; time-window of loose permissions otherwise.
1396 (set-default-file-modes 448)
1397 (while (condition-case err
1398 (progn
1399 (setq file
1400 (make-temp-name
1401 (expand-file-name
1402 prefix
1403 (if (fboundp 'temp-directory)
1404 ;; XEmacs
1405 (temp-directory)
1406 temporary-file-directory))))
1407 (if suffix
1408 (setq file (concat file suffix)))
1409 (if dir-flag
1410 (make-directory file)
1411 ;; NOTE: This is unsafe if Emacs 20
1412 ;; users and XEmacs users don't use
1413 ;; a secure temp directory.
1414 (gmm-write-region "" nil file nil 'silent
1415 nil 'excl))
1416 nil)
1417 (file-already-exists t)
1418 ;; The XEmacs version of `make-directory' issues
1419 ;; `file-error'.
1420 (file-error (or (and (featurep 'xemacs)
1421 (file-exists-p file))
1422 (signal (car err) (cdr err)))))
1423 ;; the file was somehow created by someone else between
1424 ;; `make-temp-name' and `write-region', let's try again.
1425 nil)
1426 file)
1427 ;; Reset the umask.
1428 (set-default-file-modes umask)))))
1429
1430 (defvar mm-image-load-path-cache nil)
1431
1432 (defun mm-image-load-path (&optional package)
1433 (if (and mm-image-load-path-cache
1434 (equal load-path (car mm-image-load-path-cache)))
1435 (cdr mm-image-load-path-cache)
1436 (let (dir result)
1437 (dolist (path load-path)
1438 (when (and path
1439 (file-directory-p
1440 (setq dir (concat (file-name-directory
1441 (directory-file-name path))
1442 "etc/images/" (or package "gnus/")))))
1443 (push dir result)))
1444 (setq result (nreverse result)
1445 mm-image-load-path-cache (cons load-path result))
1446 result)))
1447
1448 ;; Fixme: This doesn't look useful where it's used.
1449 (if (fboundp 'detect-coding-region)
1450 (defun mm-detect-coding-region (start end)
1451 "Like `detect-coding-region' except returning the best one."
1452 (let ((coding-systems
1453 (detect-coding-region start end)))
1454 (or (car-safe coding-systems)
1455 coding-systems)))
1456 (defun mm-detect-coding-region (start end)
1457 (let ((point (point)))
1458 (goto-char start)
1459 (skip-chars-forward "\0-\177" end)
1460 (prog1
1461 (if (eq (point) end) 'ascii (mm-guess-charset))
1462 (goto-char point)))))
1463
1464 (declare-function mm-detect-coding-region "mm-util" (start end))
1465
1466 (if (fboundp 'coding-system-get)
1467 (defun mm-detect-mime-charset-region (start end)
1468 "Detect MIME charset of the text in the region between START and END."
1469 (let ((cs (mm-detect-coding-region start end)))
1470 (or (coding-system-get cs :mime-charset)
1471 (coding-system-get cs 'mime-charset))))
1472 (defun mm-detect-mime-charset-region (start end)
1473 "Detect MIME charset of the text in the region between START and END."
1474 (let ((cs (mm-detect-coding-region start end)))
1475 cs)))
1476
1477 (eval-when-compile
1478 (unless (fboundp 'coding-system-to-mime-charset)
1479 (defalias 'coding-system-to-mime-charset 'ignore)))
1480
1481 (defun mm-coding-system-to-mime-charset (coding-system)
1482 "Return the MIME charset corresponding to CODING-SYSTEM.
1483 To make this function work with XEmacs, the APEL package is required."
1484 (when coding-system
1485 (or (and (fboundp 'coding-system-get)
1486 (or (coding-system-get coding-system :mime-charset)
1487 (coding-system-get coding-system 'mime-charset)))
1488 (and (featurep 'xemacs)
1489 (or (and (fboundp 'coding-system-to-mime-charset)
1490 (not (eq (symbol-function 'coding-system-to-mime-charset)
1491 'ignore)))
1492 (and (condition-case nil
1493 (require 'mcharset)
1494 (error nil))
1495 (fboundp 'coding-system-to-mime-charset)))
1496 (coding-system-to-mime-charset coding-system)))))
1497
1498 (eval-when-compile
1499 (require 'jka-compr))
1500
1501 (defun mm-decompress-buffer (filename &optional inplace force)
1502 "Decompress buffer's contents, depending on jka-compr.
1503 Only when FORCE is t or `auto-compression-mode' is enabled and FILENAME
1504 agrees with `jka-compr-compression-info-list', decompression is done.
1505 Signal an error if FORCE is neither nil nor t and compressed data are
1506 not decompressed because `auto-compression-mode' is disabled.
1507 If INPLACE is nil, return decompressed data or nil without modifying
1508 the buffer. Otherwise, replace the buffer's contents with the
1509 decompressed data. The buffer's multibyteness must be turned off."
1510 (when (and filename
1511 (if force
1512 (prog1 t (require 'jka-compr))
1513 (and (fboundp 'jka-compr-installed-p)
1514 (jka-compr-installed-p))))
1515 (let ((info (jka-compr-get-compression-info filename)))
1516 (when info
1517 (unless (or (memq force (list nil t))
1518 (jka-compr-installed-p))
1519 (error ""))
1520 (let ((prog (jka-compr-info-uncompress-program info))
1521 (args (jka-compr-info-uncompress-args info))
1522 (msg (format "%s %s..."
1523 (jka-compr-info-uncompress-message info)
1524 filename))
1525 (err-file (jka-compr-make-temp-name))
1526 (cur (current-buffer))
1527 (coding-system-for-read mm-binary-coding-system)
1528 (coding-system-for-write mm-binary-coding-system)
1529 retval err-msg)
1530 (message "%s" msg)
1531 (mm-with-unibyte-buffer
1532 (insert-buffer-substring cur)
1533 (condition-case err
1534 (progn
1535 (unless (memq (apply 'call-process-region
1536 (point-min) (point-max)
1537 prog t (list t err-file) nil args)
1538 jka-compr-acceptable-retval-list)
1539 (erase-buffer)
1540 (insert (mapconcat 'identity
1541 (split-string
1542 (prog2
1543 (insert-file-contents err-file)
1544 (buffer-string)
1545 (erase-buffer)) t)
1546 " ")
1547 "\n")
1548 (setq err-msg
1549 (format "Error while executing \"%s %s < %s\""
1550 prog (mapconcat 'identity args " ")
1551 filename)))
1552 (setq retval (buffer-string)))
1553 (error
1554 (setq err-msg (error-message-string err)))))
1555 (when (file-exists-p err-file)
1556 (ignore-errors (delete-file err-file)))
1557 (when inplace
1558 (unless err-msg
1559 (delete-region (point-min) (point-max))
1560 (insert retval))
1561 (setq retval nil))
1562 (message "%s" (or err-msg (concat msg "done")))
1563 retval)))))
1564
1565 (eval-when-compile
1566 (unless (fboundp 'coding-system-name)
1567 (defalias 'coding-system-name 'ignore))
1568 (unless (fboundp 'find-file-coding-system-for-read-from-filename)
1569 (defalias 'find-file-coding-system-for-read-from-filename 'ignore))
1570 (unless (fboundp 'find-operation-coding-system)
1571 (defalias 'find-operation-coding-system 'ignore)))
1572
1573 (defun mm-find-buffer-file-coding-system (&optional filename)
1574 "Find coding system used to decode the contents of the current buffer.
1575 This function looks for the coding system magic cookie or examines the
1576 coding system specified by `file-coding-system-alist' being associated
1577 with FILENAME which defaults to `buffer-file-name'. Data compressed by
1578 gzip, bzip2, etc. are allowed."
1579 (unless filename
1580 (setq filename buffer-file-name))
1581 (save-excursion
1582 (let ((decomp (unless ;; No worth to examine charset of tar files.
1583 (and filename
1584 (string-match
1585 "\\.\\(?:tar\\.[^.]+\\|tbz\\|tgz\\)\\'"
1586 filename))
1587 (mm-decompress-buffer filename nil t))))
1588 (when decomp
1589 (set-buffer (generate-new-buffer " *temp*"))
1590 (mm-disable-multibyte)
1591 (insert decomp)
1592 (setq filename (file-name-sans-extension filename)))
1593 (goto-char (point-min))
1594 (prog1
1595 (cond
1596 ((boundp 'set-auto-coding-function) ;; Emacs
1597 (if filename
1598 (or (funcall (symbol-value 'set-auto-coding-function)
1599 filename (- (point-max) (point-min)))
1600 (car (find-operation-coding-system 'insert-file-contents
1601 filename)))
1602 (let (auto-coding-alist)
1603 (condition-case nil
1604 (funcall (symbol-value 'set-auto-coding-function)
1605 nil (- (point-max) (point-min)))
1606 (error nil)))))
1607 ((and (featurep 'xemacs) (featurep 'file-coding)) ;; XEmacs
1608 (let ((case-fold-search t)
1609 (end (point-at-eol))
1610 codesys start)
1611 (or
1612 (and (re-search-forward "-\\*-+[\t ]*" end t)
1613 (progn
1614 (setq start (match-end 0))
1615 (re-search-forward "[\t ]*-+\\*-" end t))
1616 (progn
1617 (setq end (match-beginning 0))
1618 (goto-char start)
1619 (or (looking-at "coding:[\t ]*\\([^\t ;]+\\)")
1620 (re-search-forward
1621 "[\t ;]+coding:[\t ]*\\([^\t ;]+\\)"
1622 end t)))
1623 (find-coding-system (setq codesys
1624 (intern (match-string 1))))
1625 codesys)
1626 (and (re-search-forward "^[\t ]*;+[\t ]*Local[\t ]+Variables:"
1627 nil t)
1628 (progn
1629 (setq start (match-end 0))
1630 (re-search-forward "^[\t ]*;+[\t ]*End:" nil t))
1631 (progn
1632 (setq end (match-beginning 0))
1633 (goto-char start)
1634 (re-search-forward
1635 "^[\t ]*;+[\t ]*coding:[\t ]*\\([^\t\n\r ]+\\)"
1636 end t))
1637 (find-coding-system (setq codesys
1638 (intern (match-string 1))))
1639 codesys)
1640 (and (progn
1641 (goto-char (point-min))
1642 (setq case-fold-search nil)
1643 (re-search-forward "^;;;coding system: "
1644 ;;(+ (point-min) 3000) t))
1645 nil t))
1646 (looking-at "[^\t\n\r ]+")
1647 (find-coding-system
1648 (setq codesys (intern (match-string 0))))
1649 codesys)
1650 (and filename
1651 (setq codesys
1652 (find-file-coding-system-for-read-from-filename
1653 filename))
1654 (coding-system-name (coding-system-base codesys)))))))
1655 (when decomp
1656 (kill-buffer (current-buffer)))))))
1657
1658 (provide 'mm-util)
1659
1660 ;;; mm-util.el ends here