1 ;;; mm-util.el --- Utility functions for Mule and low level things
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006 Free Software Foundation, Inc.
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
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 2, or (at your option)
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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
29 (eval-when-compile (require 'cl))
35 (let ((nfunc (intern (format "mm-%s" (car elem)))))
36 (if (fboundp (car elem))
37 (defalias nfunc (car elem))
38 (defalias nfunc (cdr elem)))))
39 '((decode-coding-string . (lambda (s a) s))
40 (encode-coding-string . (lambda (s a) s))
41 (encode-coding-region . ignore)
42 (coding-system-list . ignore)
43 (decode-coding-region . ignore)
45 (coding-system-equal . equal)
46 (annotationp . ignore)
47 (set-buffer-file-coding-system . ignore)
49 . (lambda (charset int)
57 (mapcar (lambda (e) (list (symbol-name (car e))))
58 mm-mime-mule-charset-alist)
61 . (lambda (from to string &optional inplace)
62 ;; stolen (and renamed) from nnheader.el
63 "Replace characters in STRING from FROM to TO.
64 Unless optional argument INPLACE is non-nil, return a new string."
65 (let ((string (if inplace string (copy-sequence string)))
68 ;; Replace all occurrences of FROM with TO.
70 (when (= (aref string idx) from)
74 (string-as-unibyte . identity)
75 (string-make-unibyte . identity)
76 ;; string-as-multibyte often doesn't really do what you think it does.
78 ;; (aref (string-as-multibyte "\201") 0) -> 129 (aka ?\201)
79 ;; (aref (string-as-multibyte "\300") 0) -> 192 (aka ?\300)
80 ;; (aref (string-as-multibyte "\300\201") 0) -> 192 (aka ?\300)
81 ;; (aref (string-as-multibyte "\300\201") 1) -> 129 (aka ?\201)
83 ;; (aref (string-as-multibyte "\201\300") 0) -> 2240
84 ;; (aref (string-as-multibyte "\201\300") 1) -> <error>
85 ;; Better use string-to-multibyte or encode-coding-string.
86 ;; If you really need string-as-multibyte somewhere it's usually
87 ;; because you're using the internal emacs-mule representation (maybe
88 ;; because you're using string-as-unibyte somewhere), which is
89 ;; generally a problem in itself.
90 ;; Here is an approximate equivalence table to help think about it:
91 ;; (string-as-multibyte s) ~= (decode-coding-string s 'emacs-mule)
92 ;; (string-to-multibyte s) ~= (decode-coding-string s 'binary)
93 ;; (string-make-multibyte s) ~= (decode-coding-string s locale-coding-system)
94 (string-as-multibyte . identity)
97 "Return a multibyte string with the same individual chars as string."
99 (lambda (ch) (mm-string-as-multibyte (char-to-string ch)))
101 (multibyte-string-p . ignore)
102 (insert-byte . insert-char)
103 (multibyte-char-to-unibyte . identity))))
107 ((fboundp 'replace-in-string)
108 (defalias 'mm-replace-in-string 'replace-in-string))
109 ((fboundp 'replace-regexp-in-string)
110 (defun mm-replace-in-string (string regexp newtext &optional literal)
111 "Replace all matches for REGEXP with NEWTEXT in STRING.
112 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
113 string containing the replacements.
115 This is a compatibility function for different Emacsen."
116 (replace-regexp-in-string regexp newtext string nil literal)))
118 (defun mm-replace-in-string (string regexp newtext &optional literal)
119 "Replace all matches for REGEXP with NEWTEXT in STRING.
120 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
121 string containing the replacements.
123 This is a compatibility function for different Emacsen."
124 (let ((start 0) tail)
125 (while (string-match regexp string start)
126 (setq tail (- (length string) (match-end 0)))
127 (setq string (replace-match newtext nil literal string))
128 (setq start (- (length string) tail))))
132 (defalias 'mm-char-or-char-int-p
134 ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
135 ((fboundp 'char-valid-p) 'char-valid-p)
138 ;; Fixme: This seems always to be used to read a MIME charset, so it
139 ;; should be re-named and fixed (in Emacs) to offer completion only on
140 ;; proper charset names (base coding systems which have a
141 ;; mime-charset defined). XEmacs doesn't believe in mime-charset;
143 ;; `(or (coding-system-get 'iso-8859-1 'mime-charset)
144 ;; (coding-system-get 'iso-8859-1 :mime-charset))'
145 ;; Actually, there should be an `mm-coding-system-mime-charset'.
147 (defalias 'mm-read-coding-system
149 ((fboundp 'read-coding-system)
150 (if (and (featurep 'xemacs)
151 (<= (string-to-number emacs-version) 21.1))
152 (lambda (prompt &optional default-coding-system)
153 (read-coding-system prompt))
154 'read-coding-system))
155 (t (lambda (prompt &optional default-coding-system)
156 "Prompt the user for a coding system."
158 prompt (mapcar (lambda (s) (list (symbol-name (car s))))
159 mm-mime-mule-charset-alist)))))))
161 (defvar mm-coding-system-list nil)
162 (defun mm-get-coding-system-list ()
163 "Get the coding system list."
164 (or mm-coding-system-list
165 (setq mm-coding-system-list (mm-coding-system-list))))
167 (defun mm-coding-system-p (cs)
168 "Return non-nil if CS is a symbol naming a coding system.
169 In XEmacs, also return non-nil if CS is a coding system object.
170 If CS is available, return CS itself in Emacs, and return a coding
171 system object in XEmacs."
172 (if (fboundp 'find-coding-system)
173 (and cs (find-coding-system cs))
174 (if (fboundp 'coding-system-p)
175 (when (coding-system-p cs)
178 (car (memq cs (mm-get-coding-system-list))))))
180 (defun mm-codepage-setup (number &optional alias)
181 "Create a coding system cpNUMBER.
182 The coding system is created using `codepage-setup'. If ALIAS is
183 non-nil, an alias is created and added to
184 `mm-charset-synonym-alist'. If ALIAS is a string, it's used as
185 the alias. Else windows-NUMBER is used."
187 (let ((completion-ignore-case t)
188 (candidates (cp-supported-codepages)))
189 (list (completing-read "Setup DOS Codepage: (default 437) " candidates
190 nil t nil nil "437"))))
192 (setq alias (if (stringp alias)
194 (intern (format "windows-%s" number)))))
195 (let* ((cp (intern (format "cp%s" number))))
196 (unless (mm-coding-system-p cp)
197 (codepage-setup number))
199 ;; Don't add alias if setup of cp failed.
200 (mm-coding-system-p cp))
201 (add-to-list 'mm-charset-synonym-alist (cons alias cp)))))
203 (defvar mm-charset-synonym-alist
205 ;; Not in XEmacs, but it's not a proper MIME charset anyhow.
206 ,@(unless (mm-coding-system-p 'x-ctext)
207 '((x-ctext . ctext)))
208 ;; ISO-8859-15 is very similar to ISO-8859-1. But it's _different_!
209 ,@(unless (mm-coding-system-p 'iso-8859-15)
210 '((iso-8859-15 . iso-8859-1)))
211 ;; BIG-5HKSCS is similar to, but different than, BIG-5.
212 ,@(unless (mm-coding-system-p 'big5-hkscs)
213 '((big5-hkscs . big5)))
214 ;; Windows-1252 is actually a superset of Latin-1. See also
215 ;; `gnus-article-dumbquotes-map'.
216 ,@(unless (mm-coding-system-p 'windows-1252)
217 (if (mm-coding-system-p 'cp1252)
218 '((windows-1252 . cp1252))
219 '((windows-1252 . iso-8859-1))))
220 ;; Windows-1250 is a variant of Latin-2 heavily used by Microsoft
221 ;; Outlook users in Czech republic. Use this to allow reading of their
222 ;; e-mails. cp1250 should be defined by M-x codepage-setup.
223 ,@(if (and (not (mm-coding-system-p 'windows-1250))
224 (mm-coding-system-p 'cp1250))
225 '((windows-1250 . cp1250)))
226 ;; A Microsoft misunderstanding.
227 ,@(if (and (not (mm-coding-system-p 'unicode))
228 (mm-coding-system-p 'utf-16-le))
229 '((unicode . utf-16-le)))
230 ;; A Microsoft misunderstanding.
231 ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
232 (if (mm-coding-system-p 'cp949)
233 '((ks_c_5601-1987 . cp949))
234 '((ks_c_5601-1987 . euc-kr))))
236 "A mapping from unknown or invalid charset names to the real charset names.")
238 (defcustom mm-charset-override-alist
239 `((iso-8859-1 . windows-1252))
240 "A mapping from undesired charset names to their replacement.
242 You may add pairs like (iso-8859-1 . windows-1252) here,
243 i.e. treat iso-8859-1 as windows-1252. windows-1252 is a
244 superset of iso-8859-1."
245 :type '(list (set :inline t
246 (const (iso-8859-1 . windows-1252))
247 (const (undecided . windows-1252)))
250 (cons (symbol :tag "From charset")
251 (symbol :tag "To charset"))))
252 :version "23.0" ;; No Gnus
255 (defcustom mm-charset-eval-alist
256 (if (featurep 'xemacs)
257 nil ;; I don't know what would be useful for XEmacs.
258 '(;; Emacs 21 offers 1250 1251 1253 1257. Emacs 22 provides autoloads for
259 ;; 1250-1258 (i.e. `mm-codepage-setup' does nothing).
260 (windows-1250 . (mm-codepage-setup 1250 t))
261 (windows-1251 . (mm-codepage-setup 1251 t))
262 (windows-1253 . (mm-codepage-setup 1253 t))
263 (windows-1257 . (mm-codepage-setup 1257 t))))
264 "An alist of (CHARSET . FORM) pairs.
265 If an article is encoded in an unknown CHARSET, FORM is
266 evaluated. This allows to load additional libraries providing
267 charsets on demand. If supported by your Emacs version, you
268 could use `autoload-coding-system' here."
269 :version "23.0" ;; No Gnus
270 :type '(list (set :inline t
271 (const (windows-1250 . (mm-codepage-setup 1250 t)))
272 (const (windows-1251 . (mm-codepage-setup 1251 t)))
273 (const (windows-1253 . (mm-codepage-setup 1253 t)))
274 (const (windows-1257 . (mm-codepage-setup 1257 t)))
275 (const (cp850 . (mm-codepage-setup 850 nil))))
278 (cons (symbol :tag "charset")
279 (symbol :tag "form"))))
282 (defvar mm-binary-coding-system
284 ((mm-coding-system-p 'binary) 'binary)
285 ((mm-coding-system-p 'no-conversion) 'no-conversion)
287 "100% binary coding system.")
289 (defvar mm-text-coding-system
290 (or (if (memq system-type '(windows-nt ms-dos ms-windows))
291 (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
292 (and (mm-coding-system-p 'raw-text) 'raw-text))
293 mm-binary-coding-system)
294 "Text-safe coding system (For removing ^M).")
296 (defvar mm-text-coding-system-for-write nil
297 "Text coding system for write.")
299 (defvar mm-auto-save-coding-system
301 ((mm-coding-system-p 'utf-8-emacs) ; Mule 7
302 (if (memq system-type '(windows-nt ms-dos ms-windows))
303 (if (mm-coding-system-p 'utf-8-emacs-dos)
304 'utf-8-emacs-dos mm-binary-coding-system)
306 ((mm-coding-system-p 'emacs-mule)
307 (if (memq system-type '(windows-nt ms-dos ms-windows))
308 (if (mm-coding-system-p 'emacs-mule-dos)
309 'emacs-mule-dos mm-binary-coding-system)
311 ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
312 (t mm-binary-coding-system))
313 "Coding system of auto save file.")
315 (defvar mm-universal-coding-system mm-auto-save-coding-system
316 "The universal coding system.")
318 ;; Fixme: some of the cars here aren't valid MIME charsets. That
319 ;; should only matter with XEmacs, though.
320 (defvar mm-mime-mule-charset-alist
322 (iso-8859-1 latin-iso8859-1)
323 (iso-8859-2 latin-iso8859-2)
324 (iso-8859-3 latin-iso8859-3)
325 (iso-8859-4 latin-iso8859-4)
326 (iso-8859-5 cyrillic-iso8859-5)
327 ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
328 ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
329 ;; charset is koi8-r, not iso-8859-5.
330 (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
331 (iso-8859-6 arabic-iso8859-6)
332 (iso-8859-7 greek-iso8859-7)
333 (iso-8859-8 hebrew-iso8859-8)
334 (iso-8859-9 latin-iso8859-9)
335 (iso-8859-14 latin-iso8859-14)
336 (iso-8859-15 latin-iso8859-15)
337 (viscii vietnamese-viscii-lower)
338 (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
339 (euc-kr korean-ksc5601)
340 (gb2312 chinese-gb2312)
341 (big5 chinese-big5-1 chinese-big5-2)
343 (thai-tis620 thai-tis620)
344 (windows-1251 cyrillic-iso8859-5)
345 (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
346 (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
347 latin-jisx0201 japanese-jisx0208-1978
348 chinese-gb2312 japanese-jisx0208
349 korean-ksc5601 japanese-jisx0212)
350 (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
351 latin-jisx0201 japanese-jisx0208-1978
352 chinese-gb2312 japanese-jisx0208
353 korean-ksc5601 japanese-jisx0212
354 chinese-cns11643-1 chinese-cns11643-2)
355 (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
356 cyrillic-iso8859-5 greek-iso8859-7
357 latin-jisx0201 japanese-jisx0208-1978
358 chinese-gb2312 japanese-jisx0208
359 korean-ksc5601 japanese-jisx0212
360 chinese-cns11643-1 chinese-cns11643-2
361 chinese-cns11643-3 chinese-cns11643-4
362 chinese-cns11643-5 chinese-cns11643-6
364 (iso-2022-jp-3 latin-jisx0201 japanese-jisx0208-1978 japanese-jisx0208
365 japanese-jisx0213-1 japanese-jisx0213-2)
366 (shift_jis latin-jisx0201 katakana-jisx0201 japanese-jisx0208)
367 ,(cond ((fboundp 'unicode-precedence-list)
368 (cons 'utf-8 (delq 'ascii (mapcar 'charset-name
369 (unicode-precedence-list)))))
370 ((or (not (fboundp 'charsetp)) ;; non-Mule case
371 (charsetp 'unicode-a)
372 (not (mm-coding-system-p 'mule-utf-8)))
373 '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e))
374 (t ;; If we have utf-8 we're in Mule 5+.
377 (coding-system-get 'mule-utf-8 'safe-charsets))))))
378 "Alist of MIME-charset/MULE-charsets.")
380 (defun mm-enrich-utf-8-by-mule-ucs ()
381 "Make the `utf-8' MIME charset usable by the Mule-UCS package.
382 This function will run when the `un-define' module is loaded under
383 XEmacs, and fill the `utf-8' entry in `mm-mime-mule-charset-alist'
384 with Mule charsets. It is completely useless for Emacs."
385 (when (boundp 'unicode-basic-translation-charset-order-list)
391 'unicode-basic-translation-charset-order-list))))
392 (elem (assq 'utf-8 mm-mime-mule-charset-alist)))
395 (setq mm-mime-mule-charset-alist
396 (nconc mm-mime-mule-charset-alist
397 (list (cons 'utf-8 val))))))
400 ;; Correct by construction, but should be unnecessary for Emacs:
401 (if (featurep 'xemacs)
402 (eval-after-load "un-define" '(mm-enrich-utf-8-by-mule-ucs))
403 (when (and (fboundp 'coding-system-list)
404 (fboundp 'sort-coding-systems))
405 (let ((css (sort-coding-systems (coding-system-list 'base-only)))
409 mime (or (coding-system-get cs :mime-charset); Emacs 23 (unicode)
410 (coding-system-get cs 'mime-charset)))
412 (not (eq t (setq mule
413 (coding-system-get cs 'safe-charsets))))
414 (not (assq mime alist)))
415 (push (cons mime (delq 'ascii mule)) alist)))
416 (setq mm-mime-mule-charset-alist (nreverse alist)))))
418 (defcustom mm-coding-system-priorities
419 (if (boundp 'current-language-environment)
420 (let ((lang (symbol-value 'current-language-environment)))
421 (cond ((string= lang "Japanese")
422 ;; Japanese users prefer iso-2022-jp to euc-japan or
423 ;; shift_jis, however iso-8859-1 should be used when
424 ;; there are only ASCII text and Latin-1 characters.
425 '(iso-8859-1 iso-2022-jp iso-2022-jp-2 shift_jis utf-8)))))
426 "Preferred coding systems for encoding outgoing messages.
428 More than one suitable coding system may be found for some text.
429 By default, the coding system with the highest priority is used
430 to encode outgoing messages (see `sort-coding-systems'). If this
431 variable is set, it overrides the default priority."
433 :type '(repeat (symbol :tag "Coding system"))
437 (defvar mm-use-find-coding-systems-region
438 (fboundp 'find-coding-systems-region)
439 "Use `find-coding-systems-region' to find proper coding systems.
441 Setting it to nil is useful on Emacsen supporting Unicode if sending
442 mail with multiple parts is preferred to sending a Unicode one.")
444 ;;; Internal variables:
448 (defun mm-mule-charset-to-mime-charset (charset)
449 "Return the MIME charset corresponding to the given Mule CHARSET."
450 (if (and (fboundp 'find-coding-systems-for-charsets)
451 (fboundp 'sort-coding-systems))
452 (let ((css (sort (sort-coding-systems
453 (find-coding-systems-for-charsets (list charset)))
454 'mm-sort-coding-systems-predicate))
456 (while (and (not mime)
458 (when (setq cs (pop css))
459 (setq mime (or (coding-system-get cs :mime-charset)
460 (coding-system-get cs 'mime-charset)))))
462 (let ((alist (mapcar (lambda (cs)
463 (assq cs mm-mime-mule-charset-alist))
464 (sort (mapcar 'car mm-mime-mule-charset-alist)
465 'mm-sort-coding-systems-predicate)))
468 (when (memq charset (cdar alist))
469 (setq out (caar alist)
474 (defun mm-charset-to-coding-system (charset &optional lbt
476 "Return coding-system corresponding to CHARSET.
477 CHARSET is a symbol naming a MIME charset.
478 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
479 used as the line break code type of the coding system.
481 If ALLOW-OVERRIDE is given, use `mm-charset-override-alist' to
482 map undesired charset names to their replacement. This should
483 only be used for decoding, not for encoding."
484 ;; OVERRIDE is used (only) in `mm-decode-body' and `mm-decode-string'.
485 (when (stringp charset)
486 (setq charset (intern (downcase charset))))
488 (setq charset (intern (format "%s-%s" charset lbt))))
492 ;; Running in a non-MULE environment.
493 ((or (null (mm-get-coding-system-list))
494 (not (fboundp 'coding-system-get)))
496 ;; Check override list quite early. Should only used for decoding, not for
499 (let ((cs (cdr (assq charset mm-charset-override-alist))))
500 (and cs (mm-coding-system-p cs) cs))))
502 ((eq charset 'us-ascii)
504 ;; Check to see whether we can handle this charset. (This depends
505 ;; on there being some coding system matching each `mime-charset'
506 ;; property defined, as there should be.)
507 ((and (mm-coding-system-p charset)
508 ;;; Doing this would potentially weed out incorrect charsets.
510 ;;; (eq charset (coding-system-get charset 'mime-charset))
513 ;; Eval expressions from `mm-charset-eval-alist'
514 ((let* ((el (assq charset mm-charset-eval-alist))
521 (condition-case nil (eval form) (error nil))
522 ;; (message "Failed to eval `%s'" form))
523 (mm-coding-system-p cs)
524 (message "Added charset `%s' via `mm-charset-eval-alist'" cs))
526 ;; Translate invalid charsets.
527 ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
529 (mm-coding-system-p cs)
531 ;; "Using synonym `%s' from `mm-charset-synonym-alist' for `%s'"
534 ;; Last resort: search the coding system list for entries which
535 ;; have the right mime-charset in case the canonical name isn't
536 ;; defined (though it should be).
538 ;; mm-get-coding-system-list returns a list of cs without lbt.
540 (dolist (c (mm-get-coding-system-list))
542 (eq charset (or (coding-system-get c :mime-charset)
543 (coding-system-get c 'mime-charset))))
546 ;; Warn the user about unknown charset:
547 (if (fboundp 'gnus-message)
548 (gnus-message 7 "Unknown charset: %s" charset)
549 (message "Unknown charset: %s" charset)))
552 (defsubst mm-replace-chars-in-string (string from to)
553 (mm-subst-char-in-string from to string))
556 (defvar mm-emacs-mule (and (not (featurep 'xemacs))
557 (boundp 'default-enable-multibyte-characters)
558 default-enable-multibyte-characters
559 (fboundp 'set-buffer-multibyte))
560 "True in Emacs with Mule.")
563 (defun mm-enable-multibyte ()
564 "Set the multibyte flag of the current buffer.
565 Only do this if the default value of `enable-multibyte-characters' is
566 non-nil. This is a no-op in XEmacs."
567 (set-buffer-multibyte 'to))
568 (defalias 'mm-enable-multibyte 'ignore))
571 (defun mm-disable-multibyte ()
572 "Unset the multibyte flag of in the current buffer.
573 This is a no-op in XEmacs."
574 (set-buffer-multibyte nil))
575 (defalias 'mm-disable-multibyte 'ignore)))
577 (defun mm-preferred-coding-system (charset)
578 ;; A typo in some Emacs versions.
579 (or (get-charset-property charset 'preferred-coding-system)
580 (get-charset-property charset 'prefered-coding-system)))
582 ;; Mule charsets shouldn't be used.
583 (defsubst mm-guess-charset ()
584 "Guess Mule charset from the language environment."
586 mail-parse-mule-charset ;; cached mule-charset
588 (setq mail-parse-mule-charset
589 (and (boundp 'current-language-environment)
592 (assoc current-language-environment
593 language-info-alist))))))
594 (if (or (not mail-parse-mule-charset)
595 (eq mail-parse-mule-charset 'ascii))
596 (setq mail-parse-mule-charset
597 (or (car (last (assq mail-parse-charset
598 mm-mime-mule-charset-alist)))
601 mail-parse-mule-charset)))
603 (defun mm-charset-after (&optional pos)
604 "Return charset of a character in current buffer at position POS.
605 If POS is nil, it defauls to the current point.
606 If POS is out of range, the value is nil.
607 If the charset is `composition', return the actual one."
608 (let ((char (char-after pos)) charset)
609 (if (< (mm-char-int char) 128)
610 (setq charset 'ascii)
611 ;; charset-after is fake in some Emacsen.
612 (setq charset (and (fboundp 'char-charset) (char-charset char)))
613 (if (eq charset 'composition) ; Mule 4
614 (let ((p (or pos (point))))
615 (cadr (find-charset-region p (1+ p))))
616 (if (and charset (not (memq charset '(ascii eight-bit-control
617 eight-bit-graphic))))
619 (mm-guess-charset))))))
621 (defun mm-mime-charset (charset)
622 "Return the MIME charset corresponding to the given Mule CHARSET."
623 (if (eq charset 'unknown)
624 (error "The message contains non-printable characters, please use attachment"))
625 (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
626 ;; This exists in Emacs 20.
628 (and (mm-preferred-coding-system charset)
629 (or (coding-system-get
630 (mm-preferred-coding-system charset) :mime-charset)
632 (mm-preferred-coding-system charset) 'mime-charset)))
633 (and (eq charset 'ascii)
635 (mm-preferred-coding-system charset)
636 (mm-mule-charset-to-mime-charset charset))
637 ;; This is for XEmacs.
638 (mm-mule-charset-to-mime-charset charset)))
640 (if (fboundp 'delete-dups)
641 (defalias 'mm-delete-duplicates 'delete-dups)
642 (defun mm-delete-duplicates (list)
643 "Destructively remove `equal' duplicates from LIST.
644 Store the result in LIST and return it. LIST must be a proper list.
645 Of several `equal' occurrences of an element in LIST, the first
648 This is a compatibility function for Emacsen without `delete-dups'."
649 ;; Code from `subr.el' in Emacs 22:
652 (setcdr tail (delete (car tail) (cdr tail)))
653 (setq tail (cdr tail))))
656 ;; Fixme: This is used in places when it should be testing the
657 ;; default multibyteness. See mm-default-multibyte-p.
659 (if (and (not (featurep 'xemacs))
660 (boundp 'enable-multibyte-characters))
661 (defun mm-multibyte-p ()
662 "Non-nil if multibyte is enabled in the current buffer."
663 enable-multibyte-characters)
664 (defun mm-multibyte-p () (featurep 'mule))))
666 (defun mm-default-multibyte-p ()
667 "Return non-nil if the session is multibyte.
668 This affects whether coding conversion should be attempted generally."
670 (if (boundp 'default-enable-multibyte-characters)
671 default-enable-multibyte-characters
674 (defun mm-sort-coding-systems-predicate (a b)
677 ;; Note: invalid entries are dropped silently
678 (and (setq cs (mm-coding-system-p cs))
679 (coding-system-base cs)))
680 mm-coding-system-priorities)))
681 (and (setq a (mm-coding-system-p a))
682 (if (setq b (mm-coding-system-p b))
683 (> (length (memq (coding-system-base a) priorities))
684 (length (memq (coding-system-base b) priorities)))
688 (autoload 'latin-unity-massage-name "latin-unity")
689 (autoload 'latin-unity-maybe-remap "latin-unity")
690 (autoload 'latin-unity-representations-feasible-region "latin-unity")
691 (autoload 'latin-unity-representations-present-region "latin-unity")
692 (defvar latin-unity-coding-systems)
693 (defvar latin-unity-ucs-list))
695 (defun mm-xemacs-find-mime-charset-1 (begin end)
696 "Determine which MIME charset to use to send region as message.
697 This uses the XEmacs-specific latin-unity package to better handle the
698 case where identical characters from diverse ISO-8859-? character sets
699 can be encoded using a single one of the corresponding coding systems.
701 It treats `mm-coding-system-priorities' as the list of preferred
702 coding systems; a useful example setting for this list in Western
703 Europe would be '(iso-8859-1 iso-8859-15 utf-8), which would default
704 to the very standard Latin 1 coding system, and only move to coding
705 systems that are less supported as is necessary to encode the
706 characters that exist in the buffer.
708 Latin Unity doesn't know about those non-ASCII Roman characters that
709 are available in various East Asian character sets. As such, its
710 behavior if you have a JIS 0212 LATIN SMALL LETTER A WITH ACUTE in a
711 buffer and it can otherwise be encoded as Latin 1, won't be ideal.
712 But this is very much a corner case, so don't worry about it."
713 (let ((systems mm-coding-system-priorities) csets psets curset)
715 ;; Load the Latin Unity library, if available.
716 (when (and (not (featurep 'latin-unity)) (locate-library "latin-unity"))
717 (ignore-errors (require 'latin-unity)))
719 ;; Now, can we use it?
720 (if (featurep 'latin-unity)
722 (setq csets (latin-unity-representations-feasible-region begin end)
723 psets (latin-unity-representations-present-region begin end))
727 ;; Pass back the first coding system in the preferred list
728 ;; that can encode the whole region.
729 (dolist (curset systems)
730 (setq curset (latin-unity-massage-name 'buffer-default curset))
732 ;; If the coding system is a universal coding system, then
733 ;; it can certainly encode all the characters in the region.
734 (if (memq curset latin-unity-ucs-list)
735 (throw 'done (list curset)))
737 ;; If a coding system isn't universal, and isn't in
738 ;; the list that latin unity knows about, we can't
739 ;; decide whether to use it here. Leave that until later
740 ;; in `mm-find-mime-charset-region' function, whence we
742 (unless (memq curset latin-unity-coding-systems)
745 ;; Right, we know about this coding system, and it may
746 ;; conceivably be able to encode all the characters in
748 (if (latin-unity-maybe-remap begin end curset csets psets t)
749 (throw 'done (list curset))))
751 ;; Can't encode using anything from the
752 ;; `mm-coding-system-priorities' list.
753 ;; Leave `mm-find-mime-charset' to do most of the work.
756 ;; Right, latin unity isn't available; let `mm-find-charset-region'
757 ;; take its default action, which equally applies to GNU Emacs.
760 (defmacro mm-xemacs-find-mime-charset (begin end)
761 (when (featurep 'xemacs)
762 `(and (featurep 'mule) (mm-xemacs-find-mime-charset-1 ,begin ,end))))
764 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
765 "Return the MIME charsets needed to encode the region between B and E.
766 nil means ASCII, a single-element list represents an appropriate MIME
767 charset, and a longer list means no appropriate charset."
769 ;; The return possibilities of this function are a mess...
770 (or (and (mm-multibyte-p)
771 mm-use-find-coding-systems-region
772 ;; Find the mime-charset of the most preferred coding
773 ;; system that has one.
774 (let ((systems (find-coding-systems-region b e)))
775 (when mm-coding-system-priorities
777 (sort systems 'mm-sort-coding-systems-predicate)))
778 (setq systems (delq 'compound-text systems))
779 (unless (equal systems '(undecided))
781 (let* ((head (pop systems))
782 (cs (or (coding-system-get head :mime-charset)
783 (coding-system-get head 'mime-charset))))
784 ;; The mime-charset (`x-ctext') of
785 ;; `compound-text' is not in the IANA list. We
786 ;; shouldn't normally use anything here with a
787 ;; mime-charset having an `x-' prefix.
788 ;; Fixme: Allow this to be overridden, since
789 ;; there is existing use of x-ctext.
790 ;; Also people apparently need the coding system
791 ;; `iso-2022-jp-3' (which Mule-UCS defines with
792 ;; mime-charset, though it's not valid).
794 (not (string-match "^[Xx]-" (symbol-name cs)))
795 ;; UTF-16 of any variety is invalid for
796 ;; text parts and, unfortunately, has
797 ;; mime-charset defined both in Mule-UCS
798 ;; and versions of Emacs. (The name
799 ;; might be `mule-utf-16...' or
801 (not (string-match "utf-16" (symbol-name cs))))
803 charsets (list cs))))))
805 ;; If we're XEmacs, and some coding system is appropriate,
806 ;; mm-xemacs-find-mime-charset will return an appropriate list.
807 ;; Otherwise, we'll get nil, and the next setq will get invoked.
808 (setq charsets (mm-xemacs-find-mime-charset b e))
810 ;; Fixme: won't work for unibyte Emacs 23:
812 ;; We're not multibyte, or a single coding system won't cover it.
814 (mm-delete-duplicates
815 (mapcar 'mm-mime-charset
817 (mm-find-charset-region b e))))))
820 (defmacro mm-with-unibyte-buffer (&rest forms)
821 "Create a temporary buffer, and evaluate FORMS there like `progn'.
822 Use unibyte mode for this."
823 `(let (default-enable-multibyte-characters)
824 (with-temp-buffer ,@forms)))
825 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
826 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
828 (defmacro mm-with-multibyte-buffer (&rest forms)
829 "Create a temporary buffer, and evaluate FORMS there like `progn'.
830 Use multibyte mode for this."
831 `(let ((default-enable-multibyte-characters t))
832 (with-temp-buffer ,@forms)))
833 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
834 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
836 (defmacro mm-with-unibyte-current-buffer (&rest forms)
837 "Evaluate FORMS with current buffer temporarily made unibyte.
838 Also bind `default-enable-multibyte-characters' to nil.
839 Equivalent to `progn' in XEmacs
841 NOTE: Use this macro with caution in multibyte buffers (it is not
842 worth using this macro in unibyte buffers of course). Use of
843 `(set-buffer-multibyte t)', which is run finally, is generally
844 harmful since it is likely to modify existing data in the buffer.
845 For instance, it converts \"\\300\\255\" into \"\\255\" in
847 (let ((multibyte (make-symbol "multibyte"))
848 (buffer (make-symbol "buffer")))
850 (let ((,multibyte enable-multibyte-characters)
851 (,buffer (current-buffer)))
853 (let (default-enable-multibyte-characters)
854 (set-buffer-multibyte nil)
857 (set-buffer-multibyte ,multibyte)))
858 (let (default-enable-multibyte-characters)
860 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
861 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
863 (defmacro mm-with-unibyte (&rest forms)
864 "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
865 `(let (default-enable-multibyte-characters)
867 (put 'mm-with-unibyte 'lisp-indent-function 0)
868 (put 'mm-with-unibyte 'edebug-form-spec '(body))
870 (defmacro mm-with-multibyte (&rest forms)
871 "Eval the FORMS with the default value of `enable-multibyte-characters' t."
872 `(let ((default-enable-multibyte-characters t))
874 (put 'mm-with-multibyte 'lisp-indent-function 0)
875 (put 'mm-with-multibyte 'edebug-form-spec '(body))
877 (defun mm-find-charset-region (b e)
878 "Return a list of Emacs charsets in the region B to E."
880 ((and (mm-multibyte-p)
881 (fboundp 'find-charset-region))
882 ;; Remove composition since the base charsets have been included.
883 ;; Remove eight-bit-*, treat them as ascii.
884 (let ((css (find-charset-region b e)))
885 (mapcar (lambda (cs) (setq css (delq cs css)))
886 '(composition eight-bit-control eight-bit-graphic
890 ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
893 (narrow-to-region b e)
894 (goto-char (point-min))
895 (skip-chars-forward "\0-\177")
900 (and (boundp 'current-language-environment)
901 (car (last (assq 'charset
902 (assoc current-language-environment
903 language-info-alist))))))
904 (if (eq charset 'ascii) (setq charset nil))
907 (car (last (assq mail-parse-charset
908 mm-mime-mule-charset-alist)))))
909 (list 'ascii (or charset 'latin-iso8859-1)))))))))
911 (if (fboundp 'shell-quote-argument)
912 (defalias 'mm-quote-arg 'shell-quote-argument)
913 (defun mm-quote-arg (arg)
914 "Return a version of ARG that is safe to evaluate in a shell."
915 (let ((pos 0) new-pos accum)
916 ;; *** bug: we don't handle newline characters properly
917 (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
918 (push (substring arg pos new-pos) accum)
920 (push (list (aref arg new-pos)) accum)
921 (setq pos (1+ new-pos)))
924 (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
926 (defun mm-auto-mode-alist ()
927 "Return an `auto-mode-alist' with only the .gz (etc) thingies."
928 (let ((alist auto-mode-alist)
931 (when (listp (cdar alist))
932 (push (car alist) out))
936 (defvar mm-inhibit-file-name-handlers
937 '(jka-compr-handler image-file-handler)
938 "A list of handlers doing (un)compression (etc) thingies.")
940 (defun mm-insert-file-contents (filename &optional visit beg end replace
942 "Like `insert-file-contents', but only reads in the file.
943 A buffer may be modified in several ways after reading into the buffer due
944 to advanced Emacs features, such as file-name-handlers, format decoding,
945 `find-file-hooks', etc.
946 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
947 This function ensures that none of these modifications will take place."
948 (let* ((format-alist nil)
949 (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
950 (default-major-mode 'fundamental-mode)
951 (enable-local-variables nil)
952 (after-insert-file-functions nil)
953 (enable-local-eval nil)
954 (inhibit-file-name-operation (if inhibit
955 'insert-file-contents
956 inhibit-file-name-operation))
957 (inhibit-file-name-handlers
959 (append mm-inhibit-file-name-handlers
960 inhibit-file-name-handlers)
961 inhibit-file-name-handlers))
962 (ffh (if (boundp 'find-file-hook)
965 (val (symbol-value ffh)))
968 (insert-file-contents filename visit beg end replace)
971 (defun mm-append-to-file (start end filename &optional codesys inhibit)
972 "Append the contents of the region to the end of file FILENAME.
973 When called from a function, expects three arguments,
974 START, END and FILENAME. START and END are buffer positions
975 saying what text to write.
976 Optional fourth argument specifies the coding system to use when
978 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
979 (let ((coding-system-for-write
980 (or codesys mm-text-coding-system-for-write
981 mm-text-coding-system))
982 (inhibit-file-name-operation (if inhibit
984 inhibit-file-name-operation))
985 (inhibit-file-name-handlers
987 (append mm-inhibit-file-name-handlers
988 inhibit-file-name-handlers)
989 inhibit-file-name-handlers)))
990 (write-region start end filename t 'no-message)
991 (message "Appended to %s" filename)))
993 (defun mm-write-region (start end filename &optional append visit lockname
994 coding-system inhibit)
996 "Like `write-region'.
997 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
998 (let ((coding-system-for-write
999 (or coding-system mm-text-coding-system-for-write
1000 mm-text-coding-system))
1001 (inhibit-file-name-operation (if inhibit
1003 inhibit-file-name-operation))
1004 (inhibit-file-name-handlers
1006 (append mm-inhibit-file-name-handlers
1007 inhibit-file-name-handlers)
1008 inhibit-file-name-handlers)))
1009 (write-region start end filename append visit lockname)))
1011 ;; It is not a MIME function, but some MIME functions use it.
1012 (if (and (fboundp 'make-temp-file)
1014 (let ((def (symbol-function 'make-temp-file)))
1015 (and (byte-code-function-p def)
1016 (setq def (if (fboundp 'compiled-function-arglist)
1018 (eval (list 'compiled-function-arglist def))
1021 (eq (nth 3 def) 'suffix)))))
1022 (defalias 'mm-make-temp-file 'make-temp-file)
1023 ;; Stolen (and modified for Emacs 20 and XEmacs) from Emacs 22.
1024 (defun mm-make-temp-file (prefix &optional dir-flag suffix)
1025 "Create a temporary file.
1026 The returned file name (created by appending some random characters at the end
1027 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1028 is guaranteed to point to a newly created empty file.
1029 You can then use `write-region' to write new data into the file.
1031 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1033 If SUFFIX is non-nil, add that at the end of the file name."
1034 (let ((umask (default-file-modes))
1038 ;; Create temp files with strict access rights. It's easy to
1039 ;; loosen them later, whereas it's impossible to close the
1040 ;; time-window of loose permissions otherwise.
1041 (set-default-file-modes 448)
1042 (while (condition-case err
1048 (if (fboundp 'temp-directory)
1051 temporary-file-directory))))
1053 (setq file (concat file suffix)))
1055 (make-directory file)
1056 (if (or (featurep 'xemacs)
1057 (= emacs-major-version 20))
1058 ;; NOTE: This is unsafe if Emacs 20
1059 ;; users and XEmacs users don't use
1060 ;; a secure temp directory.
1061 (if (file-exists-p file)
1062 (signal 'file-already-exists
1063 (list "File exists" file))
1064 (write-region "" nil file nil 'silent))
1065 (write-region "" nil file nil 'silent
1068 (file-already-exists t)
1069 ;; The Emacs 20 and XEmacs versions of
1070 ;; `make-directory' issue `file-error'.
1071 (file-error (or (and (or (featurep 'xemacs)
1072 (= emacs-major-version 20))
1073 (file-exists-p file))
1074 (signal (car err) (cdr err)))))
1075 ;; the file was somehow created by someone else between
1076 ;; `make-temp-name' and `write-region', let's try again.
1080 (set-default-file-modes umask)))))
1082 (defun mm-image-load-path (&optional package)
1084 (dolist (path load-path (nreverse result))
1087 (setq dir (concat (file-name-directory
1088 (directory-file-name path))
1089 "etc/images/" (or package "gnus/")))))
1091 (push path result))))
1093 ;; Fixme: This doesn't look useful where it's used.
1094 (if (fboundp 'detect-coding-region)
1095 (defun mm-detect-coding-region (start end)
1096 "Like `detect-coding-region' except returning the best one."
1097 (let ((coding-systems
1098 (detect-coding-region start end)))
1099 (or (car-safe coding-systems)
1101 (defun mm-detect-coding-region (start end)
1102 (let ((point (point)))
1104 (skip-chars-forward "\0-\177" end)
1106 (if (eq (point) end) 'ascii (mm-guess-charset))
1107 (goto-char point)))))
1109 (if (fboundp 'coding-system-get)
1110 (defun mm-detect-mime-charset-region (start end)
1111 "Detect MIME charset of the text in the region between START and END."
1112 (let ((cs (mm-detect-coding-region start end)))
1113 (or (coding-system-get cs :mime-charset)
1114 (coding-system-get cs 'mime-charset))))
1115 (defun mm-detect-mime-charset-region (start end)
1116 "Detect MIME charset of the text in the region between START and END."
1117 (let ((cs (mm-detect-coding-region start end)))
1123 ;; arch-tag: 94dc5388-825d-4fd1-bfa5-2100aa351238
1124 ;;; mm-util.el ends here