(Fcopy_file): Use Qfile_date_error if can't set file date.
[bpt/emacs.git] / src / fileio.c
index 388d602..cd8b0c1 100644 (file)
@@ -1,5 +1,5 @@
 /* File IO for GNU Emacs.
-   Copyright (C) 1985, 86, 87, 88, 93, 94, 95 Free Software Foundation, Inc.
+   Copyright (C) 1985,86,87,88,93,94,95,96 Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -20,6 +20,10 @@ Boston, MA 02111-1307, USA.  */
 
 #include <config.h>
 
+#if defined (USG5) || defined (BSD_SYSTEM) || defined (LINUX)
+#include <fcntl.h>
+#endif
+
 #include <sys/types.h>
 #include <sys/stat.h>
 
@@ -31,6 +35,10 @@ Boston, MA 02111-1307, USA.  */
 #  define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
 #endif
 
+#if !defined (S_ISFIFO) && defined (S_IFIFO)
+#  define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
+#endif
+
 #if !defined (S_ISREG) && defined (S_IFREG)
 #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
 #endif
@@ -84,6 +92,8 @@ extern char *strerror ();
 #include "lisp.h"
 #include "intervals.h"
 #include "buffer.h"
+#include "charset.h"
+#include "coding.h"
 #include "window.h"
 
 #ifdef WINDOWSNT
@@ -93,6 +103,25 @@ extern char *strerror ();
 #include <fcntl.h>
 #endif /* not WINDOWSNT */
 
+#ifdef DOS_NT
+#define CORRECT_DIR_SEPS(s) \
+  do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
+       else unixtodos_filename (s); \
+  } while (0)
+/* On Windows, drive letters must be alphabetic - on DOS, the Netware
+   redirector allows the six letters between 'Z' and 'a' as well. */
+#ifdef MSDOS
+#define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
+#endif
+#ifdef WINDOWSNT
+#define IS_DRIVE(x) isalpha (x)
+#endif
+/* Need to lower-case the drive letter, or else expanded
+   filenames will sometimes compare inequal, because
+   `expand-file-name' doesn't always down-case the drive letter.  */
+#define DRIVE_LETTER(x) (tolower (x))
+#endif
+
 #ifdef VMS
 #include <file.h>
 #include <rmsdef.h>
@@ -129,7 +158,7 @@ int auto_saving;
    a new file with the same mode as the original */
 int auto_save_mode_bits;
 
-/* Alist of elements (REGEXP . HANDLER) for file names 
+/* Alist of elements (REGEXP . HANDLER) for file names
    whose I/O is done with a special handler.  */
 Lisp_Object Vfile_name_handler_alist;
 
@@ -160,6 +189,14 @@ int insert_default_directory;
    Zero means use var format.  */
 int vms_stmlf_recfm;
 
+/* On NT, specifies the directory separator character, used (eg.) when
+   expanding file names.  This can be bound to / or \. */
+Lisp_Object Vdirectory_sep_char;
+
+extern Lisp_Object Vuser_login_name;
+
+extern int minibuf_level;
+
 /* These variables describe handlers that have "already" had a chance
    to handle the current operation.
 
@@ -170,7 +207,7 @@ int vms_stmlf_recfm;
 static Lisp_Object Vinhibit_file_name_handlers;
 static Lisp_Object Vinhibit_file_name_operation;
 
-Lisp_Object Qfile_error, Qfile_already_exists;
+Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
 
 Lisp_Object Qfile_name_history;
 
@@ -203,7 +240,7 @@ close_file_unwind (fd)
 /* Restore point, having saved it as a marker.  */
 
 restore_point_unwind (location)
-     Lisp_Object location; 
+     Lisp_Object location;
 {
   SET_PT (marker_position (location));
   Fset_marker (location, Qnil, Qnil);
@@ -226,8 +263,9 @@ Lisp_Object Qmake_symbolic_link;
 Lisp_Object Qfile_exists_p;
 Lisp_Object Qfile_executable_p;
 Lisp_Object Qfile_readable_p;
-Lisp_Object Qfile_symlink_p;
 Lisp_Object Qfile_writable_p;
+Lisp_Object Qfile_symlink_p;
+Lisp_Object Qaccess_file;
 Lisp_Object Qfile_directory_p;
 Lisp_Object Qfile_regular_p;
 Lisp_Object Qfile_accessible_directory_p;
@@ -312,44 +350,38 @@ on VMS, perhaps instead a string ending in `:', `]' or `>'.")
   filename = FILE_SYSTEM_CASE (filename);
 #endif
   beg = XSTRING (filename)->data;
+#ifdef DOS_NT
+  beg = strcpy (alloca (strlen (beg) + 1), beg);
+#endif
   p = beg + XSTRING (filename)->size;
 
-  while (p != beg && !IS_ANY_SEP (p[-1])
+  while (p != beg && !IS_DIRECTORY_SEP (p[-1])
 #ifdef VMS
         && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
 #endif /* VMS */
+#ifdef DOS_NT
+        /* only recognise drive specifier at beginning */
+        && !(p[-1] == ':' && p == beg + 2)
+#endif
         ) p--;
 
   if (p == beg)
     return Qnil;
 #ifdef DOS_NT
   /* Expansion of "c:" to drive and default directory.  */
-  /* (NT does the right thing.)  */
   if (p == beg + 2 && beg[1] == ':')
     {
-      int drive = (*beg) - 'a';
       /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir.  */
-      unsigned char *res = alloca (MAXPATHLEN + 5);
-      unsigned char *res1;
-#ifdef WINDOWSNT
-      res1 = res;
-      /* The NT version places the drive letter at the beginning already.  */
-#else /* not WINDOWSNT */
-      /* On MSDOG we must put the drive letter in by hand.  */
-      res1 = res + 2;
-#endif /* not WINDOWSNT */
-      if (getdefdir (drive + 1, res)) 
+      unsigned char *res = alloca (MAXPATHLEN + 1);
+      if (getdefdir (toupper (*beg) - 'A' + 1, res))
        {
-#ifdef MSDOS
-         res[0] = drive + 'a';
-         res[1] = ':';
-#endif /* MSDOS */
-         if (IS_DIRECTORY_SEP (res[strlen (res) - 1]))
+         if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
            strcat (res, "/");
          beg = res;
          p = beg + strlen (beg);
        }
     }
+  CORRECT_DIR_SEPS (beg);
 #endif /* DOS_NT */
   return make_string (beg, p - beg);
 }
@@ -377,10 +409,14 @@ or the entire name if it contains no slash.")
   beg = XSTRING (filename)->data;
   end = p = beg + XSTRING (filename)->size;
 
-  while (p != beg && !IS_ANY_SEP (p[-1])
+  while (p != beg && !IS_DIRECTORY_SEP (p[-1])
 #ifdef VMS
         && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
 #endif /* VMS */
+#ifdef DOS_NT
+        /* only recognise drive specifier at beginning */
+        && !(p[-1] == ':' && p == beg + 2)
+#endif
         ) p--;
 
   return make_string (p, end - p);
@@ -476,11 +512,14 @@ file_name_as_directory (out, in)
     }
 #else /* not VMS */
   /* For Unix syntax, Append a slash if necessary */
-  if (!IS_ANY_SEP (out[size]))
+  if (!IS_DIRECTORY_SEP (out[size]))
     {
       out[size + 1] = DIRECTORY_SEP;
       out[size + 2] = '\0';
     }
+#ifdef DOS_NT
+  CORRECT_DIR_SEPS (out);
+#endif
 #endif /* not VMS */
   return out;
 }
@@ -519,7 +558,7 @@ On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc.")
  * On VMS:
  *       xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
  *       xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
- * On UNIX, it's simple: just make sure there is a terminating /
+ * On UNIX, it's simple: just make sure there isn't a terminating /
 
  * Value is nonzero if the string output is different from the input.
  */
@@ -555,7 +594,7 @@ directory_file_name (src, dst)
       nam.nam$b_nop |= NAM$M_SYNCHK;
 
       /* We call SYS$PARSE to handle such things as [--] for us. */
-      if (SYS$PARSE(&fab, 0, 0) == RMS$_NORMAL)
+      if (SYS$PARSE (&fab, 0, 0) == RMS$_NORMAL)
        {
          slen = nam.nam$b_esl;
          if (esa[slen - 1] == ';' && esa[slen - 2] == '.')
@@ -624,7 +663,7 @@ directory_file_name (src, dst)
             then translate the device and recurse. */
          if (dst[slen - 1] == ':'
              && dst[slen - 2] != ':'   /* skip decnet nodes */
-             && strcmp(src + slen, "[000000]") == 0)
+             && strcmp (src + slen, "[000000]") == 0)
            {
              dst[slen - 1] = '\0';
              if ((ptr = egetenv (dst))
@@ -661,13 +700,16 @@ directory_file_name (src, dst)
       || (slen > 1 && dst[0] != '/' && dst[slen - 1] == '/'))
     dst[slen - 1] = 0;
 #else
-  if (slen > 1 
+  if (slen > 1
       && IS_DIRECTORY_SEP (dst[slen - 1])
 #ifdef DOS_NT
       && !IS_ANY_SEP (dst[slen - 2])
 #endif
       )
     dst[slen - 1] = 0;
+#endif
+#ifdef DOS_NT
+  CORRECT_DIR_SEPS (dst);
 #endif
   return 1;
 }
@@ -726,6 +768,9 @@ so there is no danger of generating a name being used by another process.")
   val = concat2 (prefix, build_string ("XXXXXX"));
 #endif
   mktemp (XSTRING (val)->data);
+#ifdef DOS_NT
+  CORRECT_DIR_SEPS (XSTRING (val)->data);
+#endif
   return val;
 }
 \f
@@ -734,10 +779,10 @@ DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
 Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative\n\
  (does not start with slash); if DEFAULT-DIRECTORY is nil or missing,\n\
 the current buffer's value of default-directory is used.\n\
-Path components that are `.' are removed, and \n\
-path components followed by `..' are removed, along with the `..' itself;\n\
+File name components that are `.' are removed, and \n\
+so are file name components followed by `..', along with the `..' itself;\n\
 note that these simplifications are done without checking the resulting\n\
-paths in the file system.\n\
+file names in the file system.\n\
 An initial `~/' expands to your home directory.\n\
 An initial `~USER/' expands to USER's home directory.\n\
 See also the function `substitute-in-file-name'.")
