(ctext-non-standard-encodings-table):
[bpt/emacs.git] / lisp / international / mule.el
index 72336e7..03d8b0f 100644 (file)
@@ -1,8 +1,10 @@
 ;;; mule.el --- basic commands for multilingual environment
 
-;; Copyright (C) 1995 Electrotechnical Laboratory, JAPAN.
-;;   Licensed to the Free Software Foundation.
-;; Copyright (C) 2001, 2002 Free Software Foundation, Inc.
+;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+;;   Free Software Foundation, Inc.
+;; Copyright (C) 1995, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+;;   National Institute of Advanced Industrial Science and Technology (AIST)
+;;   Registration Number H14PRO021
 ;; Copyright (C) 2003
 ;;   National Institute of Advanced Industrial Science and Technology (AIST)
 ;;   Registration Number H13PRO009
@@ -23,8 +25,8 @@
 
 ;; You should have received a copy of the GNU General Public License
 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
-;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-;; Boston, MA 02111-1307, USA.
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
 
 ;;; Commentary:
 
@@ -329,7 +331,9 @@ Return t if file exists."
                (inhibit-file-name-operation nil))
            (save-excursion
              (set-buffer buffer)
-             (insert-file-contents fullname)
+             ;; Don't let deactivate-mark remain set.
+             (let (deactivate-mark)
+               (insert-file-contents fullname))
              ;; If the loaded file was inserted with no-conversion or
              ;; raw-text coding system, make the buffer unibyte.
              ;; Otherwise, eval-buffer might try to interpret random
@@ -341,7 +345,9 @@ Return t if file exists."
              ;; Make `kill-buffer' quiet.
              (set-buffer-modified-p nil))
            ;; Have the original buffer current while we eval.
-           (eval-buffer buffer nil file
+           (eval-buffer buffer nil
+                        ;; This is compatible with what `load' does.
+                        (if purify-flag file fullname)
                         ;; If this Emacs is running with --unibyte,
                         ;; convert multibyte strings to unibyte
                         ;; after reading them.
@@ -467,17 +473,17 @@ Return -1 if charset isn't an ISO 2022 one."
 This function is provided for backward compatibility.
 Now we have the variable `charset-list'."
   charset-list)
-(make-obsolete 'charset-list "Use variable `charset-list'" "22.1")
+(make-obsolete 'charset-list "Use variable `charset-list'" "23.1")
 
 \f
 ;;; CHARACTER
 (defalias 'char-valid-p 'characterp)
-(make-obsolete 'char-valid-p 'characterp "22.1")
+(make-obsolete 'char-valid-p 'characterp "23.1")
 
 (defun generic-char-p (char)
   "Always return nil.  This is provided for backward compatibility."
   nil)
-(make-obsolete 'generic-char-p "Generic characters no longer exist" "22.1")
+(make-obsolete 'generic-char-p "Generic characters no longer exist" "23.1")
 
 (defun make-char-internal (charset-id &optional code1 code2)
   (let ((charset (aref emacs-mule-charset-table charset-id)))
@@ -840,11 +846,12 @@ For compatibility with Emacs 20/21, this accepts old-style symbols
 like `mime-charset' as well as the current style like `:mime-charset'."
   (or (plist-get (coding-system-plist coding-system) prop)
       (if (not (keywordp prop))
-         (plist-get (coding-system-plist coding-system)
-                    (intern (concat ":" (symbol-name prop)))))))
-
-(defalias 'coding-system-parent 'coding-system-base)
-(make-obsolete 'coding-system-parent 'coding-system-base "20.3")
+         ;; For backward compatiblity.
+         (if (eq prop 'ascii-incompatible)
+             (not (plist-get (coding-system-plist coding-system)
+                             :ascii-compatible-p))
+           (plist-get (coding-system-plist coding-system)
+                      (intern (concat ":" (symbol-name prop))))))))
 
 (defun coding-system-eol-type-mnemonic (coding-system)
   "Return the string indicating end-of-line format of CODING-SYSTEM."
@@ -1119,6 +1126,18 @@ Return the resulting coding system."
                     first eol)))
     first))
 
