(Fsubstitute_in_file_name): Adjusted for the change of
[bpt/emacs.git] / src / fileio.c
index e9f9a98..17be8ac 100644 (file)
@@ -1,5 +1,5 @@
 /* File IO for GNU Emacs.
-   Copyright (C) 1985,86,87,88,93,94,95,96,97,1998 Free Software Foundation, Inc.
+   Copyright (C) 1985,86,87,88,93,94,95,96,97,98,1999 Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -65,8 +65,6 @@ Boston, MA 02111-1307, USA.  */
 extern int errno;
 #endif
 
-extern char *strerror ();
-
 #ifdef APOLLO
 #include <sys/time.h>
 #endif
@@ -232,14 +230,15 @@ static Lisp_Object Vinhibit_file_name_handlers;
 static Lisp_Object Vinhibit_file_name_operation;
 
 Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
-
+Lisp_Object Qexcl;
 Lisp_Object Qfile_name_history;
 
 Lisp_Object Qcar_less_than_car;
 
-static int a_write P_ ((int, char *, int, int,
+static int a_write P_ ((int, Lisp_Object, int, int,
                        Lisp_Object *, struct coding_system *));
-static int e_write P_ ((int, char *, int, struct coding_system *));
+static int e_write P_ ((int, Lisp_Object, int, int, struct coding_system *));
+
 \f
 void
 report_file_error (string, data)
@@ -247,24 +246,34 @@ report_file_error (string, data)
      Lisp_Object data;
 {
   Lisp_Object errstring;
+  int errorno = errno;
 
-  errstring = build_string (strerror (errno));
-
-  /* System error messages are capitalized.  Downcase the initial
-     unless it is followed by a slash.  */
-  if (XSTRING (errstring)->data[1] != '/')
-    XSTRING (errstring)->data[0] = DOWNCASE (XSTRING (errstring)->data[0]);
+  synchronize_system_messages_locale ();
+  errstring = code_convert_string_norecord (build_string (strerror (errorno)),
+                                           Vlocale_coding_system, 0);
 
   while (1)
-    Fsignal (Qfile_error,
-            Fcons (build_string (string), Fcons (errstring, data)));
+    switch (errorno)
+      {
+      case EEXIST:
+       Fsignal (Qfile_already_exists, Fcons (errstring, data));
+       break;
+      default:
+       /* System error messages are capitalized.  Downcase the initial
+          unless it is followed by a slash.  */
+       if (XSTRING (errstring)->data[1] != '/')
+         XSTRING (errstring)->data[0] = DOWNCASE (XSTRING (errstring)->data[0]);
+
+       Fsignal (Qfile_error,
+                Fcons (build_string (string), Fcons (errstring, data)));
+      }
 }
 
 Lisp_Object
 close_file_unwind (fd)
      Lisp_Object fd;
 {
-  close (XFASTINT (fd));
+  emacs_close (XFASTINT (fd));
   return Qnil;
 }
 
@@ -333,19 +342,19 @@ use the standard functions without calling themselves recursively.")
     inhibited_handlers = Qnil;
 
   for (chain = Vfile_name_handler_alist; CONSP (chain);
-       chain = XCONS (chain)->cdr)
+       chain = XCDR (chain))
     {
       Lisp_Object elt;
-      elt = XCONS (chain)->car;
+      elt = XCAR (chain);
       if (CONSP (elt))
        {
          Lisp_Object string;
-         string = XCONS (elt)->car;
+         string = XCAR (elt);
          if (STRINGP (string) && fast_string_match (string, filename) >= 0)
            {
              Lisp_Object handler, tem;
 
-             handler = XCONS (elt)->cdr;
+             handler = XCDR (elt);
              tem = Fmemq (handler, inhibited_handlers);
              if (NILP (tem))
                return handler;
@@ -835,7 +844,11 @@ so there is no danger of generating a name being used by another process.\n\
 \n\
 In addition, this function makes an attempt to choose a name\n\
 which has no existing file.  To make this work,\n\
-PREFIX should be an absolute file name.")
+PREFIX should be an absolute file name.\n\
+\n\
+There is a race condition between calling `make-temp-name' and creating the\n\
+file which opens all kinds of security holes.  For that reason, you should\n\
+probably use `make-temp-file' instead.")
   (prefix)
      Lisp_Object prefix;
 {
@@ -2078,21 +2091,10 @@ duplicates what `expand-file-name' does.")
          {
            /* If the original string is multibyte,
               convert what we substitute into multibyte.  */
-           unsigned char workbuf[4], *str;
-           int len;
-
            while (*o)
              {
-               int c = *o++;
-               c = unibyte_char_to_multibyte (c);
-               if (! SINGLE_BYTE_CHAR_P (c))
-                 {
-                   len = CHAR_STRING (c, workbuf, str);
-                   bcopy (str, x, len);
-                   x += len;
-                 }
-               else
-                 *x++ = c;
+               int c = unibyte_char_to_multibyte (*o++);
+               x += CHAR_STRING (c, x);
              }
          }
        else
@@ -2272,7 +2274,7 @@ A prefix arg makes KEEP-TIME non-nil.")
   else if (stat (XSTRING (encoded_newname)->data, &out_st) < 0)
     out_st.st_mode = 0;
 
-  ifd = open (XSTRING (encoded_file)->data, O_RDONLY);
+  ifd = emacs_open (XSTRING (encoded_file)->data, O_RDONLY, 0);
   if (ifd < 0)
     report_file_error ("Opening input file", Fcons (file, Qnil));
 
@@ -2324,13 +2326,13 @@ A prefix arg makes KEEP-TIME non-nil.")
 
   immediate_quit = 1;
   QUIT;
-  while ((n = read (ifd, buf, sizeof buf)) > 0)
-    if (write (ofd, buf, n) != n)
+  while ((n = emacs_read (ifd, buf, sizeof buf)) > 0)
+    if (emacs_write (ofd, buf, n) != n)
       report_file_error ("I/O error", Fcons (newname, Qnil));
   immediate_quit = 0;
 
   /* Closing the output clobbers the file times on some systems.  */
-  if (close (ofd) < 0)
+  if (emacs_close (ofd) < 0)
     report_file_error ("I/O error", Fcons (newname, Qnil));
 
   if (input_file_statable_p)
@@ -2360,7 +2362,7 @@ A prefix arg makes KEEP-TIME non-nil.")
 #endif /* MSDOS */
     }
 
-  close (ifd);
+  emacs_close (ifd);
 
   /* Discard the unwind protects.  */
   specpdl_ptr = specpdl + count;
@@ -2899,10 +2901,10 @@ See also `file-exists-p' and `file-attributes'.")
   if (S_ISFIFO (statbuf.st_mode))
     flags |= O_NONBLOCK;
 #endif
-  desc = open (XSTRING (absname)->data, flags);
+  desc = emacs_open (XSTRING (absname)->data, flags, 0);
   if (desc < 0)
     return Qnil;
-  close (desc);
+  emacs_close (desc);
   return Qt;
 #endif /* not DOS_NT */
 }
@@ -2968,10 +2970,10 @@ If there is no error, we return nil.")
 
   encoded_filename = ENCODE_FILE (filename);
 
-  fd = open (XSTRING (encoded_filename)->data, O_RDONLY);
+  fd = emacs_open (XSTRING (encoded_filename)->data, O_RDONLY, 0);
   if (fd < 0)
     report_file_error (XSTRING (string)->data, Fcons (filename, Qnil));
-  close (fd);
+  emacs_close (fd);
 
   return Qnil;
 }
@@ -3276,22 +3278,44 @@ Lisp_Object Qfind_buffer_file_type;
 #define READ_BUF_SIZE (64 << 10)
 #endif
 
-/* This function is called when a function bound to
-   Vset_auto_coding_function causes some error.  At that time, a text
-   of a file has already been inserted in the current buffer, but,
-   markers has not yet been adjusted.  Thus we must adjust markers
-   here.  We are sure that the buffer was empty before the text of the
-   file was inserted.  */
+extern void adjust_markers_for_delete P_ ((int, int, int, int));
+
+/* This function is called after Lisp functions to decide a coding
+   system are called, or when they cause an error.  Before they are
+   called, the current buffer is set unibyte and it contains only a
+   newly inserted text (thus the buffer was empty before the
+   insertion).
+
+   The functions may set markers, overlays, text properties, or even
+   alter the buffer contents, change the current buffer.
+
+   Here, we reset all those changes by:
+       o set back the current buffer.
+       o move all markers and overlays to BEG.
+       o remove all text properties.
+       o set back the buffer multibyteness.  */
 
 static Lisp_Object
-set_auto_coding_unwind (multibyte)
-     Lisp_Object multibyte;
+decide_coding_unwind (unwind_data)
+     Lisp_Object unwind_data;
 {
-  int inserted = Z_BYTE - BEG_BYTE;
+  Lisp_Object multibyte, undo_list, buffer;
+
+  multibyte = XCAR (unwind_data);
+  unwind_data = XCDR (unwind_data);
+  undo_list = XCAR (unwind_data);
+  buffer = XCDR (unwind_data);
 
-  if (!NILP (multibyte))
-    inserted = multibyte_chars_in_text (GPT_ADDR - inserted, inserted);
-  adjust_after_insert (PT, PT_BYTE, Z, Z_BYTE, inserted);
+  if (current_buffer != XBUFFER (buffer))
+    set_buffer_internal (XBUFFER (buffer));
+  adjust_markers_for_delete (BEG, BEG_BYTE, Z, Z_BYTE);
+  adjust_overlays_for_delete (BEG, Z - BEG);
+  BUF_INTERVALS (current_buffer) = 0;
+  TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
+
+  /* Now we are safe to change the buffer's multibyteness directly.  */
+  current_buffer->enable_multibyte_characters = multibyte;
+  current_buffer->undo_list = undo_list;
 
   return Qnil;
 }
@@ -3364,8 +3388,8 @@ actually used.")
     {
       val = call6 (handler, Qinsert_file_contents, filename,
                   visit, beg, end, replace);
-      if (CONSP (val) && CONSP (XCONS (val)->cdr))
-       inserted = XINT (XCONS (XCONS (val)->cdr)->car);
+      if (CONSP (val) && CONSP (XCDR (val)))
+       inserted = XINT (XCAR (XCDR (val)));
       goto handled;
     }
 
@@ -3388,19 +3412,19 @@ actually used.")
 #ifndef APOLLO
   if (stat (XSTRING (filename)->data, &st) < 0)
 #else
-  if ((fd = open (XSTRING (filename)->data, O_RDONLY)) < 0
+  if ((fd = emacs_open (XSTRING (filename)->data, O_RDONLY, 0)) < 0
       || fstat (fd, &st) < 0)
 #endif /* not APOLLO */
 #endif /* WINDOWSNT */
     {
-      if (fd >= 0) close (fd);
+      if (fd >= 0) emacs_close (fd);
     badopen:
       if (NILP (visit))
        report_file_error ("Opening input file", Fcons (orig_filename, Qnil));
       st.st_mtime = -1;
       how_much = 0;
       if (!NILP (Vcoding_system_for_read))
-       current_buffer->buffer_file_coding_system = Vcoding_system_for_read;
+       Fset (Qbuffer_file_coding_system, Vcoding_system_for_read);
       goto notfound;
     }
 
@@ -3423,7 +3447,7 @@ actually used.")
 #endif
 
   if (fd < 0)
-    if ((fd = open (XSTRING (filename)->data, O_RDONLY)) < 0)
+    if ((fd = emacs_open (XSTRING (filename)->data, O_RDONLY, 0)) < 0)
       goto badopen;
 
   /* Replacement should preserve point as it preserves markers.  */
@@ -3455,7 +3479,13 @@ actually used.")
       if (! not_regular)
        {
          XSETINT (end, st.st_size);
-         if (XINT (end) != st.st_size)
+
+         /* Arithmetic overflow can occur if an Emacs integer cannot
+            represent the file size, or if the calculations below
+            overflow.  The calculations below double the file size
+            twice, so check that it can be multiplied by 4 safely.  */
+         if (XINT (end) != st.st_size
+             || ((int) st.st_size * 4) / 4 != st.st_size)
            error ("Maximum buffer size exceeded");
        }
     }
@@ -3488,22 +3518,22 @@ actually used.")
              int how_many, nread;
 
              if (st.st_size <= (1024 * 4))
-               nread = read (fd, read_buf, 1024 * 4);
+               nread = emacs_read (fd, read_buf, 1024 * 4);
              else
                {
-                 nread = read (fd, read_buf, 1024);
+                 nread = emacs_read (fd, read_buf, 1024);
                  if (nread >= 0)
                    {
                      if (lseek (fd, st.st_size - (1024 * 3), 0) < 0)
                        report_file_error ("Setting file position",
                                           Fcons (orig_filename, Qnil));
-                     nread += read (fd, read_buf + nread, 1024 * 3);
+                     nread += emacs_read (fd, read_buf + nread, 1024 * 3);
                    }
                }
 
              if (nread < 0)
                error ("IO error reading %s: %s",
-                      XSTRING (orig_filename)->data, strerror (errno));
+                      XSTRING (orig_filename)->data, emacs_strerror (errno));
              else if (nread > 0)
                {
                  int count = specpdl_ptr - specpdl;
@@ -3539,7 +3569,7 @@ actually used.")
              args[2] = visit, args[3] = beg, args[4] = end, args[5] = replace;
              coding_systems = Ffind_operation_coding_system (6, args);
              if (CONSP (coding_systems))
-               val = XCONS (coding_systems)->car;
+               val = XCAR (coding_systems);
            }
        }
 
@@ -3603,10 +3633,10 @@ actually used.")
        {
          int nread, bufpos;
 
-         nread = read (fd, buffer, sizeof buffer);
+         nread = emacs_read (fd, buffer, sizeof buffer);
          if (nread < 0)
            error ("IO error reading %s: %s",
-                  XSTRING (orig_filename)->data, strerror (errno));
+                  XSTRING (orig_filename)->data, emacs_strerror (errno));
          else if (nread == 0)
            break;
 
@@ -3645,10 +3675,10 @@ actually used.")
         there's no need to replace anything.  */
       if (same_at_start - BEGV_BYTE == XINT (end))
        {
-         close (fd);
+         emacs_close (fd);
          specpdl_ptr--;
          /* Truncate the buffer to the size of the file.  */
-         del_range_1 (same_at_start, same_at_end, 0);
+         del_range_1 (same_at_start, same_at_end, 0, 0);
          goto handled;
        }
       immediate_quit = 1;
@@ -3674,10 +3704,10 @@ actually used.")
          total_read = 0;
          while (total_read < trial)
            {
-             nread = read (fd, buffer + total_read, trial - total_read);
+             nread = emacs_read (fd, buffer + total_read, trial - total_read);
              if (nread <= 0)
                error ("IO error reading %s: %s",
-                      XSTRING (orig_filename)->data, strerror (errno));
+                      XSTRING (orig_filename)->data, emacs_strerror (errno));
              total_read += nread;
            }
          /* Scan this bufferful from the end, comparing with
@@ -3794,7 +3824,7 @@ actually used.")
          /* Allow quitting out of the actual I/O.  */
          immediate_quit = 1;
          QUIT;
