(toplevel) [STDC_HEADERS]: Include float.h.
[bpt/emacs.git] / src / editfns.c
index 10a52ca..2cf1092 100644 (file)
@@ -1,5 +1,6 @@
 /* Lisp functions pertaining to editing.
-   Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999 Free Software Foundation, Inc.
+   Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999, 2000, 2001
+       Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -37,10 +38,18 @@ Boston, MA 02111-1307, USA.  */
 #include "buffer.h"
 #include "charset.h"
 #include "coding.h"
+#include "frame.h"
 #include "window.h"
 
 #include "systime.h"
 
+#ifdef STDC_HEADERS
+#include <float.h>
+#define MAX_10_EXP     DBL_MAX_10_EXP
+#else
+#define MAX_10_EXP     310
+#endif
+
 #define min(a, b) ((a) < (b) ? (a) : (b))
 #define max(a, b) ((a) > (b) ? (a) : (b))
 
@@ -48,20 +57,37 @@ Boston, MA 02111-1307, USA.  */
 #define NULL 0
 #endif
 
+#ifndef USE_CRT_DLL
 extern char **environ;
-extern int use_dialog_box;
-extern Lisp_Object make_time ();
-extern void insert_from_buffer ();
-static int tm_diff ();
-static void update_buffer_properties ();
-size_t emacs_strftimeu ();
-void set_time_zone_rule ();
+#endif
+
+extern Lisp_Object make_time P_ ((time_t));
+extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
+                                  const struct tm *, int));
+static int tm_diff P_ ((struct tm *, struct tm *));
+static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
+static void update_buffer_properties P_ ((int, int));
+static Lisp_Object region_limit P_ ((int));
+static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
+static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
+                                  size_t, const struct tm *, int));
+static void general_insert_function P_ ((void (*) (unsigned char *, int),
+                                        void (*) (Lisp_Object, int, int, int,
+                                                  int, int),
+                                        int, int, Lisp_Object *));
+static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
+static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
+static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
+
+#ifdef HAVE_INDEX
+extern char *index P_ ((const char *, int));
+#endif
 
 Lisp_Object Vbuffer_access_fontify_functions;
 Lisp_Object Qbuffer_access_fontify_functions;
 Lisp_Object Vbuffer_access_fontified_property;
 
-Lisp_Object Fuser_full_name ();
+Lisp_Object Fuser_full_name P_ ((Lisp_Object));
 
 /* Non-nil means don't stop at field boundary in text motion commands.  */
 
@@ -74,6 +100,15 @@ Lisp_Object Vuser_real_login_name;  /* login name of current user ID */
 Lisp_Object Vuser_full_name;           /* full name of current user */
 Lisp_Object Vuser_login_name;          /* user name from LOGNAME or USER */
 
+/* Symbol for the text property used to mark fields.  */
+
+Lisp_Object Qfield;
+
+/* A special value for Qfield properties.  */
+
+Lisp_Object Qboundary;
+
+
 void
 init_editfns ()
 {
@@ -140,7 +175,9 @@ DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
 
   CHECK_NUMBER (character, 0);
 
-  len = CHAR_STRING (XFASTINT (character), str);
+  len = (SINGLE_BYTE_CHAR_P (XFASTINT (character))
+        ? (*str = (unsigned char)(XFASTINT (character)), 1)
+        : char_to_string (XFASTINT (character), str));
   return make_string_from_bytes (str, 1, len);
 }
 