@@ -745,7 +790,7 @@ See also the function `substitute-in-file-name'.")
      Lisp_Object name, default_directory;
 {
   unsigned char *nm;
-  
+
   register unsigned char *newdir, *p, *o;
   int tlen;
   unsigned char *target;
@@ -759,13 +804,12 @@ See also the function `substitute-in-file-name'.")
   int dots = 0;
 #endif /* VMS */
 #ifdef DOS_NT
-  /* Demacs 1.1.2 91/10/20 Manabu Higashida */
-  int drive = -1;
-  int relpath = 0;
-  unsigned char *tmp, *defdir;
+  int drive = 0;
+  int collapse_newdir = 1;
 #endif /* DOS_NT */
+  int length;
   Lisp_Object handler;
-  
+
   CHECK_STRING (name, 0);
 
   /* If the file name has special constructs in it,
@@ -799,15 +843,22 @@ See also the function `substitute-in-file-name'.")
 
      The EQ test avoids infinite recursion.  */
   if (! NILP (default_directory) && !EQ (default_directory, name)
-      /* Save time in some common cases.  */
+      /* Save time in some common cases - as long as default_directory
+        is not relative, it can be canonicalized with name below (if it
+        is needed at all) without requiring it to be expanded now.  */
 #ifdef DOS_NT
-      /* Detect MSDOS file names with device names.  */
-      && ! (XSTRING (default_directory)->size >= 3
-           && IS_DEVICE_SEP (o[1]) && IS_DIRECTORY_SEP (o[2]))
+      /* Detect MSDOS file names with drive specifiers.  */
+      && ! (IS_DRIVE (o[0]) && (IS_DEVICE_SEP (o[1]) && IS_DIRECTORY_SEP (o[2])))
+#ifdef WINDOWSNT
+      /* Detect Windows file names in UNC format.  */
+      && ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
 #endif
-      /* Detect Unix absolute file names.  */
-      && ! (XSTRING (default_directory)->size >= 2
-           && IS_DIRECTORY_SEP (o[0])))
+#else /* not DOS_NT */
+      /* Detect Unix absolute file names (/... alone is not absolute on
+        DOS or Windows).  */
+      && ! (IS_DIRECTORY_SEP (o[0]))
+#endif /* not DOS_NT */
+      )
     {
       struct gcpro gcpro1;
 
@@ -825,62 +876,60 @@ See also the function `substitute-in-file-name'.")
 #endif
 
   nm = XSTRING (name)->data;
-  
-#ifdef MSDOS
-  /* First map all backslashes to slashes.  */
-  dostounix_filename (nm = strcpy (alloca (strlen (nm) + 1), nm));
-#endif
 
 #ifdef DOS_NT
-  /* Now strip drive name. */
+  /* We will force directory separators to be either all \ or /, so make
+     a local copy to modify, even if there ends up being no change. */
+  nm = strcpy (alloca (strlen (nm) + 1), nm);
+
+  /* Find and remove drive specifier if present; this makes nm absolute
+     even if the rest of the name appears to be relative. */
   {
     unsigned char *colon = rindex (nm, ':');
+
     if (colon)
+      /* Only recognize colon as part of drive specifier if there is a
+        single alphabetic character preceeding the colon (and if the
+        character before the drive letter, if present, is a directory
+        separator); this is to support the remote system syntax used by
+        ange-ftp, and the "po:username" syntax for POP mailboxes. */
+    look_again:
       if (nm == colon)
        nm++;
-      else
+      else if (IS_DRIVE (colon[-1])
+              && (colon == nm + 1 || IS_DIRECTORY_SEP (colon[-2])))
        {
          drive = colon[-1];
          nm = colon + 1;
-         if (!IS_DIRECTORY_SEP (*nm))
-           {
-             defdir = alloca (MAXPATHLEN + 1);
-             relpath = getdefdir (tolower (drive) - 'a' + 1, defdir);
-           }
-       }       
+       }
+      else
+       {
+         while (--colon >= nm)
+           if (colon[0] == ':')
+             goto look_again;
+       }
   }
 #endif /* DOS_NT */
 
-  /* Handle // and /~ in middle of file name
-     by discarding everything through the first / of that sequence.  */
-  p = nm;
-  while (*p)
+#ifdef WINDOWSNT
+  /* Discard any previous drive specifier if nm is now in UNC format. */
+  if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
     {
-      /* Since we know the path is absolute, we can assume that each
-        element starts with a "/".  */
-
-      /* "//" anywhere isn't necessarily hairy; we just start afresh
-        with the second slash.  */
-      if (IS_DIRECTORY_SEP (p[0]) && IS_DIRECTORY_SEP (p[1])
-#if defined (APOLLO) || defined (WINDOWSNT)
-         /* // at start of filename is meaningful on Apollo 
-            and WindowsNT systems */
-         && nm != p
-#endif /* APOLLO || WINDOWSNT */
-         )
-       nm = p + 1;
-
-      /* "~" is hairy as the start of any path element.  */
-      if (IS_DIRECTORY_SEP (p[0]) && p[1] == '~')
-       nm = p + 1;
-
-      p++;
+      drive = 0;
     }
+#endif
 
-  /* If nm is absolute, flush ...// and detect /./ and /../.
-     If no /./ or /../ we can return right away. */
+  /* If nm is absolute, look for /./ or /../ sequences; if none are
+     found, we can probably return right away.  We will avoid allocating
+     a new string if name is already fully expanded.  */
   if (
       IS_DIRECTORY_SEP (nm[0])
+#ifdef MSDOS
+      && drive
+#endif
+#ifdef WINDOWSNT
+      && (drive || IS_DIRECTORY_SEP (nm[1]))
+#endif
 #ifdef VMS
       || index (nm, ':')
 #endif /* VMS */
@@ -897,7 +946,7 @@ See also the function `substitute-in-file-name'.")
       p = nm;
       while (*p)
        {
-         /* Since we know the path is absolute, we can assume that each
+         /* Since we know the name is absolute, we can assume that each
             element starts with a "/".  */
 
          /* "." and ".." are hairy.  */
@@ -957,7 +1006,7 @@ See also the function `substitute-in-file-name'.")
                nm = brack + 1;
                brack = 0;
              }
-           /* if /pathname/dev:, move nm to dev: */
+           /* if /name/dev:, move nm to dev: */
            else if (slash)
              nm = slash + 1;
            /* if node::dev:, move colon following dev */
@@ -989,7 +1038,28 @@ See also the function `substitute-in-file-name'.")
          if (index (nm, '/'))
            return build_string (sys_translate_unix (nm));
 #endif /* VMS */
-#ifndef DOS_NT
+#ifdef DOS_NT
+         /* Make sure directories are all separated with / or \ as
+            desired, but avoid allocation of a new string when not
+            required. */
+         CORRECT_DIR_SEPS (nm);
+#ifdef WINDOWSNT
+         if (IS_DIRECTORY_SEP (nm[1]))
+           {
+             if (strcmp (nm, XSTRING (name)->data) != 0)
+               name = build_string (nm);
+           }
+         else
+#endif
+         /* drive must be set, so this is okay */
+         if (strcmp (nm - 2, XSTRING (name)->data) != 0)
+           {
+             name = make_string (nm - 2, p - nm + 2);
+             XSTRING (name)->data[0] = DRIVE_LETTER (drive);
+             XSTRING (name)->data[1] = ':';
+           }
+         return name;
+#else /* not DOS_NT */
          if (nm == XSTRING (name)->data)
            return name;
          return build_string (nm);
@@ -997,7 +1067,21 @@ See also the function `substitute-in-file-name'.")
        }
     }
 
-  /* Now determine directory to start with and put it in newdir */
+  /* At this point, nm might or might not be an absolute file name.  We
+     need to expand ~ or ~user if present, otherwise prefix nm with
+     default_directory if nm is not absolute, and finally collapse /./
+     and /foo/../ sequences.
+
+     We set newdir to be the appropriate prefix if one is needed:
+       - the relevant user directory if nm starts with ~ or ~user
+       - the specified drive's working dir (DOS/NT only) if nm does not
+         start with /
+       - the value of default_directory.
+
+     Note that these prefixes are not guaranteed to be absolute (except
+     for the working dir of a drive).  Therefore, to ensure we always
+     return an absolute name, if the final prefix is not absolute we
+     append it to the current working directory.  */
 
   newdir = 0;
 
@@ -1011,14 +1095,10 @@ See also the function `substitute-in-file-name'.")
        {
          if (!(newdir = (unsigned char *) egetenv ("HOME")))
            newdir = (unsigned char *) "";
+         nm++;
 #ifdef DOS_NT
-         /* Problem when expanding "~\" if HOME is not on current drive.
-            Ulrich Leodolter, Wed Jan 11 10:20:35 1995 */
-         if (newdir[1] == ':')
-           drive = newdir[0];
-         dostounix_filename (newdir);
+         collapse_newdir = 0;
 #endif
-         nm++;
 #ifdef VMS
          nm++;                 /* Don't leave the slash in nm.  */
 #endif /* VMS */
@@ -1034,10 +1114,6 @@ See also the function `substitute-in-file-name'.")
          bcopy ((char *) nm, o, p - nm);
          o [p - nm] = 0;
 
-#ifdef  WINDOWSNT
-         newdir = (unsigned char *) egetenv ("HOME");
-         dostounix_filename (newdir);
-#else  /* not WINDOWSNT */
          pw = (struct passwd *) getpwnam (o + 1);
          if (pw)
            {
@@ -1046,42 +1122,140 @@ See also the function `substitute-in-file-name'.")
              nm = p + 1;       /* skip the terminator */
 #else
              nm = p;
+#ifdef DOS_NT
+             collapse_newdir = 0;
+#endif
 #endif /* VMS */
            }
-#endif /* not WINDOWSNT */
 
          /* If we don't find a user of that name, leave the name
             unchanged; don't move nm forward to p.  */
        }
     }
 