-         this = read (fd, destination, trytry);
+         this = emacs_read (fd, destination, trytry);
          immediate_quit = 0;
 
          if (this < 0 || this + unprocessed == 0)
@@ -3847,7 +3877,7 @@ actually used.")
 
          if (how_much == -1)
            error ("IO error reading %s: %s",
-                  XSTRING (orig_filename)->data, strerror (errno));
+                  XSTRING (orig_filename)->data, emacs_strerror (errno));
          else if (how_much == -2)
            error ("maximum buffer size exceeded");
        }
@@ -3866,7 +3896,7 @@ actually used.")
       if (bufpos == inserted)
        {
          xfree (conversion_buffer);
-         close (fd);
+         emacs_close (fd);
          specpdl_ptr--;
          /* Truncate the buffer to the size of the file.  */
          del_range_byte (same_at_start, same_at_end, 0);
@@ -3931,7 +3961,7 @@ actually used.")
       inserted = PT - temp;
 
       free (conversion_buffer);
-      close (fd);
+      emacs_close (fd);
       specpdl_ptr--;
 
       goto handled;
@@ -3988,7 +4018,8 @@ actually used.")
       /* Allow quitting out of the actual I/O.  */
       immediate_quit = 1;
       QUIT;
-      this = read (fd, BYTE_POS_ADDR (PT_BYTE + inserted - 1) + 1, trytry);
+      this = emacs_read (fd, BYTE_POS_ADDR (PT_BYTE + inserted - 1) + 1,
+                        trytry);
       immediate_quit = 0;
 
       if (this <= 0)
@@ -4019,19 +4050,22 @@ actually used.")
     /* Put an anchor to ensure multi-byte form ends at gap.  */
     *GPT_ADDR = 0;
 
-  close (fd);
+  emacs_close (fd);
 
   /* Discard the unwind protect for closing the file.  */
   specpdl_ptr--;
 
   if (how_much < 0)
     error ("IO error reading %s: %s",
-          XSTRING (orig_filename)->data, strerror (errno));
+          XSTRING (orig_filename)->data, emacs_strerror (errno));
 
   if (! coding_system_decided)
     {
       /* The coding system is not yet decided.  Decide it by an
-        optimized method for handling `coding:' tag.  */
+        optimized method for handling `coding:' tag.
+
+        Note that we can get here only if the buffer was empty
+        before the insertion.  */
       Lisp_Object val;
       val = Qnil;
 
@@ -4039,27 +4073,26 @@ actually used.")
        val = Vcoding_system_for_read;
       else
        {
-         if (inserted > 0 && ! NILP (Vset_auto_coding_function))
-           {
-             /* Since we are sure that the current buffer was
-                empty before the insertion, we can toggle
-                enable-multibyte-characters directly here without
-                taking care of marker adjustment and byte
-                combining problem.  */
-             Lisp_Object prev_multibyte;
+         /* Since we are sure that the current buffer was empty
+            before the insertion, we can toggle
+            enable-multibyte-characters directly here without taking
+            care of marker adjustment and byte combining problem.  By
+            this way, we can run Lisp program safely before decoding
+            the inserted text.  */
+         Lisp_Object unwind_data;
              int count = specpdl_ptr - specpdl;
 
-             prev_multibyte = current_buffer->enable_multibyte_characters;
+         unwind_data = Fcons (current_buffer->enable_multibyte_characters,
+                              Fcons (current_buffer->undo_list,
+                                     Fcurrent_buffer ()));
              current_buffer->enable_multibyte_characters = Qnil;
-             record_unwind_protect (set_auto_coding_unwind,
-                                    prev_multibyte);
+         current_buffer->undo_list = Qt;
+         record_unwind_protect (decide_coding_unwind, unwind_data);
+
+         if (inserted > 0 && ! NILP (Vset_auto_coding_function))
+           {
              val = call2 (Vset_auto_coding_function,
                           filename, make_number (inserted));
-             /* Discard the unwind protect for recovering the
-                error of Vset_auto_coding_function.  */
-             specpdl_ptr--;
-             current_buffer->enable_multibyte_characters = prev_multibyte;
-             TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
            }
 
          if (NILP (val))
@@ -4072,8 +4105,11 @@ actually used.")
              args[2] = visit, args[3] = beg, args[4] = end, args[5] = Qnil;
              coding_systems = Ffind_operation_coding_system (6, args);
              if (CONSP (coding_systems))
-               val = XCONS (coding_systems)->car;
+               val = XCAR (coding_systems);
            }
+
+         unbind_to (count, Qnil);
+         inserted = Z_BYTE - BEG_BYTE;
        }
 
       /* The following kludgy code is to avoid some compiler bug.
@@ -4182,15 +4218,18 @@ actually used.")
       inserted = XFASTINT (insval);
     }
 
+  if (set_coding_system)
+    Vlast_coding_system_used = coding.symbol;
+
   /* Call after-change hooks for the inserted text, aside from the case
      of normal visiting (not with REPLACE), which is done in a new buffer
      "before" the buffer is changed.  */
   if (inserted > 0 && total > 0
       && (NILP (visit) || !NILP (replace)))
-    signal_after_change (PT, 0, inserted);
-
-  if (set_coding_system)
-    Vlast_coding_system_used = coding.symbol;
+    {
+      signal_after_change (PT, 0, inserted);
+      update_compositions (PT, PT, CHECK_BORDER);
+    }
 
   if (inserted > 0)
     {
@@ -4258,8 +4297,12 @@ If VISIT is neither t nor nil nor a string,\n\
   that means do not print the \"Wrote file\" message.\n\
 The optional sixth arg LOCKNAME, if non-nil, specifies the name to\n\
   use for locking and unlocking, overriding FILENAME and VISIT.\n\
-The optional seventh arg CONFIRM, if non-nil, says ask for confirmation\n\
-  before overwriting an existing file.\n\
+The optional seventh arg MUSTBENEW, if non-nil, insists on a check\n\
+  for an existing file with the same name.  If MUSTBENEW is `excl',\n\
+  that means to get an error if the file already exists; never overwrite.\n\
+  If MUSTBENEW is neither nil nor `excl', that means ask for\n\
+  confirmation before overwriting, but do go ahead and overwrite the file\n\
+  if the user confirms.\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.\n\
 \n\
@@ -4268,8 +4311,8 @@ This does code conversion according to the value of\n\
 `file-coding-system-alist', and sets the variable\n\
 `last-coding-system-used' to the coding system actually used.")
 
-  (start, end, filename, append, visit, lockname, confirm)
-     Lisp_Object start, end, filename, append, visit, lockname, confirm;
+  (start, end, filename, append, visit, lockname, mustbenew)
+     Lisp_Object start, end, filename, append, visit, lockname, mustbenew;
 {
   register int desc;
   int failure;
@@ -4342,8 +4385,8 @@ This does code conversion according to the value of\n\
            args[3] = filename; args[4] = append; args[5] = visit;
            args[6] = lockname;
            coding_systems = Ffind_operation_coding_system (7, args);
-           if (CONSP (coding_systems) && !NILP (XCONS (coding_systems)->cdr))
-             val = XCONS (coding_systems)->cdr;
+           if (CONSP (coding_systems) && !NILP (XCDR (coding_systems)))
+             val = XCDR (coding_systems);
          }
 
        if (NILP (val)
@@ -4397,7 +4440,7 @@ This does code conversion according to the value of\n\
 
   filename = Fexpand_file_name (filename, Qnil);
 
-  if (! NILP (confirm))
+  if (! NILP (mustbenew) && mustbenew != Qexcl)
     barf_or_query_if_file_exists (filename, "overwrite", 1, 0, 1);
 
   if (STRINGP (visit))
@@ -4477,9 +4520,9 @@ This does code conversion according to the value of\n\
   desc = -1;
   if (!NILP (append))
 #ifdef DOS_NT
-    desc = open (fn, O_WRONLY | buffer_file_type);
+    desc = emacs_open (fn, O_WRONLY | buffer_file_type, 0);
 #else  /* not DOS_NT */
-    desc = open (fn, O_WRONLY);
+    desc = emacs_open (fn, O_WRONLY, 0);
 #endif /* not DOS_NT */
 
   if (desc < 0 && (NILP (append) || errno == ENOENT))
@@ -4487,7 +4530,7 @@ This does code conversion according to the value of\n\
     if (auto_saving)    /* Overwrite any previous version of autosave file */
       {
        vms_truncate (fn);      /* if fn exists, truncate to zero length */
-       desc = open (fn, O_RDWR);
+       desc = emacs_open (fn, O_RDWR, 0);
        if (desc < 0)
          desc = creat_copy_attrs (STRINGP (current_buffer->filename)
                                   ? XSTRING (current_buffer->filename)->data : 0,
@@ -4520,7 +4563,7 @@ This does code conversion according to the value of\n\
                    /* We can't make a new version;
                       try to truncate and rewrite existing version if any.  */
                    vms_truncate (fn);
-                   desc = open (fn, O_RDWR);
+                   desc = emacs_open (fn, O_RDWR, 0);
                  }
 #endif
              }
@@ -4530,11 +4573,14 @@ This does code conversion according to the value of\n\
       }
 #else /* not VMS */
 #ifdef DOS_NT
-  desc = open (fn,
-              O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type,
-              S_IREAD | S_IWRITE);
+  desc = emacs_open (fn,
+                    O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type
+                    | (mustbenew == Qexcl ? O_EXCL : 0),
+                    S_IREAD | S_IWRITE);
 #else  /* not DOS_NT */
-  desc = creat (fn, auto_saving ? auto_save_mode_bits : 0666);
+  desc = emacs_open (fn, O_WRONLY | O_TRUNC | O_CREAT
+                    | (mustbenew == Qexcl ? O_EXCL : 0),
+                    auto_saving ? auto_save_mode_bits : 0666);
 #endif /* not DOS_NT */
 #endif /* not VMS */
 
@@ -4599,9 +4645,8 @@ This does code conversion according to the value of\n\
 
   if (STRINGP (start))
     {
-      failure = 0 > a_write (desc, XSTRING (start)->data,
-                            STRING_BYTES (XSTRING (start)), 0, &annotations,
-                            &coding);
+      failure = 0 > a_write (desc, start, 0, XSTRING (start)->size,
+                            &annotations, &coding);
       save_errno = errno;
     }
   else if (XINT (start) != XINT (end))
@@ -4612,17 +4657,17 @@ This does code conversion according to the value of\n\
 
       if (XINT (start) < GPT)
        {
-         failure = 0 > a_write (desc, BYTE_POS_ADDR (tem),
-                                min (GPT_BYTE, end1) - tem, tem, &annotations,
-                                &coding);
+         failure = 0 > a_write (desc, Qnil, XINT (start),
+                                min (GPT, XINT (end)) - XINT (start),
+                                &annotations, &coding);
          save_errno = errno;
        }
 
       if (XINT (end) > GPT && !failure)
        {
-         tem = max (tem, GPT_BYTE);
-         failure = 0 > a_write (desc, BYTE_POS_ADDR (tem), end1 - tem,
-                                tem, &annotations, &coding);
+         tem = max (XINT (start), GPT);
+         failure = 0 > a_write (desc, Qnil, tem , XINT (end) - tem,
+                                &annotations, &coding);
          save_errno = errno;
        }
     }
