* uudecode.el (uudecode-use-external): Add :version.
[gnus] / lisp / mm-util.el
1 ;;; mm-util.el --- Utility functions for Mule and low level things
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
3 ;;   Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (require 'mail-prsvr)
30
31 (eval-and-compile
32   (mapcar
33    (lambda (elem)
34      (let ((nfunc (intern (format "mm-%s" (car elem)))))
35        (if (fboundp (car elem))
36            (defalias nfunc (car elem))
37          (defalias nfunc (cdr elem)))))
38    '((decode-coding-string . (lambda (s a) s))
39      (encode-coding-string . (lambda (s a) s))
40      (encode-coding-region . ignore)
41      (coding-system-list . ignore)
42      (decode-coding-region . ignore)
43      (char-int . identity)
44      (coding-system-equal . equal)
45      (annotationp . ignore)
46      (set-buffer-file-coding-system . ignore)
47      (read-charset
48       . (lambda (prompt)
49           "Return a charset."
50           (intern
51            (completing-read
52             prompt
53             (mapcar (lambda (e) (list (symbol-name (car e))))
54                     mm-mime-mule-charset-alist)
55             nil t))))
56      (subst-char-in-string
57       . (lambda (from to string &optional inplace) ;; stolen (and renamed) from nnheader.el
58           "Replace characters in STRING from FROM to TO.
59           Unless optional argument INPLACE is non-nil, return a new string."
60           (let ((string (if inplace string (copy-sequence string)))
61                 (len (length string))
62                 (idx 0))
63             ;; Replace all occurrences of FROM with TO.
64             (while (< idx len)
65               (when (= (aref string idx) from)
66                 (aset string idx to))
67               (setq idx (1+ idx)))
68             string)))
69      (replace-in-string
70       . (lambda (string regexp rep &optional literal)
71           "See `replace-regexp-in-string', only the order of args differs."
72           (replace-regexp-in-string regexp rep string nil literal)))
73      (string-as-unibyte . identity)
74      (string-make-unibyte . identity)
75      (string-as-multibyte . identity)
76      (multibyte-string-p . ignore)
77      ;; It is not a MIME function, but some MIME functions use it.
78      (make-temp-file . (lambda (prefix &optional dir-flag)
79                          (let ((file (expand-file-name
80                                       (make-temp-name prefix)
81                                       (if (fboundp 'temp-directory)
82                                           (temp-directory)
83                                         temporary-file-directory))))
84                            (if dir-flag
85                                (make-directory file))
86                            file)))
87      (insert-byte . insert-char)
88      (multibyte-char-to-unibyte . identity))))
89
90 (eval-and-compile
91   (defalias 'mm-char-or-char-int-p
92     (cond
93      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
94      ((fboundp 'char-valid-p) 'char-valid-p)
95      (t 'identity))))
96
97 ;; Fixme:  This seems always to be used to read a MIME charset, so it
98 ;; should be re-named and fixed (in Emacs) to offer completion only on
99 ;; proper charset names (base coding systems which have a
100 ;; mime-charset defined).  XEmacs doesn't believe in mime-charset;
101 ;; test with
102 ;;   `(or (coding-system-get 'iso-8859-1 'mime-charset)
103 ;;        (coding-system-get 'iso-8859-1 :mime-charset))'
104 ;; Actually, there should be an `mm-coding-system-mime-charset'.
105 (eval-and-compile
106   (defalias 'mm-read-coding-system
107     (cond
108      ((fboundp 'read-coding-system)
109       (if (and (featurep 'xemacs)
110                (<= (string-to-number emacs-version) 21.1))
111           (lambda (prompt &optional default-coding-system)
112             (read-coding-system prompt))
113         'read-coding-system))
114      (t (lambda (prompt &optional default-coding-system)
115           "Prompt the user for a coding system."
116           (completing-read
117            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
118                           mm-mime-mule-charset-alist)))))))
119
120 (defvar mm-coding-system-list nil)
121 (defun mm-get-coding-system-list ()
122   "Get the coding system list."
123   (or mm-coding-system-list
124       (setq mm-coding-system-list (mm-coding-system-list))))
125
126 (defun mm-coding-system-p (cs)
127   "Return non-nil if CS is a symbol naming a coding system.
128 In XEmacs, also return non-nil if CS is a coding system object.
129 If CS is available, return CS itself in Emacs, and return a coding
130 system object in XEmacs."
131   (if (fboundp 'find-coding-system)
132       (find-coding-system cs)
133     (if (fboundp 'coding-system-p)
134         (when (coding-system-p cs)
135           cs)
136       ;; Is this branch ever actually useful?
137       (car (memq cs (mm-get-coding-system-list))))))
138
139 (defvar mm-charset-synonym-alist
140   `(
141     ;; Not in XEmacs, but it's not a proper MIME charset anyhow.
142     ,@(unless (mm-coding-system-p 'x-ctext)
143        '((x-ctext . ctext)))
144     ;; ISO-8859-15 is very similar to ISO-8859-1.  But it's _different_!
145     ,@(unless (mm-coding-system-p 'iso-8859-15)
146        '((iso-8859-15 . iso-8859-1)))
147     ;; BIG-5HKSCS is similar to, but different than, BIG-5.
148     ,@(unless (mm-coding-system-p 'big5-hkscs)
149         '((big5-hkscs . big5)))
150     ;; Windows-1252 is actually a superset of Latin-1.  See also
151     ;; `gnus-article-dumbquotes-map'.
152     ,@(unless (mm-coding-system-p 'windows-1252)
153        (if (mm-coding-system-p 'cp1252)
154            '((windows-1252 . cp1252))
155          '((windows-1252 . iso-8859-1))))
156     ;; Windows-1250 is a variant of Latin-2 heavily used by Microsoft
157     ;; Outlook users in Czech republic. Use this to allow reading of their
158     ;; e-mails. cp1250 should be defined by M-x codepage-setup.
159     ,@(if (and (not (mm-coding-system-p 'windows-1250))
160                (mm-coding-system-p 'cp1250))
161           '((windows-1250 . cp1250)))
162     ;; A Microsoft misunderstanding.
163     ,@(unless (mm-coding-system-p 'ks_c_5601-1987)
164         (if (mm-coding-system-p 'cp949)
165             '((ks_c_5601-1987 . cp949))
166           '((ks_c_5601-1987 . euc-kr))))
167     )
168   "A mapping from invalid charset names to the real charset names.")
169
170 (defvar mm-binary-coding-system
171   (cond
172    ((mm-coding-system-p 'binary) 'binary)
173    ((mm-coding-system-p 'no-conversion) 'no-conversion)
174    (t nil))
175   "100% binary coding system.")
176
177 (defvar mm-text-coding-system
178   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
179           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
180         (and (mm-coding-system-p 'raw-text) 'raw-text))
181       mm-binary-coding-system)
182   "Text-safe coding system (For removing ^M).")
183
184 (defvar mm-text-coding-system-for-write nil
185   "Text coding system for write.")
186
187 (defvar mm-auto-save-coding-system
188   (cond
189    ((mm-coding-system-p 'utf-8-emacs)   ; Mule 7
190     (if (memq system-type '(windows-nt ms-dos ms-windows))
191         (if (mm-coding-system-p 'utf-8-emacs-dos)
192             'utf-8-emacs-dos mm-binary-coding-system)
193       'utf-8-emacs))
194    ((mm-coding-system-p 'emacs-mule)
195     (if (memq system-type '(windows-nt ms-dos ms-windows))
196         (if (mm-coding-system-p 'emacs-mule-dos)
197             'emacs-mule-dos mm-binary-coding-system)
198       'emacs-mule))
199    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
200    (t mm-binary-coding-system))
201   "Coding system of auto save file.")
202
203 (defvar mm-universal-coding-system mm-auto-save-coding-system
204   "The universal coding system.")
205
206 ;; Fixme: some of the cars here aren't valid MIME charsets.  That
207 ;; should only matter with XEmacs, though.
208 (defvar mm-mime-mule-charset-alist
209   `((us-ascii ascii)
210     (iso-8859-1 latin-iso8859-1)
211     (iso-8859-2 latin-iso8859-2)
212     (iso-8859-3 latin-iso8859-3)
213     (iso-8859-4 latin-iso8859-4)
214     (iso-8859-5 cyrillic-iso8859-5)
215     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
216     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default
217     ;; charset is koi8-r, not iso-8859-5.
218     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
219     (iso-8859-6 arabic-iso8859-6)
220     (iso-8859-7 greek-iso8859-7)
221     (iso-8859-8 hebrew-iso8859-8)
222     (iso-8859-9 latin-iso8859-9)
223     (iso-8859-14 latin-iso8859-14)
224     (iso-8859-15 latin-iso8859-15)
225     (viscii vietnamese-viscii-lower)
226     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
227     (euc-kr korean-ksc5601)
228     (gb2312 chinese-gb2312)
229     (big5 chinese-big5-1 chinese-big5-2)
230     (tibetan tibetan)
231     (thai-tis620 thai-tis620)
232     (windows-1251 cyrillic-iso8859-5)
233     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
234     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
235                    latin-jisx0201 japanese-jisx0208-1978
236                    chinese-gb2312 japanese-jisx0208
237                    korean-ksc5601 japanese-jisx0212)
238     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
239                     latin-jisx0201 japanese-jisx0208-1978
240                     chinese-gb2312 japanese-jisx0208
241                     korean-ksc5601 japanese-jisx0212
242                     chinese-cns11643-1 chinese-cns11643-2)
243     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
244                     cyrillic-iso8859-5 greek-iso8859-7
245                     latin-jisx0201 japanese-jisx0208-1978
246                     chinese-gb2312 japanese-jisx0208
247                     korean-ksc5601 japanese-jisx0212
248                     chinese-cns11643-1 chinese-cns11643-2
249                     chinese-cns11643-3 chinese-cns11643-4
250                     chinese-cns11643-5 chinese-cns11643-6
251                     chinese-cns11643-7)
252     (iso-2022-jp-3 latin-jisx0201 japanese-jisx0208-1978 japanese-jisx0208
253                    japanese-jisx0213-1 japanese-jisx0213-2)
254     (shift_jis latin-jisx0201 katakana-jisx0201 japanese-jisx0208)
255     ,(if (or (not (fboundp 'charsetp)) ;; non-Mule case
256              (charsetp 'unicode-a)
257              (not (mm-coding-system-p 'mule-utf-8)))
258          '(utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e)
259        ;; If we have utf-8 we're in Mule 5+.
260        (append '(utf-8)
261                (delete 'ascii
262                        (coding-system-get 'mule-utf-8 'safe-charsets)))))
263   "Alist of MIME-charset/MULE-charsets.")
264
265 (defun mm-enrich-utf-8-by-mule-ucs ()
266   "Make the `utf-8' MIME charset usable by the Mule-UCS package.
267 This function will run when the `un-define' module is loaded under
268 XEmacs, and fill the `utf-8' entry in `mm-mime-mule-charset-alist'
269 with Mule charsets.  It is completely useless for Emacs."
270   (unless (cdr (delete '(mm-enrich-utf-8-by-mule-ucs)
271                        (assoc "un-define" after-load-alist)))
272     (setq after-load-alist
273           (delete '("un-define") after-load-alist)))
274   (when (boundp 'unicode-basic-translation-charset-order-list)
275     (condition-case nil
276         (let ((val (delq
277                     'ascii
278                     (copy-sequence
279                      (symbol-value
280                       'unicode-basic-translation-charset-order-list))))
281               (elem (assq 'utf-8 mm-mime-mule-charset-alist)))
282           (if elem
283               (setcdr elem val)
284             (setq mm-mime-mule-charset-alist
285                   (nconc mm-mime-mule-charset-alist
286                          (list (cons 'utf-8 val))))))
287       (error))))
288
289 ;; Correct by construction, but should be unnecessary for Emacs:
290 (if (featurep 'xemacs)
291     (eval-after-load "un-define" '(mm-enrich-utf-8-by-mule-ucs))
292   (when (and (fboundp 'coding-system-list)
293              (fboundp 'sort-coding-systems))
294     (let ((css (sort-coding-systems (coding-system-list 'base-only)))
295           cs mime mule alist)
296       (while css
297         (setq cs (pop css)
298               mime (or (coding-system-get cs :mime-charset) ; Emacs 22
299                        (coding-system-get cs 'mime-charset)))
300         (when (and mime
301                    (not (eq t (setq mule
302                                     (coding-system-get cs 'safe-charsets))))
303                    (not (assq mime alist)))
304           (push (cons mime (delq 'ascii mule)) alist)))
305       (setq mm-mime-mule-charset-alist (nreverse alist)))))
306
307 (defvar mm-hack-charsets '(iso-8859-15 iso-2022-jp-2)
308   "A list of special charsets.
309 Valid elements include:
310 `iso-8859-15'    convert ISO-8859-1, -9 to ISO-8859-15 if ISO-8859-15 exists.
311 `iso-2022-jp-2'  convert ISO-2022-jp to ISO-2022-jp-2 if ISO-2022-jp-2 exists."
312 )
313
314 (defvar mm-iso-8859-15-compatible
315   '((iso-8859-1 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")
316     (iso-8859-9 "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xD0\xDD\xDE\xF0\xFD\xFE"))
317   "ISO-8859-15 exchangeable coding systems and inconvertible characters.")
318
319 (defvar mm-iso-8859-x-to-15-table
320   (and (fboundp 'coding-system-p)
321        (mm-coding-system-p 'iso-8859-15)
322        (mapcar
323         (lambda (cs)
324           (if (mm-coding-system-p (car cs))
325               (let ((c (string-to-char
326                         (decode-coding-string "\341" (car cs)))))
327                 (cons (char-charset c)
328                       (cons
329                        (- (string-to-char
330                            (decode-coding-string "\341" 'iso-8859-15)) c)
331                        (string-to-list (decode-coding-string (car (cdr cs))
332                                                              (car cs))))))
333             '(gnus-charset 0)))
334         mm-iso-8859-15-compatible))
335   "A table of the difference character between ISO-8859-X and ISO-8859-15.")
336
337 (defcustom mm-coding-system-priorities
338   (if (boundp 'current-language-environment)
339       (let ((lang (symbol-value 'current-language-environment)))
340         (cond ((string= lang "Japanese")
341                ;; Japanese users may prefer iso-2022-jp to shift_jis.
342                '(iso-2022-jp iso-2022-jp-2 shift_jis iso-8859-1 utf-8)))))
343   "Preferred coding systems for encoding outgoing messages.
344
345 More than one suitable coding system may be found for some text.
346 By default, the coding system with the highest priority is used
347 to encode outgoing messages (see `sort-coding-systems').  If this
348 variable is set, it overrides the default priority."
349   :version "21.2"
350   :type '(repeat (symbol :tag "Coding system"))
351   :group 'mime)
352
353 ;; ??
354 (defvar mm-use-find-coding-systems-region
355   (fboundp 'find-coding-systems-region)
356   "Use `find-coding-systems-region' to find proper coding systems.
357
358 Setting it to nil is useful on Emacsen supporting Unicode if sending
359 mail with multiple parts is preferred to sending a Unicode one.")
360
361 ;;; Internal variables:
362
363 ;;; Functions:
364
365 (defun mm-mule-charset-to-mime-charset (charset)
366   "Return the MIME charset corresponding to the given Mule CHARSET."
367   (if (and (fboundp 'find-coding-systems-for-charsets)
368            (fboundp 'sort-coding-systems))
369       (let ((css (sort (sort-coding-systems
370                         (find-coding-systems-for-charsets (list charset)))
371                        'mm-sort-coding-systems-predicate))
372             cs mime)
373         (while (and (not mime)
374                     css)
375           (when (setq cs (pop css))
376             (setq mime (or (coding-system-get cs :mime-charset)
377                            (coding-system-get cs 'mime-charset)))))
378         mime)
379     (let ((alist (mapcar (lambda (cs)
380                            (assq cs mm-mime-mule-charset-alist))
381                          (sort (mapcar 'car mm-mime-mule-charset-alist)
382                                'mm-sort-coding-systems-predicate)))
383           out)
384       (while alist
385         (when (memq charset (cdar alist))
386           (setq out (caar alist)
387                 alist nil))
388         (pop alist))
389       out)))
390
391 (defun mm-charset-to-coding-system (charset &optional lbt)
392   "Return coding-system corresponding to CHARSET.
393 CHARSET is a symbol naming a MIME charset.
394 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
395 used as the line break code type of the coding system."
396   (when (stringp charset)
397     (setq charset (intern (downcase charset))))
398   (when lbt
399     (setq charset (intern (format "%s-%s" charset lbt))))
400   (cond
401    ((null charset)
402     charset)
403    ;; Running in a non-MULE environment.
404    ((or (null (mm-get-coding-system-list))
405         (not (fboundp 'coding-system-get)))
406     charset)
407    ;; ascii
408    ((eq charset 'us-ascii)
409     'ascii)
410    ;; Check to see whether we can handle this charset.  (This depends
411    ;; on there being some coding system matching each `mime-charset'
412    ;; property defined, as there should be.)
413    ((and (mm-coding-system-p charset)
414 ;;; Doing this would potentially weed out incorrect charsets.
415 ;;;      charset
416 ;;;      (eq charset (coding-system-get charset 'mime-charset))
417          )
418     charset)
419    ;; Translate invalid charsets.
420    ((let ((cs (cdr (assq charset mm-charset-synonym-alist))))
421       (and cs (mm-coding-system-p cs) cs)))
422    ;; Last resort: search the coding system list for entries which
423    ;; have the right mime-charset in case the canonical name isn't
424    ;; defined (though it should be).
425    ((let (cs)
426       ;; mm-get-coding-system-list returns a list of cs without lbt.
427       ;; Do we need -lbt?
428       (dolist (c (mm-get-coding-system-list))
429         (if (and (null cs)
430                  (eq charset (or (coding-system-get c :mime-charset)
431                                  (coding-system-get c 'mime-charset))))
432             (setq cs c)))
433       cs))))
434
435 (eval-and-compile
436   (defvar mm-emacs-mule (and (not (featurep 'xemacs))
437                              (boundp 'default-enable-multibyte-characters)
438                              default-enable-multibyte-characters
439                              (fboundp 'set-buffer-multibyte))
440     "True in Emacs with Mule.")
441
442   (if mm-emacs-mule
443       (defun mm-enable-multibyte ()
444         "Set the multibyte flag of the current buffer.
445 Only do this if the default value of `enable-multibyte-characters' is
446 non-nil.  This is a no-op in XEmacs."
447         (set-buffer-multibyte 'to))
448     (defalias 'mm-enable-multibyte 'ignore))
449
450   (if mm-emacs-mule
451       (defun mm-disable-multibyte ()
452         "Unset the multibyte flag of in the current buffer.
453 This is a no-op in XEmacs."
454         (set-buffer-multibyte nil))
455     (defalias 'mm-disable-multibyte 'ignore)))
456
457 (defun mm-preferred-coding-system (charset)
458   ;; A typo in some Emacs versions.
459   (or (get-charset-property charset 'preferred-coding-system)
460       (get-charset-property charset 'prefered-coding-system)))
461
462 ;; Mule charsets shouldn't be used.
463 (defsubst mm-guess-charset ()
464   "Guess Mule charset from the language environment."
465   (or
466    mail-parse-mule-charset ;; cached mule-charset
467    (progn
468      (setq mail-parse-mule-charset
469            (and (boundp 'current-language-environment)
470                 (car (last
471                       (assq 'charset
472                             (assoc current-language-environment
473                                    language-info-alist))))))
474      (if (or (not mail-parse-mule-charset)
475              (eq mail-parse-mule-charset 'ascii))
476          (setq mail-parse-mule-charset
477                (or (car (last (assq mail-parse-charset
478                                     mm-mime-mule-charset-alist)))
479                    ;; default
480                    'latin-iso8859-1)))
481      mail-parse-mule-charset)))
482
483 (defun mm-charset-after (&optional pos)
484   "Return charset of a character in current buffer at position POS.
485 If POS is nil, it defauls to the current point.
486 If POS is out of range, the value is nil.
487 If the charset is `composition', return the actual one."
488   (let ((char (char-after pos)) charset)
489     (if (< (mm-char-int char) 128)
490         (setq charset 'ascii)
491       ;; charset-after is fake in some Emacsen.
492       (setq charset (and (fboundp 'char-charset) (char-charset char)))
493       (if (eq charset 'composition)     ; Mule 4
494           (let ((p (or pos (point))))
495             (cadr (find-charset-region p (1+ p))))
496         (if (and charset (not (memq charset '(ascii eight-bit-control
497                                                     eight-bit-graphic))))
498             charset
499           (mm-guess-charset))))))
500
501 (defun mm-mime-charset (charset)
502   "Return the MIME charset corresponding to the given Mule CHARSET."
503   (if (eq charset 'unknown)
504       (error "The message contains non-printable characters, please use attachment"))
505   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
506       ;; This exists in Emacs 20.
507       (or
508        (and (mm-preferred-coding-system charset)
509             (or (coding-system-get
510                  (mm-preferred-coding-system charset) :mime-charset)
511                 (coding-system-get
512                  (mm-preferred-coding-system charset) 'mime-charset)))
513        (and (eq charset 'ascii)
514             'us-ascii)
515        (mm-preferred-coding-system charset)
516        (mm-mule-charset-to-mime-charset charset))
517     ;; This is for XEmacs.
518     (mm-mule-charset-to-mime-charset charset)))
519
520 (defun mm-delete-duplicates (list)
521   "Simple substitute for CL `delete-duplicates', testing with `equal'."
522   (let (result head)
523     (while list
524       (setq head (car list))
525       (setq list (delete head list))
526       (setq result (cons head result)))
527     (nreverse result)))
528
529 ;; Fixme:  This is used in places when it should be testing the
530 ;; default multibyteness.  See mm-default-multibyte-p.
531 (eval-and-compile
532   (if (and (not (featurep 'xemacs))
533            (boundp 'enable-multibyte-characters))
534       (defun mm-multibyte-p ()
535         "Non-nil if multibyte is enabled in the current buffer."
536         enable-multibyte-characters)
537     (defun mm-multibyte-p () (featurep 'mule))))
538
539 (defun mm-default-multibyte-p ()
540   "Return non-nil if the session is multibyte.
541 This affects whether coding conversion should be attempted generally."
542   (if (featurep 'mule)
543       (if (boundp 'default-enable-multibyte-characters)
544           default-enable-multibyte-characters
545         t)))
546
547 (defun mm-iso-8859-x-to-15-region (&optional b e)
548   (if (fboundp 'char-charset)
549       (let (charset item c inconvertible)
550         (save-restriction
551           (if e (narrow-to-region b e))
552           (goto-char (point-min))
553           (skip-chars-forward "\0-\177")
554           (while (not (eobp))
555             (cond
556              ((not (setq item (assq (char-charset (setq c (char-after)))
557                                     mm-iso-8859-x-to-15-table)))
558               (forward-char))
559              ((memq c (cdr (cdr item)))
560               (setq inconvertible t)
561               (forward-char))
562              (t
563               (insert-before-markers (prog1 (+ c (car (cdr item)))
564                                        (delete-char 1)))))
565             (skip-chars-forward "\0-\177")))
566         (not inconvertible))))
567
568 (defun mm-sort-coding-systems-predicate (a b)
569   (let ((priorities
570          (mapcar (lambda (cs)
571                    ;; Note: invalid entries are dropped silently
572                    (and (setq cs (mm-coding-system-p cs))
573                         (coding-system-base cs)))
574                  mm-coding-system-priorities)))
575     (and (setq a (mm-coding-system-p a))
576          (if (setq b (mm-coding-system-p b))
577              (> (length (memq (coding-system-base a) priorities))
578                 (length (memq (coding-system-base b) priorities)))
579            t))))
580
581 (defun mm-find-mime-charset-region (b e &optional hack-charsets)
582   "Return the MIME charsets needed to encode the region between B and E.
583 nil means ASCII, a single-element list represents an appropriate MIME
584 charset, and a longer list means no appropriate charset."
585   (let (charsets)
586     ;; The return possibilities of this function are a mess...
587     (or (and (mm-multibyte-p)
588              mm-use-find-coding-systems-region
589              ;; Find the mime-charset of the most preferred coding
590              ;; system that has one.
591              (let ((systems (find-coding-systems-region b e)))
592                (when mm-coding-system-priorities
593                  (setq systems
594                        (sort systems 'mm-sort-coding-systems-predicate)))
595                (setq systems (delq 'compound-text systems))
596                (unless (equal systems '(undecided))
597                  (while systems
598                    (let* ((head (pop systems))
599                           (cs (or (coding-system-get head :mime-charset)
600                                   (coding-system-get head 'mime-charset))))
601                      ;; The mime-charset (`x-ctext') of
602                      ;; `compound-text' is not in the IANA list.  We
603                      ;; shouldn't normally use anything here with a
604                      ;; mime-charset having an `x-' prefix.
605                      ;; Fixme:  Allow this to be overridden, since
606                      ;; there is existing use of x-ctext.
607                      ;; Also people apparently need the coding system
608                      ;; `iso-2022-jp-3' (which Mule-UCS defines with
609                      ;; mime-charset, though it's not valid).
610                      (if (and cs
611                               (not (string-match "^[Xx]-" (symbol-name cs)))
612                               ;; UTF-16 of any variety is invalid for
613                               ;; text parts and, unfortunately, has
614                               ;; mime-charset defined both in Mule-UCS
615                               ;; and versions of Emacs.  (The name
616                               ;; might be `mule-utf-16...'  or
617                               ;; `utf-16...'.)
618                               (not (string-match "utf-16" (symbol-name cs))))
619                          (setq systems nil
620                                charsets (list cs))))))
621                charsets))
622         ;; Otherwise we're not multibyte, we're XEmacs, or a single
623         ;; coding system won't cover it.
624         (setq charsets
625               (mm-delete-duplicates
626                (mapcar 'mm-mime-charset
627                        (delq 'ascii
628                              (mm-find-charset-region b e))))))
629     (if (and (> (length charsets) 1)
630              (memq 'iso-8859-15 charsets)
631              (memq 'iso-8859-15 hack-charsets)
632              (save-excursion (mm-iso-8859-x-to-15-region b e)))
633         (mapcar (lambda (x) (setq charsets (delq (car x) charsets)))
634                 mm-iso-8859-15-compatible))
635     (if (and (memq 'iso-2022-jp-2 charsets)
636              (memq 'iso-2022-jp-2 hack-charsets))
637         (setq charsets (delq 'iso-2022-jp charsets)))
638     charsets))
639
640 (defmacro mm-with-unibyte-buffer (&rest forms)
641   "Create a temporary buffer, and evaluate FORMS there like `progn'.
642 Use unibyte mode for this."
643   `(let (default-enable-multibyte-characters)
644      (with-temp-buffer ,@forms)))
645 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
646 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
647
648 (defmacro mm-with-multibyte-buffer (&rest forms)
649   "Create a temporary buffer, and evaluate FORMS there like `progn'.
650 Use multibyte mode for this."
651   `(let ((default-enable-multibyte-characters t))
652      (with-temp-buffer ,@forms)))
653 (put 'mm-with-multibyte-buffer 'lisp-indent-function 0)
654 (put 'mm-with-multibyte-buffer 'edebug-form-spec '(body))
655
656 (defmacro mm-with-unibyte-current-buffer (&rest forms)
657   "Evaluate FORMS with current buffer temporarily made unibyte.
658 Also bind `default-enable-multibyte-characters' to nil.
659 Equivalent to `progn' in XEmacs"
660   (let ((multibyte (make-symbol "multibyte"))
661         (buffer (make-symbol "buffer")))
662     `(if mm-emacs-mule
663          (let ((,multibyte enable-multibyte-characters)
664                (,buffer (current-buffer)))
665            (unwind-protect
666                (let (default-enable-multibyte-characters)
667                  (set-buffer-multibyte nil)
668                  ,@forms)
669              (set-buffer ,buffer)
670              (set-buffer-multibyte ,multibyte)))
671        (let (default-enable-multibyte-characters)
672          ,@forms))))
673 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
674 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
675
676 (defmacro mm-with-unibyte (&rest forms)
677   "Eval the FORMS with the default value of `enable-multibyte-characters' nil."
678   `(let (default-enable-multibyte-characters)
679      ,@forms))
680 (put 'mm-with-unibyte 'lisp-indent-function 0)
681 (put 'mm-with-unibyte 'edebug-form-spec '(body))
682
683 (defmacro mm-with-multibyte (&rest forms)
684   "Eval the FORMS with the default value of `enable-multibyte-characters' t."
685   `(let ((default-enable-multibyte-characters t))
686      ,@forms))
687 (put 'mm-with-multibyte 'lisp-indent-function 0)
688 (put 'mm-with-multibyte 'edebug-form-spec '(body))
689
690 (defun mm-find-charset-region (b e)
691   "Return a list of Emacs charsets in the region B to E."
692   (cond
693    ((and (mm-multibyte-p)
694          (fboundp 'find-charset-region))
695     ;; Remove composition since the base charsets have been included.
696     ;; Remove eight-bit-*, treat them as ascii.
697     (let ((css (find-charset-region b e)))
698       (mapcar (lambda (cs) (setq css (delq cs css)))
699               '(composition eight-bit-control eight-bit-graphic
700                             control-1))
701       css))
702    (t
703     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
704     (save-excursion
705       (save-restriction
706         (narrow-to-region b e)
707         (goto-char (point-min))
708         (skip-chars-forward "\0-\177")
709         (if (eobp)
710             '(ascii)
711           (let (charset)
712             (setq charset
713                   (and (boundp 'current-language-environment)
714                        (car (last (assq 'charset
715                                         (assoc current-language-environment
716                                                language-info-alist))))))
717             (if (eq charset 'ascii) (setq charset nil))
718             (or charset
719                 (setq charset
720                       (car (last (assq mail-parse-charset
721                                        mm-mime-mule-charset-alist)))))
722             (list 'ascii (or charset 'latin-iso8859-1)))))))))
723
724 (defun mm-auto-mode-alist ()
725   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
726   (let ((alist auto-mode-alist)
727         out)
728     (while alist
729       (when (listp (cdar alist))
730         (push (car alist) out))
731       (pop alist))
732     (nreverse out)))
733
734 (defvar mm-inhibit-file-name-handlers
735   '(jka-compr-handler image-file-handler)
736   "A list of handlers doing (un)compression (etc) thingies.")
737
738 (defun mm-insert-file-contents (filename &optional visit beg end replace
739                                          inhibit)
740   "Like `insert-file-contents', but only reads in the file.
741 A buffer may be modified in several ways after reading into the buffer due
742 to advanced Emacs features, such as file-name-handlers, format decoding,
743 `find-file-hooks', etc.
744 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'.
745   This function ensures that none of these modifications will take place."
746   (let ((format-alist nil)
747         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
748         (default-major-mode 'fundamental-mode)
749         (enable-local-variables nil)
750         (after-insert-file-functions nil)
751         (enable-local-eval nil)
752         (find-file-hooks nil)
753         (inhibit-file-name-operation (if inhibit
754                                          'insert-file-contents
755                                        inhibit-file-name-operation))
756         (inhibit-file-name-handlers
757          (if inhibit
758              (append mm-inhibit-file-name-handlers
759                      inhibit-file-name-handlers)
760            inhibit-file-name-handlers)))
761     (insert-file-contents filename visit beg end replace)))
762
763 (defun mm-append-to-file (start end filename &optional codesys inhibit)
764   "Append the contents of the region to the end of file FILENAME.
765 When called from a function, expects three arguments,
766 START, END and FILENAME.  START and END are buffer positions
767 saying what text to write.
768 Optional fourth argument specifies the coding system to use when
769 encoding the file.
770 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
771   (let ((coding-system-for-write
772          (or codesys mm-text-coding-system-for-write
773              mm-text-coding-system))
774         (inhibit-file-name-operation (if inhibit
775                                          'append-to-file
776                                        inhibit-file-name-operation))
777         (inhibit-file-name-handlers
778          (if inhibit
779              (append mm-inhibit-file-name-handlers
780                      inhibit-file-name-handlers)
781            inhibit-file-name-handlers)))
782     (write-region start end filename t 'no-message)
783     (message "Appended to %s" filename)))
784
785 (defun mm-write-region (start end filename &optional append visit lockname
786                               coding-system inhibit)
787
788   "Like `write-region'.
789 If INHIBIT is non-nil, inhibit `mm-inhibit-file-name-handlers'."
790   (let ((coding-system-for-write
791          (or coding-system mm-text-coding-system-for-write
792              mm-text-coding-system))
793         (inhibit-file-name-operation (if inhibit
794                                          'write-region
795                                        inhibit-file-name-operation))
796         (inhibit-file-name-handlers
797          (if inhibit
798              (append mm-inhibit-file-name-handlers
799                      inhibit-file-name-handlers)
800            inhibit-file-name-handlers)))
801     (write-region start end filename append visit lockname)))
802
803 (defun mm-image-load-path (&optional package)
804   (let (dir result)
805     (dolist (path load-path (nreverse result))
806       (when (and path
807                  (file-directory-p
808                   (setq dir (concat (file-name-directory
809                                      (directory-file-name path))
810                                     "etc/" (or package "gnus/")))))
811         (push dir result))
812       (push path result))))
813
814 ;; Fixme: This doesn't look useful where it's used.
815 (if (fboundp 'detect-coding-region)
816     (defun mm-detect-coding-region (start end)
817       "Like `detect-coding-region' except returning the best one."
818       (let ((coding-systems
819              (detect-coding-region (point) (point-max))))
820         (or (car-safe coding-systems)
821             coding-systems)))
822   (defun mm-detect-coding-region (start end)
823     (let ((point (point)))
824       (goto-char start)
825       (skip-chars-forward "\0-\177" end)
826       (prog1
827           (if (eq (point) end) 'ascii (mm-guess-charset))
828         (goto-char point)))))
829
830 (if (fboundp 'coding-system-get)
831     (defun mm-detect-mime-charset-region (start end)
832       "Detect MIME charset of the text in the region between START and END."
833       (let ((cs (mm-detect-coding-region start end)))
834         (coding-system-get cs 'mime-charset)))
835   (defun mm-detect-mime-charset-region (start end)
836     "Detect MIME charset of the text in the region between START and END."
837     (let ((cs (mm-detect-coding-region start end)))
838       cs)))
839
840
841 (provide 'mm-util)
842
843 ;;; arch-tag: 94dc5388-825d-4fd1-bfa5-2100aa351238
844 ;;; mm-util.el ends here