-  if (!IS_ANY_SEP (nm[0])
-#ifdef VMS
-      && !index (nm, ':')
-#endif /* not VMS */
 #ifdef DOS_NT
-      && drive == -1
+  /* On DOS and Windows, nm is absolute if a drive name was specified;
+     use the drive's current directory as the prefix if needed.  */
+  if (!newdir && drive)
+    {
+      /* Get default directory if needed to make nm absolute. */
+      if (!IS_DIRECTORY_SEP (nm[0]))
+       {
+         newdir = alloca (MAXPATHLEN + 1);
+         if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
+           newdir = NULL;
+       }
+      if (!newdir)
+       {
+         /* Either nm starts with /, or drive isn't mounted. */
+         newdir = alloca (4);
+         newdir[0] = DRIVE_LETTER (drive);
+         newdir[1] = ':';
+         newdir[2] = '/';
+         newdir[3] = 0;
+       }
+    }
 #endif /* DOS_NT */
+
+  /* Finally, if no prefix has been specified and nm is not absolute,
+     then it must be expanded relative to default_directory. */
+
+  if (1
+#ifndef DOS_NT
+      /* /... alone is not absolute on DOS and Windows. */
+      && !IS_DIRECTORY_SEP (nm[0])
+#endif
+#ifdef WINDOWSNT
+      && !(IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
+#endif
+#ifdef VMS
+      && !index (nm, ':')
+#endif
       && !newdir)
     {
       newdir = XSTRING (default_directory)->data;
     }
 
 #ifdef DOS_NT
-  if (newdir == 0 && relpath)
-    newdir = defdir; 
+  if (newdir)
+    {
+      /* First ensure newdir is an absolute name. */
+      if (
+         /* Detect MSDOS file names with drive specifiers.  */
+         ! (IS_DRIVE (newdir[0])
+            && IS_DEVICE_SEP (newdir[1]) && IS_DIRECTORY_SEP (newdir[2]))
+#ifdef WINDOWSNT
+         /* Detect Windows file names in UNC format.  */
+         && ! (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
+#endif
+         )
+       {
+         /* Effectively, let newdir be (expand-file-name newdir cwd).
+            Because of the admonition against calling expand-file-name
+            when we have pointers into lisp strings, we accomplish this
+            indirectly by prepending newdir to nm if necessary, and using
+            cwd (or the wd of newdir's drive) as the new newdir. */
+
+         if (IS_DRIVE (newdir[0]) && newdir[1] == ':')
+           {
+             drive = newdir[0];
+             newdir += 2;
+           }
+         if (!IS_DIRECTORY_SEP (nm[0]))
+           {
+             char * tmp = alloca (strlen (newdir) + strlen (nm) + 2);
+             file_name_as_directory (tmp, newdir);
+             strcat (tmp, nm);
+             nm = tmp;
+           }
+         newdir = alloca (MAXPATHLEN + 1);
+         if (drive)
+           {
+             if (!getdefdir (toupper (drive) - 'A' + 1, newdir))
+               newdir = "/";
+           }
+         else
+           getwd (newdir);
+       }
+
+      /* Strip off drive name from prefix, if present. */
+      if (IS_DRIVE (newdir[0]) && newdir[1] == ':')
+       {
+         drive = newdir[0];
+         newdir += 2;
+       }
+
+      /* Keep only a prefix from newdir if nm starts with slash
+         (//server/share for UNC, nothing otherwise). */
+      if (IS_DIRECTORY_SEP (nm[0]) && collapse_newdir)
+       {
+#ifdef WINDOWSNT
+         if (IS_DIRECTORY_SEP (newdir[0]) && IS_DIRECTORY_SEP (newdir[1]))
+           {
+             newdir = strcpy (alloca (strlen (newdir) + 1), newdir);
+             p = newdir + 2;
+             while (*p && !IS_DIRECTORY_SEP (*p)) p++;
+             p++;
+             while (*p && !IS_DIRECTORY_SEP (*p)) p++;
+             *p = 0;
+           }
+         else
+#endif
+           newdir = "";
+       }
+    }
 #endif /* DOS_NT */
-  if (newdir != 0)
+
+  if (newdir)
     {
-      /* Get rid of any slash at the end of newdir.  */
-      int length = strlen (newdir);
-      /* Adding `length > 1 &&' makes ~ expand into / when homedir
-        is the root dir.  People disagree about whether that is right.
-        Anyway, we can't take the risk of this change now.  */
-#ifdef DOS_NT
-      if (newdir[1] != ':' && length > 1)
+      /* Get rid of any slash at the end of newdir, unless newdir is
+       just // (an incomplete UNC name). */
+      length = strlen (newdir);
+      if (IS_DIRECTORY_SEP (newdir[length - 1])
+#ifdef WINDOWSNT
+         && !(length == 2 && IS_DIRECTORY_SEP (newdir[0]))
 #endif
-      if (IS_DIRECTORY_SEP (newdir[length - 1]))
+         )
        {
          unsigned char *temp = (unsigned char *) alloca (length);
          bcopy (newdir, temp, length - 1);
@@ -1096,7 +1270,7 @@ See also the function `substitute-in-file-name'.")
   /* Now concatenate the directory and name to new space in the stack frame */
   tlen += strlen (nm) + 1;
 #ifdef DOS_NT
-  /* Add reserved space for drive name.  (The Microsoft x86 compiler 
+  /* Add reserved space for drive name.  (The Microsoft x86 compiler
      produces incorrect code if the following two lines are combined.)  */
   target = (unsigned char *) alloca (tlen + 2);
   target += 2;
@@ -1121,6 +1295,8 @@ See also the function `substitute-in-file-name'.")
     strcpy (target, sys_translate_unix (target));
 #endif /* VMS */
 
+  /* ASSERT (IS_DIRECTORY_SEP (target[0])) if not VMS */
+
   /* Now canonicalize by removing /. and /foo/.. if they appear.  */
 
   p = target;
@@ -1176,10 +1352,10 @@ See also the function `substitute-in-file-name'.")
        }
       else if (IS_DIRECTORY_SEP (p[0]) && IS_DIRECTORY_SEP (p[1])
 #if defined (APOLLO) || defined (WINDOWSNT)
-              /* // at start of filename is meaningful in Apollo 
+              /* // at start of filename is meaningful in Apollo
                  and WindowsNT systems */
               && o != target
-#endif /* APOLLO */
+#endif /* APOLLO || WINDOWSNT */
               )
        {
          o = target;
@@ -1203,12 +1379,6 @@ See also the function `substitute-in-file-name'.")
        {
          while (o != target && (--o) && !IS_DIRECTORY_SEP (*o))
            ;
-#if defined (APOLLO) || defined (WINDOWSNT)
-         if (o == target + 1 
-             && IS_DIRECTORY_SEP (o[-1]) && IS_DIRECTORY_SEP (o[0]))
-           ++o;
-         else
-#endif /* APOLLO || WINDOWSNT */
          if (o == target && IS_ANY_SEP (*o))
            ++o;
          p += 3;
@@ -1221,18 +1391,18 @@ See also the function `substitute-in-file-name'.")
     }
 
 #ifdef DOS_NT
-  /* at last, set drive name. */
-  if (target[1] != ':'
+  /* At last, set drive name. */
 #ifdef WINDOWSNT
-      /* Allow network paths that look like "\\foo" */
-      && !(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))
+  /* Except for network file name.  */
+  if (!(IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1])))
 #endif /* WINDOWSNT */
-      )
     {
+      if (!drive) abort ();
       target -= 2;
-      target[0] = (drive < 0 ? getdisk () + 'A' : drive);
+      target[0] = DRIVE_LETTER (drive);
       target[1] = ':';
     }
+  CORRECT_DIR_SEPS (target);
 #endif /* DOS_NT */
 
   return make_string (target, o - target);
@@ -1252,7 +1422,7 @@ See also the function `substitute-in-file-name'.")
      Lisp_Object name, defalt;
 {
   unsigned char *nm;
-  
+
   register unsigned char *newdir, *p, *o;
   int tlen;
   unsigned char *target;
@@ -1266,7 +1436,7 @@ See also the function `substitute-in-file-name'.")
   int lbrack = 0, rbrack = 0;
   int dots = 0;
 #endif /* VMS */
-  
+
   CHECK_STRING (name, 0);
 
 #ifdef VMS
@@ -1275,7 +1445,7 @@ See also the function `substitute-in-file-name'.")
 #endif
 
   nm = XSTRING (name)->data;
-  
+
   /* If nm is absolute, flush ...// and detect /./ and /../.
      If no /./ or /../ we can return right away. */
   if (
@@ -1351,13 +1521,13 @@ See also the function `substitute-in-file-name'.")
                nm = brack + 1;
                brack = 0;
              }
-           /* if /pathname/dev:, move nm to dev: */
+           /* If /name/dev:, move nm to dev: */
            else if (slash)
              nm = slash + 1;
-           /* if node::dev:, move colon following dev */
+           /* If node::dev:, move colon following dev */
            else if (colon && colon[-1] == ':')
              colon = p;
-           /* if dev1:dev2:, move nm to dev2: */
+           /* If dev1:dev2:, move nm to dev2: */
            else if (colon && colon[-1] != ':')
              {
                nm = colon + 1;
@@ -1593,9 +1763,10 @@ duplicates what `expand-file-name' does.")
     return call2 (handler, Qsubstitute_in_file_name, filename);
 
   nm = XSTRING (filename)->data;
-#ifdef MSDOS
-  dostounix_filename (nm = strcpy (alloca (strlen (nm) + 1), nm));
-  substituted = !strcmp (nm, XSTRING (filename)->data);
+#ifdef DOS_NT
+  nm = strcpy (alloca (strlen (nm) + 1), nm);
+  CORRECT_DIR_SEPS (nm);
+  substituted = (strcmp (nm, XSTRING (filename)->data) != 0);
 #endif
   endp = nm + XSTRING (filename)->size;
 
@@ -1603,17 +1774,14 @@ duplicates what `expand-file-name' does.")
 
   for (p = nm; p != endp; p++)
     {
-      if ((p[0] == '~' ||
-#ifdef APOLLO
-          /* // at start of file name is meaningful in Apollo system */
-          (p[0] == '/' && p - 1 != nm)
-#else /* not APOLLO */
-#ifdef WINDOWSNT
-          (IS_DIRECTORY_SEP (p[0]) && p - 1 != nm)
-#else /* not WINDOWSNT */
-          p[0] == '/'
-#endif /* not WINDOWSNT */
-#endif /* not APOLLO */
+      if ((p[0] == '~'
+#if defined (APOLLO) || defined (WINDOWSNT)
+          /* // at start of file name is meaningful in Apollo and
+             WindowsNT systems */
+          || (IS_DIRECTORY_SEP (p[0]) && p - 1 != nm)
+#else /* not (APOLLO || WINDOWSNT) */
+          || IS_DIRECTORY_SEP (p[0])
+#endif /* not (APOLLO || WINDOWSNT) */
           )
          && p != nm
          && (0
@@ -1626,7 +1794,9 @@ duplicates what `expand-file-name' does.")
          substituted = 1;
        }
 #ifdef DOS_NT
-      if (p[0] && p[1] == ':')
+      /* see comment in expand-file-name about drive specifiers */
+      else if (IS_DRIVE (p[0]) && p[1] == ':'
+              && p > nm && IS_DIRECTORY_SEP (p[-1]))
        {
          nm = p;
          substituted = 1;
@@ -1745,22 +1915,18 @@ duplicates what `expand-file-name' does.")
 
   for (p = xnm; p != x; p++)
     if ((p[0] == '~'
-#ifdef APOLLO
-        /* // at start of file name is meaningful in Apollo system */
-        || (p[0] == '/' && p - 1 != xnm)
-#else /* not APOLLO */
-#ifdef WINDOWSNT
+#if defined (APOLLO) || defined (WINDOWSNT)
         || (IS_DIRECTORY_SEP (p[0]) && p - 1 != xnm)
-#else /* not WINDOWSNT */
-        || p[0] == '/'
-#endif /* not WINDOWSNT */
-#endif /* not APOLLO */
+#else /* not (APOLLO || WINDOWSNT) */
+        || IS_DIRECTORY_SEP (p[0])
+#endif /* not (APOLLO || WINDOWSNT) */
         )
        && p != nm && IS_DIRECTORY_SEP (p[-1]))
       xnm = p;
 #ifdef DOS_NT
-    else if (p[0] && p[1] == ':')
-       xnm = p;
+    else if (IS_DRIVE (p[0]) && p[1] == ':'
+            && p > nm && IS_DIRECTORY_SEP (p[-1]))
+      xnm = p;
 #endif
 
   return make_string (xnm, x - xnm);
@@ -1783,25 +1949,25 @@ Lisp_Object
 expand_and_dir_to_file (filename, defdir)
      Lisp_Object filename, defdir;
 {
-  register Lisp_Object abspath;
+  register Lisp_Object absname;
 
-  abspath = Fexpand_file_name (filename, defdir);
+  absname = Fexpand_file_name (filename, defdir);
 #ifdef VMS
   {
-    register int c = XSTRING (abspath)->data[XSTRING (abspath)->size - 1];
+    register int c = XSTRING (absname)->data[XSTRING (absname)->size - 1];
     if (c == ':' || c == ']' || c == '>')
-      abspath = Fdirectory_file_name (abspath);
+      absname = Fdirectory_file_name (absname);
   }
 #else
-  /* Remove final slash, if any (unless path is root).
+  /* Remove final slash, if any (unless this is the root dir).
      stat behaves differently depending!  */
-  if (XSTRING (abspath)->size > 1
-      && IS_DIRECTORY_SEP (XSTRING (abspath)->data[XSTRING (abspath)->size - 1])
-      && !IS_DEVICE_SEP (XSTRING (abspath)->data[XSTRING (abspath)->size-2]))
+  if (XSTRING (absname)->size > 1
+      && IS_DIRECTORY_SEP (XSTRING (absname)->data[XSTRING (absname)->size - 1])
+      && !IS_DEVICE_SEP (XSTRING (absname)->data[XSTRING (absname)->size-2]))
     /* We cannot take shortcuts; they might be wrong for magic file names.  */
-    abspath = Fdirectory_file_name (abspath);
+    absname = Fdirectory_file_name (absname);
 #endif
-  return abspath;
+  return absname;
 }
 \f
 /* Signal an error if the file ABSNAME already exists.
@@ -1904,7 +2070,7 @@ A prefix arg makes KEEP-TIME non-nil.")
      copyable by us. */
   input_file_statable_p = (fstat (ifd, &st) >= 0);
 
-#ifndef DOS_NT
+#if !defined (MSDOS) || __DJGPP__ > 1
   if (out_st.st_mode != 0
       && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino)
     {
@@ -1963,7 +2129,9 @@ A prefix arg makes KEEP-TIME non-nil.")
          EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
          EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
          if (set_file_times (XSTRING (newname)->data, atime, mtime))
-           report_file_error ("I/O error", Fcons (newname, Qnil));
+           Fsignal (Qfile_date_error,
+                    Fcons (build_string ("File already exists"),
+                           Fcons (absname, Qnil)));
        }
 #ifndef MSDOS
       chmod (XSTRING (newname)->data, st.st_mode & 07777);
@@ -2308,10 +2476,10 @@ DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
      Lisp_Object path, login;
 {
   int netresult;
-  
+
   CHECK_STRING (path, 0);
-  CHECK_STRING (login, 0);  
-  
+  CHECK_STRING (login, 0);
+
   netresult = netunam (XSTRING (path)->data, XSTRING (login)->data);
 
   if (netresult == -1)
@@ -2323,7 +2491,7 @@ DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
 \f
 DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
        1, 1, 0,
-       "Return t if file FILENAME specifies an absolute path name.\n\
+       "Return t if file FILENAME specifies an absolute file name.\n\
 On Unix, this is a name starting with a `/' or a `~'.")
      (filename)
      Lisp_Object filename;
@@ -2340,7 +2508,7 @@ On Unix, this is a name starting with a `/' or a `~'.")
          && ptr[1] != '.')
 #endif /* VMS */
 #ifdef DOS_NT
-      || (*ptr != 0 && ptr[1] == ':' && (ptr[2] == '/' || ptr[2] == '\\'))
+      || (IS_DRIVE (*ptr) && ptr[1] == ':' && IS_DIRECTORY_SEP (ptr[2]))
 #endif
       )
     return Qt;
@@ -2360,15 +2528,19 @@ check_executable (filename)
   struct stat st;
   if (stat (filename, &st) < 0)
     return 0;
+#if defined (WINDOWSNT) || (defined (MSDOS) && __DJGPP__ > 1)
+  return ((st.st_mode & S_IEXEC) != 0);
+#else
   return (S_ISREG (st.st_mode)
          && len >= 5
          && (stricmp ((suffix = filename + len-4), ".com") == 0
              || stricmp (suffix, ".exe") == 0
              || stricmp (suffix, ".bat") == 0)
          || (st.st_mode & S_IFMT) == S_IFDIR);
+#endif /* not WINDOWSNT */
 #else /* not DOS_NT */
-#ifdef HAVE_EACCESS
-  return (eaccess (filename, 1) >= 0);
+#ifdef HAVE_EUIDACCESS
+  return (euidaccess (filename, 1) >= 0);
 #else
   /* Access isn't quite right because it uses the real uid
      and we really want to test with the effective uid.
@@ -2390,8 +2562,8 @@ check_writable (filename)
     return 0;
   return (st.st_mode & S_IWRITE || (st.st_mode & S_IFMT) == S_IFDIR);
 #else /* not MSDOS */
-#ifdef HAVE_EACCESS
-  return (eaccess (filename, 2) >= 0);
+#ifdef HAVE_EUIDACCESS
+  return (euidaccess (filename, 2) >= 0);
 #else
   /* Access isn't quite right because it uses the real uid
      and we really want to test with the effective uid.
@@ -2409,20 +2581,20 @@ See also `file-readable-p' and `file-attributes'.")
   (filename)
      Lisp_Object filename;
 {
-  Lisp_Object abspath;
+  Lisp_Object absname;
   Lisp_Object handler;
   struct stat statbuf;
 
   CHECK_STRING (filename, 0);
-  abspath = Fexpand_file_name (filename, Qnil);
+  absname = Fexpand_file_name (filename, Qnil);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_exists_p);
+  handler = Ffind_file_name_handler (absname, Qfile_exists_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_exists_p, abspath);
+    return call2 (handler, Qfile_exists_p, absname);
 
-  return (stat (XSTRING (abspath)->data, &statbuf) >= 0) ? Qt : Qnil;
+  return (stat (XSTRING (absname)->data, &statbuf) >= 0) ? Qt : Qnil;
 }
 
 DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
@@ -2432,19 +2604,19 @@ For a directory, this means you can access files in that directory.")
     Lisp_Object filename;
 
 {
-  Lisp_Object abspath;
+  Lisp_Object absname;
   Lisp_Object handler;
 
   CHECK_STRING (filename, 0);
-  abspath = Fexpand_file_name (filename, Qnil);
+  absname = Fexpand_file_name (filename, Qnil);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_executable_p);
+  handler = Ffind_file_name_handler (absname, Qfile_executable_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_executable_p, abspath);
+    return call2 (handler, Qfile_executable_p, absname);
 
-  return (check_executable (XSTRING (abspath)->data) ? Qt : Qnil);
+  return (check_executable (XSTRING (absname)->data) ? Qt : Qnil);
 }
 
 DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
@@ -2453,32 +2625,44 @@ See also `file-exists-p' and `file-attributes'.")
   (filename)
      Lisp_Object filename;
 {
-  Lisp_Object abspath;
+  Lisp_Object absname;
   Lisp_Object handler;
   int desc;
+  int flags;
+  struct stat statbuf;
 
   CHECK_STRING (filename, 0);
-  abspath = Fexpand_file_name (filename, Qnil);
+  absname = Fexpand_file_name (filename, Qnil);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_readable_p);
+  handler = Ffind_file_name_handler (absname, Qfile_readable_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_readable_p, abspath);
+    return call2 (handler, Qfile_readable_p, absname);
 
-#ifdef MSDOS
-  /* Under MS-DOS, open does not work't right, because it doesn't work for
-     directories (MS-DOS won't let you open a directory).  */
-  if (access (XSTRING (abspath)->data, 0) == 0)
+#ifdef DOS_NT
+  /* Under MS-DOS and Windows, open does not work for directories.  */
+  if (access (XSTRING (absname)->data, 0) == 0)
     return Qt;
   return Qnil;
-#else /* not MSDOS */
-  desc = open (XSTRING (abspath)->data, O_RDONLY);
+#else /* not DOS_NT */
+  flags = O_RDONLY;
+#if defined (S_ISFIFO) && defined (O_NONBLOCK)
+  /* Opening a fifo without O_NONBLOCK can wait.
+     We don't want to wait.  But we don't want to mess wth O_NONBLOCK
+     except in the case of a fifo, on a system which handles it.  */
+  desc = stat (XSTRING (absname)->data, &statbuf);
+  if (desc < 0)
+    return Qnil;
+  if (S_ISFIFO (statbuf.st_mode))
+    flags |= O_NONBLOCK;
+#endif
+  desc = open (XSTRING (absname)->data, flags);
   if (desc < 0)
     return Qnil;
   close (desc);
   return Qt;
-#endif /* not MSDOS */
+#endif /* not DOS_NT */
 }
 
 /* Having this before file-symlink-p mysteriously caused it to be forgotten
@@ -2488,23 +2672,23 @@ DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
   (filename)
      Lisp_Object filename;
 {
-  Lisp_Object abspath, dir;
+  Lisp_Object absname, dir;
   Lisp_Object handler;
   struct stat statbuf;
 
   CHECK_STRING (filename, 0);
-  abspath = Fexpand_file_name (filename, Qnil);
+  absname = Fexpand_file_name (filename, Qnil);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_writable_p);
+  handler = Ffind_file_name_handler (absname, Qfile_writable_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_writable_p, abspath);
+    return call2 (handler, Qfile_writable_p, absname);
 
-  if (stat (XSTRING (abspath)->data, &statbuf) >= 0)
-    return (check_writable (XSTRING (abspath)->data)
+  if (stat (XSTRING (absname)->data, &statbuf) >= 0)
+    return (check_writable (XSTRING (absname)->data)
            ? Qt : Qnil);
-  dir = Ffile_name_directory (abspath);
+  dir = Ffile_name_directory (absname);
 #ifdef VMS
   if (!NILP (dir))
     dir = Fdirectory_file_name (dir);
@@ -2517,6 +2701,32 @@ DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
          ? Qt : Qnil);
 }
 \f
+DEFUN ("access-file", Faccess_file, Saccess_file, 2, 2, 0,
+  "Access file FILENAME, and get an error if that does not work.\n\
+The second argument STRING is used in the error message.\n\
+If there is no error, we return nil.")
+  (filename, string)
+     Lisp_Object filename, string;
+{
+  Lisp_Object handler;
+  int fd;
+
+  CHECK_STRING (filename, 0);
+
+  /* If the file name has special constructs in it,
+     call the corresponding file handler.  */
+  handler = Ffind_file_name_handler (filename, Qaccess_file);
+  if (!NILP (handler))
+    return call3 (handler, Qaccess_file, filename, string);
+
+  fd = open (XSTRING (filename)->data, O_RDONLY);
+  if (fd < 0)
+    report_file_error (XSTRING (string)->data, Fcons (filename, Qnil));
+  close (fd);
+
+  return Qnil;
+}
+\f
 DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
   "Return non-nil if file FILENAME is the name of a symbolic link.\n\
 The value is the name of the file to which it is linked.\n\
@@ -2571,19 +2781,19 @@ if the directory so specified exists and really is a directory.")
   (filename)
      Lisp_Object filename;
 {
-  register Lisp_Object abspath;
+  register Lisp_Object absname;
   struct stat st;
   Lisp_Object handler;
 
-  abspath = expand_and_dir_to_file (filename, current_buffer->directory);
+  absname = expand_and_dir_to_file (filename, current_buffer->directory);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_directory_p);
+  handler = Ffind_file_name_handler (absname, Qfile_directory_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_directory_p, abspath);
+    return call2 (handler, Qfile_directory_p, absname);
 
-  if (stat (XSTRING (abspath)->data, &st) < 0)
+  if (stat (XSTRING (absname)->data, &st) < 0)
     return Qnil;
   return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
 }
@@ -2627,19 +2837,19 @@ This is the sort of file that holds an ordinary stream of data bytes.")
   (filename)
      Lisp_Object filename;
 {
-  register Lisp_Object abspath;
+  register Lisp_Object absname;
   struct stat st;
   Lisp_Object handler;
 
-  abspath = expand_and_dir_to_file (filename, current_buffer->directory);
+  absname = expand_and_dir_to_file (filename, current_buffer->directory);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_regular_p);
+  handler = Ffind_file_name_handler (absname, Qfile_regular_p);
   if (!NILP (handler))
-    return call2 (handler, Qfile_regular_p, abspath);
+    return call2 (handler, Qfile_regular_p, absname);
 
-  if (stat (XSTRING (abspath)->data, &st) < 0)
+  if (stat (XSTRING (absname)->data, &st) < 0)
     return Qnil;
   return (st.st_mode & S_IFMT) == S_IFREG ? Qt : Qnil;
 }
@@ -2649,24 +2859,24 @@ DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
   (filename)
      Lisp_Object filename;
 {
-  Lisp_Object abspath;
+  Lisp_Object absname;
   struct stat st;
   Lisp_Object handler;
 
-  abspath = expand_and_dir_to_file (filename, current_buffer->directory);
+  absname = expand_and_dir_to_file (filename, current_buffer->directory);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qfile_modes);
+  handler = Ffind_file_name_handler (absname, Qfile_modes);
   if (!NILP (handler))
-    return call2 (handler, Qfile_modes, abspath);
+    return call2 (handler, Qfile_modes, absname);
 
-  if (stat (XSTRING (abspath)->data, &st) < 0)
+  if (stat (XSTRING (absname)->data, &st) < 0)
     return Qnil;
-#ifdef DOS_NT
-  if (check_executable (XSTRING (abspath)->data))
+#if defined (MSDOS) && __DJGPP__ < 2
+  if (check_executable (XSTRING (absname)->data))
     st.st_mode |= S_IEXEC;
-#endif /* DOS_NT */
+#endif /* MSDOS && __DJGPP__ < 2 */
 
   return make_number (st.st_mode & 07777);
 }