@@ -4630,7 +4675,7 @@ This does code conversion according to the value of\n\
     {
       /* If file was empty, still need to write the annotations */
       coding.mode |= CODING_MODE_LAST_BLOCK;
-      failure = 0 > a_write (desc, "", 0, XINT (start), &annotations, &coding);
+      failure = 0 > a_write (desc, Qnil, XINT (end), 0, &annotations, &coding);
       save_errno = errno;
     }
 
@@ -4640,7 +4685,7 @@ This does code conversion according to the value of\n\
     {
       /* We have to flush out a data. */
       coding.mode |= CODING_MODE_LAST_BLOCK;
-      failure = 0 > e_write (desc, "", 0, &coding);
+      failure = 0 > e_write (desc, Qnil, 0, 0, &coding);
       save_errno = errno;
     }
 
@@ -4679,7 +4724,7 @@ This does code conversion according to the value of\n\
 #endif
 
   /* NFS can report a write failure now.  */
-  if (close (desc) < 0)
+  if (emacs_close (desc) < 0)
     failure = 1, save_errno = errno;
 
 #ifdef VMS
@@ -4713,7 +4758,7 @@ This does code conversion according to the value of\n\
 
   if (failure)
     error ("IO error writing %s: %s", XSTRING (filename)->data,
-          strerror (save_errno));
+          emacs_strerror (save_errno));
 
   if (visiting)
     {
@@ -4823,10 +4868,10 @@ build_annotations (start, end, pre_write_conversion)
   return annotations;
 }
 \f