@@ -237,35 +274,44 @@ except in the case that `enable-multibyte-characters' is nil.")
   return position;
 }
 
+
+/* Return the start or end position of the region.
+   BEGINNINGP non-zero means return the start.
+   If there is no region active, signal an error. */
+
 static Lisp_Object
 region_limit (beginningp)
      int beginningp;
 {
   extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
-  register Lisp_Object m;
-  if (!NILP (Vtransient_mark_mode) && NILP (Vmark_even_if_inactive)
+  Lisp_Object m;
+  
+  if (!NILP (Vtransient_mark_mode)
+      && NILP (Vmark_even_if_inactive)
       && NILP (current_buffer->mark_active))
     Fsignal (Qmark_inactive, Qnil);
+  
   m = Fmarker_position (current_buffer->mark);
-  if (NILP (m)) error ("There is no region now");
+  if (NILP (m))
+    error ("There is no region now");
+  
   if ((PT < XFASTINT (m)) == beginningp)
-    return (make_number (PT));
-  else
-    return (m);
+    m = make_number (PT);
+  return m;
 }
 
 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
   "Return position of beginning of region, as an integer.")
   ()
 {
-  return (region_limit (1));
+  return region_limit (1);
 }
 
 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
   "Return position of end of region, as an integer.")
   ()
 {
-  return (region_limit (0));
+  return region_limit (0);
 }
 
 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
@@ -276,7 +322,10 @@ If you set the marker not to point anywhere, the buffer will have no mark.")
 {
   return current_buffer->mark;
 }
+
 \f
+#if 0 /* Not used.  */
+
 /* Return nonzero if POS1 and POS2 have the same value
    for the text property PROP.  */
 
@@ -293,13 +342,15 @@ char_property_eq (prop, pos1, pos2)
   return EQ (pval1, pval2);
 }
 
-/* Return the direction from which the char-property PROP would be
+#endif /* 0 */
+
+/* Return the direction from which the text-property PROP would be
    inherited by any new text inserted at POS: 1 if it would be
    inherited from the char after POS, -1 if it would be inherited from
    the char before POS, and 0 if from neither.  */
 
 static int
-char_property_stickiness (prop, pos)
+text_property_stickiness (prop, pos)
      Lisp_Object prop;
      Lisp_Object pos;
 {
@@ -311,7 +362,7 @@ char_property_stickiness (prop, pos)
       Lisp_Object prev_pos, rear_non_sticky;
 
       prev_pos = make_number (XINT (pos) - 1);
-      rear_non_sticky = Fget_char_property (prev_pos, Qrear_nonsticky, Qnil);
+      rear_non_sticky = Fget_text_property (prev_pos, Qrear_nonsticky, Qnil);
 
       if (EQ (rear_non_sticky, Qnil)
          || (CONSP (rear_non_sticky)
@@ -322,7 +373,7 @@ char_property_stickiness (prop, pos)
     }
 
   /* Consider following character.  */
-  front_sticky = Fget_char_property (pos, Qfront_sticky, Qnil);
+  front_sticky = Fget_text_property (pos, Qfront_sticky, Qnil);
 
   if (EQ (front_sticky, Qt)
       || (CONSP (front_sticky)
@@ -333,15 +384,11 @@ char_property_stickiness (prop, pos)
   /* PROP is not inherited from either side.  */
   return 0;
 }
-\f
-/* Symbol for the text property used to mark fields.  */
-Lisp_Object Qfield;
-
-/* A special value for Qfield properties.  */
-Lisp_Object Qboundary;
 
+\f
 /* Find the field surrounding POS in *BEG and *END.  If POS is nil,
-   the value of point is used instead.
+   the value of point is used instead.  If BEG or END null,
+   means don't store the beginning or end of the field.
 
    If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
    position of a field, then the beginning of the previous field is
@@ -356,7 +403,7 @@ Lisp_Object Qboundary;
    Either BEG or END may be 0, in which case the corresponding value
    is not stored.  */
 
-void
+static void
 find_field (pos, merge_at_boundary, beg, end)
      Lisp_Object pos;
      Lisp_Object merge_at_boundary;
@@ -364,6 +411,9 @@ find_field (pos, merge_at_boundary, beg, end)
 {
   /* Fields right before and after the point.  */
   Lisp_Object before_field, after_field;
+  /* If the fields came from overlays, the associated overlays.
+     Qnil means they came from text-properties.  */
+  Lisp_Object before_overlay = Qnil, after_overlay = Qnil;
   /* 1 if POS counts as the start of a field.  */
   int at_field_start = 0;
   /* 1 if POS counts as the end of a field.  */
@@ -374,12 +424,14 @@ find_field (pos, merge_at_boundary, beg, end)
   else
     CHECK_NUMBER_COERCE_MARKER (pos, 0);
 
-  after_field =
-    Fget_char_property (pos, Qfield, Qnil);
-  before_field =
-    (XFASTINT (pos) > BEGV
-     ? Fget_char_property (make_number (XINT (pos) - 1), Qfield, Qnil)
-     : Qnil);
+  after_field
+    = get_char_property_and_overlay (pos, Qfield, Qnil, &after_overlay);
+  before_field
+    = (XFASTINT (pos) > BEGV
+       ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
+                                       Qfield, Qnil,
+                                       &before_overlay)
+       : Qnil);
 
   /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
      and POS is at beginning of a field, which can also be interpreted
@@ -391,7 +443,42 @@ find_field (pos, merge_at_boundary, beg, end)
     /* We are at a boundary, see which direction is inclusive.  We
        decide by seeing which field the `field' property sticks to.  */
     {
-      int stickiness = char_property_stickiness (Qfield, pos);
+      /* -1 means insertions go into before_field, 1 means they go
+        into after_field, 0 means neither.  */
+      int stickiness;
+      /* Whether the before/after_field come from overlays.  */
+      int bop = !NILP (before_overlay);
+      int aop = !NILP (after_overlay);
+
+      if (bop && XMARKER (OVERLAY_END (before_overlay))->insertion_type == 1)
+       /* before_field is from an overlay, which expands upon
+          end-insertions.  Note that it's possible for after_overlay to
+          also eat insertions here, but then they will overlap, and
+          there's not much we can do.  */
+       stickiness = -1;
+      else if (aop
+              && XMARKER (OVERLAY_START (after_overlay))->insertion_type == 0)
+       /* after_field is from an overlay, which expand to contain
+          start-insertions.  */
+       stickiness = 1;
+      else if (bop && aop)
+       /* Both fields come from overlays, but neither will contain any
+          insertion here.  */
+       stickiness = 0;
+      else if (bop)
+       /* before_field is an overlay that won't eat any insertion, but
+          after_field is from a text-property.  Assume that the
+          text-property continues underneath the overlay, and so will
+          be inherited by any insertion, regardless of any stickiness
+          settings.  */
+       stickiness = 1;
+      else if (aop)
+       /* Similarly, when after_field is the overlay.  */
+       stickiness = -1;
+      else
+       /* Both fields come from text-properties.  Look for explicit
+          stickiness properties.  */
+       stickiness = text_property_stickiness (Qfield, pos);
 
       if (stickiness > 0)
        at_field_start = 1;
@@ -433,37 +520,42 @@ find_field (pos, merge_at_boundary, beg, end)
      the `x' field, and the end as being the end of the `y' field.  */
 
   if (beg)
-    if (at_field_start)
-      /* POS is at the edge of a field, and we should consider it as
-        the beginning of the following field.  */
-      *beg = XFASTINT (pos);
-    else
-      /* Find the previous field boundary.  */
-      {
-       if (!NILP (merge_at_boundary) && before_field == Qboundary)
-         /* Skip a `boundary' field.  */
-         pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
+    {
+      if (at_field_start)
+       /* POS is at the edge of a field, and we should consider it as
+          the beginning of the following field.  */
+       *beg = XFASTINT (pos);
+      else
+       /* Find the previous field boundary.  */
+       {
+         if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
+           /* Skip a `boundary' field.  */
+           pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
 
-       pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
-       *beg = NILP (pos) ? BEGV : XFASTINT (pos);
-      }
+         pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
+         *beg = NILP (pos) ? BEGV : XFASTINT (pos);
+       }
+    }
 
   if (end)
-    if (at_field_end)
-      /* POS is at the edge of a field, and we should consider it as
-        the end of the previous field.  */
-      *end = XFASTINT (pos);
-    else
-      /* Find the next field boundary.  */
-      {
-       if (!NILP (merge_at_boundary) && after_field == Qboundary)
-         /* Skip a `boundary' field.  */
-         pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
+    {
+      if (at_field_end)
+       /* POS is at the edge of a field, and we should consider it as
+          the end of the previous field.  */
+       *end = XFASTINT (pos);
+      else
+       /* Find the next field boundary.  */
+       {
+         if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
+           /* Skip a `boundary' field.  */
+           pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
 
-       pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
-       *end = NILP (pos) ? ZV : XFASTINT (pos);
-      }
+         pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
+         *end = NILP (pos) ? ZV : XFASTINT (pos);
+       }
+    }
 }
