(Fsubstitute_in_file_name): Adjusted for the change of
[bpt/emacs.git] / src / fileio.c
index 3992700..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.
 
@@ -32,10 +32,6 @@ Boston, MA 02111-1307, USA.  */
 #include <unistd.h>
 #endif
 
-#ifdef STDC_HEADERS
-#include <stdlib.h>
-#endif
-
 #if !defined (S_ISLNK) && defined (S_IFLNK)
 #  define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
 #endif
@@ -69,8 +65,6 @@ Boston, MA 02111-1307, USA.  */
 extern int errno;
 #endif
 
-extern char *strerror ();
-
 #ifdef APOLLO
 #include <sys/time.h>
 #endif
@@ -241,9 +235,10 @@ 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)
@@ -253,7 +248,10 @@ report_file_error (string, data)
   Lisp_Object errstring;
   int errorno = errno;
 
-  errstring = build_string (strerror (errno));
+  synchronize_system_messages_locale ();
+  errstring = code_convert_string_norecord (build_string (strerror (errorno)),
+                                           Vlocale_coding_system, 0);
+
   while (1)
     switch (errorno)
       {
@@ -275,7 +273,7 @@ Lisp_Object
 close_file_unwind (fd)
      Lisp_Object fd;
 {
-  close (XFASTINT (fd));
+  emacs_close (XFASTINT (fd));
   return Qnil;
 }
 
@@ -2093,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
@@ -2287,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));
 
@@ -2339,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)
@@ -2375,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;
@@ -2914,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 */
 }
@@ -2983,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;
 }
@@ -3291,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;
 
-  if (!NILP (multibyte))
-    inserted = multibyte_chars_in_text (GPT_ADDR - inserted, inserted);
-  adjust_after_insert (PT, PT_BYTE, Z, Z_BYTE, inserted);
+  multibyte = XCAR (unwind_data);
+  unwind_data = XCDR (unwind_data);
+  undo_list = XCAR (unwind_data);
+  buffer = XCDR (unwind_data);
+
+  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;
 }
@@ -3403,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;
     }
 
@@ -3438,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.  */
@@ -3470,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");
        }
     }
@@ -3503,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;
@@ -3618,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;
 
@@ -3660,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;
@@ -3689,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
@@ -3809,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)
@@ -3862,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");
        }
@@ -3881,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);
@@ -3946,7 +3961,7 @@ actually used.")
       inserted = PT - temp;
 
       free (conversion_buffer);
-      close (fd);
+      emacs_close (fd);
       specpdl_ptr--;
 
       goto handled;
@@ -4003,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)
@@ -4034,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;
 
@@ -4054,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))
@@ -4089,6 +4107,9 @@ actually used.")
              if (CONSP (coding_systems))
                val = XCAR (coding_systems);
            }
+
+         unbind_to (count, Qnil);
+         inserted = Z_BYTE - BEG_BYTE;
        }
 
       /* The following kludgy code is to avoid some compiler bug.
@@ -4197,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)
     {
@@ -4496,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))
@@ -4506,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,
@@ -4539,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
              }
@@ -4549,14 +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
-              | (mustbenew == Qexcl ? O_EXCL : 0),
-              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 = open (fn, O_WRONLY | O_TRUNC | O_CREAT
-              | (mustbenew == Qexcl ? O_EXCL : 0),
-              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 */
 
@@ -4621,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))
@@ -4634,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;
        }
     }
@@ -4652,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;
     }
 
@@ -4662,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;
     }
 
@@ -4701,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
@@ -4735,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)
     {
@@ -4845,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.
@@ -4856,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);
@@ -4905,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.  */
@@ -4924,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;
 }