-/* Write to descriptor DESC the NBYTES bytes starting at ADDR,
-   assuming they start at byte position BYTEPOS in the buffer.
+/* Write to descriptor DESC the NCHARS chars starting at POS of STRING.
+   If STRING is nil, POS is the character position in the current buffer.
    Intersperse with them the annotations from *ANNOT
-   which fall within the range of byte positions BYTEPOS to BYTEPOS + NBYTES,
+   which fall within the range of POS to POS + NCHARS,
    each at its appropriate position.
 
    We modify *ANNOT by discarding elements as we use them up.
@@ -4834,44 +4879,42 @@ build_annotations (start, end, pre_write_conversion)
    The return value is negative in case of system call failure.  */
 
 static int
-a_write (desc, addr, nbytes, bytepos, annot, coding)
+a_write (desc, string, pos, nchars, annot, coding)
      int desc;
-     register char *addr;
-     register int nbytes;
-     int bytepos;
+     Lisp_Object string;
+     register int nchars;
+     int pos;
      Lisp_Object *annot;
      struct coding_system *coding;
 {
   Lisp_Object tem;
   int nextpos;
-  int lastpos = bytepos + nbytes;
+  int lastpos = pos + nchars;
 
   while (NILP (*annot) || CONSP (*annot))
     {
       tem = Fcar_safe (Fcar (*annot));
-      nextpos = bytepos - 1;
+      nextpos = pos - 1;
       if (INTEGERP (tem))
-       nextpos = CHAR_TO_BYTE (XFASTINT (tem));
+       nextpos = XFASTINT (tem);
 
       /* If there are no more annotations in this range,
         output the rest of the range all at once.  */
-      if (! (nextpos >= bytepos && nextpos <= lastpos))
-       return e_write (desc, addr, lastpos - bytepos, coding);
+      if (! (nextpos >= pos && nextpos <= lastpos))
+       return e_write (desc, string, pos, lastpos, coding);
 
       /* Output buffer text up to the next annotation's position.  */
-      if (nextpos > bytepos)
+      if (nextpos > pos)
        {
-         if (0 > e_write (desc, addr, nextpos - bytepos, coding))
+         if (0 > e_write (desc, string, pos, nextpos, coding));
            return -1;
-         addr += nextpos - bytepos;
-         bytepos = nextpos;
+         pos = nextpos;
        }
       /* Output the annotation.  */
       tem = Fcdr (Fcar (*annot));
       if (STRINGP (tem))
        {
-         if (0 > e_write (desc, XSTRING (tem)->data, STRING_BYTES (XSTRING (tem)),
-                          coding))
+         if (0 > e_write (desc, tem, 0, XSTRING (tem)->size, coding));
            return -1;
        }
       *annot = Fcdr (*annot);
@@ -4883,17 +4926,45 @@ a_write (desc, addr, nbytes, bytepos, annot, coding)
 #define WRITE_BUF_SIZE (16 * 1024)
 #endif
 
-/* Write NBYTES bytes starting at ADDR into descriptor DESC,
-   encoding them with coding system CODING.  */
+/* Write text in the range START and END into descriptor DESC,
+   encoding them with coding system CODING.  If STRING is nil, START
+   and END are character positions of the current buffer, else they
+   are indexes to the string STRING.  */
 
 static int
-e_write (desc, addr, nbytes, coding)
+e_write (desc, string, start, end, coding)
      int desc;
-     register char *addr;
-     register int nbytes;
+     Lisp_Object string;
+     int start, end;
      struct coding_system *coding;
 {
+  register char *addr;
+  register int nbytes;
   char buf[WRITE_BUF_SIZE];
+  int composing = coding->composing;
+  int return_val = 0;
+
+  if (start >= end)
+    coding->composing = COMPOSITION_DISABLED;
+  if (coding->composing != COMPOSITION_DISABLED)
+    coding_save_composition (coding, start, end, string);
+
+  if (STRINGP (string))
+    {
+      addr = XSTRING (string)->data;
+      nbytes = STRING_BYTES (XSTRING (string));
+    }
+  else if (start < end)
+    {
+      /* It is assured that the gap is not in the range START and END-1.  */
+      addr = CHAR_POS_ADDR (start);
+      nbytes = CHAR_TO_BYTE (end) - CHAR_TO_BYTE (start);
+    }
+  else
+    {
+      addr = "";
+      nbytes = 0;
+    }
 
   /* We used to have a code for handling selective display here.  But,
      now it is handled within encode_coding.  */
@@ -4902,21 +4973,33 @@ e_write (desc, addr, nbytes, coding)
       int result;
 
       result = encode_coding (coding, addr, buf, nbytes, WRITE_BUF_SIZE);
-      nbytes -= coding->consumed, addr += coding->consumed;
       if (coding->produced > 0)
        {
-         coding->produced -= write (desc, buf, coding->produced);
-         if (coding->produced) return -1;
+         coding->produced -= emacs_write (desc, buf, coding->produced);
+         if (coding->produced)
+           {
+             return_val = -1;
+             break;
+           }
        }
       if (result == CODING_FINISH_INSUFFICIENT_SRC)
        {
          /* The source text ends by an incomplete multibyte form.
              There's no way other than write it out as is.  */
-         nbytes -= write (desc, addr, nbytes);
-         if (nbytes) return -1;
+         nbytes -= emacs_write (desc, addr, nbytes);
+         if (nbytes)
+           {
+             return_val = -1;
+             break;
+           }
        }
       if (nbytes <= 0)
        break;
+      nbytes -= coding->consumed;
+      addr += coding->consumed;
+      start += coding->consumed_char;
+      if (coding->cmp_data)
+       coding_adjust_composition_offset (coding, start);
     }
   return 0;
 }
@@ -5061,8 +5144,8 @@ do_auto_save_unwind (stream)  /* used as unwind-protect function */
 {
   auto_saving = 0;
   if (!NILP (stream))
-    fclose ((FILE *) (XFASTINT (XCONS (stream)->car) << 16
-                     | XFASTINT (XCONS (stream)->cdr)));
+    fclose ((FILE *) (XFASTINT (XCAR (stream)) << 16
+                     | XFASTINT (XCDR (stream))));
   return Qnil;
 }
 
@@ -5123,8 +5206,8 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
          /* Arrange to close that file whether or not we get an error.
             Also reset auto_saving to 0.  */
          lispstream = Fcons (Qnil, Qnil);
-         XSETFASTINT (XCONS (lispstream)->car, (EMACS_UINT)stream >> 16);
-         XSETFASTINT (XCONS (lispstream)->cdr, (EMACS_UINT)stream & 0xffff);
+         XSETFASTINT (XCAR (lispstream), (EMACS_UINT)stream >> 16);
+         XSETFASTINT (XCDR (lispstream), (EMACS_UINT)stream & 0xffff);
        }
       else
        lispstream = Qnil;