+(defun autoload-coding-system (symbol form)
+  "Define SYMBOL as a coding-system that is defined on demand.
+
+FROM is a form to evaluate to define the coding-system."
+  (put symbol 'coding-system-define-form form)
+  (setq coding-system-alist (cons (list (symbol-name symbol))
+                                 coding-system-alist))
+  (dolist (elt '("-unix" "-dos" "-mac"))
+    (let ((name (concat (symbol-name symbol) elt)))
+      (put (intern name) 'coding-system-define-form form)
+      (setq coding-system-alist (cons (list name) coding-system-alist)))))
+
 (defun set-buffer-file-coding-system (coding-system &optional force nomodify)
   "Set the file coding-system of the current buffer to CODING-SYSTEM.
 This means that when you save the buffer, it will be converted
@@ -1136,7 +1155,7 @@ surely saves the buffer with CODING-SYSTEM.  From a program, if you
 don't want to mark the buffer modified, specify t for NOMODIFY.
 If you know exactly what coding system you want to use,
 just set the variable `buffer-file-coding-system' directly."
-  (interactive "zCoding system for saving file (default, nil): \nP")
+  (interactive "zCoding system for saving file (default nil): \nP")
   (check-coding-system coding-system)
   (if (and coding-system buffer-file-coding-system (null force))
       (setq coding-system
@@ -1160,7 +1179,7 @@ do.  If FORCE is nil, get the unspecified aspect (or aspects) from the
 buffer's previous `buffer-file-coding-system' value (if it is
 specified there).  Otherwise, determine it from the file contents as
 usual for visiting a file."
-  (interactive "zCoding system for visited file (default, nil): \nP")
+  (interactive "zCoding system for visited file (default nil): \nP")
   (check-coding-system coding-system)
   (if (and coding-system buffer-file-coding-system (null force))
       (setq coding-system
@@ -1172,8 +1191,12 @@ usual for visiting a file."
   "Set coding system for decoding and encoding file names to CODING-SYSTEM.
 It actually just set the variable `file-name-coding-system' (which
 see) to CODING-SYSTEM."
-  (interactive "zCoding system for file names (default, nil): ")
+  (interactive "zCoding system for file names (default nil): ")
   (check-coding-system coding-system)
+  (if (and coding-system
+          (not (coding-system-get coding-system :ascii-compatible-p))
+          (not (coding-system-get coding-system :suitable-for-file-name)))
+      (error "%s is not suitable for file names" coding-system))
   (setq file-name-coding-system coding-system))
 
 (defvar default-terminal-coding-system nil
@@ -1193,7 +1216,7 @@ or by the previous use of this command."
                                 default-terminal-coding-system)
                            default-terminal-coding-system)))
           (read-coding-system
-           (format "Coding system for terminal display (default, %s): "
+           (format "Coding system for terminal display (default %s): "
                    default)
            default))))
   (if (and (not coding-system)
@@ -1222,7 +1245,7 @@ or by the previous use of this command."
                                 default-keyboard-coding-system)
                            default-keyboard-coding-system)))
           (read-coding-system
-           (format "Coding system for keyboard input (default, %s): "
+           (format "Coding system for keyboard input (default %s): "
                    default)
            default))))
   (if (and (not coding-system)
@@ -1230,6 +1253,10 @@ or by the previous use of this command."
       (setq coding-system default-keyboard-coding-system))
   (if coding-system
       (setq default-keyboard-coding-system coding-system))
+  (if (and coding-system
+          (not (coding-system-get coding-system :ascii-compatible-p))
+          (not (coding-system-get coding-system :suitable-for-keyboard)))
+      (error "%s is not suitable for keyboard" coding-system))
   (set-keyboard-coding-system-internal coding-system)
   (setq keyboard-coding-system coding-system)
   (encoded-kbd-mode (if coding-system 1 0)))
@@ -1252,7 +1279,7 @@ use either \\[customize] or \\[set-keyboard-coding-system]."
         (if (or value (boundp 'encoded-kbd-mode))
             (set-keyboard-coding-system value)
           (set-default 'keyboard-coding-system nil))) ; must initialize
-  :version "21.4"
+  :version "22.1"
   :group 'keyboard
   :group 'mule)
 
@@ -1292,7 +1319,7 @@ This setting is effective for the next communication only."
   (interactive
    (list (read-coding-system
          (if last-next-selection-coding-system
-             (format "Coding system for the next selection (default, %S): "
+             (format "Coding system for the next selection (default %S): "
                      last-next-selection-coding-system)
            "Coding system for the next selection: ")
          last-next-selection-coding-system)))
@@ -1311,14 +1338,15 @@ This function is provided for backward compatibility.
 Now we have more convenient function `set-coding-system-priority'."
   (apply 'set-coding-system-priority
         (mapcar #'(lambda (x) (symbol-value x)) arg)))
-(make-obsolete 'set-coding-priority 'set-coding-system-priority "22.1")
+(make-obsolete 'set-coding-priority 'set-coding-system-priority "23.1")
 
 ;;; X selections
 
 (defvar ctext-non-standard-encodings-alist
-  '(("big5-0" big5 2 (chinese-big5-1 chinese-big5-2))
+  '(("big5-0" big5 2 big5)
     ("ISO8859-14" iso-8859-14 1 latin-iso8859-14)
-    ("ISO8859-15" iso-8859-15 1 latin-iso8859-15))
+    ("ISO8859-15" iso-8859-15 1 latin-iso8859-15)
+    ("gbk-0" gbk 2 chinese-gbk))
   "Alist of non-standard encoding names vs the corresponding usages in CTEXT.
 
 It controls how extended segments of a compound text are handled
@@ -1336,9 +1364,7 @@ in the segment.  It can be 0 (meaning the number of octets per
 character is variable), 1, 2, 3, or 4.
 
 CHARSET is a charater set containing characters that are encoded
-in the segment.  It can be a list of character sets.  It can also
-be a char-table, in which case characters that have non-nil value
-in the char-table are the target.
+in the segment.  It can be a list of character sets.
 
 On decoding CTEXT, all encoding names listed here are recognized.
 
@@ -1347,8 +1373,7 @@ On encoding CTEXT, encoding names in the variable
 listed for the current language environment under the key
 `ctext-non-standard-encodings' are used.")
 
-(defvar ctext-non-standard-encodings
-  '("big5-0")
+(defvar ctext-non-standard-encodings nil
   "List of non-standard encoding names used in extended segments of CTEXT.
 Each element must be one of the names listed in the variable
 `ctext-non-standard-encodings-alist' (which see).")
@@ -1385,8 +1410,8 @@ Each element must be one of the names listed in the variable
          (setq pos (match-beginning 0))
          (if (match-beginning 1)
              ;; ESC % / [0-4] M L --ENCODING-NAME-- \002 --BYTES--
-             (let* ((M (char-after (+ pos 4)))
-                    (L (char-after (+ pos 5)))
+             (let* ((M (multibyte-char-to-unibyte (char-after (+ pos 4))))
+                    (L (multibyte-char-to-unibyte (char-after (+ pos 5))))
                     (encoding (match-string 2))
                     (encoding-info (assoc-string
                                     encoding
@@ -1409,33 +1434,46 @@ Each element must be one of the names listed in the variable
       (goto-char (point-min))
       (- (point-max) (point)))))
 
-;; Return a char table of extended segment usage for each character.
-;; Each value of the char table is nil, one of the elements of
-;; `ctext-non-standard-encodings-alist', or the symbol `utf-8'.
+;; Return an alist of CHARSET vs CTEXT-USAGE-INFO generated from
+;; `ctext-non-standard-encodings' and a list specified by the key
+;; `ctext-non-standard-encodings' for the currrent language
+;; environment.  CTEXT-USAGE-INFO is one of the element of
+;; `ctext-non-standard-encodings-alist' or nil.  In the former case, a
+;; character in CHARSET is encoded using extended segment.  In the
+;; latter case, a character in CHARSET is encoded using normal ISO2022
+;; designation sequence.  If a character is not in any of CHARSETs, it
+;; is encoded using UTF-8 encoding extention.
 
 (defun ctext-non-standard-encodings-table ()
-  (let ((table (make-char-table 'translation-table)))
-    (aset table (make-char 'mule-unicode-0100-24ff) 'utf-8)
-    (aset table (make-char 'mule-unicode-2500-33ff) 'utf-8)
-    (aset table (make-char 'mule-unicode-e000-ffff) 'utf-8)
-    (dolist (encoding (reverse
-                      (append
+  (let (table)
+    ;; Setup charsets specified by the key
+    ;; `ctext-non-standard-encodings' for the current language
+    ;; environment and in `ctext-non-standard-encodings'.
+    (dolist (encoding (append
                        (get-language-info current-language-environment
                                           'ctext-non-standard-encodings)
-                       ctext-non-standard-encodings)))
+                       ctext-non-standard-encodings))
       (let* ((slot (assoc encoding ctext-non-standard-encodings-alist))
             (charset (nth 3 slot)))
-       (if charset
-           (cond ((charsetp charset)
-                  (aset table (make-char charset) slot))
-                 ((listp charset)
-                  (dolist (elt charset)
-                    (aset table (make-char elt) slot)))
-                 ((char-table-p charset)
-                  (map-char-table #'(lambda (k v)
-                                  (if (and v (> k 128)) (aset table k slot)))
-                                  charset))))))
-    table))
+       (if (charsetp charset)
+           (push (cons charset slot) table)
+         (dolist (cs charset)
+           (push (cons cs slot) table)))))
+
+    ;; Next prepend charsets for ISO2022 designation sequence.
+    (dolist (charset charset-list)
+      (let ((final (plist-get (charset-plist charset) :iso-final-char)))
+       (if (and (integerp final)
+                (>= final #x40) (<= final #x7e)
+                ;; Exclude ascii and chinese-cns11643-X.
+                (not (eq charset 'ascii))
+                (not (string-match "cns11643" (symbol-name charset))))
+           (push (cons charset nil) table))))
+
+    ;; Returned reversed list so that the charsets specified by the
+    ;; key `ctext-non-standard-encodings' for the current language
+    ;; have the highest priority.
+    (nreverse table)))
 
 (defun ctext-pre-write-conversion (from to)
   "Encode characters between FROM and TO as Compound Text w/Extended Segments.
@@ -1454,20 +1492,30 @@ text, and convert it in the temporary buffer.  Otherwise, convert in-place."
     (let ((encoding-table (ctext-non-standard-encodings-table))
          last-coding-system-used
          last-pos last-encoding-info
-         encoding-info end-pos)
+         encoding-info end-pos ch)
       (goto-char (setq last-pos (point-min)))
       (setq end-pos (point-marker))
       (while (re-search-forward "[^\000-\177]+" nil t)
        ;; Found a sequence of non-ASCII characters.
        (setq last-pos (match-beginning 0)
-             last-encoding-info (aref encoding-table (char-after last-pos)))
+             ch (char-after last-pos)
+             last-encoding-info (catch 'tag
+                                  (dolist (elt encoding-table)
+                                    (if (encode-char ch (car elt))
+                                        (throw 'tag (cdr elt))))
+                                  'utf-8))
        (set-marker end-pos (match-end 0))
        (goto-char (1+ last-pos))
        (catch 'tag
          (while t
            (setq encoding-info
                  (if (< (point) end-pos)
-                     (aref encoding-table (following-char))))
+                     (catch 'tag
+                       (setq ch (following-char))
+                       (dolist (elt encoding-table)
+                         (if (encode-char ch (car elt))
+                             (throw 'tag (cdr elt))))
+                       'utf-8)))
            (unless (eq last-encoding-info encoding-info)
              (cond ((consp last-encoding-info)
                     ;; Encode the previous range using an extended
@@ -1481,12 +1529,11 @@ text, and convert it in the temporary buffer.  Otherwise, convert in-place."
                                    (- (point) last-pos)))
                       (save-excursion
                         (goto-char last-pos)
-                        (insert (string-to-multibyte
-                                 (format "\e%%/%d%c%c%s\ 2"
-                                         noctets
-                                         (+ (/ len 128) 128)
-                                         (+ (% len 128) 128)
-                                         encoding-name))))))
+                        (insert (format "\e%%/%d" noctets))
+                        (insert-byte (+ (/ len 128) 128) 1)
+                        (insert-byte (+ (% len 128) 128) 1)
+                        (insert encoding-name)
+                        (insert 2))))
                    ((eq last-encoding-info 'utf-8)
                     ;; Encode the previous range using UTF-8 encoding
                     ;; extention.
@@ -1508,9 +1555,11 @@ text, and convert it in the temporary buffer.  Otherwise, convert in-place."
 ;;; FILE I/O
 
 (defcustom auto-coding-alist
-  '(("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\|sx[dmicw]\\|tar\\)\\'" . no-conversion-multibyte)
-    ("\\.tgz\\'" . no-conversion)
+  '(("\\.\\(arc\\|zip\\|lzh\\|zoo\\|[jew]ar\\|xpi\\)\\'" . no-conversion)
+    ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|[JEW]AR\\|XPI\\)\\'" . no-conversion)
+    ("\\.\\(sx[dmicw]\\|tar\\|tgz\\)\\'" . no-conversion)
     ("\\.\\(gz\\|Z\\|bz\\|bz2\\|gpg\\)\\'" . no-conversion)
+    ("\\.\\(jpe?g\\|png\\|gif\\|tiff?\\|p[bpgn]m\\)\\'" . no-conversion)
     ("/#[^/]+#\\'" . emacs-mule))
   "Alist of filename patterns vs corresponding coding systems.
 Each element looks like (REGEXP . CODING-SYSTEM).
@@ -1526,7 +1575,7 @@ and the contents of `file-coding-system-alist'."
 
 (defcustom auto-coding-regexp-alist
   '(("^BABYL OPTIONS:[ \t]*-\\*-[ \t]*rmail[ \t]*-\\*-" . no-conversion)
-    ("\\`;ELC\14\0\0\0" . emacs-mule))      ; Emacs 20-compiled
+    ("\\`;ELC\024\0\0\0" . emacs-mule))        ; Emacs 20-compiled
   "Alist of patterns vs corresponding coding systems.
 Each element looks like (REGEXP . CODING-SYSTEM).
 A file whose first bytes match REGEXP is decoded by CODING-SYSTEM on reading.
@@ -1539,6 +1588,23 @@ and the contents of `file-coding-system-alist'."
   :type '(repeat (cons (regexp :tag "Regexp")
                       (symbol :tag "Coding system"))))
 
+(defun auto-coding-regexp-alist-lookup (from to)
+  "Lookup `auto-coding-regexp-alist' for the contents of the current buffer.
+The value is a coding system is specified for the region FROM and TO,
+or nil."
+  (save-excursion
+    (goto-char from)
+    (let ((alist auto-coding-regexp-alist)
+         coding-system)
+      (while (and alist (not coding-system))
+       (let ((regexp (car (car alist))))
+         (if enable-multibyte-characters
+             (setq regexp (string-to-multibyte regexp)))
+         (if (re-search-forward regexp to t)
+             (setq coding-system (cdr (car alist)))
+           (setq alist (cdr alist)))))
+      coding-system)))
+
 ;; See the bottom of this file for built-in auto coding functions.
 (defcustom auto-coding-functions '(sgml-xml-auto-coding-function
                                   sgml-html-meta-auto-coding-function)
@@ -1575,8 +1641,8 @@ This is used for loading and byte-compiling Emacs Lisp files.")
        (setq alist (cdr alist))))
     coding-system))
 
-(defun set-auto-coding (filename size)
-  "Return coding system for a file FILENAME of which SIZE bytes follow point.
+(defun find-auto-coding (filename size)
+  "Find a coding system for a file FILENAME of which SIZE bytes follow point.
 These bytes should include at least the first 1k of the file
 and the last 3k of the file, but the middle may be omitted.
 
@@ -1590,22 +1656,23 @@ contents of the current buffer following point against
 succeed, it checks to see if any function in `auto-coding-functions'
 gives a match.
 
-The return value is the specified coding system, or nil if nothing is
-specified.
-
-The variable `set-auto-coding-function' (which see) is set to this
-function by default."
-  (or (auto-coding-alist-lookup filename)
+If a coding system is specifed, the return value is a
+cons (CODING . SOURCE), where CODING is the specified coding
+system and SOURCE is a symbol `auto-coding-alist',
+`auto-coding-regexp-alist', `coding:', or `auto-coding-functions'
+indicating by what CODING is specified.  Note that the validity
+of CODING is not checked; it's callers responsibility to check
+it.
+
+If nothing is specified, the return value is nil."
+  (or (let ((coding-system (auto-coding-alist-lookup filename)))
+       (if coding-system
+           (cons coding-system 'auto-coding-alist)))
       ;; Try using `auto-coding-regexp-alist'.
-      (save-excursion
-       (let ((alist auto-coding-regexp-alist)
-             coding-system)
-         (while (and alist (not coding-system))
-           (let ((regexp (car (car alist))))
-             (when (re-search-forward regexp (+ (point) size) t)
-               (setq coding-system (cdr (car alist)))))
-           (setq alist (cdr alist)))
-         coding-system))
+      (let ((coding-system (auto-coding-regexp-alist-lookup (point)
+                                                           (+ (point) size))))
+       (if coding-system
+           (cons coding-system 'auto-coding-regexp-alist)))
       (let* ((case-fold-search t)
             (head-start (point))
             (head-end (+ head-start (min size 1024)))
@@ -1639,9 +1706,7 @@ function by default."
                       (re-search-forward
                        "\\(.*;\\)?[ \t]*coding:[ \t]*\\([^ ;]+\\)"
                        head-end t))
-             (setq coding-system (intern (match-string 2)))
-             (or (coding-system-p coding-system)
-                 (setq coding-system nil)))))
+             (setq coding-system (intern (match-string 2))))))
 
        ;; If no coding: tag in the head, check the tail.
        ;; Here we must pay attention to the case that the end-of-line
@@ -1682,10 +1747,9 @@ function by default."
                  (setq coding-system 'raw-text))
                (when (and (not coding-system)
                           (re-search-forward re-coding tail-end t))
-                 (setq coding-system (intern (match-string 1)))
-                 (or (coding-system-p coding-system)
-                     (setq coding-system nil))))))
-       coding-system)
+                 (setq coding-system (intern (match-string 1)))))))
+       (if coding-system
+           (cons coding-system :coding)))
       ;; Finally, try all the `auto-coding-functions'.
       (let ((funcs auto-coding-functions)
            (coding-system nil))
@@ -1695,16 +1759,47 @@ function by default."
                                    (goto-char (point-min))
                                    (funcall (pop funcs) size))
                                (error nil))))
-       coding-system)))
+       (if coding-system
+           (cons coding-system 'auto-coding-functions)))))
+
+(defun set-auto-coding (filename size)
+  "Return coding system for a file FILENAME of which SIZE bytes follow point.
+See `find-auto-coding' for how the coding system is found.
+Return nil if an invalid coding system is found.
+
+The variable `set-auto-coding-function' (which see) is set to this
+function by default."
+  (let ((found (find-auto-coding filename size)))
+    (if (and found (coding-system-p (car found)))
+       (car found))))
 
 (setq set-auto-coding-function 'set-auto-coding)
 
-(defun after-insert-file-set-coding (inserted)
+;; This variable is set in these two cases:
+;;   (1) A file is read by a coding system specified explicitly.
+;;       after-insert-file-set-coding sets this value to
+;;       coding-system-for-read.
+;;   (2) A buffer is saved.
+;;       After writing, basic-save-buffer-1 sets this value to
+;;       last-coding-system-used.
+;; This variable is used for decoding in revert-buffer.
+(defvar buffer-file-coding-system-explicit nil
+  "The file coding system explicitly specified for the current buffer.
+Internal use only.")
+(make-variable-buffer-local 'buffer-file-coding-system-explicit)
+(put 'buffer-file-coding-system-explicit 'permanent-local t)
+
+(defun after-insert-file-set-coding (inserted &optional visit)
   "Set `buffer-file-coding-system' of current buffer after text is inserted.
 INSERTED is the number of characters that were inserted, as figured
 in the situation before this function.  Return the number of characters
 inserted, as figured in the situation after.  The two numbers can be
-different if the buffer has become unibyte."
+different if the buffer has become unibyte.
+The optional second arg VISIT non-nil means that we are visiting a file."
+  (if (and visit
+          coding-system-for-read
+          (not (eq coding-system-for-read 'auto-save-coding)))
+      (setq buffer-file-coding-system-explicit coding-system-for-read))
   (if last-coding-system-used
       (let ((coding-system
             (find-new-buffer-file-coding-system last-coding-system-used)))
@@ -1832,13 +1927,27 @@ or a function symbol which, when called, returns such a cons cell."
 (defun decode-coding-inserted-region (from to filename
                                           &optional visit beg end replace)
   "Decode the region between FROM and TO as if it is read from file FILENAME.
+The idea is that the text between FROM and TO was just inserted somehow.
 Optional arguments VISIT, BEG, END, and REPLACE are the same as those
-of the function `insert-file-contents'."
+of the function `insert-file-contents'.
+Part of the job of this function is setting `buffer-undo-list' appropriately."
   (save-excursion
     (save-restriction
-      (narrow-to-region from to)
-      (goto-char (point-min))
-      (let ((coding coding-system-for-read))
+      (let ((coding coding-system-for-read)
+           undo-list-saved)
+       (if visit
+           ;; Temporarily turn off undo recording, if we're decoding the
+           ;; text of a visited file.
+           (setq buffer-undo-list t)
+         ;; Otherwise, if we can recognize the undo elt for the insertion,
+         ;; remove it and get ready to replace it later.
+         ;; In the mean time, turn off undo recording.
+         (let ((last (car-safe buffer-undo-list)))
+           (if (and (consp last) (eql (car last) from) (eql (cdr last) to))
+               (setq undo-list-saved (cdr buffer-undo-list)
+                     buffer-undo-list t))))
+       (narrow-to-region from to)
+       (goto-char (point-min))
        (or coding
            (setq coding (funcall set-auto-coding-function
                                  filename (- (point-max) (point-min)))))
@@ -1853,7 +1962,35 @@ of the function `insert-file-contents'."
          (setq coding nil))
        (if coding
            (decode-coding-region (point-min) (point-max) coding)
-         (setq last-coding-system-used coding))))))
+         (setq last-coding-system-used coding))
+       ;; If we're decoding the text of a visited file,
+       ;; the undo list should start out empty.
+       (if visit
+           (setq buffer-undo-list nil)
+         ;; If we decided to replace the undo entry for the insertion,
+         ;; do so now.
+         (if undo-list-saved
+             (setq buffer-undo-list
+                   (cons (cons from (point-max)) undo-list-saved))))))))
+
+(defun recode-region (start end new-coding coding)
+  "Re-decode the region (previously decoded by CODING) by NEW-CODING."
+  (interactive
+   (list (region-beginning) (region-end)
+        (read-coding-system "Text was really in: ")
+        (let ((coding (or buffer-file-coding-system last-coding-system-used)))
+          (read-coding-system
+           (concat "But was interpreted as"
+                   (if coding (format " (default %S): " coding) ": "))
+           coding))))
+  (or (and new-coding coding)
+      (error "Coding system not specified"))
+  ;; Check it before we encode the region.
+  (check-coding-system new-coding)
+  (save-restriction
+    (narrow-to-region start end)
+    (encode-coding-region (point-min) (point-max) coding)
+    (decode-coding-region (point-min) (point-max) new-coding)))
 
 (defun make-translation-table (&rest args)
   "Make a translation table from arguments.
@@ -2075,7 +2212,7 @@ Analogous to `define-translation-table', but updates
       (make-char-table 'ignore-relative-composition))
 
 (make-obsolete 'set-char-table-default
-              "Generic characters no longer exist" "22.1")
+              "Generic characters no longer exist" "23.1")
 
 ;;; Built-in auto-coding-functions:
 
@@ -2086,9 +2223,9 @@ This function is intended to be added to `auto-coding-functions'."
   (when (re-search-forward "\\`[[:space:]\n]*<\\?xml" size t)
     (let ((end (save-excursion
                 ;; This is a hack.
-                (re-search-forward "\"\\s-*\\?>" size t))))
+                (re-search-forward "[\"']\\s-*\\?>" size t))))
       (when end
-       (if (re-search-forward "encoding=\"\\(.+?\\)\"" end t)
+       (if (re-search-forward "encoding=[\"']\\(.+?\\)[\"']" end t)
            (let* ((match (match-string 1))
                   (sym (intern (downcase match))))
              (if (coding-system-p sym)