@@ -2677,20 +2887,20 @@ Only the 12 low bits of MODE are used.")
   (filename, mode)
      Lisp_Object filename, mode;
 {
-  Lisp_Object abspath;
+  Lisp_Object absname;
   Lisp_Object handler;
 
-  abspath = Fexpand_file_name (filename, current_buffer->directory);
+  absname = Fexpand_file_name (filename, current_buffer->directory);
   CHECK_NUMBER (mode, 1);
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath, Qset_file_modes);
+  handler = Ffind_file_name_handler (absname, Qset_file_modes);
   if (!NILP (handler))
-    return call3 (handler, Qset_file_modes, abspath, mode);
+    return call3 (handler, Qset_file_modes, absname, mode);
 
-  if (chmod (XSTRING (abspath)->data, XINT (mode)) < 0)
-    report_file_error ("Doing chmod", Fcons (abspath, Qnil));
+  if (chmod (XSTRING (absname)->data, XINT (mode)) < 0)
+    report_file_error ("Doing chmod", Fcons (absname, Qnil));
 
   return Qnil;
 }
@@ -2703,7 +2913,7 @@ This setting is inherited by subprocesses.")
      Lisp_Object mode;
 {
   CHECK_NUMBER (mode, 0);
-  
+
   umask ((~ XINT (mode)) & 0777);
 
   return Qnil;
@@ -2743,7 +2953,7 @@ otherwise, if FILE2 does not exist, the answer is t.")
   (file1, file2)
      Lisp_Object file1, file2;
 {
-  Lisp_Object abspath1, abspath2;
+  Lisp_Object absname1, absname2;
   struct stat st;
   int mtime1;
   Lisp_Object handler;
@@ -2752,26 +2962,26 @@ otherwise, if FILE2 does not exist, the answer is t.")
   CHECK_STRING (file1, 0);
   CHECK_STRING (file2, 0);
 
-  abspath1 = Qnil;
-  GCPRO2 (abspath1, file2);
-  abspath1 = expand_and_dir_to_file (file1, current_buffer->directory);
-  abspath2 = expand_and_dir_to_file (file2, current_buffer->directory);
+  absname1 = Qnil;
+  GCPRO2 (absname1, file2);
+  absname1 = expand_and_dir_to_file (file1, current_buffer->directory);
+  absname2 = expand_and_dir_to_file (file2, current_buffer->directory);
   UNGCPRO;
 
   /* If the file name has special constructs in it,
      call the corresponding file handler.  */
-  handler = Ffind_file_name_handler (abspath1, Qfile_newer_than_file_p);
+  handler = Ffind_file_name_handler (absname1, Qfile_newer_than_file_p);
   if (NILP (handler))
-    handler = Ffind_file_name_handler (abspath2, Qfile_newer_than_file_p);
+    handler = Ffind_file_name_handler (absname2, Qfile_newer_than_file_p);
   if (!NILP (handler))
-    return call3 (handler, Qfile_newer_than_file_p, abspath1, abspath2);
+    return call3 (handler, Qfile_newer_than_file_p, absname1, absname2);
 
-  if (stat (XSTRING (abspath1)->data, &st) < 0)
+  if (stat (XSTRING (absname1)->data, &st) < 0)
     return Qnil;
 
   mtime1 = st.st_mtime;
 
-  if (stat (XSTRING (abspath2)->data, &st) < 0)
+  if (stat (XSTRING (absname2)->data, &st) < 0)
     return Qt;
 
   return (mtime1 > st.st_mtime) ? Qt : Qnil;
@@ -2781,6 +2991,10 @@ otherwise, if FILE2 does not exist, the answer is t.")
 Lisp_Object Qfind_buffer_file_type;
 #endif /* DOS_NT */
 
+#ifndef READ_BUF_SIZE
+#define READ_BUF_SIZE (64 << 10)
+#endif
+
 DEFUN ("insert-file-contents", Finsert_file_contents, Sinsert_file_contents,
   1, 5, 0,
   "Insert contents of file FILENAME after point.\n\
@@ -2788,15 +3002,21 @@ Returns list of absolute file name and length of data inserted.\n\
 If second argument VISIT is non-nil, the buffer's visited filename\n\
 and last save file modtime are set, and it is marked unmodified.\n\
 If visiting and the file does not exist, visiting is completed\n\
-before the error is signaled.\n\n\
+before the error is signaled.\n\
 The optional third and fourth arguments BEG and END\n\
 specify what portion of the file to insert.\n\
 If VISIT is non-nil, BEG and END must be nil.\n\
+\n\
 If optional fifth argument REPLACE is non-nil,\n\
 it means replace the current buffer contents (in the accessible portion)\n\
 with the file contents.  This is better than simply deleting and inserting\n\
 the whole thing because (1) it preserves some marker positions\n\
-and (2) it puts less data in the undo list.")
+and (2) it puts less data in the undo list.\n\
+When REPLACE is non-nil, the value is the number of characters actually read,\n\
+which is often less than the number of characters to be read.\n\
+This does code conversion according to the value of\n\
+  `coding-system-for-read' or `coding-system-alist', and sets the variable\n\
+  `last-coding-system-used' to the coding system actually used.")
   (filename, visit, beg, end, replace)
      Lisp_Object filename, visit, beg, end, replace;
 {
@@ -2804,12 +3024,15 @@ and (2) it puts less data in the undo list.")
   register int fd;
   register int inserted = 0;
   register int how_much;
+  register int unprocessed;
   int count = specpdl_ptr - specpdl;
   struct gcpro gcpro1, gcpro2, gcpro3;
   Lisp_Object handler, val, insval;
   Lisp_Object p;
   int total;
   int not_regular = 0;
+  char read_buf[READ_BUF_SIZE];
+  struct coding_system coding;
 
   if (current_buffer->base_buffer && ! NILP (visit))
     error ("Cannot do file visiting in an indirect buffer");
@@ -2835,6 +3058,23 @@ and (2) it puts less data in the undo list.")
       goto handled;
     }
 
+  /* Decide the coding-system of the file.  */
+  {
+    Lisp_Object val = Vcoding_system_for_read;
+    if (NILP (current_buffer->enable_multibyte_characters))
+      val = Qnil;
+    else if (NILP (val))
+      {
+       Lisp_Object args[6], coding_systems;
+
+       args[0] = Qinsert_file_contents, args[1] = filename, args[2] = visit,
+         args[3] = beg, args[4] = end, args[5] = replace;
+       coding_systems = Ffind_coding_system (6, args);
+       val = CONSP (coding_systems) ? XCONS (coding_systems)->car : Qnil;
+      }
+    setup_coding_system (Fcheck_coding_system (val), &coding);
+  }
+
   fd = -1;
 
 #ifndef APOLLO
@@ -2905,23 +3145,30 @@ and (2) it puts less data in the undo list.")
      with the file contents.  Avoid replacing text at the
      beginning or end of the buffer that matches the file contents;
      that preserves markers pointing to the unchanged parts.  */
-#ifdef DOS_NT
-  /* On MSDOS, replace mode doesn't really work, except for binary files,
-     and it's not worth supporting just for them.  */
-  if (!NILP (replace))
+  if (!NILP (replace) && CODING_REQUIRE_CONVERSION (&coding))
     {
+      /* We have to decode the input, which means replace mode is
+         quite difficult.  We give it up for the moment.  */
       replace = Qnil;
-      XSETFASTINT (beg, 0);
-      XSETFASTINT (end, st.st_size);
       del_range_1 (BEGV, ZV, 0);
     }
-#else /* not DOS_NT */
   if (!NILP (replace))
     {
       unsigned char buffer[1 << 14];
       int same_at_start = BEGV;
       int same_at_end = ZV;
       int overlap;
+      /* There is still a possibility we will find the need to do code
+        conversion.  If that happens, we set this variable to 1 to
+        give up on the REPLACE feature.  */
+      int giveup_match_end = 0;
+
+      if (XINT (beg) != 0)
+       {
+         if (lseek (fd, XINT (beg), 0) < 0)
+           report_file_error ("Setting file position",
+                              Fcons (filename, Qnil));
+       }
 
       immediate_quit = 1;
       QUIT;
@@ -2937,9 +3184,30 @@ and (2) it puts less data in the undo list.")
                   XSTRING (filename)->data, strerror (errno));
          else if (nread == 0)
            break;
+
+         if (coding.type == coding_type_automatic)
+           detect_coding (&coding, buffer, nread);
+         if (CODING_REQUIRE_TEXT_CONVERSION (&coding))
+           /* We found that the file should be decoded somehow.
+               Let's give up here.  */
+           {
+             giveup_match_end = 1;
+             break;
+           }
+
+         if (coding.eol_type == CODING_EOL_AUTOMATIC)
+           detect_eol (&coding, buffer, nread);
+         if (CODING_REQUIRE_EOL_CONVERSION (&coding))
+           /* We found that the format of eol should be decoded.
+               Let's give up here.  */
+           {
+             giveup_match_end = 1;
+             break;
+           }
+
          bufpos = 0;
          while (bufpos < nread && same_at_start < ZV
-                && FETCH_CHAR (same_at_start) == buffer[bufpos])
+                && FETCH_BYTE (same_at_start) == buffer[bufpos])
            same_at_start++, bufpos++;
          /* If we found a discrepancy, stop the scan.
             Otherwise loop around and scan the next bufferful.  */
@@ -2949,7 +3217,7 @@ and (2) it puts less data in the undo list.")
       immediate_quit = 0;
       /* If the file matches the buffer completely,
         there's no need to replace anything.  */
-      if (same_at_start - BEGV == st.st_size)
+      if (same_at_start - BEGV == XINT (end))
        {
          close (fd);
          specpdl_ptr--;
@@ -2960,13 +3228,14 @@ and (2) it puts less data in the undo list.")
       immediate_quit = 1;
       QUIT;
       /* Count how many chars at the end of the file
-        match the text at the end of the buffer.  */
-      while (1)
+        match the text at the end of the buffer.  But, if we have
+        already found that decoding is necessary, don't waste time.  */
+      while (!giveup_match_end)
        {
          int total_read, nread, bufpos, curpos, trial;
 
          /* At what file position are we now scanning?  */
-         curpos = st.st_size - (ZV - same_at_end);
+         curpos = XINT (end) - (ZV - same_at_end);
          /* If the entire file matches the buffer tail, stop the scan.  */
          if (curpos == 0)
            break;
@@ -2991,7 +3260,7 @@ and (2) it puts less data in the undo list.")
          /* Compare with same_at_start to avoid counting some buffer text
             as matching both at the file's beginning and at the end.  */
          while (bufpos > 0 && same_at_end > same_at_start
-                && FETCH_CHAR (same_at_end - 1) == buffer[bufpos - 1])
+                && FETCH_BYTE (same_at_end - 1) == buffer[bufpos - 1])
            same_at_end--, bufpos--;
          /* If we found a discrepancy, stop the scan.
             Otherwise loop around and scan the preceding bufferful.  */
@@ -3010,14 +3279,13 @@ and (2) it puts less data in the undo list.")
        same_at_end += overlap;
 
       /* Arrange to read only the nonmatching middle part of the file.  */
-      XSETFASTINT (beg, same_at_start - BEGV);
-      XSETFASTINT (end, st.st_size - (ZV - same_at_end));
+      XSETFASTINT (beg, XINT (beg) + (same_at_start - BEGV));
+      XSETFASTINT (end, XINT (end) - (ZV - same_at_end));
 
       del_range_1 (same_at_start, same_at_end, 0);
       /* Insert from the file at the proper position.  */
       SET_PT (same_at_start);
     }
-#endif /* not DOS_NT */
 
   total = XINT (end) - XINT (beg);
 
@@ -3031,9 +3299,9 @@ and (2) it puts less data in the undo list.")
   }
 
   if (NILP (visit) && total > 0)