@@ -5147,9 +5230,9 @@ A non-nil CURRENT-ONLY argument means save only current buffer.")
      autosave perfectly ordinary files because it couldn't handle some
      ange-ftp'd file.  */
   for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
-    for (tail = Vbuffer_alist; GC_CONSP (tail); tail = XCONS (tail)->cdr)
+    for (tail = Vbuffer_alist; GC_CONSP (tail); tail = XCDR (tail))
       {
-       buf = XCONS (XCONS (tail)->car)->cdr;
+       buf = XCDR (XCAR (tail));
        b = XBUFFER (buf);
 
        /* Record all the buffers that have auto save mode
@@ -5506,7 +5589,7 @@ DIR defaults to current buffer's directory default.")
                            Qfile_name_history, default_filename, Qnil);
 
   tem = Fsymbol_value (Qfile_name_history);
-  if (CONSP (tem) && EQ (XCONS (tem)->car, val))
+  if (CONSP (tem) && EQ (XCAR (tem), val))
     replace_in_history = 1;
 
   /* If Fcompleting_read returned the inserted default string itself
@@ -5545,14 +5628,14 @@ DIR defaults to current buffer's directory default.")
   if (replace_in_history)
     /* Replace what Fcompleting_read added to the history
        with what we will actually return.  */
-    XCONS (Fsymbol_value (Qfile_name_history))->car = double_dollars (val);
+    XCAR (Fsymbol_value (Qfile_name_history)) = double_dollars (val);
   else if (add_to_history)
     {
       /* Add the value to the history--but not if it matches
         the last value already there.  */
       Lisp_Object val1 = double_dollars (val);
       tem = Fsymbol_value (Qfile_name_history);
-      if (! CONSP (tem) || NILP (Fequal (XCONS (tem)->car, val1)))
+      if (! CONSP (tem) || NILP (Fequal (XCAR (tem), val1)))
        Fset (Qfile_name_history,
              Fcons (val1, tem));
     }
@@ -5644,6 +5727,8 @@ syms_of_fileio ()
   staticpro (&Qfile_already_exists);
   Qfile_date_error = intern ("file-date-error");
   staticpro (&Qfile_date_error);
+  Qexcl = intern ("excl");
+  staticpro (&Qexcl);
 
 #ifdef DOS_NT
   Qfind_buffer_file_type = intern ("find-buffer-file-type");