+
 \f
 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
   "Delete the field surrounding POS.\n\
@@ -536,7 +628,7 @@ DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
 \n\
 A field is a region of text with the same `field' property.\n\
 If NEW-POS is nil, then the current point is used instead, and set to the\n\
-constrained position if that is is different.\n\
+constrained position if that is different.\n\
 \n\
 If OLD-POS is at the boundary of two fields, then the allowable\n\
 positions for NEW-POS depends on the value of the optional argument\n\
@@ -574,7 +666,8 @@ Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
 
   if (NILP (Vinhibit_field_text_motion)
       && !EQ (new_pos, old_pos)
-      && !char_property_eq (Qfield, new_pos, old_pos)
+      && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
+         || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
       && (NILP (inhibit_capture_property)
          || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
     /* NEW_POS is not within the same field as OLD_POS; try to
@@ -593,20 +686,23 @@ Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
       else
        field_bound = Ffield_beginning (old_pos, escape_from_edge);
 
-      if (/* If ONLY_IN_LINE is non-nil, we only constrain NEW_POS if doing
-            so would remain within the same line.  */
-         NILP (only_in_line)
-         /* In that case, see if ESCAPE_FROM_EDGE caused FIELD_BOUND
-             to jump to the other side of NEW_POS, which would mean
-             that NEW_POS is already acceptable, and that we don't
-             have to do the line-check.  */
-         || ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? !fwd : fwd)
-         /* If not, see if there's no newline intervening between
-             NEW_POS and FIELD_BOUND.  */
-         || (scan_buffer ('\n',
-                          XFASTINT (new_pos), XFASTINT (field_bound),
-                          fwd ? -1 : 1, &shortage, 1),
-             shortage != 0))
+      if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
+             other side of NEW_POS, which would mean that NEW_POS is
+             already acceptable, and it's not necessary to constrain it
+             to FIELD_BOUND.  */
+         ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
+         /* NEW_POS should be constrained, but only if either
+            ONLY_IN_LINE is nil (in which case any constraint is OK),
+            or NEW_POS and FIELD_BOUND are on the same line (in which
+            case the constraint is OK even if ONLY_IN_LINE is non-nil). */
+         && (NILP (only_in_line)
+             /* This is the ONLY_IN_LINE case, check that NEW_POS and
+                FIELD_BOUND are on the same line by seeing whether
+                there's an intervening newline or not.  */
+             || (scan_buffer ('\n',
+                              XFASTINT (new_pos), XFASTINT (field_bound),
+                              fwd ? -1 : 1, &shortage, 1),
+                 shortage != 0)))
        /* Constrain NEW_POS to FIELD_BOUND.  */
        new_pos = field_bound;
 
@@ -617,6 +713,7 @@ Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
 
   return new_pos;
 }
+
 \f
 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
   0, 1, 0,
@@ -632,7 +729,7 @@ This function does not move point.")
   (n)
      Lisp_Object n;
 {
-  register int orig, orig_byte, end;
+  int orig, orig_byte, end;
 
   if (NILP (n))
     XSETFASTINT (n, 1);
@@ -662,7 +759,7 @@ This function does not move point.")
      Lisp_Object n;
 {
   int end_pos;
-  register int orig = PT;
+  int orig = PT;
 
   if (NILP (n))
     XSETFASTINT (n, 1);
@@ -679,13 +776,14 @@ This function does not move point.")
 Lisp_Object
 save_excursion_save ()
 {
-  register int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
-                         == current_buffer);
+  int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
+                == current_buffer);
 
   return Fcons (Fpoint_marker (),
                Fcons (Fcopy_marker (current_buffer->mark, Qnil),
                       Fcons (visible ? Qt : Qnil,
-                             current_buffer->mark_active)));
+                             Fcons (current_buffer->mark_active,
+                                    selected_window))));
 }
 
 Lisp_Object
@@ -694,8 +792,9 @@ save_excursion_restore (info)
 {
   Lisp_Object tem, tem1, omark, nmark;
   struct gcpro gcpro1, gcpro2, gcpro3;
+  int visible_p;
 
-  tem = Fmarker_buffer (Fcar (info));
+  tem = Fmarker_buffer (XCAR (info));
   /* If buffer being returned to is now deleted, avoid error */
   /* Otherwise could get error here while unwinding to top level
      and crash */
@@ -707,15 +806,24 @@ save_excursion_restore (info)
   GCPRO3 (info, omark, nmark);
 
   Fset_buffer (tem);
-  tem = Fcar (info);
+
+  /* Point marker.  */
+  tem = XCAR (info);
   Fgoto_char (tem);
   unchain_marker (tem);
-  tem = Fcar (Fcdr (info));
+
+  /* Mark marker.  */
+  info = XCDR (info);
+  tem = XCAR (info);
   omark = Fmarker_position (current_buffer->mark);
   Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
   nmark = Fmarker_position (tem);
   unchain_marker (tem);
-  tem = Fcdr (Fcdr (info));
+
+  /* visible */
+  info = XCDR (info);
+  visible_p = !NILP (XCAR (info));
+  
 #if 0 /* We used to make the current buffer visible in the selected window
         if that was true previously.  That avoids some anomalies.
         But it creates others, and it wasn't documented, and it is simpler
@@ -726,8 +834,12 @@ save_excursion_restore (info)
     Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
 #endif /* 0 */
 
+  /* Mark active */
+  info = XCDR (info);
+  tem = XCAR (info);
   tem1 = current_buffer->mark_active;
-  current_buffer->mark_active = Fcdr (tem);
+  current_buffer->mark_active = tem;
+
   if (!NILP (Vrun_hooks))
     {
       /* If mark is active now, and either was not active
@@ -741,6 +853,20 @@ save_excursion_restore (info)
       else if (! NILP (tem1))
        call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
     }
+
+  /* If buffer was visible in a window, and a different window was
+     selected, and the old selected window is still showing this
+     buffer, restore point in that window.  */
+  tem = XCDR (info);
+  if (visible_p
+      && !EQ (tem, selected_window)
+      && (tem1 = XWINDOW (tem)->buffer,
+         (/* Window is live...  */
+          BUFFERP (tem1)
+          /* ...and it shows the current buffer.  */
+          && XBUFFER (tem1) == current_buffer)))
+    Fset_window_point (tem, make_number (PT));
+
   UNGCPRO;
   return Qnil;
 }
@@ -774,7 +900,7 @@ Executes BODY just like `progn'.")
   (args)
      Lisp_Object args;
 {
-  register Lisp_Object val;
+  Lisp_Object val;
   int count = specpdl_ptr - specpdl;
 
   record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
@@ -1100,7 +1226,6 @@ name, or nil if there is no such user.")
 {
   struct passwd *pw;
   register unsigned char *p, *q;
-  extern char *index ();
   Lisp_Object full;
 
   if (NILP (uid))
@@ -1151,6 +1276,7 @@ DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
 }
 
 /* For the benefit of callers who don't want to include lisp.h */
+
 char *
 get_system_name ()
 {
@@ -1247,7 +1373,10 @@ If an argument is given, it specifies a time to convert to float\n\
 instead of the current time.  The argument should have the forms:\n\
  (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
 Thus, you can use times obtained from `current-time'\n\
-and from `file-attributes'.")
+and from `file-attributes'.\n\
+\n\
+WARNING: Since the result is floating point, it may not be exact.\n\
+Do not use this function if precise time stamps are required.")
   (specified_time)
      Lisp_Object specified_time;
 {
@@ -1257,7 +1386,7 @@ and from `file-attributes'.")
   if (! lisp_time_argument (specified_time, &sec, &usec))
     error ("Invalid time specification");
 
-  return make_float (sec + usec * 0.0000001);
+  return make_float ((sec * 1e6 + usec) / 1e6);
 }
 
 /* Write information into buffer S of size MAXSIZE, according to the
@@ -1353,8 +1482,11 @@ by text that describes the specified date and time in TIME:\n\
 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
 \n\
 Certain flags and modifiers are available with some format controls.\n\
-The flags are `_' and `-'.  For certain characters X, %_X is like %X,\n\
-but padded with blanks; %-X is like %X, but without padding.\n\
+The flags are `_', `-', `^' and `#'.  For certain characters X,\n\
+%_X is like %X, but padded with blanks; %-X is like %X,\n\
+ut without padding.  %^X is like %X but with all textual\n\
+characters up-cased; %#X is like %X but with letter-case of\n\
+all textual characters reversed.\n\
 %NX (where N stands for an integer) is like %X,\n\
 but takes up at least N (a number) positions.\n\
 The modifiers are `E' and `O'.  For certain characters X,\n\
@@ -1643,6 +1775,20 @@ the data it can't find.")
        s = tzname[t->tm_isdst];
 #endif
 #endif /* not HAVE_TM_ZONE */
+
+#if defined HAVE_TM_ZONE || defined HAVE_TZNAME
+      if (s)
+       {
+         /* On Japanese w32, we can get a Japanese string as time
+            zone name.  Don't accept that.  */
+         char *p;
+         for (p = s; *p && (isalnum (*p) || *p == ' '); ++p)
+           ;
+         if (p == s || *p)
+           s = NULL;
+       }
+#endif
+
       if (!s)
        {
          /* No local time zone name is available; use "+-NNNN" instead.  */
@@ -1707,6 +1853,7 @@ static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
 /* Set the local time zone rule to TZSTRING.
    This allocates memory into `environ', which it is the caller's
    responsibility to free.  */
+
 void
 set_time_zone_rule (tzstring)
      char *tzstring;
@@ -1788,7 +1935,7 @@ set_time_zone_rule (tzstring)
    type of object is Lisp_String).  INHERIT is passed to
    INSERT_FROM_STRING_FUNC as the last argument.  */
 
-void
+static void
 general_insert_function (insert_func, insert_from_string_func,
                         inherit, nargs, args)
      void (*insert_func) P_ ((unsigned char *, int));
@@ -2082,7 +2229,11 @@ DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
   "Return the contents of part of the current buffer as a string.\n\
 The two arguments START and END are character positions;\n\
 they can be in either order.\n\
-The string returned is multibyte if the buffer is multibyte.")
+The string returned is multibyte if the buffer is multibyte.\n\
+\n\
+This function copies the text properties of that part of the buffer\n\
+into the result string; if you don't want the text properties,\n\
+use `buffer-substring-no-properties' instead.")
   (start, end)
      Lisp_Object start, end;
 {
@@ -2115,8 +2266,7 @@ they can be in either order.")
 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
   "Return the contents of the current buffer as a string.\n\
 If narrowing is in effect, this function returns only the visible part\n\
-of the buffer.  If in a mini-buffer, don't include the prompt in the\n\
-string returned.")
+of the buffer.")
   ()
 {
   return make_buffer_string (BEGV, ZV, 1);
@@ -2362,7 +2512,7 @@ Both characters must have the same length of multi-byte form.")
 #define COMBINING_AFTER  2
 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
   int maybe_byte_combining = COMBINING_NO;
-  int last_changed;
+  int last_changed = 0;
   int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
 
   validate_region (&start, &end);
@@ -2678,53 +2828,71 @@ or markers) bounding the text that should remain visible.")
 Lisp_Object
 save_restriction_save ()
 {
-  register Lisp_Object bottom, top;
-  /* Note: I tried using markers here, but it does not win
-     because insertion at the end of the saved region
-     does not advance mh and is considered "outside" the saved region. */
-  XSETFASTINT (bottom, BEGV - BEG);
-  XSETFASTINT (top, Z - ZV);
+  if (BEGV == BEG && ZV == Z)
+    /* The common case that the buffer isn't narrowed.
+       We return just the buffer object, which save_restriction_restore
+       recognizes as meaning `no restriction'.  */
+    return Fcurrent_buffer ();
+  else
+    /* We have to save a restriction, so return a pair of markers, one
+       for the beginning and one for the end.  */
+    {
+      Lisp_Object beg, end;
+
+      beg = buildmark (BEGV, BEGV_BYTE);
+      end = buildmark (ZV, ZV_BYTE);
 
-  return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
+      /* END must move forward if text is inserted at its exact location.  */
+      XMARKER(end)->insertion_type = 1;
+
+      return Fcons (beg, end);
+    }
 }
 
 Lisp_Object
 save_restriction_restore (data)
      Lisp_Object data;
 {
-  register struct buffer *buf;
-  register int newhead, newtail;
-  register Lisp_Object tem;
-  int obegv, ozv;
-
-  buf = XBUFFER (XCAR (data));
-
-  data = XCDR (data);
-
-  tem = XCAR (data);
-  newhead = XINT (tem);
-  tem = XCDR (data);
-  newtail = XINT (tem);
-  if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
+  if (CONSP (data))
+    /* A pair of marks bounding a saved restriction.  */
     {
-      newhead = 0;
-      newtail = 0;
-    }
-
-  obegv = BUF_BEGV (buf);
-  ozv = BUF_ZV (buf);
+      struct Lisp_Marker *beg = XMARKER (XCAR (data));
+      struct Lisp_Marker *end = XMARKER (XCDR (data));
+      struct buffer *buf = beg->buffer; /* END should have the same buffer. */
 
-  SET_BUF_BEGV (buf, BUF_BEG (buf) + newhead);
-  SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
+      if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
+       /* The restriction has changed from the saved one, so restore
+          the saved restriction.  */
+       {
+         int pt = BUF_PT (buf);
+
+         SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
+         SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
+
+         if (pt < beg->charpos || pt > end->charpos)
+           /* The point is outside the new visible range, move it inside. */
+           SET_BUF_PT_BOTH (buf,
+                            clip_to_bounds (beg->charpos, pt, end->charpos),
+                            clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
+                                            end->bytepos));
+         
+         buf->clip_changed = 1; /* Remember that the narrowing changed. */
+       }
+    }
+  else
+    /* A buffer, which means that there was no old restriction.  */
+    {
+      struct buffer *buf = XBUFFER (data);
 
-  if (obegv != BUF_BEGV (buf) || ozv != BUF_ZV (buf))
-    current_buffer->clip_changed = 1;
+      if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
+       /* The buffer has been narrowed, get rid of the narrowing.  */
+       {
+         SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
+         SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
 
-  /* If point is outside the new visible range, move it inside. */
-  SET_BUF_PT_BOTH (buf,
-                  clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)),
-                  clip_to_bounds (BUF_BEGV_BYTE (buf), BUF_PT_BYTE (buf),
-                                  BUF_ZV_BYTE (buf)));
+         buf->clip_changed = 1; /* Remember that the narrowing changed. */
+       }
+    }
 
   return Qnil;
 }