-    prepare_to_modify_buffer (point, point);
+    prepare_to_modify_buffer (PT, PT);
 
-  move_gap (point);
+  move_gap (PT);
   if (GAP_SIZE < total)
     make_gap (total - GAP_SIZE);
 
@@ -3043,32 +3311,81 @@ and (2) it puts less data in the undo list.")
        report_file_error ("Setting file position", Fcons (filename, Qnil));
     }
 
+  /* In the following loop, HOW_MUCH contains the total bytes read so
+     far.  Before exiting the loop, it is set to -1 if I/O error
+     occurs, set to -2 if the maximum buffer size is exceeded.  */
   how_much = 0;
-  while (inserted < total)
+  /* Total bytes inserted.  */
+  inserted = 0;
+  /* Bytes not processed in the previous loop because short gap size.  */
+  unprocessed = 0;
+  while (how_much < total)
     {
        /* try is reserved in some compilers (Microsoft C) */
-      int trytry = min (total - inserted, 64 << 10);
+      int trytry = min (total - how_much, READ_BUF_SIZE - unprocessed);
+      char *destination = (CODING_REQUIRE_CONVERSION (&coding)
+                          ? read_buf + unprocessed
+                          : (char *) (POS_ADDR (PT + inserted - 1) + 1));
       int this;
 
       /* Allow quitting out of the actual I/O.  */
       immediate_quit = 1;
       QUIT;
-      this = read (fd, &FETCH_CHAR (point + inserted - 1) + 1, trytry);
+      this = read (fd, destination, trytry);
       immediate_quit = 0;
 
-      if (this <= 0)
+      if (this < 0 || this + unprocessed == 0)
        {
          how_much = this;
          break;
        }
 
+      how_much += this;
+
+      if (CODING_REQUIRE_CONVERSION (&coding))
+       {
+         int require, produced, consumed;
+
+         this += unprocessed;
+         /* Make sure that the gap is large enough.  */
+         require = decoding_buffer_size (&coding, this);
+         if (GAP_SIZE < require)
+           make_gap (require - GAP_SIZE);
+         if (how_much >= total)  /* This is the last block.  */
+           coding.last_block = 1;
+         produced = decode_coding (&coding, read_buf,
+                                   POS_ADDR (PT + inserted - 1) + 1,
+                                   this, GAP_SIZE, &consumed);
+         if (produced > 0) 
+           {
+             Lisp_Object temp;
+
+             XSET (temp, Lisp_Int, Z + produced);
+             if (Z + produced != XINT (temp))
+               {
+                 how_much = -2;
+                 break;
+               }
+           }
+         unprocessed = this - consumed;
+         bcopy (read_buf + consumed, read_buf, unprocessed);
+         this = produced;
+       }
+
       GPT += this;
       GAP_SIZE -= this;
       ZV += this;
       Z += this;
+      if (GAP_SIZE > 0)
+       /* Put an anchor to ensure multi-byte form ends at gap.  */
+       *GPT_ADDR = 0;
       inserted += this;
     }
 
