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