@@ -2741,10 +2909,6 @@ even in case of abnormal exit (throw or error).\n\
 \n\
 The value returned is the value of the last form in BODY.\n\
 \n\
-`save-restriction' can get confused if, within the BODY, you widen\n\
-and then make changes outside the area within the saved restrictions.\n\
-See Info node `(elisp)Narrowing' for details and an appropriate technique.\n\
-\n\
 Note: if you are using both `save-excursion' and `save-restriction',\n\
 use `save-excursion' outermost:\n\
     (save-excursion (save-restriction ...))")
@@ -2759,16 +2923,12 @@ use `save-excursion' outermost:\n\
   return unbind_to (count, val);
 }
 \f
-#ifndef HAVE_MENUS
-
-/* Buffer for the most recent text displayed by Fmessage.  */
+/* Buffer for the most recent text displayed by Fmessage_box.  */
 static char *message_text;
 
 /* Allocated length of that buffer.  */
 static int message_length;
 
-#endif /* not HAVE_MENUS */
-
 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
   "Print a one-line message at the bottom of the screen.\n\
 The first argument is a format control string, and the rest are data\n\
@@ -2816,6 +2976,10 @@ minibuffer contents show.")
       register Lisp_Object val;
       val = Fformat (nargs, args);
 #ifdef HAVE_MENUS
+      /* The MS-DOS frames support popup menus even though they are
+        not FRAME_WINDOW_P.  */
+      if (FRAME_WINDOW_P (XFRAME (selected_frame))
+         || FRAME_MSDOS_P (XFRAME (selected_frame)))
       {
        Lisp_Object pane, menu, obj;
        struct gcpro gcpro1;
@@ -2826,7 +2990,7 @@ minibuffer contents show.")
        UNGCPRO;
        return val;
       }
-#else /* not HAVE_MENUS */
+#endif /* HAVE_MENUS */
       /* Copy the data so that it won't move when we GC.  */
       if (! message_text)
        {
@@ -2842,7 +3006,6 @@ minibuffer contents show.")
       message2 (message_text, STRING_BYTES (XSTRING (val)),
                STRING_MULTIBYTE (val));
       return val;
-#endif /* not HAVE_MENUS */
     }
 }
 #ifdef HAVE_MENUS
@@ -2851,7 +3014,8 @@ extern Lisp_Object last_nonmenu_event;
 
 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
   "Display a message in a dialog box or in the echo area.\n\
-If this command was invoked with the mouse, use a dialog box.\n\
+If this command was invoked with the mouse, use a dialog box if\n\
+`use-dialog-box' is non-nil.\n\
 Otherwise, use the echo area.\n\
 The first argument is a format control string, and the rest are data\n\
 to be formatted under control of the string.  See `format' for details.\n\