+  /* We don't have to consider file type of MSDOS because all files
+     are read as binary and end-of-line format has already been
+     decoded appropriately.  */
+#if 0
 #ifdef DOS_NT
   /* Demacs 1.1.1 91/10/16 HIRANO Satoshi, MW July 1993 */
   /* Determine file type from name and remove LFs from CR-LFs if the file
@@ -3079,7 +3396,7 @@ and (2) it puts less data in the undo list.")
     if (NILP (current_buffer->buffer_file_type))
       {
        int reduced_size
-         = inserted - crlf_to_lf (inserted, &FETCH_CHAR (point - 1) + 1);
+         = inserted - crlf_to_lf (inserted, POS_ADDR (PT - 1) + 1);
        ZV -= reduced_size;
        Z -= reduced_size;
        GPT -= reduced_size;
@@ -3088,13 +3405,14 @@ and (2) it puts less data in the undo list.")
       }
   }
 #endif /* DOS_NT */
+#endif /* 0 */
 
   if (inserted > 0)
     {
-      record_insert (point, inserted);
+      record_insert (PT, inserted);
 
       /* Only defined if Emacs is compiled with USE_TEXT_PROPERTIES */
-      offset_intervals (current_buffer, point, inserted);
+      offset_intervals (current_buffer, PT, inserted);
       MODIFF++;
     }
 
@@ -3103,9 +3421,11 @@ and (2) it puts less data in the undo list.")
   /* Discard the unwind protect for closing the file.  */
   specpdl_ptr--;
 
-  if (how_much < 0)
+  if (how_much == -1)
     error ("IO error reading %s: %s",
           XSTRING (filename)->data, strerror (errno));
