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