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