@@ -2931,6 +3095,7 @@ The other arguments are substituted into it to make the result, a string.\n\
 It may contain %-sequences meaning to substitute the next argument.\n\
 %s means print a string argument.  Actually, prints any object, with `princ'.\n\
 %d means print as number in decimal (%o octal, %x hex).\n\
+%X is like %x, but uses upper case.\n\
 %e means print a number in exponential notation.\n\
 %f means print a number in decimal-point notation.\n\
 %g means print a number in exponential notation\n\
@@ -2964,8 +3129,6 @@ Use %% to put a single % into the output.")
     int start, end;
   } *info = 0;
 
-  extern char *index ();
-
   /* It should not be necessary to GCPRO ARGS, because
      the caller in the interpreter should take care of that.  */
 
@@ -2996,17 +3159,45 @@ Use %% to put a single % into the output.")
   while (format != end)
     if (*format++ == '%')
       {
-       int minlen, thissize = 0;
+       int thissize = 0;
        unsigned char *this_format_start = format - 1;
+       int field_width, precision;
 
-       /* Process a numeric arg and skip it.  */
-       minlen = atoi (format);
-       if (minlen < 0)
-         minlen = - minlen;
+       /* General format specifications look like
 
-       while ((*format >= '0' && *format <= '9')
-              || *format == '-' || *format == ' ' || *format == '.')
-         format++;
+          '%' [flags] [field-width] [precision] format
+
+          where
+
+          flags        ::= [#-* 0]+
+          field-width  ::= [0-9]+
+          precision    ::= '.' [0-9]*
+
+          If a field-width is specified, it specifies to which width
+          the output should be padded with blanks, iff the output
+          string is shorter than field-width.
+
+          if precision is specified, it specifies the number of
+          digits to print after the '.' for floats, or the max.
+          number of chars to print from a string.  */
+
+       precision = field_width = 0;
+       
+       while (index ("-*# 0", *format))
+         ++format;
+
+       if (*format >= '0' && *format <= '9')
+         {
+           for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
+             field_width = 10 * field_width + *format - '0';
+         }
+
+       if (*format == '.')
+         {
+           ++format;
+           for (precision = 0; *format >= '0' && *format <= '9'; ++format)
+             precision = 10 * precision + *format - '0';
+         }
 
        if (format - this_format_start + 1 > longest_format)
          longest_format = format - this_format_start + 1;
@@ -3082,7 +3273,11 @@ Use %% to put a single % into the output.")
          {
            if (! (*format == 'e' || *format == 'f' || *format == 'g'))
              args[n] = Ftruncate (args[n], Qnil);
-           thissize = 200;
+
+           /* Note that we're using sprintf to print floats,
+              so we have to take into account what that function
+              prints.  */
+           thissize = MAX_10_EXP + 100 + precision;
          }
        else
          {
@@ -3098,9 +3293,7 @@ Use %% to put a single % into the output.")
            goto string;
          }
 
-       if (thissize < minlen)
-         thissize = minlen;
-
+       thissize = max (field_width, thissize);
        total += thissize + 4;
       }
 
@@ -3153,10 +3346,8 @@ Use %% to put a single % into the output.")
 
          if (STRINGP (args[n]))
            {
-             int padding, nbytes;
-             int width = strwidth (XSTRING (args[n])->data,
-                                   STRING_BYTES (XSTRING (args[n])));
-             int start = nchars;
+             int padding, nbytes, start, end;
+             int width = lisp_string_width (args[n], -1, NULL, NULL);
 
              /* If spec requires it, pad on right with spaces.  */
              padding = minlen - width;
@@ -3164,9 +3355,11 @@ Use %% to put a single % into the output.")
                while (padding-- > 0)
                  {
                    *p++ = ' ';
-                   nchars++;
+                   ++nchars;
                  }
 
+             start = nchars;
+             
              if (p > buf
                  && multibyte
                  && !ASCII_BYTE_P (*((unsigned char *) p - 1))
@@ -3178,6 +3371,7 @@ Use %% to put a single % into the output.")
                                  STRING_MULTIBYTE (args[n]), multibyte);
              p += nbytes;
              nchars += XSTRING (args[n])->size;
+             end = nchars;
 
              if (negative)
                while (padding-- > 0)
@@ -3198,7 +3392,7 @@ Use %% to put a single % into the output.")
                    }
 
                  info[n].start = start;
-                 info[n].end = nchars;
+                 info[n].end = end;
                }
            }
          else if (INTEGERP (args[n]) || FLOATP (args[n]))
@@ -3252,6 +3446,9 @@ Use %% to put a single % into the output.")
        *p++ = *format++, nchars++;
     }
 
+  if (p > buf + total + 1)
+    abort ();
+
   if (maybe_combine_byte)
     nchars = multibyte_chars_in_text (buf, p - buf);
   val = make_specified_string (buf, nchars, p - buf, multibyte);
@@ -3369,7 +3566,7 @@ Case is ignored if `case-fold-search' is non-nil in the current buffer.")
 
    It's the caller's job to ensure that START1 <= END1 <= START2 <= END2.  */
 