+  else if (how_much == -2)
+    error ("maximum buffer size exceeded");
 
  notfound:
  handled:
@@ -3148,18 +3468,21 @@ and (2) it puts less data in the undo list.")
   /* Decode file format */
   if (inserted > 0)
     {
-      insval = call3 (Qformat_decode, 
+      insval = call3 (Qformat_decode,
                      Qnil, make_number (inserted), visit);
       CHECK_NUMBER (insval, 0);
       inserted = XFASTINT (insval);
     }
 
   if (inserted > 0 && NILP (visit) && total > 0)
-    signal_after_change (point, 0, inserted);
-  
+    signal_after_change (PT, 0, inserted);
+
   if (inserted > 0)
     {
       p = Vafter_insert_file_functions;
+      if (!NILP (coding.post_read_conversion))
+       p = Fcons (coding.post_read_conversion, p);
+
       while (!NILP (p))
        {
          insval = call1 (Fcar (p), make_number (inserted));
@@ -3184,9 +3507,13 @@ and (2) it puts less data in the undo list.")
 static Lisp_Object build_annotations ();
 
 /* If build_annotations switched buffers, switch back to BUF.
-   Kill the temporary buffer that was selected in the meantime.  */
+   Kill the temporary buffer that was selected in the meantime.
 
-static Lisp_Object 
+   Since this kill only the last temporary buffer, some buffers remain
+   not killed if build_annotations switched buffers more than once.
+   -- K.Handa */
+
+static Lisp_Object
 build_annotations_unwind (buf)
      Lisp_Object buf;
 {
@@ -3218,7 +3545,10 @@ If VISIT is neither t nor nil nor a string,\n\
 The optional sixth arg LOCKNAME, if non-nil, specifies the name to\n\
   use for locking and unlocking, overriding FILENAME and VISIT.\n\
 Kludgy feature: if START is a string, then that string is written\n\
-to the file, instead of any buffer contents, and END is ignored.")
+to the file, instead of any buffer contents, and END is ignored.\n\
+This does code conversion according to the value of\n\
+ `coding-system-for-write' or `coding-system-alist', and sets the variable\n\
+ `last-coding-system-used' to the coding system actually used.")
   (start, end, filename, append, visit, lockname)
      Lisp_Object start, end, filename, append, visit, lockname;
 {
@@ -3243,6 +3573,7 @@ to the file, instead of any buffer contents, and END is ignored.")
   int buffer_file_type
     = NILP (current_buffer->buffer_file_type) ? O_TEXT : O_BINARY;
 #endif /* DOS_NT */
+  struct coding_system coding;
 
   if (current_buffer->base_buffer && ! NILP (visit))
     error ("Cannot do file visiting in an indirect buffer");
@@ -3273,7 +3604,7 @@ to the file, instead of any buffer contents, and END is ignored.")
   handler = Ffind_file_name_handler (filename, Qwrite_region);
   /* If FILENAME has no handler, see if VISIT has one.  */
   if (NILP (handler) && STRINGP (visit))
-    handler = Ffind_file_name_handler (visit, Qwrite_region);    
+    handler = Ffind_file_name_handler (visit, Qwrite_region);
 
   if (!NILP (handler))
     {
@@ -3291,6 +3622,38 @@ to the file, instead of any buffer contents, and END is ignored.")
       return val;
     }
 
+  /* Decide the coding-system to be encoded to.  */
+  {
+    Lisp_Object val;
+
+    if (auto_saving || NILP (current_buffer->enable_multibyte_characters))
+      val = Qnil;
+    else if (!NILP (Vcoding_system_for_write))
+      val = Vcoding_system_for_write;
+    else if (!NILP (Flocal_variable_if_set_p (Qbuffer_file_coding_system,
+                                             Qnil)))
+      val = Fsymbol_value (Qbuffer_file_coding_system);
+    else
+      {
+       Lisp_Object args[7], coding_systems;
+
+       args[0] = Qwrite_region, args[1] = start, args[2] = end,
+         args[3] = filename, args[4] = append, args[5] = visit,
+         args[6] = lockname;
+       coding_systems = Ffind_coding_system (7, args);
+       val = (CONSP (coding_systems)
+              ? XCONS (coding_systems)->cdr
+              : Fsymbol_value (Qbuffer_file_coding_system));
+      }
+    setup_coding_system (Fcheck_coding_system (val), &coding); 
+    if (!STRINGP (start) && !NILP (current_buffer->selective_display))
+      coding.selective = 1;
+#ifdef DOS_NT
+    if (!NILP (current_buffer->buffer_file_type))
+      coding.eol_type = CODING_EOL_LF;
+#endif /* DOS_NT */
+  }
+
   /* Special kludge to simplify auto-saving.  */
   if (NILP (start))
     {
@@ -3302,7 +3665,7 @@ to the file, instead of any buffer contents, and END is ignored.")
   count1 = specpdl_ptr - specpdl;
 
   given_buffer = current_buffer;
-  annotations = build_annotations (start, end);
+  annotations = build_annotations (start, end, coding.pre_write_conversion);
   if (current_buffer != given_buffer)
     {
       start = BEGV;
@@ -3311,7 +3674,14 @@ to the file, instead of any buffer contents, and END is ignored.")
 
 #ifdef CLASH_DETECTION
   if (!auto_saving)
-    lock_file (lockname);
+    {
+      /* If we've locked this file for some other buffer,
+        query before proceeding.  */
+      if (!visiting && EQ (Ffile_locked_p (lockname), Qt))
+       call2 (intern ("ask-user-about-lock"), fn, Vuser_login_name);
+
+      lock_file (lockname);
+    }
 #endif /* CLASH_DETECTION */
 
   fn = XSTRING (filename)->data;
@@ -3323,7 +3693,7 @@ to the file, instead of any buffer contents, and END is ignored.")
     desc = open (fn, O_WRONLY);
 #endif /* not DOS_NT */
 
-  if (desc < 0)
+  if (desc < 0 && (NILP (append) || errno == ENOENT) )
 #ifdef VMS
     if (auto_saving)    /* Overwrite any previous version of autosave file */
       {
@@ -3371,8 +3741,8 @@ to the file, instead of any buffer contents, and END is ignored.")
       }
 #else /* not VMS */
 #ifdef DOS_NT
-  desc = open (fn, 
-              O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type, 
+  desc = open (fn,
+              O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type,
               S_IREAD | S_IWRITE);
 #else  /* not DOS_NT */
   desc = creat (fn, auto_saving ? auto_save_mode_bits : 0666);
@@ -3428,7 +3798,7 @@ to the file, instead of any buffer contents, and END is ignored.")
   if (STRINGP (start))
     {
       failure = 0 > a_write (desc, XSTRING (start)->data,
-                            XSTRING (start)->size, 0, &annotations);
+                            XSTRING (start)->size, 0, &annotations, &coding);
       save_errno = errno;
     }
   else if (XINT (start) != XINT (end))
@@ -3438,8 +3808,9 @@ to the file, instead of any buffer contents, and END is ignored.")
        {
          register int end1 = XINT (end);
          tem = XINT (start);
-         failure = 0 > a_write (desc, &FETCH_CHAR (tem),
-                                min (GPT, end1) - tem, tem, &annotations);
+         failure = 0 > a_write (desc, POS_ADDR (tem),
+                                min (GPT, end1) - tem, tem, &annotations,
+                                &coding);
          nwritten += min (GPT, end1) - tem;
          save_errno = errno;
        }
@@ -3448,8 +3819,8 @@ to the file, instead of any buffer contents, and END is ignored.")
        {
          tem = XINT (start);
          tem = max (tem, GPT);
-         failure = 0 > a_write (desc, &FETCH_CHAR (tem), XINT (end) - tem,
-                                tem, &annotations);
+         failure = 0 > a_write (desc, POS_ADDR (tem), XINT (end) - tem,
+                                tem, &annotations, &coding);
          nwritten += XINT (end) - tem;
          save_errno = errno;
        }
@@ -3457,7 +3828,15 @@ to the file, instead of any buffer contents, and END is ignored.")
   else
     {
       /* If file was empty, still need to write the annotations */
-      failure = 0 > a_write (desc, "", 0, XINT (start), &annotations);
+      failure = 0 > a_write (desc, "", 0, XINT (start), &annotations, &coding);
+      save_errno = errno;
+    }
+
+  if (coding.require_flushing)
+    {
+      /* We have to flush out a data. */
+      coding.last_block = 1;
+      failure = 0 > e_write (desc, "", 0, &coding);
       save_errno = errno;
     }
 
@@ -3476,7 +3855,7 @@ to the file, instead of any buffer contents, and END is ignored.")
     }
 #endif
 
-  /* Spurious "file has changed on disk" warnings have been 
+  /* Spurious "file has changed on disk" warnings have been
      observed on Suns as well.
      It seems that `close' can change the modtime, under nfs.
 
@@ -3566,12 +3945,15 @@ DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
    as save-excursion would do.  */
 
 static Lisp_Object
-build_annotations (start, end)
-     Lisp_Object start, end;
+build_annotations (start, end, pre_write_conversion)
+     Lisp_Object start, end, pre_write_conversion;
 {
   Lisp_Object annotations;
   Lisp_Object p, res;
   struct gcpro gcpro1, gcpro2;
+  Lisp_Object original_buffer;
+
+  XSETBUFFER (original_buffer, current_buffer);
 
   annotations = Qnil;
   p = Vwrite_region_annotate_functions;
@@ -3606,7 +3988,8 @@ build_annotations (start, end)
     {
       struct buffer *given_buffer = current_buffer;
       Vwrite_region_annotations_so_far = annotations;
-      res = call3 (Qformat_annotate_function, Fcar (p), start, end);
+      res = call4 (Qformat_annotate_function, Fcar (p), start, end,
+                  original_buffer);
       if (current_buffer != given_buffer)
        {
          start = BEGV;
@@ -3617,6 +4000,24 @@ build_annotations (start, end)
       annotations = merge (annotations, res, Qcar_less_than_car);
       p = Fcdr (p);
     }
+
+  /* At last, do the same for the function PRE_WRITE_CONVERSION
+     implied by the current coding-system.  */
+  if (!NILP (pre_write_conversion))
+    {
+      struct buffer *given_buffer = current_buffer;
+      Vwrite_region_annotations_so_far = annotations;
+      res = call2 (pre_write_conversion, start, end);
+      if (current_buffer != given_buffer)
+       {
+         start = BEGV;
+         end = ZV;
+         annotations = Qnil;
+       }
+      Flength (res);
+      annotations = merge (annotations, res, Qcar_less_than_car);
+    }
+
   UNGCPRO;
   return annotations;
 }
@@ -3631,12 +4032,13 @@ build_annotations (start, end)
    The return value is negative in case of system call failure.  */
 
 int
-a_write (desc, addr, len, pos, annot)
+a_write (desc, addr, len, pos, annot, coding)
      int desc;
      register char *addr;
      register int len;
      int pos;
      Lisp_Object *annot;
+     struct coding_system *coding;
 {
   Lisp_Object tem;
   int nextpos;
@@ -3648,10 +4050,10 @@ a_write (desc, addr, len, pos, annot)
       if (INTEGERP (tem) && XINT (tem) >= pos && XFASTINT (tem) <= lastpos)
        nextpos = XFASTINT (tem);
       else
-       return e_write (desc, addr, lastpos - pos);
+       return e_write (desc, addr, lastpos - pos, coding);
       if (nextpos > pos)
        {
-         if (0 > e_write (desc, addr, nextpos - pos))
+         if (0 > e_write (desc, addr, nextpos - pos, coding))
            return -1;
          addr += nextpos - pos;
          pos = nextpos;
@@ -3659,43 +4061,50 @@ a_write (desc, addr, len, pos, annot)
       tem = Fcdr (Fcar (*annot));
       if (STRINGP (tem))
        {
-         if (0 > e_write (desc, XSTRING (tem)->data, XSTRING (tem)->size))
+         if (0 > e_write (desc, XSTRING (tem)->data, XSTRING (tem)->size,
+                          coding))
            return -1;
        }
       *annot = Fcdr (*annot);
     }
 }
 
+#ifndef WRITE_BUF_SIZE
+#define WRITE_BUF_SIZE (16 * 1024)
+#endif
+
 int
-e_write (desc, addr, len)
+e_write (desc, addr, len, coding)
      int desc;
      register char *addr;
      register int len;
+     struct coding_system *coding;
 {
-  char buf[16 * 1024];
-  register char *p, *end;
+  char buf[WRITE_BUF_SIZE];
+  int produced, consumed;
 
-  if (!EQ (current_buffer->selective_display, Qt))
-    return write (desc, addr, len) - len;
-  else
+  /* We used to have a code for handling selective display here.  But,
+     now it is handled within encode_coding.  */
+  while (1)
     {
-      p = buf;
-      end = p + sizeof buf;
-      while (len--)
+      produced = encode_coding (coding, addr, buf, len, WRITE_BUF_SIZE,
+                               &consumed);
+      len -= consumed, addr += consumed;
+      if (produced == 0 && len > 0)
        {
-         if (p == end)
-           {
-             if (write (desc, buf, sizeof buf) != sizeof buf)
-               return -1;
-             p = buf;
-           }
-         *p = *addr++;
-         if (*p++ == '\015')
-           p[-1] = '\n';
+         /* There was a carry over because of invalid codes in the source.
+            We just write out them as is.  */
+         bcopy (addr, buf, len);
+         produced = len;
+         len = 0;
        }
-      if (p != buf)
-       if (write (desc, buf, p - buf) != p - buf)
-         return -1;
+      if (produced > 0)
+       {
+         produced -= write (desc, buf, produced);
+         if (produced) return -1;
+       }
+      if (len <= 0)
+       break;
     }
   return 0;
 }
@@ -3856,7 +4265,6 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
   int auto_saved = 0;
   char *omessage = echo_area_glyphs;
   int omessage_length = echo_area_glyphs_length;
-  extern int minibuf_level;
   int do_handled_files;
   Lisp_Object oquit;
   int listdesc;
@@ -3882,7 +4290,7 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
       Lisp_Object listfile;
       listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
 #ifdef DOS_NT
-      listdesc = open (XSTRING (listfile)->data, 
+      listdesc = open (XSTRING (listfile)->data,
                       O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
                       S_IREAD | S_IWRITE);
 #else  /* not DOS_NT */
@@ -3891,7 +4299,7 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
     }
   else
     listdesc = -1;
-  
+
   /* Arrange to close that file whether or not we get an error.
      Also reset auto_saving to 0.  */
   record_unwind_protect (do_auto_save_unwind, make_number (listdesc));
@@ -3908,7 +4316,7 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
       {
        buf = XCONS (XCONS (tail)->car)->cdr;
        b = XBUFFER (buf);
-      
+
        /* Record all the buffers that have auto save mode
           in the special file that lists them.  For each of these buffers,
           Record visited name (if any) and auto save name.  */
@@ -4088,6 +4496,8 @@ DEFUN ("read-file-name-internal", Fread_file_name_internal, Sread_file_name_inte
   int changed;
   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
 
+  CHECK_STRING (string, 0);
+
   realdir = dir;
   name = string;
   orig_string = Qnil;
@@ -4179,6 +4589,10 @@ DIR defaults to current buffer's directory default.")
 
   /* If dir starts with user's homedir, change that to ~. */
   homedir = (char *) egetenv ("HOME");
+#ifdef DOS_NT
+  homedir = strcpy (alloca (strlen (homedir) + 1), homedir);
+  CORRECT_DIR_SEPS (homedir);
+#endif
   if (homedir != 0
       && STRINGP (dir)
       && !strncmp (homedir, XSTRING (dir)->data, strlen (homedir))
@@ -4189,7 +4603,7 @@ DIR defaults to current buffer's directory default.")
       XSTRING (dir)->data[0] = '~';
     }
 
-  if (insert_default_directory)
+  if (insert_default_directory && STRINGP (dir))
     {
       insdef = dir;
       if (!NILP (initial))
@@ -4205,7 +4619,7 @@ DIR defaults to current buffer's directory default.")
       else
        insdef1 = double_dollars (insdef);
     }
-  else if (!NILP (initial))
+  else if (STRINGP (initial))
     {
       insdef = initial;
       insdef1 = Fcons (double_dollars (insdef), 0);
@@ -4324,8 +4738,9 @@ syms_of_fileio ()
   Qfile_exists_p = intern ("file-exists-p");
   Qfile_executable_p = intern ("file-executable-p");
   Qfile_readable_p = intern ("file-readable-p");
-  Qfile_symlink_p = intern ("file-symlink-p");
   Qfile_writable_p = intern ("file-writable-p");
+  Qfile_symlink_p = intern ("file-symlink-p");
+  Qaccess_file = intern ("access-file");
   Qfile_directory_p = intern ("file-directory-p");
   Qfile_regular_p = intern ("file-regular-p");
   Qfile_accessible_directory_p = intern ("file-accessible-directory-p");
@@ -4354,8 +4769,9 @@ syms_of_fileio ()
   staticpro (&Qfile_exists_p);
   staticpro (&Qfile_executable_p);
   staticpro (&Qfile_readable_p);
-  staticpro (&Qfile_symlink_p);
   staticpro (&Qfile_writable_p);
+  staticpro (&Qaccess_file);
+  staticpro (&Qfile_symlink_p);
   staticpro (&Qfile_directory_p);
   staticpro (&Qfile_regular_p);
   staticpro (&Qfile_accessible_directory_p);
@@ -4365,6 +4781,7 @@ syms_of_fileio ()
   staticpro (&Qinsert_file_contents);
   staticpro (&Qwrite_region);
   staticpro (&Qverify_visited_file_modtime);
+  staticpro (&Qset_visited_file_modtime);
 
   Qfile_name_history = intern ("file-name-history");
   Fset (Qfile_name_history, Qnil);
@@ -4372,8 +4789,10 @@ syms_of_fileio ()
 
   Qfile_error = intern ("file-error");
   staticpro (&Qfile_error);
-  Qfile_already_exists = intern("file-already-exists");
+  Qfile_already_exists = intern ("file-already-exists");
   staticpro (&Qfile_already_exists);
+  Qfile_date_error = intern ("file-date-error");
+  staticpro (&Qfile_date_error);
 
 #ifdef DOS_NT
   Qfind_buffer_file_type = intern ("find-buffer-file-type");
@@ -4406,6 +4825,12 @@ same format as a regular save would use.");
   Fput (Qfile_already_exists, Qerror_message,
        build_string ("File already exists"));
 
+  Fput (Qfile_date_error, Qerror_conditions,
+       Fcons (Qfile_date_error,
+              Fcons (Qfile_error, Fcons (Qerror, Qnil))));
+  Fput (Qfile_date_error, Qerror_message,
+       build_string ("Cannot set file date"));
+
   DEFVAR_BOOL ("insert-default-directory", &insert_default_directory,
     "*Non-nil means when reading a filename start with default dir in minibuffer.");
   insert_default_directory = 1;
@@ -4415,6 +4840,14 @@ same format as a regular save would use.");
 nil means use format `var'.  This variable is meaningful only on VMS.");
   vms_stmlf_recfm = 0;
 
+  DEFVAR_LISP ("directory-sep-char", &Vdirectory_sep_char,
+    "Directory separator character for built-in functions that return file names.\n\
+The value should be either ?/ or ?\\ (any other value is treated as ?\\).\n\
+This variable affects the built-in functions only on Windows,\n\
+on other platforms, it is initialized so that Lisp code can find out\n\
+what the normal separator is.");
+  Vdirectory_sep_char = '/';
+
   DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
     "*Alist of elements (REGEXP . HANDLER) for file names handled specially.\n\
 If a file name matches REGEXP, then all I/O on that file is done by calling\n\
@@ -4440,8 +4873,10 @@ responsible for calling the after-insert-file-functions if appropriate.");
 
   DEFVAR_LISP ("write-region-annotate-functions", &Vwrite_region_annotate_functions,
     "A list of functions to be called at the start of `write-region'.\n\
-Each is passed two arguments, START and END as for `write-region'.  It should\n\
-return a list of pairs (POSITION . STRING) of strings to be effectively\n\
+Each is passed two arguments, START and END as for `write-region'.\n\
+These are usually two numbers but not always; see the documentation\n\
+for `write-region'.  The function should return a list of pairs\n\
+of the form (POSITION . STRING), consisting of strings to be effectively\n\
 inserted at the specified positions of the file being written (1 means to\n\
 insert before the first byte written).  The POSITIONs must be sorted into\n\
 increasing order.  If there are several functions in the list, the several\n\
@@ -4500,6 +4935,7 @@ a non-nil value.");
   defsubr (&Sfile_executable_p);
   defsubr (&Sfile_readable_p);
   defsubr (&Sfile_writable_p);
+  defsubr (&Saccess_file);
   defsubr (&Sfile_symlink_p);
   defsubr (&Sfile_directory_p);
   defsubr (&Sfile_accessible_directory_p);