-void
+static void
 transpose_markers (start1, end1, start2, end2,
                   start1_byte, end1_byte, start2_byte, end2_byte)
      register int start1, end1, start2, end2;
@@ -3455,7 +3652,6 @@ Transposing beyond buffer boundaries is an error.")
   int start1_byte, start2_byte, len1_byte, len2_byte;
   int gap, len1, len_mid, len2;
   unsigned char *start1_addr, *start2_addr, *temp;
-  struct gcpro gcpro1, gcpro2;
 
   INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
   cur_intv = BUF_INTERVALS (current_buffer);
@@ -3587,7 +3783,7 @@ Transposing beyond buffer boundaries is an error.")
           bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
           bcopy (temp, start1_addr, len2_byte);
          if (len2_byte > 20000)
-           free (temp);
+           xfree (temp);
         }
       else
        /* First region not smaller than second.  */
@@ -3602,7 +3798,7 @@ Transposing beyond buffer boundaries is an error.")
           bcopy (start2_addr, start1_addr, len2_byte);
           bcopy (temp, start1_addr + len2_byte, len1_byte);
          if (len1_byte > 20000)
-           free (temp);
+           xfree (temp);
         }
       graft_intervals_into_buffer (tmp_interval1, start1 + len2,
                                    len1, current_buffer, 0);
@@ -3640,7 +3836,7 @@ Transposing beyond buffer boundaries is an error.")
           bcopy (start2_addr, start1_addr, len2_byte);
           bcopy (temp, start2_addr, len1_byte);
          if (len1_byte > 20000)
-           free (temp);
+           xfree (temp);
           graft_intervals_into_buffer (tmp_interval1, start2,
                                        len1, current_buffer, 0);
           graft_intervals_into_buffer (tmp_interval2, start1,
@@ -3670,7 +3866,7 @@ Transposing beyond buffer boundaries is an error.")
           safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
           bcopy (temp, start1_addr, len2_byte);
          if (len2_byte > 20000)
-           free (temp);
+           xfree (temp);
           graft_intervals_into_buffer (tmp_interval1, end2 - len1,
                                        len1, current_buffer, 0);
           graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
@@ -3702,7 +3898,7 @@ Transposing beyond buffer boundaries is an error.")
           bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
           bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
          if (len1_byte > 20000)
-           free (temp);
+           xfree (temp);
           graft_intervals_into_buffer (tmp_interval1, end2 - len1,
                                        len1, current_buffer, 0);
           graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,