root/src/buffer.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. CHECK_OVERLAY
  2. fix_position
  3. bset_abbrev_mode
  4. bset_abbrev_table
  5. bset_auto_fill_function
  6. bset_auto_save_file_format
  7. bset_auto_save_file_name
  8. bset_backed_up
  9. bset_begv_marker
  10. bset_bidi_display_reordering
  11. bset_bidi_paragraph_start_re
  12. bset_bidi_paragraph_separate_re
  13. bset_buffer_file_coding_system
  14. bset_case_fold_search
  15. bset_ctl_arrow
  16. bset_cursor_in_non_selected_windows
  17. bset_cursor_type
  18. bset_display_table
  19. bset_extra_line_spacing
  20. bset_ts_parser_list
  21. bset_file_format
  22. bset_file_truename
  23. bset_fringe_cursor_alist
  24. bset_fringe_indicator_alist
  25. bset_fringes_outside_margins
  26. bset_header_line_format
  27. bset_tab_line_format
  28. bset_indicate_buffer_boundaries
  29. bset_indicate_empty_lines
  30. bset_invisibility_spec
  31. bset_left_fringe_width
  32. bset_major_mode
  33. bset_local_minor_modes
  34. bset_mark
  35. bset_mode_line_format
  36. bset_mode_name
  37. bset_name
  38. bset_overwrite_mode
  39. bset_pt_marker
  40. bset_right_fringe_width
  41. bset_save_length
  42. bset_scroll_bar_width
  43. bset_scroll_bar_height
  44. bset_scroll_down_aggressively
  45. bset_scroll_up_aggressively
  46. bset_selective_display
  47. bset_selective_display_ellipses
  48. bset_vertical_scroll_bar_type
  49. bset_horizontal_scroll_bar_type
  50. bset_word_wrap
  51. bset_zv_marker
  52. nsberror
  53. DEFUN
  54. DEFUN
  55. assoc_ignore_text_properties
  56. DEFUN
  57. DEFUN
  58. get_truename_buffer
  59. run_buffer_list_update_hook
  60. add_buffer_overlay
  61. copy_overlays
  62. valid_per_buffer_idx
  63. clone_per_buffer_values
  64. record_buffer_markers
  65. fetch_buffer_markers
  66. remove_buffer_overlay
  67. drop_overlay
  68. delete_all_overlays
  69. free_buffer_overlays
  70. set_overlays_multibyte
  71. reset_buffer
  72. reset_buffer_local_variables
  73. DEFUN
  74. DEFUN
  75. DEFUN
  76. buffer_local_value
  77. buffer_lisp_local_variables
  78. buffer_local_variables_1
  79. DEFUN
  80. DEFUN
  81. DEFUN
  82. DEFUN
  83. DEFUN
  84. DEFUN
  85. DEFUN
  86. candidate_buffer
  87. other_buffer_safely
  88. DEFUN
  89. compact_buffer
  90. DEFUN
  91. record_buffer
  92. DEFUN
  93. DEFUN
  94. DEFUN
  95. set_buffer_internal_1
  96. set_buffer_internal_2
  97. set_buffer_temp
  98. DEFUN
  99. restore_buffer
  100. set_buffer_if_live
  101. DEFUN
  102. DEFUN
  103. validate_region
  104. advance_to_char_boundary
  105. swap_buffer_overlays
  106. DEFUN
  107. DEFUN
  108. DEFUN
  109. overlays_in
  110. overlays_at
  111. next_overlay_change
  112. previous_overlay_change
  113. mouse_face_overlay_overlaps
  114. disable_line_numbers_overlay_at_eob
  115. overlay_touches_p
  116. compare_overlays
  117. make_sortvec_item
  118. sort_overlays
  119. cmp_for_strings
  120. record_overlay_string
  121. overlay_strings
  122. adjust_overlays_for_insert
  123. adjust_overlays_for_delete_in_buffer
  124. adjust_overlays_for_delete
  125. DEFUN
  126. modify_overlay
  127. DEFUN
  128. DEFUN
  129. DEFUN
  130. DEFUN
  131. DEFUN
  132. DEFUN
  133. DEFUN
  134. DEFUN
  135. DEFUN
  136. DEFUN
  137. add_overlay_mod_hooklist
  138. report_overlay_modification
  139. call_overlay_mod_hooks
  140. mmap_init
  141. mmap_free_1
  142. mmap_enlarge
  143. mmap_alloc
  144. mmap_free
  145. mmap_realloc
  146. alloc_buffer_text
  147. enlarge_buffer_text
  148. free_buffer_text
  149. init_buffer_once
  150. init_buffer
  151. defvar_per_buffer
  152. make_lispy_itree_node
  153. overlay_tree
  154. DEFUN
  155. syms_of_buffer

     1 /* Buffer manipulation primitives for GNU Emacs.
     2 
     3 Copyright (C) 1985-2023 Free Software Foundation, Inc.
     4 
     5 This file is part of GNU Emacs.
     6 
     7 GNU Emacs is free software: you can redistribute it and/or modify
     8 it under the terms of the GNU General Public License as published by
     9 the Free Software Foundation, either version 3 of the License, or (at
    10 your option) any later version.
    11 
    12 GNU Emacs is distributed in the hope that it will be useful,
    13 but WITHOUT ANY WARRANTY; without even the implied warranty of
    14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15 GNU General Public License for more details.
    16 
    17 You should have received a copy of the GNU General Public License
    18 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
    19 
    20 #include <config.h>
    21 
    22 #include <sys/types.h>
    23 #include <sys/stat.h>
    24 #include <sys/param.h>
    25 #include <errno.h>
    26 #include <stdio.h>
    27 #include <stdlib.h>
    28 #include <unistd.h>
    29 
    30 #include <verify.h>
    31 
    32 #include "lisp.h"
    33 #include "intervals.h"
    34 #include "process.h"
    35 #include "systime.h"
    36 #include "window.h"
    37 #include "commands.h"
    38 #include "character.h"
    39 #include "buffer.h"
    40 #include "region-cache.h"
    41 #include "indent.h"
    42 #include "blockinput.h"
    43 #include "keymap.h"
    44 #include "frame.h"
    45 #include "xwidget.h"
    46 #include "itree.h"
    47 #include "pdumper.h"
    48 
    49 #ifdef WINDOWSNT
    50 #include "w32heap.h"            /* for mmap_* */
    51 #endif
    52 
    53 /* This structure holds the default values of the buffer-local variables
    54    defined with DEFVAR_PER_BUFFER, that have special slots in each buffer.
    55    The default value occupies the same slot in this structure
    56    as an individual buffer's value occupies in that buffer.
    57    Setting the default value also goes through the alist of buffers
    58    and stores into each buffer that does not say it has a local value.  */
    59 
    60 struct buffer buffer_defaults;
    61 
    62 /* This structure marks which slots in a buffer have corresponding
    63    default values in buffer_defaults.
    64    Each such slot has a value in this structure.
    65    The value is a positive Lisp integer that must be smaller than
    66    MAX_PER_BUFFER_VARS.
    67 
    68    When a buffer has its own local value for a slot,
    69    the entry for that slot (found in the same slot in this structure)
    70    is turned on in the buffer's local_flags array.
    71 
    72    If a slot in this structure is -1, then even though there may
    73    be a DEFVAR_PER_BUFFER for the slot, there is no default value for it;
    74    and the corresponding slot in buffer_defaults is not used.
    75 
    76    If a slot in this structure corresponding to a DEFVAR_PER_BUFFER is
    77    zero, that is a bug.  */
    78 
    79 struct buffer buffer_local_flags;
    80 
    81 /* This structure holds the names of symbols whose values may be
    82    buffer-local.  It is indexed and accessed in the same way as the above.  */
    83 
    84 struct buffer buffer_local_symbols;
    85 
    86 /* Return the symbol of the per-buffer variable at offset OFFSET in
    87    the buffer structure.  */
    88 
    89 #define PER_BUFFER_SYMBOL(OFFSET) \
    90       (*(Lisp_Object *)((OFFSET) + (char *) &buffer_local_symbols))
    91 
    92 /* Maximum length of an overlay vector.  */
    93 #define OVERLAY_COUNT_MAX                                               \
    94   ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM,                               \
    95                     min (PTRDIFF_MAX, SIZE_MAX) / word_size))
    96 
    97 /* Flags indicating which built-in buffer-local variables
    98    are permanent locals.  */
    99 static char buffer_permanent_local_flags[MAX_PER_BUFFER_VARS];
   100 
   101 /* Number of per-buffer variables used.  */
   102 
   103 static int last_per_buffer_idx;
   104 
   105 static void call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay,
   106                                     bool after, Lisp_Object arg1,
   107                                     Lisp_Object arg2, Lisp_Object arg3);
   108 static void reset_buffer_local_variables (struct buffer *, bool);
   109 
   110 /* Alist of all buffer names vs the buffers.  This used to be
   111    a Lisp-visible variable, but is no longer, to prevent lossage
   112    due to user rplac'ing this alist or its elements.  */
   113 Lisp_Object Vbuffer_alist;
   114 
   115 static Lisp_Object QSFundamental;       /* A string "Fundamental".  */
   116 
   117 static void alloc_buffer_text (struct buffer *, ptrdiff_t);
   118 static void free_buffer_text (struct buffer *b);
   119 static void copy_overlays (struct buffer *, struct buffer *);
   120 static void modify_overlay (struct buffer *, ptrdiff_t, ptrdiff_t);
   121 static Lisp_Object buffer_lisp_local_variables (struct buffer *, bool);
   122 static Lisp_Object buffer_local_variables_1 (struct buffer *buf, int offset, Lisp_Object sym);
   123 
   124 static void
   125 CHECK_OVERLAY (Lisp_Object x)
   126 {
   127   CHECK_TYPE (OVERLAYP (x), Qoverlayp, x);
   128 }
   129 
   130 /* Convert the position POS to an EMACS_INT that fits in a fixnum.
   131    Yield POS's value if POS is already a fixnum, POS's marker position
   132    if POS is a marker, and MOST_NEGATIVE_FIXNUM or
   133    MOST_POSITIVE_FIXNUM if POS is a negative or positive bignum.
   134    Signal an error if POS is not of the proper form.  */
   135 
   136 EMACS_INT
   137 fix_position (Lisp_Object pos)
   138 {
   139   if (FIXNUMP (pos))
   140     return XFIXNUM (pos);
   141   if (MARKERP (pos))
   142     return marker_position (pos);
   143   CHECK_TYPE (BIGNUMP (pos), Qinteger_or_marker_p, pos);
   144   return !NILP (Fnatnump (pos)) ? MOST_POSITIVE_FIXNUM : MOST_NEGATIVE_FIXNUM;
   145 }
   146 
   147 /* These setters are used only in this file, so they can be private.
   148    The public setters are inline functions defined in buffer.h.  */
   149 static void
   150 bset_abbrev_mode (struct buffer *b, Lisp_Object val)
   151 {
   152   b->abbrev_mode_ = val;
   153 }
   154 static void
   155 bset_abbrev_table (struct buffer *b, Lisp_Object val)
   156 {
   157   b->abbrev_table_ = val;
   158 }
   159 static void
   160 bset_auto_fill_function (struct buffer *b, Lisp_Object val)
   161 {
   162   b->auto_fill_function_ = val;
   163 }
   164 static void
   165 bset_auto_save_file_format (struct buffer *b, Lisp_Object val)
   166 {
   167   b->auto_save_file_format_ = val;
   168 }
   169 static void
   170 bset_auto_save_file_name (struct buffer *b, Lisp_Object val)
   171 {
   172   b->auto_save_file_name_ = val;
   173 }
   174 static void
   175 bset_backed_up (struct buffer *b, Lisp_Object val)
   176 {
   177   b->backed_up_ = val;
   178 }
   179 static void
   180 bset_begv_marker (struct buffer *b, Lisp_Object val)
   181 {
   182   b->begv_marker_ = val;
   183 }
   184 static void
   185 bset_bidi_display_reordering (struct buffer *b, Lisp_Object val)
   186 {
   187   b->bidi_display_reordering_ = val;
   188 }
   189 static void
   190 bset_bidi_paragraph_start_re (struct buffer *b, Lisp_Object val)
   191 {
   192   b->bidi_paragraph_start_re_ = val;
   193 }
   194 static void
   195 bset_bidi_paragraph_separate_re (struct buffer *b, Lisp_Object val)
   196 {
   197   b->bidi_paragraph_separate_re_ = val;
   198 }
   199 static void
   200 bset_buffer_file_coding_system (struct buffer *b, Lisp_Object val)
   201 {
   202   b->buffer_file_coding_system_ = val;
   203 }
   204 static void
   205 bset_case_fold_search (struct buffer *b, Lisp_Object val)
   206 {
   207   b->case_fold_search_ = val;
   208 }
   209 static void
   210 bset_ctl_arrow (struct buffer *b, Lisp_Object val)
   211 {
   212   b->ctl_arrow_ = val;
   213 }
   214 static void
   215 bset_cursor_in_non_selected_windows (struct buffer *b, Lisp_Object val)
   216 {
   217   b->cursor_in_non_selected_windows_ = val;
   218 }
   219 static void
   220 bset_cursor_type (struct buffer *b, Lisp_Object val)
   221 {
   222   b->cursor_type_ = val;
   223 }
   224 static void
   225 bset_display_table (struct buffer *b, Lisp_Object val)
   226 {
   227   b->display_table_ = val;
   228 }
   229 static void
   230 bset_extra_line_spacing (struct buffer *b, Lisp_Object val)
   231 {
   232   b->extra_line_spacing_ = val;
   233 }
   234 #ifdef HAVE_TREE_SITTER
   235 static void
   236 bset_ts_parser_list (struct buffer *b, Lisp_Object val)
   237 {
   238   b->ts_parser_list_ = val;
   239 }
   240 #endif
   241 static void
   242 bset_file_format (struct buffer *b, Lisp_Object val)
   243 {
   244   b->file_format_ = val;
   245 }
   246 static void
   247 bset_file_truename (struct buffer *b, Lisp_Object val)
   248 {
   249   b->file_truename_ = val;
   250 }
   251 static void
   252 bset_fringe_cursor_alist (struct buffer *b, Lisp_Object val)
   253 {
   254   b->fringe_cursor_alist_ = val;
   255 }
   256 static void
   257 bset_fringe_indicator_alist (struct buffer *b, Lisp_Object val)
   258 {
   259   b->fringe_indicator_alist_ = val;
   260 }
   261 static void
   262 bset_fringes_outside_margins (struct buffer *b, Lisp_Object val)
   263 {
   264   b->fringes_outside_margins_ = val;
   265 }
   266 static void
   267 bset_header_line_format (struct buffer *b, Lisp_Object val)
   268 {
   269   b->header_line_format_ = val;
   270 }
   271 static void
   272 bset_tab_line_format (struct buffer *b, Lisp_Object val)
   273 {
   274   b->tab_line_format_ = val;
   275 }
   276 static void
   277 bset_indicate_buffer_boundaries (struct buffer *b, Lisp_Object val)
   278 {
   279   b->indicate_buffer_boundaries_ = val;
   280 }
   281 static void
   282 bset_indicate_empty_lines (struct buffer *b, Lisp_Object val)
   283 {
   284   b->indicate_empty_lines_ = val;
   285 }
   286 static void
   287 bset_invisibility_spec (struct buffer *b, Lisp_Object val)
   288 {
   289   b->invisibility_spec_ = val;
   290 }
   291 static void
   292 bset_left_fringe_width (struct buffer *b, Lisp_Object val)
   293 {
   294   b->left_fringe_width_ = val;
   295 }
   296 static void
   297 bset_major_mode (struct buffer *b, Lisp_Object val)
   298 {
   299   b->major_mode_ = val;
   300 }
   301 static void
   302 bset_local_minor_modes (struct buffer *b, Lisp_Object val)
   303 {
   304   b->local_minor_modes_ = val;
   305 }
   306 static void
   307 bset_mark (struct buffer *b, Lisp_Object val)
   308 {
   309   b->mark_ = val;
   310 }
   311 static void
   312 bset_mode_line_format (struct buffer *b, Lisp_Object val)
   313 {
   314   b->mode_line_format_ = val;
   315 }
   316 static void
   317 bset_mode_name (struct buffer *b, Lisp_Object val)
   318 {
   319   b->mode_name_ = val;
   320 }
   321 static void
   322 bset_name (struct buffer *b, Lisp_Object val)
   323 {
   324   b->name_ = val;
   325 }
   326 static void
   327 bset_overwrite_mode (struct buffer *b, Lisp_Object val)
   328 {
   329   b->overwrite_mode_ = val;
   330 }
   331 static void
   332 bset_pt_marker (struct buffer *b, Lisp_Object val)
   333 {
   334   b->pt_marker_ = val;
   335 }
   336 static void
   337 bset_right_fringe_width (struct buffer *b, Lisp_Object val)
   338 {
   339   b->right_fringe_width_ = val;
   340 }
   341 static void
   342 bset_save_length (struct buffer *b, Lisp_Object val)
   343 {
   344   b->save_length_ = val;
   345 }
   346 static void
   347 bset_scroll_bar_width (struct buffer *b, Lisp_Object val)
   348 {
   349   b->scroll_bar_width_ = val;
   350 }
   351 static void
   352 bset_scroll_bar_height (struct buffer *b, Lisp_Object val)
   353 {
   354   b->scroll_bar_height_ = val;
   355 }
   356 static void
   357 bset_scroll_down_aggressively (struct buffer *b, Lisp_Object val)
   358 {
   359   b->scroll_down_aggressively_ = val;
   360 }
   361 static void
   362 bset_scroll_up_aggressively (struct buffer *b, Lisp_Object val)
   363 {
   364   b->scroll_up_aggressively_ = val;
   365 }
   366 static void
   367 bset_selective_display (struct buffer *b, Lisp_Object val)
   368 {
   369   b->selective_display_ = val;
   370 }
   371 static void
   372 bset_selective_display_ellipses (struct buffer *b, Lisp_Object val)
   373 {
   374   b->selective_display_ellipses_ = val;
   375 }
   376 static void
   377 bset_vertical_scroll_bar_type (struct buffer *b, Lisp_Object val)
   378 {
   379   b->vertical_scroll_bar_type_ = val;
   380 }
   381 static void
   382 bset_horizontal_scroll_bar_type (struct buffer *b, Lisp_Object val)
   383 {
   384   b->horizontal_scroll_bar_type_ = val;
   385 }
   386 static void
   387 bset_word_wrap (struct buffer *b, Lisp_Object val)
   388 {
   389   b->word_wrap_ = val;
   390 }
   391 static void
   392 bset_zv_marker (struct buffer *b, Lisp_Object val)
   393 {
   394   b->zv_marker_ = val;
   395 }
   396 
   397 void
   398 nsberror (Lisp_Object spec)
   399 {
   400   if (STRINGP (spec))
   401     error ("No buffer named %s", SDATA (spec));
   402   error ("Invalid buffer argument");
   403 }
   404 
   405 DEFUN ("buffer-live-p", Fbuffer_live_p, Sbuffer_live_p, 1, 1, 0,
   406        doc: /* Return t if OBJECT is a buffer which has not been killed.
   407 Value is nil if OBJECT is not a buffer or if it has been killed.  */)
   408   (Lisp_Object object)
   409 {
   410   return ((BUFFERP (object) && BUFFER_LIVE_P (XBUFFER (object)))
   411           ? Qt : Qnil);
   412 }
   413 
   414 DEFUN ("buffer-list", Fbuffer_list, Sbuffer_list, 0, 1, 0,
   415        doc: /* Return a list of all live buffers.
   416 If the optional arg FRAME is a frame, return the buffer list in the
   417 proper order for that frame: the buffers shown in FRAME come first,
   418 followed by the rest of the buffers.  */)
   419   (Lisp_Object frame)
   420 {
   421   Lisp_Object general;
   422   general = Fmapcar (Qcdr, Vbuffer_alist);
   423 
   424   if (FRAMEP (frame))
   425     {
   426       Lisp_Object framelist, prevlist, tail;
   427 
   428       framelist = Fcopy_sequence (XFRAME (frame)->buffer_list);
   429       prevlist = Fnreverse (Fcopy_sequence
   430                             (XFRAME (frame)->buried_buffer_list));
   431 
   432       /* Remove from GENERAL any buffer that duplicates one in
   433          FRAMELIST or PREVLIST.  */
   434       tail = framelist;
   435       while (CONSP (tail))
   436         {
   437           general = Fdelq (XCAR (tail), general);
   438           tail = XCDR (tail);
   439         }
   440       tail = prevlist;
   441       while (CONSP (tail))
   442         {
   443           general = Fdelq (XCAR (tail), general);
   444           tail = XCDR (tail);
   445         }
   446 
   447       return CALLN (Fnconc, framelist, general, prevlist);
   448     }
   449   else
   450     return general;
   451 }
   452 
   453 /* Like Fassoc, but use Fstring_equal to compare
   454    (which ignores text properties), and don't ever quit.  */
   455 
   456 static Lisp_Object
   457 assoc_ignore_text_properties (Lisp_Object key, Lisp_Object list)
   458 {
   459   Lisp_Object tail;
   460   for (tail = list; CONSP (tail); tail = XCDR (tail))
   461     {
   462       Lisp_Object elt = XCAR (tail);
   463       if (!NILP (Fstring_equal (Fcar (elt), key)))
   464         return elt;
   465     }
   466   return Qnil;
   467 }
   468 
   469 DEFUN ("get-buffer", Fget_buffer, Sget_buffer, 1, 1, 0,
   470        doc: /* Return the buffer named BUFFER-OR-NAME.
   471 BUFFER-OR-NAME must be either a string or a buffer.  If BUFFER-OR-NAME
   472 is a string and there is no buffer with that name, return nil.  If
   473 BUFFER-OR-NAME is a buffer, return it as given.  */)
   474   (register Lisp_Object buffer_or_name)
   475 {
   476   if (BUFFERP (buffer_or_name))
   477     return buffer_or_name;
   478   CHECK_STRING (buffer_or_name);
   479 
   480   return Fcdr (assoc_ignore_text_properties (buffer_or_name, Vbuffer_alist));
   481 }
   482 
   483 DEFUN ("get-file-buffer", Fget_file_buffer, Sget_file_buffer, 1, 1, 0,
   484        doc: /* Return the buffer visiting file FILENAME (a string).
   485 The buffer's `buffer-file-name' must match exactly the expansion of FILENAME.
   486 If there is no such live buffer, return nil.
   487 See also `find-buffer-visiting'.  */)
   488   (register Lisp_Object filename)
   489 {
   490   register Lisp_Object tail, buf, handler;
   491 
   492   CHECK_STRING (filename);
   493   filename = Fexpand_file_name (filename, Qnil);
   494 
   495   /* If the file name has special constructs in it,
   496      call the corresponding file name handler.  */
   497   handler = Ffind_file_name_handler (filename, Qget_file_buffer);
   498   if (!NILP (handler))
   499     {
   500       Lisp_Object handled_buf = call2 (handler, Qget_file_buffer,
   501                                        filename);
   502       return BUFFERP (handled_buf) ? handled_buf : Qnil;
   503     }
   504 
   505   FOR_EACH_LIVE_BUFFER (tail, buf)
   506     {
   507       if (!STRINGP (BVAR (XBUFFER (buf), filename))) continue;
   508       if (!NILP (Fstring_equal (BVAR (XBUFFER (buf), filename), filename)))
   509         return buf;
   510     }
   511   return Qnil;
   512 }
   513 
   514 Lisp_Object
   515 get_truename_buffer (register Lisp_Object filename)
   516 {
   517   register Lisp_Object tail, buf;
   518 
   519   FOR_EACH_LIVE_BUFFER (tail, buf)
   520     {
   521       if (!STRINGP (BVAR (XBUFFER (buf), file_truename))) continue;
   522       if (!NILP (Fstring_equal (BVAR (XBUFFER (buf), file_truename), filename)))
   523         return buf;
   524     }
   525   return Qnil;
   526 }
   527 
   528 /* Run buffer-list-update-hook if Vrun_hooks is non-nil and BUF does
   529    not have buffer hooks inhibited.  */
   530 
   531 static void
   532 run_buffer_list_update_hook (struct buffer *buf)
   533 {
   534   eassert (buf);
   535   if (! (NILP (Vrun_hooks) || buf->inhibit_buffer_hooks))
   536     call1 (Vrun_hooks, Qbuffer_list_update_hook);
   537 }
   538 
   539 DEFUN ("get-buffer-create", Fget_buffer_create, Sget_buffer_create, 1, 2, 0,
   540        doc: /* Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.
   541 If BUFFER-OR-NAME is a string and a live buffer with that name exists,
   542 return that buffer.  If no such buffer exists, create a new buffer with
   543 that name and return it.
   544 
   545 If BUFFER-OR-NAME starts with a space, the new buffer does not keep undo
   546 information.  If optional argument INHIBIT-BUFFER-HOOKS is non-nil, the
   547 new buffer does not run the hooks `kill-buffer-hook',
   548 `kill-buffer-query-functions', and `buffer-list-update-hook'.  This
   549 avoids slowing down internal or temporary buffers that are never
   550 presented to users or passed on to other applications.
   551 
   552 If BUFFER-OR-NAME is a buffer instead of a string, return it as given,
   553 even if it is dead.  The return value is never nil.  */)
   554   (register Lisp_Object buffer_or_name, Lisp_Object inhibit_buffer_hooks)
   555 {
   556   register Lisp_Object buffer, name;
   557   register struct buffer *b;
   558 
   559   buffer = Fget_buffer (buffer_or_name);
   560   if (!NILP (buffer))
   561     return buffer;
   562 
   563   if (SCHARS (buffer_or_name) == 0)
   564     error ("Empty string for buffer name is not allowed");
   565 
   566   b = allocate_buffer ();
   567 
   568   /* An ordinary buffer uses its own struct buffer_text.  */
   569   b->text = &b->own_text;
   570   b->base_buffer = NULL;
   571   /* No one shares the text with us now.  */
   572   b->indirections = 0;
   573   /* No one shows us now.  */
   574   b->window_count = 0;
   575 
   576   memset (&b->local_flags, 0, sizeof (b->local_flags));
   577 
   578   BUF_GAP_SIZE (b) = 20;
   579   block_input ();
   580   /* We allocate extra 1-byte at the tail and keep it always '\0' for
   581      anchoring a search.  */
   582   alloc_buffer_text (b, BUF_GAP_SIZE (b) + 1);
   583   unblock_input ();
   584   if (! BUF_BEG_ADDR (b))
   585     buffer_memory_full (BUF_GAP_SIZE (b) + 1);
   586 
   587   b->pt = BEG;
   588   b->begv = BEG;
   589   b->zv = BEG;
   590   b->pt_byte = BEG_BYTE;
   591   b->begv_byte = BEG_BYTE;
   592   b->zv_byte = BEG_BYTE;
   593 
   594   BUF_GPT (b) = BEG;
   595   BUF_GPT_BYTE (b) = BEG_BYTE;
   596 
   597   BUF_Z (b) = BEG;
   598   BUF_Z_BYTE (b) = BEG_BYTE;
   599   BUF_MODIFF (b) = 1;
   600   BUF_CHARS_MODIFF (b) = 1;
   601   BUF_OVERLAY_MODIFF (b) = 1;
   602   BUF_SAVE_MODIFF (b) = 1;
   603   BUF_COMPACT (b) = 1;
   604   set_buffer_intervals (b, NULL);
   605   BUF_UNCHANGED_MODIFIED (b) = 1;
   606   BUF_OVERLAY_UNCHANGED_MODIFIED (b) = 1;
   607   BUF_END_UNCHANGED (b) = 0;
   608   BUF_BEG_UNCHANGED (b) = 0;
   609   *(BUF_GPT_ADDR (b)) = *(BUF_Z_ADDR (b)) = 0; /* Put an anchor '\0'.  */
   610   b->text->inhibit_shrinking = false;
   611   b->text->redisplay = false;
   612 
   613   b->newline_cache = 0;
   614   b->width_run_cache = 0;
   615   b->bidi_paragraph_cache = 0;
   616   bset_width_table (b, Qnil);
   617   b->prevent_redisplay_optimizations_p = 1;
   618 
   619   /* An ordinary buffer normally doesn't need markers
   620      to handle BEGV and ZV.  */
   621   bset_pt_marker (b, Qnil);
   622   bset_begv_marker (b, Qnil);
   623   bset_zv_marker (b, Qnil);
   624 
   625   name = Fcopy_sequence (buffer_or_name);
   626   set_string_intervals (name, NULL);
   627   bset_name (b, name);
   628 
   629   b->inhibit_buffer_hooks = !NILP (inhibit_buffer_hooks);
   630   bset_undo_list (b, SREF (name, 0) != ' ' ? Qnil : Qt);
   631 
   632   reset_buffer (b);
   633   reset_buffer_local_variables (b, 1);
   634 
   635   bset_mark (b, Fmake_marker ());
   636   BUF_MARKERS (b) = NULL;
   637 
   638   /* Put this in the alist of all live buffers.  */
   639   XSETBUFFER (buffer, b);
   640   Vbuffer_alist = nconc2 (Vbuffer_alist, list1 (Fcons (name, buffer)));
   641 
   642   run_buffer_list_update_hook (b);
   643 
   644   return buffer;
   645 }
   646 
   647 static void
   648 add_buffer_overlay (struct buffer *b, struct Lisp_Overlay *ov,
   649                     ptrdiff_t begin, ptrdiff_t end)
   650 {
   651   eassert (! ov->buffer);
   652   if (! b->overlays)
   653     b->overlays = itree_create ();
   654   ov->buffer = b;
   655   itree_insert (b->overlays, ov->interval, begin, end);
   656 }
   657 
   658 /* Copy overlays of buffer FROM to buffer TO.  */
   659 
   660 static void
   661 copy_overlays (struct buffer *from, struct buffer *to)
   662 {
   663   eassert (to && ! to->overlays);
   664   struct itree_node *node;
   665 
   666   ITREE_FOREACH (node, from->overlays, PTRDIFF_MIN, PTRDIFF_MAX, ASCENDING)
   667     {
   668       Lisp_Object ov = node->data;
   669       Lisp_Object copy = build_overlay (node->front_advance,
   670                                         node->rear_advance,
   671                                         Fcopy_sequence (OVERLAY_PLIST (ov)));
   672       add_buffer_overlay (to, XOVERLAY (copy), node->begin, node->end);
   673     }
   674 }
   675 
   676 bool
   677 valid_per_buffer_idx (int idx)
   678 {
   679   return 0 <= idx && idx < last_per_buffer_idx;
   680 }
   681 
   682 /* Clone per-buffer values of buffer FROM.
   683 
   684    Buffer TO gets the same per-buffer values as FROM, with the
   685    following exceptions: (1) TO's name is left untouched, (2) markers
   686    are copied and made to refer to TO, and (3) overlay lists are
   687    copied.  */
   688 
   689 static void
   690 clone_per_buffer_values (struct buffer *from, struct buffer *to)
   691 {
   692   int offset;
   693 
   694   FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
   695     {
   696       Lisp_Object obj;
   697 
   698       /* Don't touch the `name' which should be unique for every buffer.  */
   699       if (offset == PER_BUFFER_VAR_OFFSET (name))
   700         continue;
   701 
   702       obj = per_buffer_value (from, offset);
   703       if (MARKERP (obj) && XMARKER (obj)->buffer == from)
   704         {
   705           struct Lisp_Marker *m = XMARKER (obj);
   706 
   707           obj = build_marker (to, m->charpos, m->bytepos);
   708           XMARKER (obj)->insertion_type = m->insertion_type;
   709         }
   710 
   711       set_per_buffer_value (to, offset, obj);
   712     }
   713 
   714   memcpy (to->local_flags, from->local_flags, sizeof to->local_flags);
   715 
   716   copy_overlays (from, to);
   717 
   718   /* Get (a copy of) the alist of Lisp-level local variables of FROM
   719      and install that in TO.  */
   720   bset_local_var_alist (to, buffer_lisp_local_variables (from, 1));
   721 }
   722 
   723 
   724 /* If buffer B has markers to record PT, BEGV and ZV when it is not
   725    current, update these markers.  */
   726 
   727 static void
   728 record_buffer_markers (struct buffer *b)
   729 {
   730   if (! NILP (BVAR (b, pt_marker)))
   731     {
   732       Lisp_Object buffer;
   733 
   734       eassert (!NILP (BVAR (b, begv_marker)));
   735       eassert (!NILP (BVAR (b, zv_marker)));
   736 
   737       XSETBUFFER (buffer, b);
   738       set_marker_both (BVAR (b, pt_marker), buffer, b->pt, b->pt_byte);
   739       set_marker_both (BVAR (b, begv_marker), buffer, b->begv, b->begv_byte);
   740       set_marker_both (BVAR (b, zv_marker), buffer, b->zv, b->zv_byte);
   741     }
   742 }
   743 
   744 
   745 /* If buffer B has markers to record PT, BEGV and ZV when it is not
   746    current, fetch these values into B->begv etc.  */
   747 
   748 static void
   749 fetch_buffer_markers (struct buffer *b)
   750 {
   751   if (! NILP (BVAR (b, pt_marker)))
   752     {
   753       Lisp_Object m;
   754 
   755       eassert (!NILP (BVAR (b, begv_marker)));
   756       eassert (!NILP (BVAR (b, zv_marker)));
   757 
   758       m = BVAR (b, pt_marker);
   759       SET_BUF_PT_BOTH (b, marker_position (m), marker_byte_position (m));
   760 
   761       m = BVAR (b, begv_marker);
   762       SET_BUF_BEGV_BOTH (b, marker_position (m), marker_byte_position (m));
   763 
   764       m = BVAR (b, zv_marker);
   765       SET_BUF_ZV_BOTH (b, marker_position (m), marker_byte_position (m));
   766     }
   767 }
   768 
   769 
   770 DEFUN ("make-indirect-buffer", Fmake_indirect_buffer, Smake_indirect_buffer,
   771        2, 4,
   772        "bMake indirect buffer (to buffer): \nBName of indirect buffer: ",
   773        doc: /* Create and return an indirect buffer for buffer BASE-BUFFER, named NAME.
   774 BASE-BUFFER should be a live buffer, or the name of an existing buffer.
   775 
   776 NAME should be a string which is not the name of an existing buffer.
   777 Optional argument CLONE non-nil means preserve BASE-BUFFER's state,
   778 such as major and minor modes, in the indirect buffer.
   779 
   780 CLONE nil means the indirect buffer's state is reset to default values.
   781 
   782 If optional argument INHIBIT-BUFFER-HOOKS is non-nil, the new buffer
   783 does not run the hooks `kill-buffer-hook',
   784 `kill-buffer-query-functions', and `buffer-list-update-hook'.  */)
   785   (Lisp_Object base_buffer, Lisp_Object name, Lisp_Object clone,
   786    Lisp_Object inhibit_buffer_hooks)
   787 {
   788   Lisp_Object buf, tem;
   789   struct buffer *b;
   790 
   791   CHECK_STRING (name);
   792   buf = Fget_buffer (name);
   793   if (!NILP (buf))
   794     error ("Buffer name `%s' is in use", SDATA (name));
   795 
   796   tem = base_buffer;
   797   base_buffer = Fget_buffer (base_buffer);
   798   if (NILP (base_buffer))
   799     error ("No such buffer: `%s'", SDATA (tem));
   800   if (!BUFFER_LIVE_P (XBUFFER (base_buffer)))
   801     error ("Base buffer has been killed");
   802 
   803   if (SCHARS (name) == 0)
   804     error ("Empty string for buffer name is not allowed");
   805 
   806   b = allocate_buffer ();
   807 
   808   /* No double indirection - if base buffer is indirect,
   809      new buffer becomes an indirect to base's base.  */
   810   b->base_buffer = (XBUFFER (base_buffer)->base_buffer
   811                     ? XBUFFER (base_buffer)->base_buffer
   812                     : XBUFFER (base_buffer));
   813 
   814   /* Use the base buffer's text object.  */
   815   b->text = b->base_buffer->text;
   816   /* We have no own text.  */
   817   b->indirections = -1;
   818   /* Notify base buffer that we share the text now.  */
   819   b->base_buffer->indirections++;
   820   /* Always -1 for an indirect buffer.  */
   821   b->window_count = -1;
   822 
   823   memset (&b->local_flags, 0, sizeof (b->local_flags));
   824 
   825   b->pt = b->base_buffer->pt;
   826   b->begv = b->base_buffer->begv;
   827   b->zv = b->base_buffer->zv;
   828   b->pt_byte = b->base_buffer->pt_byte;
   829   b->begv_byte = b->base_buffer->begv_byte;
   830   b->zv_byte = b->base_buffer->zv_byte;
   831   b->inhibit_buffer_hooks = !NILP (inhibit_buffer_hooks);
   832 
   833   b->newline_cache = 0;
   834   b->width_run_cache = 0;
   835   b->bidi_paragraph_cache = 0;
   836   bset_width_table (b, Qnil);
   837 
   838   name = Fcopy_sequence (name);
   839   set_string_intervals (name, NULL);
   840   bset_name (b, name);
   841 
   842   /* An indirect buffer shares undo list of its base (Bug#18180).  */
   843   bset_undo_list (b, BVAR (b->base_buffer, undo_list));
   844 
   845   reset_buffer (b);
   846   reset_buffer_local_variables (b, 1);
   847 
   848   /* Put this in the alist of all live buffers.  */
   849   XSETBUFFER (buf, b);
   850   Vbuffer_alist = nconc2 (Vbuffer_alist, list1 (Fcons (name, buf)));
   851 
   852   bset_mark (b, Fmake_marker ());
   853 
   854   /* The multibyte status belongs to the base buffer.  */
   855   bset_enable_multibyte_characters
   856     (b, BVAR (b->base_buffer, enable_multibyte_characters));
   857 
   858   /* Make sure the base buffer has markers for its narrowing.  */
   859   if (NILP (BVAR (b->base_buffer, pt_marker)))
   860     {
   861       eassert (NILP (BVAR (b->base_buffer, begv_marker)));
   862       eassert (NILP (BVAR (b->base_buffer, zv_marker)));
   863 
   864       bset_pt_marker (b->base_buffer,
   865                       build_marker (b->base_buffer, b->base_buffer->pt,
   866                                     b->base_buffer->pt_byte));
   867 
   868       bset_begv_marker (b->base_buffer,
   869                         build_marker (b->base_buffer, b->base_buffer->begv,
   870                                       b->base_buffer->begv_byte));
   871 
   872       bset_zv_marker (b->base_buffer,
   873                       build_marker (b->base_buffer, b->base_buffer->zv,
   874                                     b->base_buffer->zv_byte));
   875 
   876       XMARKER (BVAR (b->base_buffer, zv_marker))->insertion_type = 1;
   877     }
   878 
   879   if (NILP (clone))
   880     {
   881       /* Give the indirect buffer markers for its narrowing.  */
   882       bset_pt_marker (b, build_marker (b, b->pt, b->pt_byte));
   883       bset_begv_marker (b, build_marker (b, b->begv, b->begv_byte));
   884       bset_zv_marker (b, build_marker (b, b->zv, b->zv_byte));
   885       XMARKER (BVAR (b, zv_marker))->insertion_type = 1;
   886     }
   887   else
   888     {
   889       struct buffer *old_b = current_buffer;
   890 
   891       clone_per_buffer_values (b->base_buffer, b);
   892       bset_filename (b, Qnil);
   893       bset_file_truename (b, Qnil);
   894       bset_display_count (b, make_fixnum (0));
   895       bset_backed_up (b, Qnil);
   896       bset_local_minor_modes (b, Qnil);
   897       bset_auto_save_file_name (b, Qnil);
   898       set_buffer_internal_1 (b);
   899       Fset (intern ("buffer-save-without-query"), Qnil);
   900       Fset (intern ("buffer-file-number"), Qnil);
   901       if (!NILP (Flocal_variable_p (Qbuffer_stale_function, base_buffer)))
   902         Fkill_local_variable (Qbuffer_stale_function);
   903       /* Cloned buffers need extra setup, to do things such as deep
   904          variable copies for list variables that might be mangled due
   905          to destructive operations in the indirect buffer. */
   906       run_hook (Qclone_indirect_buffer_hook);
   907       set_buffer_internal_1 (old_b);
   908     }
   909 
   910   run_buffer_list_update_hook (b);
   911 
   912   return buf;
   913 }
   914 
   915 static void
   916 remove_buffer_overlay (struct buffer *b, struct Lisp_Overlay *ov)
   917 {
   918   eassert (b->overlays);
   919   eassert (ov->buffer == b);
   920   itree_remove (ov->buffer->overlays, ov->interval);
   921   ov->buffer = NULL;
   922 }
   923 
   924 /* Mark OV as no longer associated with its buffer.  */
   925 
   926 static void
   927 drop_overlay (struct Lisp_Overlay *ov)
   928 {
   929   if (! ov->buffer)
   930     return;
   931 
   932   modify_overlay (ov->buffer, overlay_start (ov), overlay_end (ov));
   933   remove_buffer_overlay (ov->buffer, ov);
   934 }
   935 
   936 /* Delete all overlays of B and reset its overlay lists.  */
   937 
   938 void
   939 delete_all_overlays (struct buffer *b)
   940 {
   941   struct itree_node *node;
   942 
   943   if (! b->overlays)
   944     return;
   945 
   946   /* The general rule is that the tree cannot be modified from within
   947      ITREE_FOREACH, but here we bend this rule a little because we know
   948      that the POST_ORDER iterator will not need to look at `node` again.  */
   949   ITREE_FOREACH (node, b->overlays, PTRDIFF_MIN, PTRDIFF_MAX, POST_ORDER)
   950     {
   951       modify_overlay (b, node->begin, node->end);
   952       XOVERLAY (node->data)->buffer = NULL;
   953       node->parent = NULL;
   954       node->left = NULL;
   955       node->right = NULL;
   956     }
   957   itree_clear (b->overlays);
   958 }
   959 
   960 static void
   961 free_buffer_overlays (struct buffer *b)
   962 {
   963   /* Actually this does not free any overlay, but the tree only.  --ap */
   964   if (b->overlays)
   965     {
   966       itree_destroy (b->overlays);
   967       b->overlays = NULL;
   968     }
   969 }
   970 
   971 /* Adjust the position of overlays in the current buffer according to
   972    MULTIBYTE.
   973 
   974    Assume that positions currently correspond to byte positions, if
   975    MULTIBYTE is true and to character positions if not.
   976 */
   977 
   978 static void
   979 set_overlays_multibyte (bool multibyte)
   980 {
   981   if (! current_buffer->overlays || Z == Z_BYTE)
   982     return;
   983 
   984   struct itree_node **nodes = NULL;
   985   struct itree_tree *tree = current_buffer->overlays;
   986   const intmax_t size = itree_size (tree);
   987 
   988   /* We can't use `itree_node_set_region` at the same time
   989      as we iterate over the itree, so we need an auxiliary storage
   990      to keep the list of nodes.  */
   991   USE_SAFE_ALLOCA;
   992   SAFE_NALLOCA (nodes, 1, size);
   993   {
   994     struct itree_node *node, **cursor = nodes;
   995     ITREE_FOREACH (node, tree, PTRDIFF_MIN, PTRDIFF_MAX, ASCENDING)
   996       *(cursor++) = node;
   997   }
   998 
   999   for (int i = 0; i < size; ++i, ++nodes)
  1000     {
  1001       struct itree_node * const node = *nodes;
  1002 
  1003       if (multibyte)
  1004         {
  1005           ptrdiff_t begin = itree_node_begin (tree, node);
  1006           ptrdiff_t end = itree_node_end (tree, node);
  1007 
  1008           /* This models the behavior of markers.  (The behavior of
  1009              text-intervals differs slightly.) */
  1010           while (begin < Z_BYTE
  1011                  && !CHAR_HEAD_P (FETCH_BYTE (begin)))
  1012             begin++;
  1013           while (end < Z_BYTE
  1014                  && !CHAR_HEAD_P (FETCH_BYTE (end)))
  1015             end++;
  1016           itree_node_set_region (tree, node, BYTE_TO_CHAR (begin),
  1017                                     BYTE_TO_CHAR (end));
  1018         }
  1019       else
  1020         {
  1021           itree_node_set_region (tree, node, CHAR_TO_BYTE (node->begin),
  1022                                     CHAR_TO_BYTE (node->end));
  1023         }
  1024     }
  1025   SAFE_FREE ();
  1026 }
  1027 
  1028 /* Reinitialize everything about a buffer except its name and contents
  1029    and local variables.
  1030    If called on an already-initialized buffer, the list of overlays
  1031    should be deleted before calling this function, otherwise we end up
  1032    with overlays that claim to belong to the buffer but the buffer
  1033    claims it doesn't belong to it.  */
  1034 
  1035 void
  1036 reset_buffer (register struct buffer *b)
  1037 {
  1038   bset_filename (b, Qnil);
  1039   bset_file_truename (b, Qnil);
  1040   bset_directory (b, current_buffer ? BVAR (current_buffer, directory) : Qnil);
  1041   b->modtime = make_timespec (0, UNKNOWN_MODTIME_NSECS);
  1042   b->modtime_size = -1;
  1043   XSETFASTINT (BVAR (b, save_length), 0);
  1044   b->last_window_start = 1;
  1045   /* It is more conservative to start out "changed" than "unchanged".  */
  1046   b->clip_changed = 0;
  1047   b->prevent_redisplay_optimizations_p = 1;
  1048   b->long_line_optimizations_p = 0;
  1049   bset_backed_up (b, Qnil);
  1050   bset_local_minor_modes (b, Qnil);
  1051   BUF_AUTOSAVE_MODIFF (b) = 0;
  1052   b->auto_save_failure_time = 0;
  1053   bset_auto_save_file_name (b, Qnil);
  1054   bset_read_only (b, Qnil);
  1055   b->overlays = NULL;
  1056   bset_mark_active (b, Qnil);
  1057   bset_point_before_scroll (b, Qnil);
  1058   bset_file_format (b, Qnil);
  1059   bset_auto_save_file_format (b, Qt);
  1060   bset_last_selected_window (b, Qnil);
  1061   bset_display_count (b, make_fixnum (0));
  1062   bset_display_time (b, Qnil);
  1063   bset_enable_multibyte_characters
  1064     (b, BVAR (&buffer_defaults, enable_multibyte_characters));
  1065   bset_cursor_type (b, BVAR (&buffer_defaults, cursor_type));
  1066   bset_extra_line_spacing (b, BVAR (&buffer_defaults, extra_line_spacing));
  1067 #ifdef HAVE_TREE_SITTER
  1068   bset_ts_parser_list (b, Qnil);
  1069 #endif
  1070 
  1071   b->display_error_modiff = 0;
  1072 }
  1073 
  1074 /* Reset buffer B's local variables info.
  1075    Don't use this on a buffer that has already been in use;
  1076    it does not treat permanent locals consistently.
  1077    Instead, use Fkill_all_local_variables.
  1078 
  1079    If PERMANENT_TOO, reset permanent buffer-local variables.
  1080    If not, preserve those.  */
  1081 
  1082 static void
  1083 reset_buffer_local_variables (struct buffer *b, bool permanent_too)
  1084 {
  1085   int offset, i;
  1086 
  1087   /* Reset the major mode to Fundamental, together with all the
  1088      things that depend on the major mode.
  1089      default-major-mode is handled at a higher level.
  1090      We ignore it here.  */
  1091   bset_major_mode (b, Qfundamental_mode);
  1092   bset_keymap (b, Qnil);
  1093   bset_mode_name (b, QSFundamental);
  1094 
  1095   /* If the standard case table has been altered and invalidated,
  1096      fix up its insides first.  */
  1097   if (! (CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[0])
  1098          && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[1])
  1099          && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[2])))
  1100     Fset_standard_case_table (Vascii_downcase_table);
  1101 
  1102   bset_downcase_table (b, Vascii_downcase_table);
  1103   bset_upcase_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[0]);
  1104   bset_case_canon_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[1]);
  1105   bset_case_eqv_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[2]);
  1106   bset_invisibility_spec (b, Qt);
  1107 
  1108   /* Reset all (or most) per-buffer variables to their defaults.  */
  1109   if (permanent_too)
  1110     bset_local_var_alist (b, Qnil);
  1111   else
  1112     {
  1113       Lisp_Object tmp, last = Qnil;
  1114       Lisp_Object buffer;
  1115       XSETBUFFER (buffer, b);
  1116 
  1117       for (tmp = BVAR (b, local_var_alist); CONSP (tmp); tmp = XCDR (tmp))
  1118         {
  1119           Lisp_Object local_var = XCAR (XCAR (tmp));
  1120           Lisp_Object prop = Fget (local_var, Qpermanent_local);
  1121           Lisp_Object sym = local_var;
  1122 
  1123           /* Watchers are run *before* modifying the var.  */
  1124           if (XSYMBOL (local_var)->u.s.trapped_write == SYMBOL_TRAPPED_WRITE)
  1125             notify_variable_watchers (local_var, Qnil,
  1126                                       Qmakunbound, Fcurrent_buffer ());
  1127 
  1128           eassert (XSYMBOL (sym)->u.s.redirect == SYMBOL_LOCALIZED);
  1129           /* Need not do anything if some other buffer's binding is
  1130              now cached.  */
  1131           if (BASE_EQ (SYMBOL_BLV (XSYMBOL (sym))->where, buffer))
  1132             {
  1133               /* Symbol is set up for this buffer's old local value:
  1134                  swap it out!  */
  1135               swap_in_global_binding (XSYMBOL (sym));
  1136             }
  1137 
  1138           if (!NILP (prop))
  1139             {
  1140               /* If permanent-local, keep it.  */
  1141               last = tmp;
  1142               if (EQ (prop, Qpermanent_local_hook))
  1143                 {
  1144                   /* This is a partially permanent hook variable.
  1145                      Preserve only the elements that want to be preserved.  */
  1146                   Lisp_Object list, newlist;
  1147                   list = XCDR (XCAR (tmp));
  1148                   if (!CONSP (list))
  1149                     newlist = list;
  1150                   else
  1151                     for (newlist = Qnil; CONSP (list); list = XCDR (list))
  1152                       {
  1153                         Lisp_Object elt = XCAR (list);
  1154                         /* Preserve element ELT if it's t, or if it is a
  1155                            function with a `permanent-local-hook'
  1156                            property. */
  1157                         if (EQ (elt, Qt)
  1158                             || (SYMBOLP (elt)
  1159                                 && !NILP (Fget (elt, Qpermanent_local_hook))))
  1160                           newlist = Fcons (elt, newlist);
  1161                       }
  1162                   newlist = Fnreverse (newlist);
  1163                   if (XSYMBOL (local_var)->u.s.trapped_write
  1164                       == SYMBOL_TRAPPED_WRITE)
  1165                     notify_variable_watchers (local_var, newlist,
  1166                                               Qmakunbound, Fcurrent_buffer ());
  1167                   XSETCDR (XCAR (tmp), newlist);
  1168                   continue; /* Don't do variable write trapping twice.  */
  1169                 }
  1170             }
  1171           /* Delete this local variable.  */
  1172           else if (NILP (last))
  1173             bset_local_var_alist (b, XCDR (tmp));
  1174           else
  1175             XSETCDR (last, XCDR (tmp));
  1176         }
  1177     }
  1178 
  1179   for (i = 0; i < last_per_buffer_idx; ++i)
  1180     if (permanent_too || buffer_permanent_local_flags[i] == 0)
  1181       SET_PER_BUFFER_VALUE_P (b, i, 0);
  1182 
  1183   /* For each slot that has a default value, copy that into the slot.  */
  1184   FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
  1185     {
  1186       int idx = PER_BUFFER_IDX (offset);
  1187       if ((idx > 0
  1188            && (permanent_too
  1189                || buffer_permanent_local_flags[idx] == 0)))
  1190         set_per_buffer_value (b, offset, per_buffer_default (offset));
  1191     }
  1192 }
  1193 
  1194 /* We split this away from generate-new-buffer, because rename-buffer
  1195    and set-visited-file-name ought to be able to use this to really
  1196    rename the buffer properly.  */
  1197 
  1198 DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name,
  1199        Sgenerate_new_buffer_name, 1, 2, 0,
  1200        doc: /* Return a string that is the name of no existing buffer based on NAME.
  1201 If there is no live buffer named NAME, then return NAME.
  1202 Otherwise modify name by appending `<NUMBER>', incrementing NUMBER
  1203 \(starting at 2) until an unused name is found, and then return that name.
  1204 Optional second argument IGNORE specifies a name that is okay to use (if
  1205 it is in the sequence to be tried) even if a buffer with that name exists.
  1206 
  1207 If NAME begins with a space (i.e., a buffer that is not normally
  1208 visible to users), then if buffer NAME already exists a random number
  1209 is first appended to NAME, to speed up finding a non-existent buffer.  */)
  1210   (Lisp_Object name, Lisp_Object ignore)
  1211 {
  1212   Lisp_Object genbase;
  1213 
  1214   CHECK_STRING (name);
  1215 
  1216   if ((!NILP (ignore) && !NILP (Fstring_equal (name, ignore)))
  1217       || NILP (Fget_buffer (name)))
  1218     return name;
  1219 
  1220   if (SREF (name, 0) != ' ') /* See bug#1229.  */
  1221     genbase = name;
  1222   else
  1223     {
  1224       enum { bug_52711 = true };  /* https://bugs.gnu.org/57211 */
  1225       char number[bug_52711 ? INT_BUFSIZE_BOUND (int) + 1 : sizeof "-999999"];
  1226       EMACS_INT r = get_random ();
  1227       eassume (0 <= r);
  1228       int i = r % 1000000;
  1229       AUTO_STRING_WITH_LEN (lnumber, number, sprintf (number, "-%d", i));
  1230       genbase = concat2 (name, lnumber);
  1231       if (NILP (Fget_buffer (genbase)))
  1232         return genbase;
  1233     }
  1234 
  1235   for (ptrdiff_t count = 2; ; count++)
  1236     {
  1237       char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
  1238       AUTO_STRING_WITH_LEN (lnumber, number,
  1239                             sprintf (number, "<%"pD"d>", count));
  1240       Lisp_Object gentemp = concat2 (genbase, lnumber);
  1241       if (!NILP (Fstring_equal (gentemp, ignore))
  1242           || NILP (Fget_buffer (gentemp)))
  1243         return gentemp;
  1244     }
  1245 }
  1246 
  1247 
  1248 DEFUN ("buffer-name", Fbuffer_name, Sbuffer_name, 0, 1, 0,
  1249        doc: /* Return the name of BUFFER, as a string.
  1250 BUFFER defaults to the current buffer.
  1251 Return nil if BUFFER has been killed.  */)
  1252   (register Lisp_Object buffer)
  1253 {
  1254   return BVAR (decode_buffer (buffer), name);
  1255 }
  1256 
  1257 DEFUN ("buffer-file-name", Fbuffer_file_name, Sbuffer_file_name, 0, 1, 0,
  1258        doc: /* Return name of file BUFFER is visiting, or nil if none.
  1259 No argument or nil as argument means use the current buffer.  */)
  1260   (register Lisp_Object buffer)
  1261 {
  1262   return BVAR (decode_buffer (buffer), filename);
  1263 }
  1264 
  1265 DEFUN ("buffer-base-buffer", Fbuffer_base_buffer, Sbuffer_base_buffer,
  1266        0, 1, 0,
  1267        doc: /* Return the base buffer of indirect buffer BUFFER.
  1268 If BUFFER is not indirect, return nil.
  1269 BUFFER defaults to the current buffer.  */)
  1270   (register Lisp_Object buffer)
  1271 {
  1272   struct buffer *base = decode_buffer (buffer)->base_buffer;
  1273   return base ? (XSETBUFFER (buffer, base), buffer) : Qnil;
  1274 }
  1275 
  1276 DEFUN ("buffer-local-value", Fbuffer_local_value,
  1277        Sbuffer_local_value, 2, 2, 0,
  1278        doc: /* Return the value of VARIABLE in BUFFER.
  1279 If VARIABLE does not have a buffer-local binding in BUFFER, the value
  1280 is the default binding of the variable.  */)
  1281   (register Lisp_Object variable, register Lisp_Object buffer)
  1282 {
  1283   register Lisp_Object result = buffer_local_value (variable, buffer);
  1284 
  1285   if (BASE_EQ (result, Qunbound))
  1286     xsignal1 (Qvoid_variable, variable);
  1287 
  1288   return result;
  1289 }
  1290 
  1291 
  1292 /* Like Fbuffer_local_value, but return Qunbound if the variable is
  1293    locally unbound.  */
  1294 
  1295 Lisp_Object
  1296 buffer_local_value (Lisp_Object variable, Lisp_Object buffer)
  1297 {
  1298   register struct buffer *buf;
  1299   register Lisp_Object result;
  1300   struct Lisp_Symbol *sym;
  1301 
  1302   CHECK_SYMBOL (variable);
  1303   CHECK_BUFFER (buffer);
  1304   buf = XBUFFER (buffer);
  1305   sym = XSYMBOL (variable);
  1306 
  1307  start:
  1308   switch (sym->u.s.redirect)
  1309     {
  1310     case SYMBOL_VARALIAS: sym = indirect_variable (sym); goto start;
  1311     case SYMBOL_PLAINVAL: result = SYMBOL_VAL (sym); break;
  1312     case SYMBOL_LOCALIZED:
  1313       { /* Look in local_var_alist.  */
  1314         struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
  1315         XSETSYMBOL (variable, sym); /* Update In case of aliasing.  */
  1316         result = assq_no_quit (variable, BVAR (buf, local_var_alist));
  1317         if (!NILP (result))
  1318           {
  1319             if (blv->fwd.fwdptr)
  1320               { /* What binding is loaded right now?  */
  1321                 Lisp_Object current_alist_element = blv->valcell;
  1322 
  1323                 /* The value of the currently loaded binding is not
  1324                    stored in it, but rather in the realvalue slot.
  1325                    Store that value into the binding it belongs to
  1326                    in case that is the one we are about to use.  */
  1327 
  1328                 XSETCDR (current_alist_element,
  1329                          do_symval_forwarding (blv->fwd));
  1330               }
  1331             /* Now get the (perhaps updated) value out of the binding.  */
  1332             result = XCDR (result);
  1333           }
  1334         else
  1335           result = Fdefault_value (variable);
  1336         break;
  1337       }
  1338     case SYMBOL_FORWARDED:
  1339       {
  1340         lispfwd fwd = SYMBOL_FWD (sym);
  1341         if (BUFFER_OBJFWDP (fwd))
  1342           result = per_buffer_value (buf, XBUFFER_OBJFWD (fwd)->offset);
  1343         else
  1344           result = Fdefault_value (variable);
  1345         break;
  1346       }
  1347     default: emacs_abort ();
  1348     }
  1349 
  1350   return result;
  1351 }
  1352 
  1353 /* Return an alist of the Lisp-level buffer-local bindings of
  1354    buffer BUF.  That is, don't include the variables maintained
  1355    in special slots in the buffer object.
  1356    If not CLONE, replace elements of the form (VAR . unbound)
  1357    by VAR.  */
  1358 
  1359 static Lisp_Object
  1360 buffer_lisp_local_variables (struct buffer *buf, bool clone)
  1361 {
  1362   Lisp_Object result = Qnil;
  1363   Lisp_Object tail;
  1364   for (tail = BVAR (buf, local_var_alist); CONSP (tail); tail = XCDR (tail))
  1365     {
  1366       Lisp_Object val, elt;
  1367 
  1368       elt = XCAR (tail);
  1369 
  1370       /* Reference each variable in the alist in buf.
  1371          If inquiring about the current buffer, this gets the current values,
  1372          so store them into the alist so the alist is up to date.
  1373          If inquiring about some other buffer, this swaps out any values
  1374          for that buffer, making the alist up to date automatically.  */
  1375       val = find_symbol_value (XCAR (elt));
  1376       /* Use the current buffer value only if buf is the current buffer.  */
  1377       if (buf != current_buffer)
  1378         val = XCDR (elt);
  1379 
  1380       result = Fcons (!clone && BASE_EQ (val, Qunbound)
  1381                       ? XCAR (elt)
  1382                       : Fcons (XCAR (elt), val),
  1383                       result);
  1384     }
  1385 
  1386   return result;
  1387 }
  1388 
  1389 
  1390 /* If the variable at position index OFFSET in buffer BUF has a
  1391    buffer-local value, return (name . value).  If SYM is non-nil,
  1392    it replaces name.  */
  1393 
  1394 static Lisp_Object
  1395 buffer_local_variables_1 (struct buffer *buf, int offset, Lisp_Object sym)
  1396 {
  1397   int idx = PER_BUFFER_IDX (offset);
  1398   if ((idx == -1 || PER_BUFFER_VALUE_P (buf, idx))
  1399       && SYMBOLP (PER_BUFFER_SYMBOL (offset)))
  1400     {
  1401       sym = NILP (sym) ? PER_BUFFER_SYMBOL (offset) : sym;
  1402       Lisp_Object val = per_buffer_value (buf, offset);
  1403       return BASE_EQ (val, Qunbound) ? sym : Fcons (sym, val);
  1404     }
  1405   return Qnil;
  1406 }
  1407 
  1408 DEFUN ("buffer-local-variables", Fbuffer_local_variables,
  1409        Sbuffer_local_variables, 0, 1, 0,
  1410        doc: /* Return an alist of variables that are buffer-local in BUFFER.
  1411 Most elements look like (SYMBOL . VALUE), describing one variable.
  1412 For a symbol that is locally unbound, just the symbol appears in the value.
  1413 Note that storing new VALUEs in these elements doesn't change the variables.
  1414 No argument or nil as argument means use current buffer as BUFFER.  */)
  1415   (Lisp_Object buffer)
  1416 {
  1417   struct buffer *buf = decode_buffer (buffer);
  1418   Lisp_Object result = buffer_lisp_local_variables (buf, 0);
  1419   Lisp_Object tem;
  1420 
  1421   /* Add on all the variables stored in special slots.  */
  1422   {
  1423     int offset;
  1424 
  1425     FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
  1426       {
  1427         tem = buffer_local_variables_1 (buf, offset, Qnil);
  1428         if (!NILP (tem))
  1429           result = Fcons (tem, result);
  1430       }
  1431   }
  1432 
  1433   tem = buffer_local_variables_1 (buf, PER_BUFFER_VAR_OFFSET (undo_list),
  1434                                   intern ("buffer-undo-list"));
  1435   if (!NILP (tem))
  1436     result = Fcons (tem, result);
  1437 
  1438   return result;
  1439 }
  1440 
  1441 DEFUN ("buffer-modified-p", Fbuffer_modified_p, Sbuffer_modified_p,
  1442        0, 1, 0,
  1443        doc: /* Return non-nil if BUFFER was modified since its file was last read or saved.
  1444 No argument or nil as argument means use current buffer as BUFFER.
  1445 
  1446 If BUFFER was autosaved since it was last modified, this function
  1447 returns the symbol `autosaved'.  */)
  1448   (Lisp_Object buffer)
  1449 {
  1450   struct buffer *buf = decode_buffer (buffer);
  1451   if (BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf))
  1452     {
  1453       if (BUF_AUTOSAVE_MODIFF (buf) == BUF_MODIFF (buf))
  1454         return Qautosaved;
  1455       else
  1456         return Qt;
  1457     }
  1458   else
  1459     return Qnil;
  1460 }
  1461 
  1462 DEFUN ("force-mode-line-update", Fforce_mode_line_update,
  1463        Sforce_mode_line_update, 0, 1, 0,
  1464        doc: /* Force redisplay of the current buffer's mode line and header line.
  1465 With optional non-nil ALL, force redisplay of all mode lines, tab lines and
  1466 header lines.  This function also forces recomputation of the
  1467 menu bar menus and the frame title.  */)
  1468      (Lisp_Object all)
  1469 {
  1470   if (!NILP (all))
  1471     {
  1472       update_mode_lines = 10;
  1473       /* FIXME: This can't be right.  */
  1474       current_buffer->prevent_redisplay_optimizations_p = true;
  1475     }
  1476   else if (buffer_window_count (current_buffer))
  1477     {
  1478       bset_update_mode_line (current_buffer);
  1479       current_buffer->prevent_redisplay_optimizations_p = true;
  1480     }
  1481   return all;
  1482 }
  1483 
  1484 DEFUN ("set-buffer-modified-p", Fset_buffer_modified_p, Sset_buffer_modified_p,
  1485        1, 1, 0,
  1486        doc: /* Mark current buffer as modified or unmodified according to FLAG.
  1487 A non-nil FLAG means mark the buffer modified.
  1488 In addition, this function unconditionally forces redisplay of the
  1489 mode lines of the windows that display the current buffer, and also
  1490 locks or unlocks the file visited by the buffer, depending on whether
  1491 the function's argument is non-nil, but only if both `buffer-file-name'
  1492 and `buffer-file-truename' are non-nil.  */)
  1493   (Lisp_Object flag)
  1494 {
  1495   Frestore_buffer_modified_p (flag);
  1496 
  1497   /* Set update_mode_lines only if buffer is displayed in some window.
  1498      Packages like jit-lock or lazy-lock preserve a buffer's modified
  1499      state by recording/restoring the state around blocks of code.
  1500      Setting update_mode_lines makes redisplay consider all windows
  1501      (on all frames).  Stealth fontification of buffers not displayed
  1502      would incur additional redisplay costs if we'd set
  1503      update_modes_lines unconditionally.
  1504 
  1505      Ideally, I think there should be another mechanism for fontifying
  1506      buffers without "modifying" buffers, or redisplay should be
  1507      smarter about updating the `*' in mode lines.  --gerd  */
  1508   return Fforce_mode_line_update (Qnil);
  1509 }
  1510 
  1511 DEFUN ("restore-buffer-modified-p", Frestore_buffer_modified_p,
  1512        Srestore_buffer_modified_p, 1, 1, 0,
  1513        doc: /* Like `set-buffer-modified-p', but doesn't redisplay buffer's mode line.
  1514 A nil FLAG means to mark the buffer as unmodified.  A non-nil FLAG
  1515 means mark the buffer as modified.  A special value of `autosaved'
  1516 will mark the buffer as modified and also as autosaved since it was
  1517 last modified.
  1518 
  1519 This function also locks or unlocks the file visited by the buffer,
  1520 if both `buffer-file-truename' and `buffer-file-name' are non-nil.
  1521 
  1522 It is not ensured that mode lines will be updated to show the modified
  1523 state of the current buffer.  Use with care.  */)
  1524   (Lisp_Object flag)
  1525 {
  1526 
  1527   /* If buffer becoming modified, lock the file.
  1528      If buffer becoming unmodified, unlock the file.  */
  1529 
  1530   struct buffer *b = current_buffer->base_buffer
  1531     ? current_buffer->base_buffer
  1532     : current_buffer;
  1533 
  1534   if (!inhibit_modification_hooks)
  1535     {
  1536       Lisp_Object fn = BVAR (b, file_truename);
  1537       /* Test buffer-file-name so that binding it to nil is effective.  */
  1538       if (!NILP (fn) && ! NILP (BVAR (b, filename)))
  1539         {
  1540           bool already = SAVE_MODIFF < MODIFF;
  1541           if (!already && !NILP (flag))
  1542             Flock_file (fn);
  1543           else if (already && NILP (flag))
  1544             Funlock_file (fn);
  1545         }
  1546     }
  1547 
  1548   /* Here we have a problem.  SAVE_MODIFF is used here to encode
  1549      buffer-modified-p (as SAVE_MODIFF<MODIFF) as well as
  1550      recent-auto-save-p (as SAVE_MODIFF<auto_save_modified).  So if we
  1551      modify SAVE_MODIFF to affect one, we may affect the other
  1552      as well.
  1553      E.g. if FLAG is nil we need to set SAVE_MODIFF to MODIFF, but
  1554      if SAVE_MODIFF<auto_save_modified that means we risk changing
  1555      recent-auto-save-p from t to nil.
  1556      Vice versa, if FLAG is non-nil and SAVE_MODIFF>=auto_save_modified
  1557      we risk changing recent-auto-save-p from nil to t.  */
  1558   if (NILP (flag))
  1559     /* This unavoidably sets recent-auto-save-p to nil.  */
  1560     SAVE_MODIFF = MODIFF;
  1561   else
  1562     {
  1563       /* If SAVE_MODIFF == auto_save_modified == MODIFF, we can either
  1564          decrease SAVE_MODIFF and auto_save_modified or increase
  1565          MODIFF.  */
  1566       if (SAVE_MODIFF >= MODIFF)
  1567         SAVE_MODIFF = modiff_incr (&MODIFF, 1);
  1568       if (EQ (flag, Qautosaved))
  1569         BUF_AUTOSAVE_MODIFF (b) = MODIFF;
  1570     }
  1571   return flag;
  1572 }
  1573 
  1574 DEFUN ("buffer-modified-tick", Fbuffer_modified_tick, Sbuffer_modified_tick,
  1575        0, 1, 0,
  1576        doc: /* Return BUFFER's tick counter, incremented for each change in text.
  1577 Each buffer has a tick counter which is incremented each time the
  1578 text in that buffer is changed.  No argument or nil as argument means
  1579 use current buffer as BUFFER.  */)
  1580   (Lisp_Object buffer)
  1581 {
  1582   return modiff_to_integer (BUF_MODIFF (decode_buffer (buffer)));
  1583 }
  1584 
  1585 DEFUN ("internal--set-buffer-modified-tick",
  1586        Finternal__set_buffer_modified_tick, Sinternal__set_buffer_modified_tick,
  1587        1, 2, 0,
  1588        doc: /* Set BUFFER's tick counter to TICK.
  1589 No argument or nil as argument means use current buffer as BUFFER.  */)
  1590   (Lisp_Object tick, Lisp_Object buffer)
  1591 {
  1592   CHECK_FIXNUM (tick);
  1593   BUF_MODIFF (decode_buffer (buffer)) = XFIXNUM (tick);
  1594   return Qnil;
  1595 }
  1596 
  1597 DEFUN ("buffer-chars-modified-tick", Fbuffer_chars_modified_tick,
  1598        Sbuffer_chars_modified_tick, 0, 1, 0,
  1599        doc: /* Return BUFFER's character-change tick counter.
  1600 Each buffer has a character-change tick counter, which is set to the
  1601 value of the buffer's tick counter (see `buffer-modified-tick'), each
  1602 time text in that buffer is inserted or deleted.  By comparing the
  1603 values returned by two individual calls of `buffer-chars-modified-tick',
  1604 you can tell whether a character change occurred in that buffer in
  1605 between these calls.  No argument or nil as argument means use current
  1606 buffer as BUFFER.  */)
  1607   (Lisp_Object buffer)
  1608 {
  1609   return modiff_to_integer (BUF_CHARS_MODIFF (decode_buffer (buffer)));
  1610 }
  1611 
  1612 DEFUN ("rename-buffer", Frename_buffer, Srename_buffer, 1, 2,
  1613        "(list (read-string \"Rename buffer (to new name): \" \
  1614               nil 'buffer-name-history (buffer-name (current-buffer))) \
  1615               current-prefix-arg)",
  1616        doc: /* Change current buffer's name to NEWNAME (a string).
  1617 If second arg UNIQUE is nil or omitted, it is an error if a
  1618 buffer named NEWNAME already exists.
  1619 If UNIQUE is non-nil, come up with a new name using
  1620 `generate-new-buffer-name'.
  1621 Interactively, you can set UNIQUE with a prefix argument.
  1622 We return the name we actually gave the buffer.
  1623 This does not change the name of the visited file (if any).  */)
  1624   (register Lisp_Object newname, Lisp_Object unique)
  1625 {
  1626   register Lisp_Object tem, buf;
  1627   Lisp_Object requestedname = newname;
  1628 
  1629   CHECK_STRING (newname);
  1630 
  1631   if (SCHARS (newname) == 0)
  1632     error ("Empty string is invalid as a buffer name");
  1633 
  1634   tem = Fget_buffer (newname);
  1635   if (!NILP (tem))
  1636     {
  1637       /* Don't short-circuit if UNIQUE is t.  That is a useful way to
  1638          rename the buffer automatically so you can create another
  1639          with the original name.  It makes UNIQUE equivalent to
  1640          (rename-buffer (generate-new-buffer-name NEWNAME)).  */
  1641       if (NILP (unique) && XBUFFER (tem) == current_buffer)
  1642         return BVAR (current_buffer, name);
  1643       if (!NILP (unique))
  1644         newname = Fgenerate_new_buffer_name (newname,
  1645                                              BVAR (current_buffer, name));
  1646       else
  1647         error ("Buffer name `%s' is in use", SDATA (newname));
  1648     }
  1649 
  1650   bset_name (current_buffer, newname);
  1651 
  1652   /* Catch redisplay's attention.  Unless we do this, the mode lines for
  1653      any windows displaying current_buffer will stay unchanged.  */
  1654   bset_update_mode_line (current_buffer);
  1655 
  1656   XSETBUFFER (buf, current_buffer);
  1657   Fsetcar (Frassq (buf, Vbuffer_alist), newname);
  1658   if (NILP (BVAR (current_buffer, filename))
  1659       && !NILP (BVAR (current_buffer, auto_save_file_name)))
  1660     call0 (intern ("rename-auto-save-file"));
  1661 
  1662   run_buffer_list_update_hook (current_buffer);
  1663 
  1664   call2 (intern ("uniquify--rename-buffer-advice"),
  1665          requestedname, unique);
  1666 
  1667   /* Refetch since that last call may have done GC.  */
  1668   return BVAR (current_buffer, name);
  1669 }
  1670 
  1671 /* True if B can be used as 'other-than-BUFFER' buffer.  */
  1672 
  1673 static bool
  1674 candidate_buffer (Lisp_Object b, Lisp_Object buffer)
  1675 {
  1676   return (BUFFERP (b) && !BASE_EQ (b, buffer)
  1677           && BUFFER_LIVE_P (XBUFFER (b))
  1678           && !BUFFER_HIDDEN_P (XBUFFER (b)));
  1679 }
  1680 
  1681 DEFUN ("other-buffer", Fother_buffer, Sother_buffer, 0, 3, 0,
  1682        doc: /* Return most recently selected buffer other than BUFFER.
  1683 Buffers not visible in windows are preferred to visible buffers, unless
  1684 optional second argument VISIBLE-OK is non-nil.  Ignore the argument
  1685 BUFFER unless it denotes a live buffer.  If the optional third argument
  1686 FRAME specifies a live frame, then use that frame's buffer list instead
  1687 of the selected frame's buffer list.
  1688 
  1689 The buffer is found by scanning the selected or specified frame's buffer
  1690 list first, followed by the list of all buffers.  If no other buffer
  1691 exists, return the buffer `*scratch*' (creating it if necessary).  */)
  1692   (Lisp_Object buffer, Lisp_Object visible_ok, Lisp_Object frame)
  1693 {
  1694   struct frame *f = decode_live_frame (frame);
  1695   Lisp_Object tail = f->buffer_list, pred = f->buffer_predicate;
  1696   Lisp_Object buf, notsogood = Qnil;
  1697 
  1698   /* Consider buffers that have been seen in the frame first.  */
  1699   for (; CONSP (tail); tail = XCDR (tail))
  1700     {
  1701       buf = XCAR (tail);
  1702       if (candidate_buffer (buf, buffer)
  1703           /* If the frame has a buffer_predicate, disregard buffers that
  1704              don't fit the predicate.  */
  1705           && (NILP (pred) || !NILP (call1 (pred, buf))))
  1706         {
  1707           if (!NILP (visible_ok)
  1708               || NILP (Fget_buffer_window (buf, Qvisible)))
  1709             return buf;
  1710           else if (NILP (notsogood))
  1711             notsogood = buf;
  1712         }
  1713     }
  1714 
  1715   /* Consider alist of all buffers next.  */
  1716   FOR_EACH_LIVE_BUFFER (tail, buf)
  1717     {
  1718       if (candidate_buffer (buf, buffer)
  1719           /* If the frame has a buffer_predicate, disregard buffers that
  1720              don't fit the predicate.  */
  1721           && (NILP (pred) || !NILP (call1 (pred, buf))))
  1722         {
  1723           if (!NILP (visible_ok)
  1724               || NILP (Fget_buffer_window (buf, Qvisible)))
  1725             return buf;
  1726           else if (NILP (notsogood))
  1727             notsogood = buf;
  1728         }
  1729     }
  1730 
  1731   if (!NILP (notsogood))
  1732     return notsogood;
  1733   else
  1734     return safe_call (1, Qget_scratch_buffer_create);
  1735 }
  1736 
  1737 /* The following function is a safe variant of Fother_buffer: It doesn't
  1738    pay attention to any frame-local buffer lists, doesn't care about
  1739    visibility of buffers, and doesn't evaluate any frame predicates.  */
  1740 
  1741 Lisp_Object
  1742 other_buffer_safely (Lisp_Object buffer)
  1743 {
  1744   Lisp_Object tail, buf;
  1745 
  1746   FOR_EACH_LIVE_BUFFER (tail, buf)
  1747     if (candidate_buffer (buf, buffer))
  1748       return buf;
  1749 
  1750   /* This function must return a valid buffer, since it is frequently
  1751      our last line of defense in the face of the expected buffers
  1752      becoming dead under our feet.  safe_call below could return nil
  1753      if recreating *scratch* in Lisp, which does some fancy stuff,
  1754      signals an error in some weird use case.  */
  1755   buf = safe_call (1, Qget_scratch_buffer_create);
  1756   if (NILP (buf))
  1757     {
  1758       AUTO_STRING (scratch, "*scratch*");
  1759       buf = Fget_buffer_create (scratch, Qnil);
  1760       Fset_buffer_major_mode (buf);
  1761     }
  1762   return buf;
  1763 }
  1764 
  1765 DEFUN ("buffer-enable-undo", Fbuffer_enable_undo, Sbuffer_enable_undo,
  1766        0, 1, "",
  1767        doc: /* Start keeping undo information for buffer BUFFER.
  1768 No argument or nil as argument means do this for the current buffer.  */)
  1769   (register Lisp_Object buffer)
  1770 {
  1771   Lisp_Object real_buffer;
  1772 
  1773   if (NILP (buffer))
  1774     XSETBUFFER (real_buffer, current_buffer);
  1775   else
  1776     {
  1777       real_buffer = Fget_buffer (buffer);
  1778       if (NILP (real_buffer))
  1779         nsberror (buffer);
  1780     }
  1781 
  1782   if (EQ (BVAR (XBUFFER (real_buffer), undo_list), Qt))
  1783     bset_undo_list (XBUFFER (real_buffer), Qnil);
  1784 
  1785   return Qnil;
  1786 }
  1787 
  1788 /* Truncate undo list and shrink the gap of BUFFER.  */
  1789 
  1790 void
  1791 compact_buffer (struct buffer *buffer)
  1792 {
  1793   BUFFER_CHECK_INDIRECTION (buffer);
  1794 
  1795   /* Skip dead buffers, indirect buffers and buffers
  1796      which aren't changed since last compaction.  */
  1797   if (BUFFER_LIVE_P (buffer)
  1798       && (buffer->base_buffer == NULL)
  1799       && (BUF_COMPACT (buffer) != BUF_MODIFF (buffer)))
  1800     {
  1801       /* If a buffer's undo list is Qt, that means that undo is
  1802          turned off in that buffer.  Calling truncate_undo_list on
  1803          Qt tends to return NULL, which effectively turns undo back on.
  1804          So don't call truncate_undo_list if undo_list is Qt.  */
  1805       if (!EQ (BVAR(buffer, undo_list), Qt))
  1806         truncate_undo_list (buffer);
  1807 
  1808       /* Shrink buffer gaps.  */
  1809       if (!buffer->text->inhibit_shrinking)
  1810         {
  1811           /* If a buffer's gap size is more than 10% of the buffer
  1812              size, or larger than GAP_BYTES_DFL bytes, then shrink it
  1813              accordingly.  Keep a minimum size of GAP_BYTES_MIN bytes.  */
  1814           ptrdiff_t size = clip_to_bounds (GAP_BYTES_MIN,
  1815                                            BUF_Z_BYTE (buffer) / 10,
  1816                                            GAP_BYTES_DFL);
  1817           if (BUF_GAP_SIZE (buffer) > size)
  1818             make_gap_1 (buffer, -(BUF_GAP_SIZE (buffer) - size));
  1819         }
  1820       BUF_COMPACT (buffer) = BUF_MODIFF (buffer);
  1821     }
  1822 }
  1823 
  1824 DEFUN ("kill-buffer", Fkill_buffer, Skill_buffer, 0, 1, "bKill buffer: ",
  1825        doc: /* Kill the buffer specified by BUFFER-OR-NAME.
  1826 The argument may be a buffer or the name of an existing buffer.
  1827 Argument nil or omitted means kill the current buffer.  Return t if the
  1828 buffer is actually killed, nil otherwise.
  1829 
  1830 The functions in `kill-buffer-query-functions' are called with the
  1831 buffer to be killed as the current buffer.  If any of them returns nil,
  1832 the buffer is not killed.  The hook `kill-buffer-hook' is run before the
  1833 buffer is actually killed.  The buffer being killed will be current
  1834 while the hook is running.  Functions called by any of these hooks are
  1835 supposed to not change the current buffer.  Neither hook is run for
  1836 internal or temporary buffers created by `get-buffer-create' or
  1837 `generate-new-buffer' with argument INHIBIT-BUFFER-HOOKS non-nil.
  1838 
  1839 Any processes that have this buffer as the `process-buffer' are killed
  1840 with SIGHUP.  This function calls `replace-buffer-in-windows' for
  1841 cleaning up all windows currently displaying the buffer to be killed. */)
  1842   (Lisp_Object buffer_or_name)
  1843 {
  1844   Lisp_Object buffer;
  1845   struct buffer *b;
  1846   Lisp_Object tem;
  1847   struct Lisp_Marker *m;
  1848 
  1849   if (NILP (buffer_or_name))
  1850     buffer = Fcurrent_buffer ();
  1851   else
  1852     buffer = Fget_buffer (buffer_or_name);
  1853   if (NILP (buffer))
  1854     nsberror (buffer_or_name);
  1855 
  1856   b = XBUFFER (buffer);
  1857 
  1858   /* Avoid trouble for buffer already dead.  */
  1859   if (!BUFFER_LIVE_P (b))
  1860     return Qnil;
  1861 
  1862   if (thread_check_current_buffer (b))
  1863     return Qnil;
  1864 
  1865   /* Run hooks with the buffer to be killed as the current buffer.  */
  1866   {
  1867     specpdl_ref count = SPECPDL_INDEX ();
  1868     bool modified;
  1869 
  1870     record_unwind_protect_excursion ();
  1871     set_buffer_internal (b);
  1872 
  1873     /* First run the query functions; if any query is answered no,
  1874        don't kill the buffer.  */
  1875     if (!b->inhibit_buffer_hooks)
  1876       {
  1877         tem = CALLN (Frun_hook_with_args_until_failure,
  1878                      Qkill_buffer_query_functions);
  1879         if (NILP (tem))
  1880           return unbind_to (count, Qnil);
  1881       }
  1882 
  1883     /* Is this a modified buffer that's visiting a file? */
  1884     modified = !NILP (BVAR (b, filename))
  1885       && BUF_MODIFF (b) > BUF_SAVE_MODIFF (b);
  1886 
  1887     /* Query if the buffer is still modified.  */
  1888     if (INTERACTIVE && modified)
  1889       {
  1890         /* Ask whether to kill the buffer, and exit if the user says
  1891            "no".  */
  1892         if (NILP (call1 (Qkill_buffer__possibly_save, buffer)))
  1893           return unbind_to (count, Qnil);
  1894         /* Recheck modified.  */
  1895         modified = BUF_MODIFF (b) > BUF_SAVE_MODIFF (b);
  1896       }
  1897 
  1898     /* Delete the autosave file, if requested. */
  1899     if (modified
  1900         && kill_buffer_delete_auto_save_files
  1901         && delete_auto_save_files
  1902         && !NILP (Frecent_auto_save_p ())
  1903         && STRINGP (BVAR (b, auto_save_file_name))
  1904         && !NILP (Ffile_exists_p (BVAR (b, auto_save_file_name)))
  1905         /* If `auto-save-visited-mode' is on, then we're auto-saving
  1906            to the visited file -- don't delete it.. */
  1907         && NILP (Fstring_equal (BVAR (b, auto_save_file_name),
  1908                                 BVAR (b, filename))))
  1909       {
  1910         tem = do_yes_or_no_p (build_string ("Delete auto-save file? "));
  1911         if (!NILP (tem))
  1912           call0 (intern ("delete-auto-save-file-if-necessary"));
  1913       }
  1914 
  1915     /* If the hooks have killed the buffer, exit now.  */
  1916     if (!BUFFER_LIVE_P (b))
  1917       return unbind_to (count, Qt);
  1918 
  1919     /* Then run the hooks.  */
  1920     if (!b->inhibit_buffer_hooks)
  1921       run_hook (Qkill_buffer_hook);
  1922     unbind_to (count, Qnil);
  1923   }
  1924 
  1925   /* If the hooks have killed the buffer, exit now.  */
  1926   if (!BUFFER_LIVE_P (b))
  1927     return Qt;
  1928 
  1929   /* We have no more questions to ask.  Verify that it is valid
  1930      to kill the buffer.  This must be done after the questions
  1931      since anything can happen within do_yes_or_no_p.  */
  1932 
  1933   /* Don't kill the minibuffer now current.  */
  1934   if (BASE_EQ (buffer, XWINDOW (minibuf_window)->contents))
  1935     return Qnil;
  1936 
  1937   /* When we kill an ordinary buffer which shares its buffer text
  1938      with indirect buffer(s), we must kill indirect buffer(s) too.
  1939      We do it at this stage so nothing terrible happens if they
  1940      ask questions or their hooks get errors.  */
  1941   if (!b->base_buffer && b->indirections > 0)
  1942     {
  1943       Lisp_Object tail, other;
  1944 
  1945       FOR_EACH_LIVE_BUFFER (tail, other)
  1946         if (XBUFFER (other)->base_buffer == b)
  1947           Fkill_buffer (other);
  1948 
  1949       /* Exit if we now have killed the base buffer (Bug#11665).  */
  1950       if (!BUFFER_LIVE_P (b))
  1951         return Qt;
  1952     }
  1953 
  1954   /* Run replace_buffer_in_windows before making another buffer current
  1955      since set-window-buffer-start-and-point will refuse to make another
  1956      buffer current if the selected window does not show the current
  1957      buffer (bug#10114).  */
  1958   replace_buffer_in_windows (buffer);
  1959 
  1960   /* Exit if replacing the buffer in windows has killed our buffer.  */
  1961   if (!BUFFER_LIVE_P (b))
  1962     return Qt;
  1963 
  1964   /* Make this buffer not be current.  Exit if it is the sole visible
  1965      buffer.  */
  1966   if (b == current_buffer)
  1967     {
  1968       tem = Fother_buffer (buffer, Qnil, Qnil);
  1969       Fset_buffer (tem);
  1970       if (b == current_buffer)
  1971         return Qnil;
  1972     }
  1973 
  1974   /* If the buffer now current is shown in the minibuffer and our buffer
  1975      is the sole other buffer give up.  */
  1976   XSETBUFFER (tem, current_buffer);
  1977   if (EQ (tem, XWINDOW (minibuf_window)->contents)
  1978       && BASE_EQ (buffer, Fother_buffer (buffer, Qnil, Qnil)))
  1979     return Qnil;
  1980 
  1981   /* Now there is no question: we can kill the buffer.  */
  1982 
  1983   /* Unlock this buffer's file, if it is locked.  */
  1984   unlock_buffer (b);
  1985 
  1986   kill_buffer_processes (buffer);
  1987   kill_buffer_xwidgets (buffer);
  1988 
  1989   /* Killing buffer processes may run sentinels which may have killed
  1990      our buffer.  */
  1991   if (!BUFFER_LIVE_P (b))
  1992     return Qt;
  1993 
  1994   /* These may run Lisp code and into infinite loops (if someone
  1995      insisted on circular lists) so allow quitting here.  */
  1996   frames_discard_buffer (buffer);
  1997 
  1998   clear_charpos_cache (b);
  1999 
  2000   tem = Vinhibit_quit;
  2001   Vinhibit_quit = Qt;
  2002   /* Once the buffer is removed from Vbuffer_alist, its undo_list field is
  2003      not traced by the GC in the same way.  So set it to nil early.  */
  2004   bset_undo_list (b, Qnil);
  2005   /* Remove the buffer from the list of all buffers.  */
  2006   Vbuffer_alist = Fdelq (Frassq (buffer, Vbuffer_alist), Vbuffer_alist);
  2007   /* If replace_buffer_in_windows didn't do its job fix that now.  */
  2008   replace_buffer_in_windows_safely (buffer);
  2009   Vinhibit_quit = tem;
  2010 
  2011   if (b->base_buffer)
  2012     {
  2013       INTERVAL i;
  2014       /* Unchain all markers that belong to this indirect buffer.
  2015          Don't unchain the markers that belong to the base buffer
  2016          or its other indirect buffers.  */
  2017       struct Lisp_Marker **mp = &BUF_MARKERS (b);
  2018       while ((m = *mp))
  2019         {
  2020           if (m->buffer == b)
  2021             {
  2022               m->buffer = NULL;
  2023               *mp = m->next;
  2024             }
  2025           else
  2026             mp = &m->next;
  2027         }
  2028       /* Intervals should be owned by the base buffer (Bug#16502).  */
  2029       i = buffer_intervals (b);
  2030       if (i)
  2031         {
  2032           Lisp_Object owner;
  2033           XSETBUFFER (owner, b->base_buffer);
  2034           set_interval_object (i, owner);
  2035         }
  2036     }
  2037   else
  2038     {
  2039       /* Unchain all markers of this buffer and its indirect buffers.
  2040          and leave them pointing nowhere.  */
  2041       for (m = BUF_MARKERS (b); m; )
  2042         {
  2043           struct Lisp_Marker *next = m->next;
  2044           m->buffer = 0;
  2045           m->next = NULL;
  2046           m = next;
  2047         }
  2048       BUF_MARKERS (b) = NULL;
  2049       set_buffer_intervals (b, NULL);
  2050 
  2051       /* Perhaps we should explicitly free the interval tree here...  */
  2052     }
  2053   delete_all_overlays (b);
  2054   free_buffer_overlays (b);
  2055 
  2056   /* Reset the local variables, so that this buffer's local values
  2057      won't be protected from GC.  They would be protected
  2058      if they happened to remain cached in their symbols.
  2059      This gets rid of them for certain.  */
  2060   reset_buffer_local_variables (b, 1);
  2061 
  2062   bset_name (b, Qnil);
  2063 
  2064   block_input ();
  2065   if (b->base_buffer)
  2066     {
  2067       /* Notify our base buffer that we don't share the text anymore.  */
  2068       eassert (b->indirections == -1);
  2069       b->base_buffer->indirections--;
  2070       eassert (b->base_buffer->indirections >= 0);
  2071       /* Make sure that we wasn't confused.  */
  2072       eassert (b->window_count == -1);
  2073     }
  2074   else
  2075     {
  2076       /* Make sure that no one shows us.  */
  2077       eassert (b->window_count == 0);
  2078       /* No one shares our buffer text, can free it.  */
  2079       free_buffer_text (b);
  2080     }
  2081 
  2082   if (b->newline_cache)
  2083     {
  2084       free_region_cache (b->newline_cache);
  2085       b->newline_cache = 0;
  2086     }
  2087   if (b->width_run_cache)
  2088     {
  2089       free_region_cache (b->width_run_cache);
  2090       b->width_run_cache = 0;
  2091     }
  2092   if (b->bidi_paragraph_cache)
  2093     {
  2094       free_region_cache (b->bidi_paragraph_cache);
  2095       b->bidi_paragraph_cache = 0;
  2096     }
  2097   bset_width_table (b, Qnil);
  2098   unblock_input ();
  2099 
  2100   run_buffer_list_update_hook (b);
  2101 
  2102   return Qt;
  2103 }
  2104 
  2105 /* Move association for BUFFER to the front of buffer (a)lists.  Since
  2106    we do this each time BUFFER is selected visibly, the more recently
  2107    selected buffers are always closer to the front of those lists.  This
  2108    means that other_buffer is more likely to choose a relevant buffer.
  2109 
  2110    Note that this moves BUFFER to the front of the buffer lists of the
  2111    selected frame even if BUFFER is not shown there.  If BUFFER is not
  2112    shown in the selected frame, consider the present behavior a feature.
  2113    `select-window' gets this right since it shows BUFFER in the selected
  2114    window when calling us.  */
  2115 
  2116 void
  2117 record_buffer (Lisp_Object buffer)
  2118 {
  2119   Lisp_Object aelt, aelt_cons, tem;
  2120   register struct frame *f = XFRAME (selected_frame);
  2121 
  2122   CHECK_BUFFER (buffer);
  2123 
  2124   /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
  2125      Don't allow quitting since this might leave the buffer list in an
  2126      inconsistent state.  */
  2127   tem = Vinhibit_quit;
  2128   Vinhibit_quit = Qt;
  2129   aelt = Frassq (buffer, Vbuffer_alist);
  2130   aelt_cons = Fmemq (aelt, Vbuffer_alist);
  2131   Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
  2132   XSETCDR (aelt_cons, Vbuffer_alist);
  2133   Vbuffer_alist = aelt_cons;
  2134   Vinhibit_quit = tem;
  2135 
  2136   /* Update buffer list of selected frame.  */
  2137   fset_buffer_list (f, Fcons (buffer, Fdelq (buffer, f->buffer_list)));
  2138   fset_buried_buffer_list (f, Fdelq (buffer, f->buried_buffer_list));
  2139 
  2140   run_buffer_list_update_hook (XBUFFER (buffer));
  2141 }
  2142 
  2143 
  2144 /* Move BUFFER to the end of the buffer (a)lists.  Do nothing if the
  2145    buffer is killed.  For the selected frame's buffer list this moves
  2146    BUFFER to its end even if it was never shown in that frame.  If
  2147    this happens we have a feature, hence `bury-buffer-internal' should be
  2148    called only when BUFFER was shown in the selected frame.  */
  2149 
  2150 DEFUN ("bury-buffer-internal", Fbury_buffer_internal, Sbury_buffer_internal,
  2151        1, 1, 0,
  2152        doc: /* Move BUFFER to the end of the buffer list.  */)
  2153   (Lisp_Object buffer)
  2154 {
  2155   Lisp_Object aelt, aelt_cons, tem;
  2156   register struct frame *f = XFRAME (selected_frame);
  2157 
  2158   CHECK_BUFFER (buffer);
  2159 
  2160   /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
  2161      Don't allow quitting since this might leave the buffer list in an
  2162      inconsistent state.  */
  2163   tem = Vinhibit_quit;
  2164   Vinhibit_quit = Qt;
  2165   aelt = Frassq (buffer, Vbuffer_alist);
  2166   aelt_cons = Fmemq (aelt, Vbuffer_alist);
  2167   Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
  2168   XSETCDR (aelt_cons, Qnil);
  2169   Vbuffer_alist = nconc2 (Vbuffer_alist, aelt_cons);
  2170   Vinhibit_quit = tem;
  2171 
  2172   /* Update buffer lists of selected frame.  */
  2173   fset_buffer_list (f, Fdelq (buffer, f->buffer_list));
  2174   fset_buried_buffer_list
  2175     (f, Fcons (buffer, Fdelq (buffer, f->buried_buffer_list)));
  2176 
  2177   run_buffer_list_update_hook (XBUFFER (buffer));
  2178 
  2179   return Qnil;
  2180 }
  2181 
  2182 DEFUN ("set-buffer-major-mode", Fset_buffer_major_mode, Sset_buffer_major_mode, 1, 1, 0,
  2183        doc: /* Set an appropriate major mode for BUFFER.
  2184 For the *scratch* buffer, use `initial-major-mode', otherwise choose a mode
  2185 according to the default value of `major-mode'.
  2186 Use this function before selecting the buffer, since it may need to inspect
  2187 the current buffer's major mode.  */)
  2188   (Lisp_Object buffer)
  2189 {
  2190   Lisp_Object function;
  2191 
  2192   CHECK_BUFFER (buffer);
  2193 
  2194   if (!BUFFER_LIVE_P (XBUFFER (buffer)))
  2195     error ("Attempt to set major mode for a dead buffer");
  2196 
  2197   if (strcmp (SSDATA (BVAR (XBUFFER (buffer), name)), "*scratch*") == 0)
  2198     function = find_symbol_value (intern ("initial-major-mode"));
  2199   else
  2200     {
  2201       function = BVAR (&buffer_defaults, major_mode);
  2202       if (NILP (function)
  2203           && NILP (Fget (BVAR (current_buffer, major_mode), Qmode_class)))
  2204         function = BVAR (current_buffer, major_mode);
  2205     }
  2206 
  2207   if (NILP (function)) /* If function is `fundamental-mode', allow it to run
  2208                           so that `run-mode-hooks' and thus
  2209                           `hack-local-variables' get run. */
  2210     return Qnil;
  2211 
  2212   specpdl_ref count = SPECPDL_INDEX ();
  2213 
  2214   /* To select a nonfundamental mode,
  2215      select the buffer temporarily and then call the mode function.  */
  2216 
  2217   record_unwind_current_buffer ();
  2218 
  2219   Fset_buffer (buffer);
  2220   call0 (function);
  2221 
  2222   return unbind_to (count, Qnil);
  2223 }
  2224 
  2225 DEFUN ("current-buffer", Fcurrent_buffer, Scurrent_buffer, 0, 0, 0,
  2226        doc: /* Return the current buffer as a Lisp object.  */)
  2227   (void)
  2228 {
  2229   register Lisp_Object buf;
  2230   XSETBUFFER (buf, current_buffer);
  2231   return buf;
  2232 }
  2233 
  2234 /* Set the current buffer to B, and do not set windows_or_buffers_changed.
  2235    This is used by redisplay.  */
  2236 
  2237 void
  2238 set_buffer_internal_1 (register struct buffer *b)
  2239 {
  2240 #ifdef USE_MMAP_FOR_BUFFERS
  2241   if (b->text->beg == NULL)
  2242     enlarge_buffer_text (b, 0);
  2243 #endif /* USE_MMAP_FOR_BUFFERS */
  2244 
  2245   if (current_buffer == b)
  2246     return;
  2247 
  2248   set_buffer_internal_2 (b);
  2249 }
  2250 
  2251 /* Like set_buffer_internal_1, but doesn't check whether B is already
  2252    the current buffer.  Called upon switch of the current thread, see
  2253    post_acquire_global_lock.  */
  2254 void set_buffer_internal_2 (register struct buffer *b)
  2255 {
  2256   register struct buffer *old_buf;
  2257   register Lisp_Object tail;
  2258 
  2259   BUFFER_CHECK_INDIRECTION (b);
  2260 
  2261   old_buf = current_buffer;
  2262   current_buffer = b;
  2263   last_known_column_point = -1;   /* Invalidate indentation cache.  */
  2264 
  2265   if (old_buf)
  2266     {
  2267       /* Put the undo list back in the base buffer, so that it appears
  2268          that an indirect buffer shares the undo list of its base.  */
  2269       if (old_buf->base_buffer)
  2270         bset_undo_list (old_buf->base_buffer, BVAR (old_buf, undo_list));
  2271 
  2272       /* If the old current buffer has markers to record PT, BEGV and ZV
  2273          when it is not current, update them now.  */
  2274       record_buffer_markers (old_buf);
  2275     }
  2276 
  2277   /* Get the undo list from the base buffer, so that it appears
  2278      that an indirect buffer shares the undo list of its base.  */
  2279   if (b->base_buffer)
  2280     bset_undo_list (b, BVAR (b->base_buffer, undo_list));
  2281 
  2282   /* If the new current buffer has markers to record PT, BEGV and ZV
  2283      when it is not current, fetch them now.  */
  2284   fetch_buffer_markers (b);
  2285 
  2286   /* Look down buffer's list of local Lisp variables
  2287      to find and update any that forward into C variables.  */
  2288 
  2289   do
  2290     {
  2291       for (tail = BVAR (b, local_var_alist); CONSP (tail); tail = XCDR (tail))
  2292         {
  2293           Lisp_Object var = XCAR (XCAR (tail));
  2294           struct Lisp_Symbol *sym = XSYMBOL (var);
  2295           if (sym->u.s.redirect == SYMBOL_LOCALIZED /* Just to be sure.  */
  2296               && SYMBOL_BLV (sym)->fwd.fwdptr)
  2297             /* Just reference the variable
  2298                to cause it to become set for this buffer.  */
  2299             Fsymbol_value (var);
  2300         }
  2301     }
  2302   /* Do the same with any others that were local to the previous buffer */
  2303   while (b != old_buf && (b = old_buf, b));
  2304 }
  2305 
  2306 /* Switch to buffer B temporarily for redisplay purposes.
  2307    This avoids certain things that don't need to be done within redisplay.  */
  2308 
  2309 void
  2310 set_buffer_temp (struct buffer *b)
  2311 {
  2312   register struct buffer *old_buf;
  2313 
  2314   if (current_buffer == b)
  2315     return;
  2316 
  2317   old_buf = current_buffer;
  2318   current_buffer = b;
  2319 
  2320   /* If the old current buffer has markers to record PT, BEGV and ZV
  2321      when it is not current, update them now.  */
  2322   record_buffer_markers (old_buf);
  2323 
  2324   /* If the new current buffer has markers to record PT, BEGV and ZV
  2325      when it is not current, fetch them now.  */
  2326   fetch_buffer_markers (b);
  2327 }
  2328 
  2329 DEFUN ("set-buffer", Fset_buffer, Sset_buffer, 1, 1, 0,
  2330        doc: /* Make buffer BUFFER-OR-NAME current for editing operations.
  2331 BUFFER-OR-NAME may be a buffer or the name of an existing buffer.
  2332 See also `with-current-buffer' when you want to make a buffer current
  2333 temporarily.  This function does not display the buffer, so its effect
  2334 ends when the current command terminates.  Use `switch-to-buffer' or
  2335 `pop-to-buffer' to switch buffers permanently.
  2336 The return value is the buffer made current.  */)
  2337   (register Lisp_Object buffer_or_name)
  2338 {
  2339   register Lisp_Object buffer;
  2340   buffer = Fget_buffer (buffer_or_name);
  2341   if (NILP (buffer))
  2342     nsberror (buffer_or_name);
  2343   if (!BUFFER_LIVE_P (XBUFFER (buffer)))
  2344     error ("Selecting deleted buffer");
  2345   set_buffer_internal (XBUFFER (buffer));
  2346   return buffer;
  2347 }
  2348 
  2349 void
  2350 restore_buffer (Lisp_Object buffer_or_name)
  2351 {
  2352   Fset_buffer (buffer_or_name);
  2353 }
  2354 
  2355 /* Set the current buffer to BUFFER provided if it is alive.  */
  2356 
  2357 void
  2358 set_buffer_if_live (Lisp_Object buffer)
  2359 {
  2360   if (BUFFER_LIVE_P (XBUFFER (buffer)))
  2361     set_buffer_internal (XBUFFER (buffer));
  2362 }
  2363 
  2364 DEFUN ("barf-if-buffer-read-only", Fbarf_if_buffer_read_only,
  2365                                    Sbarf_if_buffer_read_only, 0, 1, 0,
  2366        doc: /* Signal a `buffer-read-only' error if the current buffer is read-only.
  2367 If the text under POSITION (which defaults to point) has the
  2368 `inhibit-read-only' text property set, the error will not be raised.  */)
  2369   (Lisp_Object position)
  2370 {
  2371   if (NILP (position))
  2372     XSETFASTINT (position, PT);
  2373   else
  2374     CHECK_FIXNUM (position);
  2375 
  2376   if (!NILP (BVAR (current_buffer, read_only))
  2377       && NILP (Vinhibit_read_only)
  2378       && NILP (Fget_text_property (position, Qinhibit_read_only, Qnil)))
  2379     xsignal1 (Qbuffer_read_only, Fcurrent_buffer ());
  2380   return Qnil;
  2381 }
  2382 
  2383 DEFUN ("erase-buffer", Ferase_buffer, Serase_buffer, 0, 0, "*",
  2384        doc: /* Delete the entire contents of the current buffer.
  2385 Any narrowing restriction in effect (see `narrow-to-region') is removed,
  2386 so the buffer is truly empty after this.  */)
  2387   (void)
  2388 {
  2389   labeled_restrictions_remove_in_current_buffer ();
  2390   Fwiden ();
  2391 
  2392   del_range (BEG, Z);
  2393 
  2394   current_buffer->last_window_start = 1;
  2395   /* Prevent warnings, or suspension of auto saving, that would happen
  2396      if future size is less than past size.  Use of erase-buffer
  2397      implies that the future text is not really related to the past text.  */
  2398   XSETFASTINT (BVAR (current_buffer, save_length), 0);
  2399   return Qnil;
  2400 }
  2401 
  2402 void
  2403 validate_region (Lisp_Object *b, Lisp_Object *e)
  2404 {
  2405   EMACS_INT beg = fix_position (*b), end = fix_position (*e);
  2406 
  2407   if (end < beg)
  2408     {
  2409       EMACS_INT tem = beg;  beg = end;  end = tem;
  2410     }
  2411 
  2412   if (! (BEGV <= beg && end <= ZV))
  2413     args_out_of_range_3 (Fcurrent_buffer (), *b, *e);
  2414 
  2415   *b = make_fixnum (beg);
  2416   *e = make_fixnum (end);
  2417 }
  2418 
  2419 /* Advance BYTE_POS up to a character boundary
  2420    and return the adjusted position.  */
  2421 
  2422 ptrdiff_t
  2423 advance_to_char_boundary (ptrdiff_t byte_pos)
  2424 {
  2425   int c;
  2426 
  2427   if (byte_pos == BEG)
  2428     /* Beginning of buffer is always a character boundary.  */
  2429     return BEG;
  2430 
  2431   c = FETCH_BYTE (byte_pos);
  2432   if (! CHAR_HEAD_P (c))
  2433     {
  2434       /* We should advance BYTE_POS only when C is a constituent of a
  2435          multibyte sequence.  */
  2436       ptrdiff_t orig_byte_pos = byte_pos;
  2437 
  2438       do
  2439         {
  2440           byte_pos--;
  2441           c = FETCH_BYTE (byte_pos);
  2442         }
  2443       while (! CHAR_HEAD_P (c) && byte_pos > BEG);
  2444       byte_pos += next_char_len (byte_pos);
  2445       if (byte_pos < orig_byte_pos)
  2446         byte_pos = orig_byte_pos;
  2447       /* If C is a constituent of a multibyte sequence, BYTE_POS was
  2448          surely advance to the correct character boundary.  If C is
  2449          not, BYTE_POS was unchanged.  */
  2450     }
  2451 
  2452   return byte_pos;
  2453 }
  2454 
  2455 static void
  2456 swap_buffer_overlays (struct buffer *buffer, struct buffer *other)
  2457 {
  2458   struct itree_node *node;
  2459 
  2460   ITREE_FOREACH (node, buffer->overlays, PTRDIFF_MIN, PTRDIFF_MAX, ASCENDING)
  2461     XOVERLAY (node->data)->buffer = other;
  2462 
  2463   ITREE_FOREACH (node, other->overlays, PTRDIFF_MIN, PTRDIFF_MAX, ASCENDING)
  2464     XOVERLAY (node->data)->buffer = buffer;
  2465 
  2466   /* Swap the interval trees. */
  2467   void *tmp = buffer->overlays;
  2468   buffer->overlays = other->overlays;
  2469   other->overlays = tmp;
  2470 }
  2471 
  2472 DEFUN ("buffer-swap-text", Fbuffer_swap_text, Sbuffer_swap_text,
  2473        1, 1, 0,
  2474        doc: /* Swap the text between current buffer and BUFFER.
  2475 Using this function from `save-excursion' might produce surprising
  2476 results, see Info node `(elisp)Swapping Text'.  */)
  2477   (Lisp_Object buffer)
  2478 {
  2479   struct buffer *other_buffer;
  2480   CHECK_BUFFER (buffer);
  2481   other_buffer = XBUFFER (buffer);
  2482 
  2483   if (!BUFFER_LIVE_P (other_buffer))
  2484     error ("Cannot swap a dead buffer's text");
  2485 
  2486   /* Actually, it probably works just fine.
  2487    * if (other_buffer == current_buffer)
  2488    *   error ("Cannot swap a buffer's text with itself"); */
  2489 
  2490   /* Actually, this may be workable as well, tho probably only if they're
  2491      *both* indirect.  */
  2492   if (other_buffer->base_buffer
  2493       || current_buffer->base_buffer)
  2494     error ("Cannot swap indirect buffers's text");
  2495 
  2496   { /* This is probably harder to make work.  */
  2497     Lisp_Object tail, other;
  2498     FOR_EACH_LIVE_BUFFER (tail, other)
  2499       if (XBUFFER (other)->base_buffer == other_buffer
  2500           || XBUFFER (other)->base_buffer == current_buffer)
  2501         error ("One of the buffers to swap has indirect buffers");
  2502   }
  2503 
  2504 #define swapfield(field, type) \
  2505   do {                                                  \
  2506     type tmp##field = other_buffer->field;              \
  2507     other_buffer->field = current_buffer->field;        \
  2508     current_buffer->field = tmp##field;                 \
  2509   } while (0)
  2510 #define swapfield_(field, type) \
  2511   do {                                                  \
  2512     type tmp##field = BVAR (other_buffer, field);               \
  2513     bset_##field (other_buffer, BVAR (current_buffer, field));  \
  2514     bset_##field (current_buffer, tmp##field);                  \
  2515   } while (0)
  2516 
  2517   swapfield (own_text, struct buffer_text);
  2518   eassert (current_buffer->text == &current_buffer->own_text);
  2519   eassert (other_buffer->text == &other_buffer->own_text);
  2520 #ifdef REL_ALLOC
  2521   r_alloc_reset_variable ((void **) &current_buffer->own_text.beg,
  2522                           (void **) &other_buffer->own_text.beg);
  2523   r_alloc_reset_variable ((void **) &other_buffer->own_text.beg,
  2524                           (void **) &current_buffer->own_text.beg);
  2525 #endif /* REL_ALLOC */
  2526 
  2527   swapfield (pt, ptrdiff_t);
  2528   swapfield (pt_byte, ptrdiff_t);
  2529   swapfield (begv, ptrdiff_t);
  2530   swapfield (begv_byte, ptrdiff_t);
  2531   swapfield (zv, ptrdiff_t);
  2532   swapfield (zv_byte, ptrdiff_t);
  2533   eassert (!current_buffer->base_buffer);
  2534   eassert (!other_buffer->base_buffer);
  2535   swapfield (indirections, ptrdiff_t);
  2536   current_buffer->clip_changed = 1;     other_buffer->clip_changed = 1;
  2537   swapfield (newline_cache, struct region_cache *);
  2538   swapfield (width_run_cache, struct region_cache *);
  2539   swapfield (bidi_paragraph_cache, struct region_cache *);
  2540   current_buffer->prevent_redisplay_optimizations_p = 1;
  2541   other_buffer->prevent_redisplay_optimizations_p = 1;
  2542   swapfield (long_line_optimizations_p, bool_bf);
  2543   swapfield_ (undo_list, Lisp_Object);
  2544   swapfield_ (mark, Lisp_Object);
  2545   swapfield_ (mark_active, Lisp_Object); /* Belongs with the `mark'.  */
  2546   swapfield_ (enable_multibyte_characters, Lisp_Object);
  2547   swapfield_ (bidi_display_reordering, Lisp_Object);
  2548   swapfield_ (bidi_paragraph_direction, Lisp_Object);
  2549   swapfield_ (bidi_paragraph_separate_re, Lisp_Object);
  2550   swapfield_ (bidi_paragraph_start_re, Lisp_Object);
  2551   /* FIXME: Not sure what we should do with these *_marker fields.
  2552      Hopefully they're just nil anyway.  */
  2553   swapfield_ (pt_marker, Lisp_Object);
  2554   swapfield_ (begv_marker, Lisp_Object);
  2555   swapfield_ (zv_marker, Lisp_Object);
  2556   bset_point_before_scroll (current_buffer, Qnil);
  2557   bset_point_before_scroll (other_buffer, Qnil);
  2558 
  2559   modiff_incr (&current_buffer->text->modiff, 1);
  2560   modiff_incr (&other_buffer->text->modiff, 1);
  2561   modiff_incr (&current_buffer->text->chars_modiff, 1);
  2562   modiff_incr (&other_buffer->text->chars_modiff, 1);
  2563   modiff_incr (&current_buffer->text->overlay_modiff, 1);
  2564   modiff_incr (&other_buffer->text->overlay_modiff, 1);
  2565   current_buffer->text->beg_unchanged = current_buffer->text->gpt;
  2566   current_buffer->text->end_unchanged = current_buffer->text->gpt;
  2567   other_buffer->text->beg_unchanged = other_buffer->text->gpt;
  2568   other_buffer->text->end_unchanged = other_buffer->text->gpt;
  2569   swap_buffer_overlays (current_buffer, other_buffer);
  2570   {
  2571     struct Lisp_Marker *m;
  2572     for (m = BUF_MARKERS (current_buffer); m; m = m->next)
  2573       if (m->buffer == other_buffer)
  2574         m->buffer = current_buffer;
  2575       else
  2576         /* Since there's no indirect buffer in sight, markers on
  2577            BUF_MARKERS(buf) should either be for `buf' or dead.  */
  2578         eassert (!m->buffer);
  2579     for (m = BUF_MARKERS (other_buffer); m; m = m->next)
  2580       if (m->buffer == current_buffer)
  2581         m->buffer = other_buffer;
  2582       else
  2583         /* Since there's no indirect buffer in sight, markers on
  2584            BUF_MARKERS(buf) should either be for `buf' or dead.  */
  2585         eassert (!m->buffer);
  2586   }
  2587   { /* Some of the C code expects that both window markers of a
  2588        live window points to that window's buffer.  So since we
  2589        just swapped the markers between the two buffers, we need
  2590        to undo the effect of this swap for window markers.  */
  2591     Lisp_Object w = selected_window, ws = Qnil;
  2592     Lisp_Object buf1, buf2;
  2593     XSETBUFFER (buf1, current_buffer); XSETBUFFER (buf2, other_buffer);
  2594 
  2595     while (NILP (Fmemq (w, ws)))
  2596       {
  2597         ws = Fcons (w, ws);
  2598         if (MARKERP (XWINDOW (w)->pointm)
  2599             && (BASE_EQ (XWINDOW (w)->contents, buf1)
  2600                 || BASE_EQ (XWINDOW (w)->contents, buf2)))
  2601           Fset_marker (XWINDOW (w)->pointm,
  2602                        make_fixnum
  2603                        (BUF_BEGV (XBUFFER (XWINDOW (w)->contents))),
  2604                        XWINDOW (w)->contents);
  2605         /* Blindly copied from pointm part.  */
  2606         if (MARKERP (XWINDOW (w)->old_pointm)
  2607             && (BASE_EQ (XWINDOW (w)->contents, buf1)
  2608                 || BASE_EQ (XWINDOW (w)->contents, buf2)))
  2609           Fset_marker (XWINDOW (w)->old_pointm,
  2610                        make_fixnum
  2611                        (BUF_BEGV (XBUFFER (XWINDOW (w)->contents))),
  2612                        XWINDOW (w)->contents);
  2613         if (MARKERP (XWINDOW (w)->start)
  2614             && (BASE_EQ (XWINDOW (w)->contents, buf1)
  2615                 || BASE_EQ (XWINDOW (w)->contents, buf2)))
  2616           Fset_marker (XWINDOW (w)->start,
  2617                        make_fixnum
  2618                        (XBUFFER (XWINDOW (w)->contents)->last_window_start),
  2619                        XWINDOW (w)->contents);
  2620         w = Fnext_window (w, Qt, Qt);
  2621       }
  2622   }
  2623 
  2624   if (current_buffer->text->intervals)
  2625     (eassert (BASE_EQ (current_buffer->text->intervals->up.obj, buffer)),
  2626      XSETBUFFER (current_buffer->text->intervals->up.obj, current_buffer));
  2627   if (other_buffer->text->intervals)
  2628     (eassert (BASE_EQ (other_buffer->text->intervals->up.obj,
  2629                        Fcurrent_buffer ())),
  2630      XSETBUFFER (other_buffer->text->intervals->up.obj, other_buffer));
  2631 
  2632   return Qnil;
  2633 }
  2634 
  2635 DEFUN ("set-buffer-multibyte", Fset_buffer_multibyte, Sset_buffer_multibyte,
  2636        1, 1, 0,
  2637        doc: /* Set the multibyte flag of the current buffer to FLAG.
  2638 If FLAG is t, this makes the buffer a multibyte buffer.
  2639 If FLAG is nil, this makes the buffer a single-byte buffer.
  2640 In these cases, the buffer contents remain unchanged as a sequence of
  2641 bytes but the contents viewed as characters do change.
  2642 If FLAG is `to', this makes the buffer a multibyte buffer by changing
  2643 all eight-bit bytes to eight-bit characters.
  2644 If the multibyte flag was really changed, undo information of the
  2645 current buffer is cleared.  */)
  2646   (Lisp_Object flag)
  2647 {
  2648   struct Lisp_Marker *tail, *markers;
  2649   Lisp_Object btail, other;
  2650   ptrdiff_t begv, zv;
  2651   bool narrowed = (BEG != BEGV || Z != ZV);
  2652   bool modified_p = !NILP (Fbuffer_modified_p (Qnil));
  2653   Lisp_Object old_undo = BVAR (current_buffer, undo_list);
  2654 
  2655   if (current_buffer->base_buffer)
  2656     error ("Cannot do `set-buffer-multibyte' on an indirect buffer");
  2657 
  2658   /* Do nothing if nothing actually changes.  */
  2659   if (NILP (flag) == NILP (BVAR (current_buffer, enable_multibyte_characters)))
  2660     return flag;
  2661 
  2662   /* Don't record these buffer changes.  We will put a special undo entry
  2663      instead.  */
  2664   bset_undo_list (current_buffer, Qt);
  2665 
  2666   /* If the cached position is for this buffer, clear it out.  */
  2667   clear_charpos_cache (current_buffer);
  2668 
  2669   if (NILP (flag))
  2670     begv = BEGV_BYTE, zv = ZV_BYTE;
  2671   else
  2672     begv = BEGV, zv = ZV;
  2673 
  2674   if (narrowed)
  2675     error ("Changing multibyteness in a narrowed buffer");
  2676 
  2677   invalidate_buffer_caches (current_buffer, BEGV, ZV);
  2678 
  2679   if (NILP (flag))
  2680     {
  2681       ptrdiff_t pos, stop;
  2682       unsigned char *p;
  2683 
  2684       /* Do this first, so it can use CHAR_TO_BYTE
  2685          to calculate the old correspondences.  */
  2686       set_intervals_multibyte (false);
  2687       set_overlays_multibyte (false);
  2688 
  2689       bset_enable_multibyte_characters (current_buffer, Qnil);
  2690 
  2691       Z = Z_BYTE;
  2692       BEGV = BEGV_BYTE;
  2693       ZV = ZV_BYTE;
  2694       GPT = GPT_BYTE;
  2695       TEMP_SET_PT_BOTH (PT_BYTE, PT_BYTE);
  2696 
  2697 
  2698       for (tail = BUF_MARKERS (current_buffer); tail; tail = tail->next)
  2699         tail->charpos = tail->bytepos;
  2700 
  2701       /* Convert multibyte form of 8-bit characters to unibyte.  */
  2702       pos = BEG;
  2703       stop = GPT;
  2704       p = BEG_ADDR;
  2705       while (1)
  2706         {
  2707           if (pos == stop)
  2708             {
  2709               if (pos == Z)
  2710                 break;
  2711               p = GAP_END_ADDR;
  2712               stop = Z;
  2713             }
  2714           if (ASCII_CHAR_P (*p))
  2715             p++, pos++;
  2716           else if (CHAR_BYTE8_HEAD_P (*p))
  2717             {
  2718               int bytes, c = string_char_and_length (p, &bytes);
  2719               /* Delete all bytes for this 8-bit character but the
  2720                  last one, and change the last one to the character
  2721                  code.  */
  2722               bytes--;
  2723               del_range_2 (pos, pos, pos + bytes, pos + bytes, 0);
  2724               p = GAP_END_ADDR;
  2725               *p++ = c;
  2726               pos++;
  2727               if (begv > pos)
  2728                 begv -= bytes;
  2729               if (zv > pos)
  2730                 zv -= bytes;
  2731               stop = Z;
  2732             }
  2733           else
  2734             {
  2735               int bytes = BYTES_BY_CHAR_HEAD (*p);
  2736               p += bytes, pos += bytes;
  2737             }
  2738         }
  2739     }
  2740   else
  2741     {
  2742       ptrdiff_t pt = PT;
  2743       ptrdiff_t pos, stop;
  2744       unsigned char *p, *pend;
  2745 
  2746       /* Be sure not to have a multibyte sequence striding over the GAP.
  2747          Ex: We change this: "...abc\302 _GAP_ \241def..."
  2748              to: "...abc _GAP_ \302\241def..."  */
  2749 
  2750       if (EQ (flag, Qt)
  2751           && GPT_BYTE > 1 && GPT_BYTE < Z_BYTE
  2752           && ! CHAR_HEAD_P (*(GAP_END_ADDR)))
  2753         {
  2754           unsigned char *q = GPT_ADDR - 1;
  2755 
  2756           while (! CHAR_HEAD_P (*q) && q > BEG_ADDR) q--;
  2757           if (LEADING_CODE_P (*q))
  2758             {
  2759               ptrdiff_t new_gpt = GPT_BYTE - (GPT_ADDR - q);
  2760 
  2761               move_gap_both (new_gpt, new_gpt);
  2762             }
  2763         }
  2764 
  2765       /* Make the buffer contents valid as multibyte by converting
  2766          8-bit characters to multibyte form.  */
  2767       pos = BEG;
  2768       stop = GPT;
  2769       p = BEG_ADDR;
  2770       pend = GPT_ADDR;
  2771       while (1)
  2772         {
  2773           int bytes;
  2774 
  2775           if (pos == stop)
  2776             {
  2777               if (pos == Z)
  2778                 break;
  2779               p = GAP_END_ADDR;
  2780               pend = Z_ADDR;
  2781               stop = Z;
  2782             }
  2783 
  2784           if (ASCII_CHAR_P (*p))
  2785             p++, pos++;
  2786           else if (EQ (flag, Qt)
  2787                    && 0 < (bytes = multibyte_length (p, pend, true, false)))
  2788             p += bytes, pos += bytes;
  2789           else
  2790             {
  2791               unsigned char tmp[MAX_MULTIBYTE_LENGTH];
  2792               int c;
  2793 
  2794               c = BYTE8_TO_CHAR (*p);
  2795               bytes = CHAR_STRING (c, tmp);
  2796               *p = tmp[0];
  2797               TEMP_SET_PT_BOTH (pos + 1, pos + 1);
  2798               bytes--;
  2799               insert_1_both ((char *) tmp + 1, bytes, bytes, 1, 0, 0);
  2800               /* Now the gap is after the just inserted data.  */
  2801               pos = GPT;
  2802               p = GAP_END_ADDR;
  2803               if (pos <= begv)
  2804                 begv += bytes;
  2805               if (pos <= zv)
  2806                 zv += bytes;
  2807               if (pos <= pt)
  2808                 pt += bytes;
  2809               pend = Z_ADDR;
  2810               stop = Z;
  2811             }
  2812         }
  2813 
  2814       if (pt != PT)
  2815         TEMP_SET_PT (pt);
  2816 
  2817       /* Do this first, so that chars_in_text asks the right question.
  2818          set_intervals_multibyte needs it too.  */
  2819       bset_enable_multibyte_characters (current_buffer, Qt);
  2820 
  2821       GPT_BYTE = advance_to_char_boundary (GPT_BYTE);
  2822       GPT = chars_in_text (BEG_ADDR, GPT_BYTE - BEG_BYTE) + BEG;
  2823 
  2824       Z = chars_in_text (GAP_END_ADDR, Z_BYTE - GPT_BYTE) + GPT;
  2825 
  2826       BEGV_BYTE = advance_to_char_boundary (BEGV_BYTE);
  2827       if (BEGV_BYTE > GPT_BYTE)
  2828         BEGV = chars_in_text (GAP_END_ADDR, BEGV_BYTE - GPT_BYTE) + GPT;
  2829       else
  2830         BEGV = chars_in_text (BEG_ADDR, BEGV_BYTE - BEG_BYTE) + BEG;
  2831 
  2832       ZV_BYTE = advance_to_char_boundary (ZV_BYTE);
  2833       if (ZV_BYTE > GPT_BYTE)
  2834         ZV = chars_in_text (GAP_END_ADDR, ZV_BYTE - GPT_BYTE) + GPT;
  2835       else
  2836         ZV = chars_in_text (BEG_ADDR, ZV_BYTE - BEG_BYTE) + BEG;
  2837 
  2838       {
  2839         ptrdiff_t byte = advance_to_char_boundary (PT_BYTE);
  2840         ptrdiff_t position;
  2841 
  2842         if (byte > GPT_BYTE)
  2843           position = chars_in_text (GAP_END_ADDR, byte - GPT_BYTE) + GPT;
  2844         else
  2845           position = chars_in_text (BEG_ADDR, byte - BEG_BYTE) + BEG;
  2846         TEMP_SET_PT_BOTH (position, byte);
  2847       }
  2848 
  2849       tail = markers = BUF_MARKERS (current_buffer);
  2850 
  2851       /* This prevents BYTE_TO_CHAR (that is, buf_bytepos_to_charpos) from
  2852          getting confused by the markers that have not yet been updated.
  2853          It is also a signal that it should never create a marker.  */
  2854       BUF_MARKERS (current_buffer) = NULL;
  2855 
  2856       for (; tail; tail = tail->next)
  2857         {
  2858           tail->bytepos = advance_to_char_boundary (tail->bytepos);
  2859           tail->charpos = BYTE_TO_CHAR (tail->bytepos);
  2860         }
  2861 
  2862       /* Make sure no markers were put on the chain
  2863          while the chain value was incorrect.  */
  2864       if (BUF_MARKERS (current_buffer))
  2865         emacs_abort ();
  2866 
  2867       BUF_MARKERS (current_buffer) = markers;
  2868 
  2869       /* Do this last, so it can calculate the new correspondences
  2870          between chars and bytes.  */
  2871       /* FIXME: Is it worth the trouble, really?  Couldn't we just throw
  2872          away all the text-properties instead of trying to guess how
  2873          to adjust them?  AFAICT the result is not reliable anyway.  */
  2874       set_intervals_multibyte (true);
  2875       set_overlays_multibyte (true);
  2876     }
  2877 
  2878   if (!EQ (old_undo, Qt))
  2879     {
  2880       /* Represent all the above changes by a special undo entry.  */
  2881       bset_undo_list (current_buffer,
  2882                       Fcons (list3 (Qapply,
  2883                                     intern ("set-buffer-multibyte"),
  2884                                     NILP (flag) ? Qt : Qnil),
  2885                              old_undo));
  2886     }
  2887 
  2888   current_buffer->prevent_redisplay_optimizations_p = 1;
  2889 
  2890   /* If buffer is shown in a window, let redisplay consider other windows.  */
  2891   if (buffer_window_count (current_buffer))
  2892     windows_or_buffers_changed = 10;
  2893 
  2894   /* Copy this buffer's new multibyte status
  2895      into all of its indirect buffers.  */
  2896   FOR_EACH_LIVE_BUFFER (btail, other)
  2897     {
  2898       struct buffer *o = XBUFFER (other);
  2899       if (o->base_buffer == current_buffer && BUFFER_LIVE_P (o))
  2900         {
  2901           BVAR (o, enable_multibyte_characters)
  2902             = BVAR (current_buffer, enable_multibyte_characters);
  2903           o->prevent_redisplay_optimizations_p = true;
  2904         }
  2905     }
  2906 
  2907   /* Restore the modifiedness of the buffer.  */
  2908   if (!modified_p && !NILP (Fbuffer_modified_p (Qnil)))
  2909     Fset_buffer_modified_p (Qnil);
  2910 
  2911   /* Update coding systems of this buffer's process (if any).  */
  2912   {
  2913     Lisp_Object process;
  2914 
  2915     process = Fget_buffer_process (Fcurrent_buffer ());
  2916     if (PROCESSP (process))
  2917       setup_process_coding_systems (process);
  2918   }
  2919 
  2920   return flag;
  2921 }
  2922 
  2923 DEFUN ("kill-all-local-variables", Fkill_all_local_variables,
  2924        Skill_all_local_variables, 0, 1, 0,
  2925        doc: /* Switch to Fundamental mode by killing current buffer's local variables.
  2926 Most local variable bindings are eliminated so that the default values
  2927 become effective once more.  Also, the syntax table is set from
  2928 `standard-syntax-table', the local keymap is set to nil,
  2929 and the abbrev table from `fundamental-mode-abbrev-table'.
  2930 This function also forces redisplay of the mode line.
  2931 
  2932 Every function to select a new major mode starts by
  2933 calling this function.
  2934 
  2935 As a special exception, local variables whose names have a non-nil
  2936 `permanent-local' property are not eliminated by this function.  If
  2937 the optional KILL-PERMANENT argument is non-nil, clear out these local
  2938 variables, too.
  2939 
  2940 The first thing this function does is run
  2941 the normal hook `change-major-mode-hook'.  */)
  2942   (Lisp_Object kill_permanent)
  2943 {
  2944   run_hook (Qchange_major_mode_hook);
  2945 
  2946   /* Actually eliminate all local bindings of this buffer.  */
  2947 
  2948   reset_buffer_local_variables (current_buffer, !NILP (kill_permanent));
  2949 
  2950   /* Force mode-line redisplay.  Useful here because all major mode
  2951      commands call this function.  */
  2952   bset_update_mode_line (current_buffer);
  2953 
  2954   return Qnil;
  2955 }
  2956 
  2957 
  2958 /* Find all the overlays in the current buffer that overlap the range
  2959    [BEG, END).
  2960 
  2961    If EMPTY is true, include empty overlays in that range and also at
  2962    END, provided END denotes the position at the end of the accessible
  2963    part of the buffer.
  2964 
  2965    If TRAILING is true, include overlays that begin at END, provided
  2966    END denotes the position at the end of the accessible part of the
  2967    buffer.
  2968 
  2969    Return the number found, and store them in a vector in *VEC_PTR.
  2970    Store in *LEN_PTR the size allocated for the vector.
  2971    Store in *NEXT_PTR the next position after POS where an overlay starts,
  2972      or ZV if there are no more overlays.
  2973    NEXT_PTR may be 0, meaning don't store that info.
  2974 
  2975    *VEC_PTR and *LEN_PTR should contain a valid vector and size
  2976    when this function is called.
  2977 
  2978    If EXTEND, make the vector bigger if necessary.  If not, never
  2979    extend the vector, and store only as many overlays as will fit.
  2980    But still return the total number of overlays.
  2981 */
  2982 
  2983 ptrdiff_t
  2984 overlays_in (ptrdiff_t beg, ptrdiff_t end, bool extend,
  2985              Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
  2986              bool empty, bool trailing,
  2987              ptrdiff_t *next_ptr)
  2988 {
  2989   ptrdiff_t idx = 0;
  2990   ptrdiff_t len = *len_ptr;
  2991   ptrdiff_t next = ZV;
  2992   Lisp_Object *vec = *vec_ptr;
  2993   struct itree_node *node;
  2994 
  2995   /* Extend the search range if overlays beginning at ZV are
  2996      wanted.  */
  2997   ptrdiff_t search_end = ZV;
  2998   if (end >= ZV && (empty || trailing))
  2999     ++search_end;
  3000 
  3001   ITREE_FOREACH (node, current_buffer->overlays, beg, search_end,
  3002                  ASCENDING)
  3003     {
  3004       if (node->begin > end)
  3005         {
  3006           next = min (next, node->begin);
  3007           break;
  3008         }
  3009       else if (node->begin == end)
  3010         {
  3011           next = node->begin;
  3012           if ((! empty || end < ZV) && beg < end)
  3013             break;
  3014           if (empty && node->begin != node->end)
  3015             continue;
  3016         }
  3017 
  3018       if (! empty && node->begin == node->end)
  3019         continue;
  3020 
  3021       if (extend && idx == len)
  3022         {
  3023           vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
  3024                          sizeof *vec);
  3025           *vec_ptr = vec;
  3026           len = *len_ptr;
  3027         }
  3028       if (idx < len)
  3029         vec[idx] = node->data;
  3030       /* Keep counting overlays even if we can't return them all.  */
  3031       idx++;
  3032     }
  3033   if (next_ptr)
  3034     *next_ptr = next ? next : ZV;
  3035 
  3036   return idx;
  3037 }
  3038 
  3039 /* Find all non-empty overlays in the current buffer that contain
  3040    position POS.
  3041 
  3042    See overlays_in for the meaning of the arguments.
  3043   */
  3044 
  3045 ptrdiff_t
  3046 overlays_at (ptrdiff_t pos, bool extend,
  3047              Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
  3048              ptrdiff_t *next_ptr)
  3049 {
  3050   return overlays_in (pos, pos + 1, extend, vec_ptr, len_ptr,
  3051                       false, true, next_ptr);
  3052 }
  3053 
  3054 ptrdiff_t
  3055 next_overlay_change (ptrdiff_t pos)
  3056 {
  3057   ptrdiff_t next = ZV;
  3058   struct itree_node *node;
  3059 
  3060   ITREE_FOREACH (node, current_buffer->overlays, pos, next, ASCENDING)
  3061     {
  3062       if (node->begin > pos)
  3063         {
  3064           /* If we reach this branch, node->begin must be the least upper bound
  3065              of pos, because the search is limited to [pos,next) . */
  3066           eassert (node->begin < next);
  3067           next = node->begin;
  3068           break;
  3069         }
  3070       else if (node->begin < node->end && node->end < next)
  3071         {
  3072           next = node->end;
  3073           ITREE_FOREACH_NARROW (pos, next);
  3074         }
  3075     }
  3076 
  3077   return next;
  3078 }
  3079 
  3080 ptrdiff_t
  3081 previous_overlay_change (ptrdiff_t pos)
  3082 {
  3083   struct itree_node *node;
  3084   ptrdiff_t prev = BEGV;
  3085 
  3086   ITREE_FOREACH (node, current_buffer->overlays, prev, pos, DESCENDING)
  3087     {
  3088       if (node->end < pos)
  3089         prev = node->end;
  3090       else
  3091         prev = max (prev, node->begin);
  3092       ITREE_FOREACH_NARROW (prev, pos);
  3093     }
  3094 
  3095   return prev;
  3096 }
  3097 
  3098 /* Return true if there exists an overlay with a non-nil
  3099    `mouse-face' property overlapping OVERLAY.  */
  3100 
  3101 bool
  3102 mouse_face_overlay_overlaps (Lisp_Object overlay)
  3103 {
  3104   ptrdiff_t start = OVERLAY_START (overlay);
  3105   ptrdiff_t end = OVERLAY_END (overlay);
  3106   ptrdiff_t n, i, size;
  3107   Lisp_Object *v, tem;
  3108   Lisp_Object vbuf[10];
  3109   USE_SAFE_ALLOCA;
  3110 
  3111   size = ARRAYELTS (vbuf);
  3112   v = vbuf;
  3113   n = overlays_in (start, end, 0, &v, &size, true, false, NULL);
  3114   if (n > size)
  3115     {
  3116       SAFE_NALLOCA (v, 1, n);
  3117       overlays_in (start, end, 0, &v, &n, true, false, NULL);
  3118     }
  3119 
  3120   for (i = 0; i < n; ++i)
  3121     if (!EQ (v[i], overlay)
  3122         && (tem = Foverlay_get (overlay, Qmouse_face),
  3123             !NILP (tem)))
  3124       break;
  3125 
  3126   SAFE_FREE ();
  3127   return i < n;
  3128 }
  3129 
  3130 /* Return the value of the 'display-line-numbers-disable' property at
  3131    EOB, if there's an overlay at ZV with a non-nil value of that property.  */
  3132 Lisp_Object
  3133 disable_line_numbers_overlay_at_eob (void)
  3134 {
  3135   ptrdiff_t n, i, size;
  3136   Lisp_Object *v, tem = Qnil;
  3137   Lisp_Object vbuf[10];
  3138   USE_SAFE_ALLOCA;
  3139 
  3140   size = ARRAYELTS (vbuf);
  3141   v = vbuf;
  3142   n = overlays_in (ZV, ZV, 0, &v, &size, false, false, NULL);
  3143   if (n > size)
  3144     {
  3145       SAFE_NALLOCA (v, 1, n);
  3146       overlays_in (ZV, ZV, 0, &v, &n, false, false, NULL);
  3147     }
  3148 
  3149   for (i = 0; i < n; ++i)
  3150     if ((tem = Foverlay_get (v[i], Qdisplay_line_numbers_disable),
  3151          !NILP (tem)))
  3152       break;
  3153 
  3154   SAFE_FREE ();
  3155   return tem;
  3156 }
  3157 
  3158 
  3159 /* Fast function to just test if we're at an overlay boundary.
  3160 
  3161    Returns true if some overlay starts or ends (or both) at POS,
  3162 */
  3163 bool
  3164 overlay_touches_p (ptrdiff_t pos)
  3165 {
  3166   struct itree_node *node;
  3167 
  3168   /* We need to find overlays ending in pos, as well as empty ones at
  3169      pos. */
  3170   ITREE_FOREACH (node, current_buffer->overlays, pos - 1, pos + 1, DESCENDING)
  3171     if (node->begin == pos || node->end == pos)
  3172       return true;
  3173   return false;
  3174 }
  3175 
  3176 
  3177 int
  3178 compare_overlays (const void *v1, const void *v2)
  3179 {
  3180   const struct sortvec *s1 = v1;
  3181   const struct sortvec *s2 = v2;
  3182   /* Return 1 if s1 should take precedence, -1 if v2 should take precedence,
  3183      and 0 if they're equal.  */
  3184   if (s1->priority != s2->priority)
  3185     return s1->priority < s2->priority ? -1 : 1;
  3186   /* If the priority is equal, give precedence to the one not covered by the
  3187      other.  If neither covers the other, obey spriority.  */
  3188   else if (s1->beg < s2->beg)
  3189     return (s1->end < s2->end && s1->spriority > s2->spriority ? 1 : -1);
  3190   else if (s1->beg > s2->beg)
  3191     return (s1->end > s2->end && s1->spriority < s2->spriority ? -1 : 1);
  3192   else if (s1->end != s2->end)
  3193     return s2->end < s1->end ? -1 : 1;
  3194   else if (s1->spriority != s2->spriority)
  3195     return (s1->spriority < s2->spriority ? -1 : 1);
  3196   else if (EQ (s1->overlay, s2->overlay))
  3197     return 0;
  3198   else
  3199     /* Avoid the non-determinism of qsort by choosing an arbitrary ordering
  3200        between "equal" overlays.  The result can still change between
  3201        invocations of Emacs, but it won't change in the middle of
  3202        `find_field' (bug#6830).  */
  3203     return XLI (s1->overlay) < XLI (s2->overlay) ? -1 : 1;
  3204 }
  3205 
  3206 void
  3207 make_sortvec_item (struct sortvec *item, Lisp_Object overlay)
  3208 {
  3209   Lisp_Object tem;
  3210   /* This overlay is good and counts: put it into sortvec.  */
  3211   item->overlay = overlay;
  3212   item->beg = OVERLAY_START (overlay);
  3213   item->end = OVERLAY_END (overlay);
  3214   tem = Foverlay_get (overlay, Qpriority);
  3215   if (NILP (tem))
  3216     {
  3217       item->priority = 0;
  3218       item->spriority = 0;
  3219     }
  3220   else if (FIXNUMP (tem))
  3221     {
  3222       item->priority = XFIXNUM (tem);
  3223       item->spriority = 0;
  3224     }
  3225   else if (CONSP (tem))
  3226     {
  3227       Lisp_Object car = XCAR (tem);
  3228       Lisp_Object cdr = XCDR (tem);
  3229       item->priority  = FIXNUMP (car) ? XFIXNUM (car) : 0;
  3230       item->spriority = FIXNUMP (cdr) ? XFIXNUM (cdr) : 0;
  3231     }
  3232 }
  3233 /* Sort an array of overlays by priority.  The array is modified in place.
  3234    The return value is the new size; this may be smaller than the original
  3235    size if some of the overlays were invalid or were window-specific.  */
  3236 ptrdiff_t
  3237 sort_overlays (Lisp_Object *overlay_vec, ptrdiff_t noverlays, struct window *w)
  3238 {
  3239   ptrdiff_t i, j;
  3240   USE_SAFE_ALLOCA;
  3241   struct sortvec *sortvec;
  3242 
  3243   SAFE_NALLOCA (sortvec, 1, noverlays);
  3244 
  3245   /* Put the valid and relevant overlays into sortvec.  */
  3246 
  3247   for (i = 0, j = 0; i < noverlays; i++)
  3248     {
  3249       Lisp_Object overlay;
  3250 
  3251       overlay = overlay_vec[i];
  3252       if (OVERLAYP (overlay)
  3253           && OVERLAY_START (overlay) > 0
  3254           && OVERLAY_END (overlay) > 0)
  3255         {
  3256           /* If we're interested in a specific window, then ignore
  3257              overlays that are limited to some other window.  */
  3258           if (w && ! overlay_matches_window (w, overlay))
  3259             continue;
  3260           make_sortvec_item (sortvec + j, overlay);
  3261           j++;
  3262         }
  3263     }
  3264   noverlays = j;
  3265 
  3266   /* Sort the overlays into the proper order: increasing priority.  */
  3267 
  3268   if (noverlays > 1)
  3269     qsort (sortvec, noverlays, sizeof (struct sortvec), compare_overlays);
  3270 
  3271   for (i = 0; i < noverlays; i++)
  3272     overlay_vec[i] = sortvec[i].overlay;
  3273 
  3274   SAFE_FREE ();
  3275   return (noverlays);
  3276 }
  3277 
  3278 struct sortstr
  3279 {
  3280   Lisp_Object string, string2;
  3281   ptrdiff_t size;
  3282   EMACS_INT priority;
  3283 };
  3284 
  3285 struct sortstrlist
  3286 {
  3287   struct sortstr *buf;  /* An array that expands as needed; never freed.  */
  3288   ptrdiff_t size;       /* Allocated length of that array.  */
  3289   ptrdiff_t used;       /* How much of the array is currently in use.  */
  3290   ptrdiff_t bytes;      /* Total length of the strings in buf.  */
  3291 };
  3292 
  3293 /* Buffers for storing information about the overlays touching a given
  3294    position.  These could be automatic variables in overlay_strings, but
  3295    it's more efficient to hold onto the memory instead of repeatedly
  3296    allocating and freeing it.  */
  3297 static struct sortstrlist overlay_heads, overlay_tails;
  3298 static unsigned char *overlay_str_buf;
  3299 
  3300 /* Allocated length of overlay_str_buf.  */
  3301 static ptrdiff_t overlay_str_len;
  3302 
  3303 /* A comparison function suitable for passing to qsort.  */
  3304 static int
  3305 cmp_for_strings (const void *as1, const void *as2)
  3306 {
  3307   struct sortstr const *s1 = as1;
  3308   struct sortstr const *s2 = as2;
  3309   if (s1->size != s2->size)
  3310     return s2->size < s1->size ? -1 : 1;
  3311   if (s1->priority != s2->priority)
  3312     return s1->priority < s2->priority ? -1 : 1;
  3313   return 0;
  3314 }
  3315 
  3316 static void
  3317 record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
  3318                        Lisp_Object str2, Lisp_Object pri, ptrdiff_t size)
  3319 {
  3320   ptrdiff_t nbytes;
  3321 
  3322   if (ssl->used == ssl->size)
  3323     ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
  3324   ssl->buf[ssl->used].string = str;
  3325   ssl->buf[ssl->used].string2 = str2;
  3326   ssl->buf[ssl->used].size = size;
  3327   ssl->buf[ssl->used].priority = (FIXNUMP (pri) ? XFIXNUM (pri) : 0);
  3328   ssl->used++;
  3329 
  3330   if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
  3331     nbytes = SCHARS (str);
  3332   else if (! STRING_MULTIBYTE (str))
  3333     nbytes = count_size_as_multibyte (SDATA (str),
  3334                                       SBYTES (str));
  3335   else
  3336     nbytes = SBYTES (str);
  3337 
  3338   if (INT_ADD_WRAPV (ssl->bytes, nbytes, &nbytes))
  3339     memory_full (SIZE_MAX);
  3340   ssl->bytes = nbytes;
  3341 
  3342   if (STRINGP (str2))
  3343     {
  3344       if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
  3345         nbytes = SCHARS (str2);
  3346       else if (! STRING_MULTIBYTE (str2))
  3347         nbytes = count_size_as_multibyte (SDATA (str2),
  3348                                           SBYTES (str2));
  3349       else
  3350         nbytes = SBYTES (str2);
  3351 
  3352       if (INT_ADD_WRAPV (ssl->bytes, nbytes, &nbytes))
  3353         memory_full (SIZE_MAX);
  3354       ssl->bytes = nbytes;
  3355     }
  3356 }
  3357 
  3358 /* Concatenate the strings associated with overlays that begin or end
  3359    at POS, ignoring overlays that are specific to windows other than W.
  3360    The strings are concatenated in the appropriate order: shorter
  3361    overlays nest inside longer ones, and higher priority inside lower.
  3362    Normally all of the after-strings come first, but zero-sized
  3363    overlays have their after-strings ride along with the
  3364    before-strings because it would look strange to print them
  3365    inside-out.
  3366 
  3367    Returns the concatenated string's length, and return the pointer to
  3368    that string via PSTR, if that variable is non-NULL.  The storage of
  3369    the concatenated strings may be overwritten by subsequent calls.  */
  3370 
  3371 ptrdiff_t
  3372 overlay_strings (ptrdiff_t pos, struct window *w, unsigned char **pstr)
  3373 {
  3374   bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
  3375   struct itree_node *node;
  3376 
  3377   overlay_heads.used = overlay_heads.bytes = 0;
  3378   overlay_tails.used = overlay_tails.bytes = 0;
  3379 
  3380   ITREE_FOREACH (node, current_buffer->overlays, pos - 1, pos + 1, DESCENDING)
  3381     {
  3382       Lisp_Object overlay = node->data;
  3383       eassert (OVERLAYP (overlay));
  3384 
  3385       ptrdiff_t startpos = node->begin;
  3386       ptrdiff_t endpos = node->end;
  3387 
  3388       if (endpos != pos && startpos != pos)
  3389         continue;
  3390       Lisp_Object window = Foverlay_get (overlay, Qwindow);
  3391       if (WINDOWP (window) && XWINDOW (window) != w)
  3392         continue;
  3393       Lisp_Object str;
  3394       /* FIXME: Are we really sure that `record_overlay_string` can
  3395          never cause a non-local exit?  */
  3396       if (startpos == pos
  3397           && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
  3398         record_overlay_string (&overlay_heads, str,
  3399                                (startpos == endpos
  3400                                 ? Foverlay_get (overlay, Qafter_string)
  3401                                 : Qnil),
  3402                                Foverlay_get (overlay, Qpriority),
  3403                                endpos - startpos);
  3404       else if (endpos == pos
  3405           && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
  3406         record_overlay_string (&overlay_tails, str, Qnil,
  3407                                Foverlay_get (overlay, Qpriority),
  3408                                endpos - startpos);
  3409     }
  3410 
  3411   if (overlay_tails.used > 1)
  3412     qsort (overlay_tails.buf, overlay_tails.used, sizeof (struct sortstr),
  3413            cmp_for_strings);
  3414   if (overlay_heads.used > 1)
  3415     qsort (overlay_heads.buf, overlay_heads.used, sizeof (struct sortstr),
  3416            cmp_for_strings);
  3417   if (overlay_heads.bytes || overlay_tails.bytes)
  3418     {
  3419       Lisp_Object tem;
  3420       ptrdiff_t i;
  3421       unsigned char *p;
  3422       ptrdiff_t total;
  3423 
  3424       if (INT_ADD_WRAPV (overlay_heads.bytes, overlay_tails.bytes, &total))
  3425         memory_full (SIZE_MAX);
  3426       if (total > overlay_str_len)
  3427         overlay_str_buf = xpalloc (overlay_str_buf, &overlay_str_len,
  3428                                    total - overlay_str_len, -1, 1);
  3429 
  3430       p = overlay_str_buf;
  3431       for (i = overlay_tails.used; --i >= 0;)
  3432         {
  3433           ptrdiff_t nbytes;
  3434           tem = overlay_tails.buf[i].string;
  3435           nbytes = copy_text (SDATA (tem), p,
  3436                               SBYTES (tem),
  3437                               STRING_MULTIBYTE (tem), multibyte);
  3438           p += nbytes;
  3439         }
  3440       for (i = 0; i < overlay_heads.used; ++i)
  3441         {
  3442           ptrdiff_t nbytes;
  3443           tem = overlay_heads.buf[i].string;
  3444           nbytes = copy_text (SDATA (tem), p,
  3445                               SBYTES (tem),
  3446                               STRING_MULTIBYTE (tem), multibyte);
  3447           p += nbytes;
  3448           tem = overlay_heads.buf[i].string2;
  3449           if (STRINGP (tem))
  3450             {
  3451               nbytes = copy_text (SDATA (tem), p,
  3452                                   SBYTES (tem),
  3453                                   STRING_MULTIBYTE (tem), multibyte);
  3454               p += nbytes;
  3455             }
  3456         }
  3457       if (p != overlay_str_buf + total)
  3458         emacs_abort ();
  3459       if (pstr)
  3460         *pstr = overlay_str_buf;
  3461       return total;
  3462     }
  3463   return 0;
  3464 }
  3465 
  3466 
  3467 void
  3468 adjust_overlays_for_insert (ptrdiff_t pos, ptrdiff_t length, bool before_markers)
  3469 {
  3470   if (!current_buffer->indirections)
  3471     itree_insert_gap (current_buffer->overlays, pos, length, before_markers);
  3472   else
  3473     {
  3474       struct buffer *base = current_buffer->base_buffer
  3475                             ? current_buffer->base_buffer
  3476                             : current_buffer;
  3477       Lisp_Object tail, other;
  3478       itree_insert_gap (base->overlays, pos, length, before_markers);
  3479       FOR_EACH_LIVE_BUFFER (tail, other)
  3480         if (XBUFFER (other)->base_buffer == base)
  3481           itree_insert_gap (XBUFFER (other)->overlays, pos, length,
  3482                             before_markers);
  3483     }
  3484 }
  3485 
  3486 static void
  3487 adjust_overlays_for_delete_in_buffer (struct buffer * buf,
  3488                                       ptrdiff_t pos, ptrdiff_t length)
  3489 {
  3490   Lisp_Object hit_list = Qnil;
  3491   struct itree_node *node;
  3492 
  3493   /* Ideally, the evaporate check would be done directly within
  3494      `itree_delete_gap`, but that code isn't supposed to know about overlays,
  3495      only about `itree_node`s, so it would break an abstraction boundary.  */
  3496   itree_delete_gap (buf->overlays, pos, length);
  3497 
  3498   /* Delete any zero-sized overlays at position POS, if the `evaporate'
  3499      property is set.  */
  3500 
  3501   ITREE_FOREACH (node, buf->overlays, pos, pos, ASCENDING)
  3502     {
  3503       if (node->end == pos && node->begin == pos
  3504           && ! NILP (Foverlay_get (node->data, Qevaporate)))
  3505         hit_list = Fcons (node->data, hit_list);
  3506     }
  3507 
  3508   for (; CONSP (hit_list); hit_list = XCDR (hit_list))
  3509     Fdelete_overlay (XCAR (hit_list));
  3510 }
  3511 
  3512 void
  3513 adjust_overlays_for_delete (ptrdiff_t pos, ptrdiff_t length)
  3514 {
  3515   if (!current_buffer->indirections)
  3516     adjust_overlays_for_delete_in_buffer (current_buffer, pos, length);
  3517   else
  3518     {
  3519       struct buffer *base = current_buffer->base_buffer
  3520                             ? current_buffer->base_buffer
  3521                             : current_buffer;
  3522       Lisp_Object tail, other;
  3523       adjust_overlays_for_delete_in_buffer (base, pos, length);
  3524       FOR_EACH_LIVE_BUFFER (tail, other)
  3525         if (XBUFFER (other)->base_buffer == base)
  3526           adjust_overlays_for_delete_in_buffer (XBUFFER (other), pos, length);
  3527     }
  3528 }
  3529 
  3530 
  3531 DEFUN ("overlayp", Foverlayp, Soverlayp, 1, 1, 0,
  3532        doc: /* Return t if OBJECT is an overlay.  */)
  3533   (Lisp_Object object)
  3534 {
  3535   return (OVERLAYP (object) ? Qt : Qnil);
  3536 }
  3537 
  3538 DEFUN ("make-overlay", Fmake_overlay, Smake_overlay, 2, 5, 0,
  3539        doc: /* Create a new overlay with range BEG to END in BUFFER and return it.
  3540 If omitted, BUFFER defaults to the current buffer.
  3541 BEG and END may be integers or markers.
  3542 The fourth arg FRONT-ADVANCE, if non-nil, makes the marker
  3543 for the front of the overlay advance when text is inserted there
  3544 \(which means the text *is not* included in the overlay).
  3545 The fifth arg REAR-ADVANCE, if non-nil, makes the marker
  3546 for the rear of the overlay advance when text is inserted there
  3547 \(which means the text *is* included in the overlay).  */)
  3548   (Lisp_Object beg, Lisp_Object end, Lisp_Object buffer,
  3549    Lisp_Object front_advance, Lisp_Object rear_advance)
  3550 {
  3551   Lisp_Object ov;
  3552   struct buffer *b;
  3553 
  3554   if (NILP (buffer))
  3555     XSETBUFFER (buffer, current_buffer);
  3556   else
  3557     CHECK_BUFFER (buffer);
  3558 
  3559   b = XBUFFER (buffer);
  3560   if (! BUFFER_LIVE_P (b))
  3561     error ("Attempt to create overlay in a dead buffer");
  3562 
  3563   if (MARKERP (beg) && !BASE_EQ (Fmarker_buffer (beg), buffer))
  3564     signal_error ("Marker points into wrong buffer", beg);
  3565   if (MARKERP (end) && !BASE_EQ (Fmarker_buffer (end), buffer))
  3566     signal_error ("Marker points into wrong buffer", end);
  3567 
  3568   CHECK_FIXNUM_COERCE_MARKER (beg);
  3569   CHECK_FIXNUM_COERCE_MARKER (end);
  3570 
  3571   if (XFIXNUM (beg) > XFIXNUM (end))
  3572     {
  3573       Lisp_Object temp;
  3574       temp = beg; beg = end; end = temp;
  3575     }
  3576 
  3577   ptrdiff_t obeg = clip_to_bounds (BUF_BEG (b), XFIXNUM (beg), BUF_Z (b));
  3578   ptrdiff_t oend = clip_to_bounds (obeg, XFIXNUM (end), BUF_Z (b));
  3579   ov = build_overlay (! NILP (front_advance),
  3580                       ! NILP (rear_advance), Qnil);
  3581   add_buffer_overlay (b, XOVERLAY (ov), obeg, oend);
  3582 
  3583   /* We don't need to redisplay the region covered by the overlay, because
  3584      the overlay has no properties at the moment.  */
  3585 
  3586   return ov;
  3587 }
  3588 
  3589 /* Mark a section of BUF as needing redisplay because of overlays changes.  */
  3590 
  3591 static void
  3592 modify_overlay (struct buffer *buf, ptrdiff_t start, ptrdiff_t end)
  3593 {
  3594   if (start > end)
  3595     {
  3596       ptrdiff_t temp = start;
  3597       start = end;
  3598       end = temp;
  3599     }
  3600 
  3601   BUF_COMPUTE_UNCHANGED (buf, start, end);
  3602 
  3603   bset_redisplay (buf);
  3604 
  3605   modiff_incr (&BUF_OVERLAY_MODIFF (buf), 1);
  3606 }
  3607 
  3608 DEFUN ("move-overlay", Fmove_overlay, Smove_overlay, 3, 4, 0,
  3609        doc: /* Set the endpoints of OVERLAY to BEG and END in BUFFER.
  3610 If BUFFER is omitted, leave OVERLAY in the same buffer it inhabits now.
  3611 If BUFFER is omitted, and OVERLAY is in no buffer, put it in the current
  3612 buffer.  */)
  3613   (Lisp_Object overlay, Lisp_Object beg, Lisp_Object end, Lisp_Object buffer)
  3614 {
  3615   struct buffer *b, *ob = 0;
  3616   Lisp_Object obuffer;
  3617   specpdl_ref count = SPECPDL_INDEX ();
  3618   ptrdiff_t o_beg UNINIT, o_end UNINIT;
  3619 
  3620   CHECK_OVERLAY (overlay);
  3621   if (NILP (buffer))
  3622     buffer = Foverlay_buffer (overlay);
  3623   if (NILP (buffer))
  3624     XSETBUFFER (buffer, current_buffer);
  3625   CHECK_BUFFER (buffer);
  3626 
  3627   if (NILP (Fbuffer_live_p (buffer)))
  3628     error ("Attempt to move overlay to a dead buffer");
  3629 
  3630   if (MARKERP (beg) && !BASE_EQ (Fmarker_buffer (beg), buffer))
  3631     signal_error ("Marker points into wrong buffer", beg);
  3632   if (MARKERP (end) && !BASE_EQ (Fmarker_buffer (end), buffer))
  3633     signal_error ("Marker points into wrong buffer", end);
  3634 
  3635   CHECK_FIXNUM_COERCE_MARKER (beg);
  3636   CHECK_FIXNUM_COERCE_MARKER (end);
  3637 
  3638   if (XFIXNUM (beg) > XFIXNUM (end))
  3639     {
  3640       Lisp_Object temp;
  3641       temp = beg; beg = end; end = temp;
  3642     }
  3643 
  3644   specbind (Qinhibit_quit, Qt); /* FIXME: Why?  */
  3645 
  3646   obuffer = Foverlay_buffer (overlay);
  3647   b = XBUFFER (buffer);
  3648 
  3649   ptrdiff_t n_beg = clip_to_bounds (BUF_BEG (b), XFIXNUM (beg), BUF_Z (b));
  3650   ptrdiff_t n_end = clip_to_bounds (n_beg, XFIXNUM (end), BUF_Z (b));
  3651 
  3652   if (!NILP (obuffer))
  3653     {
  3654       ob = XBUFFER (obuffer);
  3655 
  3656       o_beg = OVERLAY_START (overlay);
  3657       o_end = OVERLAY_END (overlay);
  3658     }
  3659 
  3660   if (! BASE_EQ (buffer, obuffer))
  3661     {
  3662       if (! NILP (obuffer))
  3663         remove_buffer_overlay (XBUFFER (obuffer), XOVERLAY (overlay));
  3664       add_buffer_overlay (XBUFFER (buffer), XOVERLAY (overlay), n_beg, n_end);
  3665     }
  3666   else
  3667     itree_node_set_region (b->overlays, XOVERLAY (overlay)->interval,
  3668                               n_beg, n_end);
  3669 
  3670   /* If the overlay has changed buffers, do a thorough redisplay.  */
  3671   if (!BASE_EQ (buffer, obuffer))
  3672     {
  3673       /* Redisplay where the overlay was.  */
  3674       if (ob)
  3675         modify_overlay (ob, o_beg, o_end);
  3676 
  3677       /* Redisplay where the overlay is going to be.  */
  3678       modify_overlay (b, n_beg, n_end);
  3679     }
  3680   else
  3681     /* Redisplay the area the overlay has just left, or just enclosed.  */
  3682     {
  3683       if (o_beg == n_beg)
  3684         modify_overlay (b, o_end, n_end);
  3685       else if (o_end == n_end)
  3686         modify_overlay (b, o_beg, n_beg);
  3687       else
  3688         modify_overlay (b, min (o_beg, n_beg), max (o_end, n_end));
  3689     }
  3690 
  3691   /* Delete the overlay if it is empty after clipping and has the
  3692      evaporate property.  */
  3693   if (n_beg == n_end && !NILP (Foverlay_get (overlay, Qevaporate)))
  3694     { /* We used to call `Fdelete_overlay' here, but it causes problems:
  3695          - At this stage, `overlay' is not included in its buffer's lists
  3696            of overlays (the data-structure is in an inconsistent state),
  3697            contrary to `Fdelete_overlay's assumptions.
  3698          - Most of the work done by Fdelete_overlay has already been done
  3699            here for other reasons.  */
  3700       drop_overlay (XOVERLAY (overlay));
  3701       return unbind_to (count, overlay);
  3702     }
  3703 
  3704   return unbind_to (count, overlay);
  3705 }
  3706 
  3707 DEFUN ("delete-overlay", Fdelete_overlay, Sdelete_overlay, 1, 1, 0,
  3708        doc: /* Delete the overlay OVERLAY from its buffer.  */)
  3709   (Lisp_Object overlay)
  3710 {
  3711   struct buffer *b;
  3712   specpdl_ref count = SPECPDL_INDEX ();
  3713 
  3714   CHECK_OVERLAY (overlay);
  3715 
  3716   b = OVERLAY_BUFFER (overlay);
  3717   if (! b)
  3718     return Qnil;
  3719 
  3720   specbind (Qinhibit_quit, Qt);
  3721 
  3722   drop_overlay (XOVERLAY (overlay));
  3723 
  3724   /* When deleting an overlay with before or after strings, turn off
  3725      display optimizations for the affected buffer, on the basis that
  3726      these strings may contain newlines.  This is easier to do than to
  3727      check for that situation during redisplay.  */
  3728   if (!windows_or_buffers_changed
  3729       && (!NILP (Foverlay_get (overlay, Qbefore_string))
  3730           || !NILP (Foverlay_get (overlay, Qafter_string))))
  3731     b->prevent_redisplay_optimizations_p = 1;
  3732 
  3733   return unbind_to (count, Qnil);
  3734 }
  3735 
  3736 DEFUN ("delete-all-overlays", Fdelete_all_overlays, Sdelete_all_overlays, 0, 1, 0,
  3737        doc: /* Delete all overlays of BUFFER.
  3738 BUFFER omitted or nil means delete all overlays of the current
  3739 buffer.  */)
  3740   (Lisp_Object buffer)
  3741 {
  3742   delete_all_overlays (decode_buffer (buffer));
  3743   return Qnil;
  3744 }
  3745 
  3746 /* Overlay dissection functions.  */
  3747 
  3748 DEFUN ("overlay-start", Foverlay_start, Soverlay_start, 1, 1, 0,
  3749        doc: /* Return the position at which OVERLAY starts.  */)
  3750   (Lisp_Object overlay)
  3751 {
  3752   CHECK_OVERLAY (overlay);
  3753   if (! OVERLAY_BUFFER (overlay))
  3754     return Qnil;
  3755 
  3756   return make_fixnum (OVERLAY_START (overlay));
  3757 }
  3758 
  3759 DEFUN ("overlay-end", Foverlay_end, Soverlay_end, 1, 1, 0,
  3760        doc: /* Return the position at which OVERLAY ends.  */)
  3761   (Lisp_Object overlay)
  3762 {
  3763   CHECK_OVERLAY (overlay);
  3764   if (! OVERLAY_BUFFER (overlay))
  3765     return Qnil;
  3766 
  3767   return make_fixnum (OVERLAY_END (overlay));
  3768 }
  3769 
  3770 DEFUN ("overlay-buffer", Foverlay_buffer, Soverlay_buffer, 1, 1, 0,
  3771        doc: /* Return the buffer OVERLAY belongs to.
  3772 Return nil if OVERLAY has been deleted.  */)
  3773   (Lisp_Object overlay)
  3774 {
  3775   Lisp_Object buffer;
  3776 
  3777   CHECK_OVERLAY (overlay);
  3778 
  3779   if (! OVERLAY_BUFFER (overlay))
  3780     return Qnil;
  3781 
  3782   XSETBUFFER (buffer, OVERLAY_BUFFER (overlay));
  3783 
  3784   return buffer;
  3785 }
  3786 
  3787 DEFUN ("overlay-properties", Foverlay_properties, Soverlay_properties, 1, 1, 0,
  3788        doc: /* Return a list of the properties on OVERLAY.
  3789 This is a copy of OVERLAY's plist; modifying its conses has no effect on
  3790 OVERLAY.  */)
  3791   (Lisp_Object overlay)
  3792 {
  3793   CHECK_OVERLAY (overlay);
  3794 
  3795   return Fcopy_sequence (OVERLAY_PLIST (overlay));
  3796 }
  3797 
  3798 
  3799 DEFUN ("overlays-at", Foverlays_at, Soverlays_at, 1, 2, 0,
  3800        doc: /* Return a list of the overlays that contain the character at POS.
  3801 If SORTED is non-nil, then sort them by decreasing priority.
  3802 
  3803 Zero-length overlays that start and stop at POS are not included in
  3804 the return value.  Instead use `overlays-in' if those overlays are of
  3805 interest.  */)
  3806   (Lisp_Object pos, Lisp_Object sorted)
  3807 {
  3808   ptrdiff_t len, noverlays;
  3809   Lisp_Object *overlay_vec;
  3810   Lisp_Object result;
  3811 
  3812   CHECK_FIXNUM_COERCE_MARKER (pos);
  3813 
  3814   if (!buffer_has_overlays ())
  3815     return Qnil;
  3816 
  3817   len = 10;
  3818   /* We can't use alloca here because overlays_at can call xrealloc.  */
  3819   overlay_vec = xmalloc (len * sizeof *overlay_vec);
  3820 
  3821   /* Put all the overlays we want in a vector in overlay_vec.
  3822      Store the length in len.  */
  3823   noverlays = overlays_at (XFIXNUM (pos), true, &overlay_vec, &len, NULL);
  3824 
  3825   if (!NILP (sorted))
  3826     noverlays = sort_overlays (overlay_vec, noverlays,
  3827                                WINDOWP (sorted) ? XWINDOW (sorted) : NULL);
  3828 
  3829   /* Make a list of them all.  */
  3830   result = Flist (noverlays, overlay_vec);
  3831 
  3832   /* The doc string says the list should be in decreasing order of
  3833      priority, so we reverse the list, because sort_overlays sorts in
  3834      the increasing order of priority.  */
  3835   if (!NILP (sorted))
  3836     result = Fnreverse (result);
  3837 
  3838   xfree (overlay_vec);
  3839   return result;
  3840 }
  3841 
  3842 DEFUN ("overlays-in", Foverlays_in, Soverlays_in, 2, 2, 0,
  3843        doc: /* Return a list of the overlays that overlap the region BEG ... END.
  3844 Overlap means that at least one character is contained within the overlay
  3845 and also contained within the specified region.
  3846 
  3847 Empty overlays are included in the result if they are located at BEG,
  3848 between BEG and END, or at END provided END denotes the position at the
  3849 end of the accessible part of the buffer.
  3850 
  3851 The resulting list of overlays is in an arbitrary unpredictable order.  */)
  3852   (Lisp_Object beg, Lisp_Object end)
  3853 {
  3854   ptrdiff_t len, noverlays;
  3855   Lisp_Object *overlay_vec;
  3856   Lisp_Object result;
  3857 
  3858   CHECK_FIXNUM_COERCE_MARKER (beg);
  3859   CHECK_FIXNUM_COERCE_MARKER (end);
  3860 
  3861   if (!buffer_has_overlays ())
  3862     return Qnil;
  3863 
  3864   len = 10;
  3865   overlay_vec = xmalloc (len * sizeof *overlay_vec);
  3866 
  3867   /* Put all the overlays we want in a vector in overlay_vec.
  3868      Store the length in len.  */
  3869   noverlays = overlays_in (XFIXNUM (beg), XFIXNUM (end), 1, &overlay_vec, &len,
  3870                            true, false, NULL);
  3871 
  3872   /* Make a list of them all.  */
  3873   result = Flist (noverlays, overlay_vec);
  3874 
  3875   xfree (overlay_vec);
  3876   return result;
  3877 }
  3878 
  3879 DEFUN ("next-overlay-change", Fnext_overlay_change, Snext_overlay_change,
  3880        1, 1, 0,
  3881        doc: /* Return the next position after POS where an overlay starts or ends.
  3882 If there are no overlay boundaries from POS to (point-max),
  3883 the value is (point-max).  */)
  3884   (Lisp_Object pos)
  3885 {
  3886   CHECK_FIXNUM_COERCE_MARKER (pos);
  3887 
  3888   if (!buffer_has_overlays ())
  3889     return make_fixnum (ZV);
  3890 
  3891   return make_fixnum (next_overlay_change (XFIXNUM (pos)));
  3892 }
  3893 
  3894 DEFUN ("previous-overlay-change", Fprevious_overlay_change,
  3895        Sprevious_overlay_change, 1, 1, 0,
  3896        doc: /* Return the previous position before POS where an overlay starts or ends.
  3897 If there are no overlay boundaries from (point-min) to POS,
  3898 the value is (point-min).  */)
  3899   (Lisp_Object pos)
  3900 {
  3901 
  3902   CHECK_FIXNUM_COERCE_MARKER (pos);
  3903 
  3904   if (!buffer_has_overlays ())
  3905     return make_fixnum (BEGV);
  3906 
  3907   return make_fixnum (previous_overlay_change (XFIXNUM (pos)));
  3908 }
  3909 
  3910 
  3911 /* These functions are for debugging overlays.  */
  3912 
  3913 DEFUN ("overlay-lists", Foverlay_lists, Soverlay_lists, 0, 0, 0,
  3914        doc: /* Return a list giving all the overlays of the current buffer.
  3915 
  3916 For backward compatibility, the value is actually a list that
  3917 holds another list; the overlays are in the inner list.
  3918 The list you get is a copy, so that changing it has no effect.
  3919 However, the overlays you get are the real objects that the buffer uses. */)
  3920   (void)
  3921 {
  3922   Lisp_Object overlays = Qnil;
  3923   struct itree_node *node;
  3924 
  3925   ITREE_FOREACH (node, current_buffer->overlays, BEG, Z, DESCENDING)
  3926     overlays = Fcons (node->data, overlays);
  3927 
  3928   return Fcons (overlays, Qnil);
  3929 }
  3930 
  3931 DEFUN ("overlay-recenter", Foverlay_recenter, Soverlay_recenter, 1, 1, 0,
  3932        doc: /* Recenter the overlays of the current buffer around position POS.
  3933 That makes overlay lookup faster for positions near POS (but perhaps slower
  3934 for positions far away from POS).
  3935 
  3936 Since Emacs 29.1, this function is a no-op, because the implementation
  3937 of overlays changed and their lookup is now fast regardless of their
  3938 position in the buffer.  In particular, this function no longer affects
  3939 the value returned by `overlay-lists'.  */)
  3940   (Lisp_Object pos)
  3941 {
  3942   CHECK_FIXNUM_COERCE_MARKER (pos);
  3943   /* Noop */
  3944   return Qnil;
  3945 }
  3946 
  3947 DEFUN ("overlay-get", Foverlay_get, Soverlay_get, 2, 2, 0,
  3948        doc: /* Get the property of overlay OVERLAY with property name PROP.  */)
  3949   (Lisp_Object overlay, Lisp_Object prop)
  3950 {
  3951   CHECK_OVERLAY (overlay);
  3952   return lookup_char_property (XOVERLAY (overlay)->plist, prop, 0);
  3953 }
  3954 
  3955 DEFUN ("overlay-put", Foverlay_put, Soverlay_put, 3, 3, 0,
  3956        doc: /* Set one property of overlay OVERLAY: give property PROP value VALUE.
  3957 VALUE will be returned.*/)
  3958   (Lisp_Object overlay, Lisp_Object prop, Lisp_Object value)
  3959 {
  3960   Lisp_Object tail;
  3961   struct buffer *b;
  3962   bool changed;
  3963 
  3964   CHECK_OVERLAY (overlay);
  3965 
  3966   b = OVERLAY_BUFFER (overlay);
  3967 
  3968   for (tail = XOVERLAY (overlay)->plist;
  3969        CONSP (tail) && CONSP (XCDR (tail));
  3970        tail = XCDR (XCDR (tail)))
  3971     if (EQ (XCAR (tail), prop))
  3972       {
  3973         changed = !EQ (XCAR (XCDR (tail)), value);
  3974         XSETCAR (XCDR (tail), value);
  3975         goto found;
  3976       }
  3977   /* It wasn't in the list, so add it to the front.  */
  3978   changed = !NILP (value);
  3979   set_overlay_plist
  3980     (overlay, Fcons (prop, Fcons (value, XOVERLAY (overlay)->plist)));
  3981  found:
  3982   if (b)
  3983     {
  3984       if (changed)
  3985         modify_overlay (b, OVERLAY_START (overlay),
  3986                         OVERLAY_END (overlay));
  3987       if (EQ (prop, Qevaporate) && ! NILP (value)
  3988           && (OVERLAY_START (overlay)
  3989               == OVERLAY_END (overlay)))
  3990         Fdelete_overlay (overlay);
  3991     }
  3992 
  3993   return value;
  3994 }
  3995 
  3996 /* Subroutine of report_overlay_modification.  */
  3997 
  3998 /* Lisp vector holding overlay hook functions to call.
  3999    Vector elements come in pairs.
  4000    Each even-index element is a list of hook functions.
  4001    The following odd-index element is the overlay they came from.
  4002 
  4003    Before the buffer change, we fill in this vector
  4004    as we call overlay hook functions.
  4005    After the buffer change, we get the functions to call from this vector.
  4006    This way we always call the same functions before and after the change.  */
  4007 static Lisp_Object last_overlay_modification_hooks;
  4008 
  4009 /* Number of elements actually used in last_overlay_modification_hooks.  */
  4010 static ptrdiff_t last_overlay_modification_hooks_used;
  4011 
  4012 /* Add one functionlist/overlay pair
  4013    to the end of last_overlay_modification_hooks.  */
  4014 
  4015 static void
  4016 add_overlay_mod_hooklist (Lisp_Object functionlist, Lisp_Object overlay)
  4017 {
  4018   ptrdiff_t oldsize = ASIZE (last_overlay_modification_hooks);
  4019 
  4020   if (oldsize - 1 <= last_overlay_modification_hooks_used)
  4021     last_overlay_modification_hooks =
  4022       larger_vector (last_overlay_modification_hooks, 2, -1);
  4023   ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
  4024         functionlist); last_overlay_modification_hooks_used++;
  4025   ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
  4026         overlay);      last_overlay_modification_hooks_used++;
  4027 }
  4028 
  4029 /* Run the modification-hooks of overlays that include
  4030    any part of the text in START to END.
  4031    If this change is an insertion, also
  4032    run the insert-before-hooks of overlay starting at END,
  4033    and the insert-after-hooks of overlay ending at START.
  4034 
  4035    This is called both before and after the modification.
  4036    AFTER is true when we call after the modification.
  4037 
  4038    ARG1, ARG2, ARG3 are arguments to pass to the hook functions.
  4039    When AFTER is nonzero, they are the start position,
  4040    the position after the inserted new text,
  4041    and the length of deleted or replaced old text.  */
  4042 
  4043 void
  4044 report_overlay_modification (Lisp_Object start, Lisp_Object end, bool after,
  4045                              Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
  4046 {
  4047   /* True if this change is an insertion.  */
  4048   bool insertion = (after ? XFIXNAT (arg3) == 0 : EQ (start, end));
  4049 
  4050   /* We used to run the functions as soon as we found them and only register
  4051      them in last_overlay_modification_hooks for the purpose of the `after'
  4052      case.  But running elisp code as we traverse the list of overlays is
  4053      painful because the list can be modified by the elisp code so we had to
  4054      copy at several places.  We now simply do a read-only traversal that
  4055      only collects the functions to run and we run them afterwards.  It's
  4056      simpler, especially since all the code was already there.  -stef  */
  4057 
  4058   if (!after)
  4059     {
  4060       struct itree_node *node;
  4061       EMACS_INT begin_arg = XFIXNUM (start);
  4062       EMACS_INT end_arg = XFIXNUM (end);
  4063       /* We are being called before a change.
  4064          Scan the overlays to find the functions to call.  */
  4065       last_overlay_modification_hooks_used = 0;
  4066 
  4067       if (! current_buffer->overlays)
  4068         return;
  4069       ITREE_FOREACH (node, current_buffer->overlays,
  4070                      begin_arg - (insertion ? 1 : 0),
  4071                      end_arg   + (insertion ? 1 : 0),
  4072                      ASCENDING)
  4073         {
  4074           Lisp_Object overlay = node->data;
  4075           ptrdiff_t obegin = OVERLAY_START (overlay);
  4076           ptrdiff_t oend = OVERLAY_END (overlay);
  4077 
  4078           if (insertion && (begin_arg == obegin
  4079                             || end_arg == obegin))
  4080             {
  4081               Lisp_Object prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
  4082               if (!NILP (prop))
  4083                 add_overlay_mod_hooklist (prop, overlay);
  4084             }
  4085           if (insertion && (begin_arg == oend
  4086                             || end_arg == oend))
  4087             {
  4088               Lisp_Object prop = Foverlay_get (overlay, Qinsert_behind_hooks);
  4089               if (!NILP (prop))
  4090                 add_overlay_mod_hooklist (prop, overlay);
  4091             }
  4092           /* Test for intersecting intervals.  This does the right thing
  4093              for both insertion and deletion.  */
  4094           if (! insertion || (end_arg > obegin && begin_arg < oend))
  4095             {
  4096               Lisp_Object prop = Foverlay_get (overlay, Qmodification_hooks);
  4097               if (!NILP (prop))
  4098                 add_overlay_mod_hooklist (prop, overlay);
  4099             }
  4100         }
  4101     }
  4102   {
  4103     /* Call the functions recorded in last_overlay_modification_hooks.
  4104        First copy the vector contents, in case some of these hooks
  4105        do subsequent modification of the buffer.  */
  4106     ptrdiff_t size = last_overlay_modification_hooks_used;
  4107     Lisp_Object *copy;
  4108     ptrdiff_t i;
  4109 
  4110     USE_SAFE_ALLOCA;
  4111     SAFE_ALLOCA_LISP (copy, size);
  4112     memcpy (copy, XVECTOR (last_overlay_modification_hooks)->contents,
  4113             size * word_size);
  4114 
  4115     for (i = 0; i < size;)
  4116       {
  4117         Lisp_Object prop_i, overlay_i;
  4118         prop_i = copy[i++];
  4119         overlay_i = copy[i++];
  4120         /* It is possible that the recorded overlay has been deleted
  4121            (which makes its markers' buffers be nil), or that (due to
  4122            some bug) it belongs to a different buffer.  Only run this
  4123            hook if the overlay belongs to the current buffer.  */
  4124         if (OVERLAY_BUFFER (overlay_i) == current_buffer)
  4125           call_overlay_mod_hooks (prop_i, overlay_i, after, arg1, arg2, arg3);
  4126       }
  4127 
  4128     SAFE_FREE ();
  4129   }
  4130 }
  4131 
  4132 static void
  4133 call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay, bool after,
  4134                         Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
  4135 {
  4136   while (CONSP (list))
  4137     {
  4138       if (NILP (arg3))
  4139         call4 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2);
  4140       else
  4141         call5 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2, arg3);
  4142       list = XCDR (list);
  4143     }
  4144 }
  4145 
  4146 /***********************************************************************
  4147                          Allocation with mmap
  4148  ***********************************************************************/
  4149 
  4150 /* Note: WINDOWSNT implements this stuff on w32heap.c.  */
  4151 #if defined USE_MMAP_FOR_BUFFERS && !defined WINDOWSNT
  4152 
  4153 #include <sys/mman.h>
  4154 
  4155 #ifndef MAP_ANON
  4156 #ifdef MAP_ANONYMOUS
  4157 #define MAP_ANON MAP_ANONYMOUS
  4158 #else
  4159 #define MAP_ANON 0
  4160 #endif
  4161 #endif
  4162 
  4163 #ifndef MAP_FAILED
  4164 #define MAP_FAILED ((void *) -1)
  4165 #endif
  4166 
  4167 #if MAP_ANON == 0
  4168 #include <fcntl.h>
  4169 #endif
  4170 
  4171 
  4172 /* Memory is allocated in regions which are mapped using mmap(2).
  4173    The current implementation lets the system select mapped
  4174    addresses;  we're not using MAP_FIXED in general, except when
  4175    trying to enlarge regions.
  4176 
  4177    Each mapped region starts with a mmap_region structure, the user
  4178    area starts after that structure, aligned to MEM_ALIGN.
  4179 
  4180         +-----------------------+
  4181         | struct mmap_info +    |
  4182         | padding               |
  4183         +-----------------------+
  4184         | user data             |
  4185         |                       |
  4186         |                       |
  4187         +-----------------------+  */
  4188 
  4189 struct mmap_region
  4190 {
  4191   /* User-specified size.  */
  4192   size_t nbytes_specified;
  4193 
  4194   /* Number of bytes mapped */
  4195   size_t nbytes_mapped;
  4196 
  4197   /* Pointer to the location holding the address of the memory
  4198      allocated with the mmap'd block.  The variable actually points
  4199      after this structure.  */
  4200   void **var;
  4201 
  4202   /* Next and previous in list of all mmap'd regions.  */
  4203   struct mmap_region *next, *prev;
  4204 };
  4205 
  4206 /* Doubly-linked list of mmap'd regions.  */
  4207 
  4208 static struct mmap_region *mmap_regions;
  4209 
  4210 /* File descriptor for mmap.  If we don't have anonymous mapping,
  4211    /dev/zero will be opened on it.  */
  4212 
  4213 static int mmap_fd;
  4214 
  4215 /* Page size on this system.  */
  4216 
  4217 static int mmap_page_size;
  4218 
  4219 /* 1 means mmap has been initialized.  */
  4220 
  4221 static bool mmap_initialized_p;
  4222 
  4223 /* Value is X rounded up to the next multiple of N.  */
  4224 
  4225 #define ROUND(X, N)     (((X) + (N) - 1) / (N) * (N))
  4226 
  4227 /* Size of mmap_region structure plus padding.  */
  4228 
  4229 #define MMAP_REGION_STRUCT_SIZE \
  4230      ROUND (sizeof (struct mmap_region), MEM_ALIGN)
  4231 
  4232 /* Given a pointer P to the start of the user-visible part of a mapped
  4233    region, return a pointer to the start of the region.  */
  4234 
  4235 #define MMAP_REGION(P) \
  4236      ((struct mmap_region *) ((char *) (P) - MMAP_REGION_STRUCT_SIZE))
  4237 
  4238 /* Given a pointer P to the start of a mapped region, return a pointer
  4239    to the start of the user-visible part of the region.  */
  4240 
  4241 #define MMAP_USER_AREA(P) \
  4242      ((void *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
  4243 
  4244 #define MEM_ALIGN       sizeof (double)
  4245 
  4246 /* Predicate returning true if part of the address range [START .. END]
  4247    is currently mapped.  Used to prevent overwriting an existing
  4248    memory mapping.
  4249 
  4250    Default is to conservatively assume the address range is occupied by
  4251    something else.  This can be overridden by system configuration
  4252    files if system-specific means to determine this exists.  */
  4253 
  4254 #ifndef MMAP_ALLOCATED_P
  4255 #define MMAP_ALLOCATED_P(start, end) 1
  4256 #endif
  4257 
  4258 /* Perform necessary initializations for the use of mmap.  */
  4259 
  4260 static void
  4261 mmap_init (void)
  4262 {
  4263 #if MAP_ANON == 0
  4264   /* The value of mmap_fd is initially 0 in temacs, and -1
  4265      in a dumped Emacs.  */
  4266   if (mmap_fd <= 0)
  4267     {
  4268       /* No anonymous mmap -- we need the file descriptor.  */
  4269       mmap_fd = emacs_open_noquit ("/dev/zero", O_RDONLY, 0);
  4270       if (mmap_fd == -1)
  4271         fatal ("Cannot open /dev/zero: %s", emacs_strerror (errno));
  4272     }
  4273 #endif /* MAP_ANON == 0 */
  4274 
  4275   if (mmap_initialized_p)
  4276     return;
  4277   mmap_initialized_p = 1;
  4278 
  4279 #if MAP_ANON != 0
  4280   mmap_fd = -1;
  4281 #endif
  4282 
  4283   mmap_page_size = getpagesize ();
  4284 }
  4285 
  4286 /* Unmap a region.  P is a pointer to the start of the user-araa of
  4287    the region.  */
  4288 
  4289 static void
  4290 mmap_free_1 (struct mmap_region *r)
  4291 {
  4292   if (r->next)
  4293     r->next->prev = r->prev;
  4294   if (r->prev)
  4295     r->prev->next = r->next;
  4296   else
  4297     mmap_regions = r->next;
  4298 
  4299   if (munmap (r, r->nbytes_mapped) == -1)
  4300     fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
  4301 }
  4302 
  4303 
  4304 /* Enlarge region R by NPAGES pages.  NPAGES < 0 means shrink R.
  4305    Value is true if successful.  */
  4306 
  4307 static bool
  4308 mmap_enlarge (struct mmap_region *r, int npages)
  4309 {
  4310   char *region_end = (char *) r + r->nbytes_mapped;
  4311   size_t nbytes;
  4312   bool success = 0;
  4313 
  4314   if (npages < 0)
  4315     {
  4316       /* Unmap pages at the end of the region.  */
  4317       nbytes = - npages * mmap_page_size;
  4318       if (munmap (region_end - nbytes, nbytes) == -1)
  4319         fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
  4320       else
  4321         {
  4322           r->nbytes_mapped -= nbytes;
  4323           success = 1;
  4324         }
  4325     }
  4326   else if (npages > 0)
  4327     {
  4328       nbytes = npages * mmap_page_size;
  4329 
  4330       /* Try to map additional pages at the end of the region.  We
  4331          cannot do this if the address range is already occupied by
  4332          something else because mmap deletes any previous mapping.
  4333          I'm not sure this is worth doing, let's see.  */
  4334       if (!MMAP_ALLOCATED_P (region_end, region_end + nbytes))
  4335         {
  4336           void *p;
  4337 
  4338           p = mmap (region_end, nbytes, PROT_READ | PROT_WRITE,
  4339                     MAP_ANON | MAP_PRIVATE | MAP_FIXED, mmap_fd, 0);
  4340           if (p == MAP_FAILED)
  4341             ; /* fprintf (stderr, "mmap: %s\n", emacs_strerror (errno)); */
  4342           else if (p != region_end)
  4343             {
  4344               /* Kernels are free to choose a different address.  In
  4345                  that case, unmap what we've mapped above; we have
  4346                  no use for it.  */
  4347               if (munmap (p, nbytes) == -1)
  4348                 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
  4349             }
  4350           else
  4351             {
  4352               r->nbytes_mapped += nbytes;
  4353               success = 1;
  4354             }
  4355         }
  4356     }
  4357 
  4358   return success;
  4359 }
  4360 
  4361 
  4362 /* Allocate a block of storage large enough to hold NBYTES bytes of
  4363    data.  A pointer to the data is returned in *VAR.  VAR is thus the
  4364    address of some variable which will use the data area.
  4365 
  4366    The allocation of 0 bytes is valid.
  4367 
  4368    If we can't allocate the necessary memory, set *VAR to null, and
  4369    return null.  */
  4370 
  4371 static void *
  4372 mmap_alloc (void **var, size_t nbytes)
  4373 {
  4374   void *p;
  4375   size_t map;
  4376 
  4377   mmap_init ();
  4378 
  4379   map = ROUND (nbytes + MMAP_REGION_STRUCT_SIZE, mmap_page_size);
  4380   p = mmap (NULL, map, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
  4381             mmap_fd, 0);
  4382 
  4383   if (p == MAP_FAILED)
  4384     {
  4385       if (errno != ENOMEM)
  4386         fprintf (stderr, "mmap: %s\n", emacs_strerror (errno));
  4387       p = NULL;
  4388     }
  4389   else
  4390     {
  4391       struct mmap_region *r = p;
  4392 
  4393       r->nbytes_specified = nbytes;
  4394       r->nbytes_mapped = map;
  4395       r->var = var;
  4396       r->prev = NULL;
  4397       r->next = mmap_regions;
  4398       if (r->next)
  4399         r->next->prev = r;
  4400       mmap_regions = r;
  4401 
  4402       p = MMAP_USER_AREA (p);
  4403     }
  4404 
  4405   return *var = p;
  4406 }
  4407 
  4408 
  4409 /* Free a block of relocatable storage whose data is pointed to by
  4410    PTR.  Store 0 in *PTR to show there's no block allocated.  */
  4411 
  4412 static void
  4413 mmap_free (void **var)
  4414 {
  4415   mmap_init ();
  4416 
  4417   if (*var)
  4418     {
  4419       mmap_free_1 (MMAP_REGION (*var));
  4420       *var = NULL;
  4421     }
  4422 }
  4423 
  4424 
  4425 /* Given a pointer at address VAR to data allocated with mmap_alloc,
  4426    resize it to size NBYTES.  Change *VAR to reflect the new block,
  4427    and return this value.  If more memory cannot be allocated, then
  4428    leave *VAR unchanged, and return null.  */
  4429 
  4430 static void *
  4431 mmap_realloc (void **var, size_t nbytes)
  4432 {
  4433   void *result;
  4434 
  4435   mmap_init ();
  4436 
  4437   if (*var == NULL)
  4438     result = mmap_alloc (var, nbytes);
  4439   else if (nbytes == 0)
  4440     {
  4441       mmap_free (var);
  4442       result = mmap_alloc (var, nbytes);
  4443     }
  4444   else
  4445     {
  4446       struct mmap_region *r = MMAP_REGION (*var);
  4447       size_t room = r->nbytes_mapped - MMAP_REGION_STRUCT_SIZE;
  4448 
  4449       if (room < nbytes)
  4450         {
  4451           /* Must enlarge.  */
  4452           void *old_ptr = *var;
  4453 
  4454           /* Try to map additional pages at the end of the region.
  4455              If that fails, allocate a new region,  copy data
  4456              from the old region, then free it.  */
  4457           if (mmap_enlarge (r, (ROUND (nbytes - room, mmap_page_size)
  4458                                 / mmap_page_size)))
  4459             {
  4460               r->nbytes_specified = nbytes;
  4461               *var = result = old_ptr;
  4462             }
  4463           else if (mmap_alloc (var, nbytes))
  4464             {
  4465               memcpy (*var, old_ptr, r->nbytes_specified);
  4466               mmap_free_1 (MMAP_REGION (old_ptr));
  4467               result = *var;
  4468               r = MMAP_REGION (result);
  4469               r->nbytes_specified = nbytes;
  4470             }
  4471           else
  4472             {
  4473               *var = old_ptr;
  4474               result = NULL;
  4475             }
  4476         }
  4477       else if (room - nbytes >= mmap_page_size)
  4478         {
  4479           /* Shrinking by at least a page.  Let's give some
  4480              memory back to the system.
  4481 
  4482              The extra parens are to make the division happens first,
  4483              on positive values, so we know it will round towards
  4484              zero.  */
  4485           mmap_enlarge (r, - ((room - nbytes) / mmap_page_size));
  4486           result = *var;
  4487           r->nbytes_specified = nbytes;
  4488         }
  4489       else
  4490         {
  4491           /* Leave it alone.  */
  4492           result = *var;
  4493           r->nbytes_specified = nbytes;
  4494         }
  4495     }
  4496 
  4497   return result;
  4498 }
  4499 
  4500 
  4501 #endif /* USE_MMAP_FOR_BUFFERS */
  4502 
  4503 
  4504 
  4505 /***********************************************************************
  4506                             Buffer-text Allocation
  4507  ***********************************************************************/
  4508 
  4509 /* Allocate NBYTES bytes for buffer B's text buffer.  */
  4510 
  4511 static void
  4512 alloc_buffer_text (struct buffer *b, ptrdiff_t nbytes)
  4513 {
  4514   void *p;
  4515 
  4516   block_input ();
  4517 #if defined USE_MMAP_FOR_BUFFERS
  4518   p = mmap_alloc ((void **) &b->text->beg, nbytes);
  4519 #elif defined REL_ALLOC
  4520   p = r_alloc ((void **) &b->text->beg, nbytes);
  4521 #else
  4522   p = xmalloc (nbytes);
  4523 #endif
  4524 
  4525   if (p == NULL)
  4526     {
  4527       unblock_input ();
  4528       memory_full (nbytes);
  4529     }
  4530 
  4531   b->text->beg = p;
  4532   unblock_input ();
  4533 }
  4534 
  4535 /* Enlarge buffer B's text buffer by DELTA bytes.  DELTA < 0 means
  4536    shrink it.  */
  4537 
  4538 void
  4539 enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
  4540 {
  4541   block_input ();
  4542   void *p;
  4543   unsigned char *old_beg = b->text->beg;
  4544   ptrdiff_t old_nbytes =
  4545     BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1;
  4546   ptrdiff_t new_nbytes = old_nbytes + delta;
  4547 
  4548   if (pdumper_object_p (old_beg))
  4549     b->text->beg = NULL;
  4550   else
  4551     old_beg = NULL;
  4552 
  4553 #if defined USE_MMAP_FOR_BUFFERS
  4554   p = mmap_realloc ((void **) &b->text->beg, new_nbytes);
  4555 #elif defined REL_ALLOC
  4556   p = r_re_alloc ((void **) &b->text->beg, new_nbytes);
  4557 #else
  4558   p = xrealloc (b->text->beg, new_nbytes);
  4559 #endif
  4560   __lsan_ignore_object (p);
  4561 
  4562   if (p == NULL)
  4563     {
  4564       if (old_beg)
  4565         b->text->beg = old_beg;
  4566       unblock_input ();
  4567       memory_full (new_nbytes);
  4568     }
  4569 
  4570   if (old_beg)
  4571     memcpy (p, old_beg, min (old_nbytes, new_nbytes));
  4572 
  4573   BUF_BEG_ADDR (b) = p;
  4574   unblock_input ();
  4575 }
  4576 
  4577 
  4578 /* Free buffer B's text buffer.  */
  4579 
  4580 static void
  4581 free_buffer_text (struct buffer *b)
  4582 {
  4583   block_input ();
  4584 
  4585   if (!pdumper_object_p (b->text->beg))
  4586     {
  4587 #if defined USE_MMAP_FOR_BUFFERS
  4588       mmap_free ((void **) &b->text->beg);
  4589 #elif defined REL_ALLOC
  4590       r_alloc_free ((void **) &b->text->beg);
  4591 #else
  4592       xfree (b->text->beg);
  4593 #endif
  4594     }
  4595 
  4596   BUF_BEG_ADDR (b) = NULL;
  4597   unblock_input ();
  4598 }
  4599 
  4600 
  4601 
  4602 /***********************************************************************
  4603                             Initialization
  4604  ***********************************************************************/
  4605 void
  4606 init_buffer_once (void)
  4607 {
  4608   /* TODO: clean up the buffer-local machinery.  Right now,
  4609      we have:
  4610 
  4611      buffer_defaults: default values of buffer-locals
  4612      buffer_local_flags: metadata
  4613      buffer_permanent_local_flags: metadata
  4614      buffer_local_symbols: metadata
  4615 
  4616      There must be a simpler way to store the metadata.
  4617   */
  4618 
  4619   int idx;
  4620 
  4621   /* Items flagged permanent get an explicit permanent-local property
  4622      added in bindings.el, for clarity.  */
  4623   PDUMPER_REMEMBER_SCALAR (buffer_permanent_local_flags);
  4624   memset (buffer_permanent_local_flags, 0, sizeof buffer_permanent_local_flags);
  4625 
  4626   /* 0 means not a lisp var, -1 means always local, else mask.  */
  4627   memset (&buffer_local_flags, 0, sizeof buffer_local_flags);
  4628   bset_filename (&buffer_local_flags, make_fixnum (-1));
  4629   bset_directory (&buffer_local_flags, make_fixnum (-1));
  4630   bset_backed_up (&buffer_local_flags, make_fixnum (-1));
  4631   bset_save_length (&buffer_local_flags, make_fixnum (-1));
  4632   bset_auto_save_file_name (&buffer_local_flags, make_fixnum (-1));
  4633   bset_read_only (&buffer_local_flags, make_fixnum (-1));
  4634   bset_major_mode (&buffer_local_flags, make_fixnum (-1));
  4635   bset_local_minor_modes (&buffer_local_flags, make_fixnum (-1));
  4636   bset_mode_name (&buffer_local_flags, make_fixnum (-1));
  4637   bset_undo_list (&buffer_local_flags, make_fixnum (-1));
  4638   bset_mark_active (&buffer_local_flags, make_fixnum (-1));
  4639   bset_point_before_scroll (&buffer_local_flags, make_fixnum (-1));
  4640   bset_file_truename (&buffer_local_flags, make_fixnum (-1));
  4641   bset_invisibility_spec (&buffer_local_flags, make_fixnum (-1));
  4642   bset_file_format (&buffer_local_flags, make_fixnum (-1));
  4643   bset_auto_save_file_format (&buffer_local_flags, make_fixnum (-1));
  4644   bset_display_count (&buffer_local_flags, make_fixnum (-1));
  4645   bset_display_time (&buffer_local_flags, make_fixnum (-1));
  4646   bset_enable_multibyte_characters (&buffer_local_flags, make_fixnum (-1));
  4647 
  4648   /* These used to be stuck at 0 by default, but now that the all-zero value
  4649      means Qnil, we have to initialize them explicitly.  */
  4650   bset_name (&buffer_local_flags, make_fixnum (0));
  4651   bset_mark (&buffer_local_flags, make_fixnum (0));
  4652   bset_local_var_alist (&buffer_local_flags, make_fixnum (0));
  4653   bset_keymap (&buffer_local_flags, make_fixnum (0));
  4654   bset_downcase_table (&buffer_local_flags, make_fixnum (0));
  4655   bset_upcase_table (&buffer_local_flags, make_fixnum (0));
  4656   bset_case_canon_table (&buffer_local_flags, make_fixnum (0));
  4657   bset_case_eqv_table (&buffer_local_flags, make_fixnum (0));
  4658   bset_width_table (&buffer_local_flags, make_fixnum (0));
  4659   bset_pt_marker (&buffer_local_flags, make_fixnum (0));
  4660   bset_begv_marker (&buffer_local_flags, make_fixnum (0));
  4661   bset_zv_marker (&buffer_local_flags, make_fixnum (0));
  4662   bset_last_selected_window (&buffer_local_flags, make_fixnum (0));
  4663 
  4664   idx = 1;
  4665   XSETFASTINT (BVAR (&buffer_local_flags, mode_line_format), idx); ++idx;
  4666   XSETFASTINT (BVAR (&buffer_local_flags, abbrev_mode), idx); ++idx;
  4667   XSETFASTINT (BVAR (&buffer_local_flags, overwrite_mode), idx); ++idx;
  4668   XSETFASTINT (BVAR (&buffer_local_flags, case_fold_search), idx); ++idx;
  4669   XSETFASTINT (BVAR (&buffer_local_flags, auto_fill_function), idx); ++idx;
  4670   XSETFASTINT (BVAR (&buffer_local_flags, selective_display), idx); ++idx;
  4671   XSETFASTINT (BVAR (&buffer_local_flags, selective_display_ellipses), idx); ++idx;
  4672   XSETFASTINT (BVAR (&buffer_local_flags, tab_width), idx); ++idx;
  4673   XSETFASTINT (BVAR (&buffer_local_flags, truncate_lines), idx);
  4674   /* Make this one a permanent local.  */
  4675   buffer_permanent_local_flags[idx++] = 1;
  4676   XSETFASTINT (BVAR (&buffer_local_flags, word_wrap), idx); ++idx;
  4677   XSETFASTINT (BVAR (&buffer_local_flags, ctl_arrow), idx); ++idx;
  4678   XSETFASTINT (BVAR (&buffer_local_flags, fill_column), idx); ++idx;
  4679   XSETFASTINT (BVAR (&buffer_local_flags, left_margin), idx); ++idx;
  4680   XSETFASTINT (BVAR (&buffer_local_flags, abbrev_table), idx); ++idx;
  4681   XSETFASTINT (BVAR (&buffer_local_flags, display_table), idx); ++idx;
  4682   XSETFASTINT (BVAR (&buffer_local_flags, syntax_table), idx); ++idx;
  4683   XSETFASTINT (BVAR (&buffer_local_flags, cache_long_scans), idx); ++idx;
  4684   XSETFASTINT (BVAR (&buffer_local_flags, category_table), idx); ++idx;
  4685   XSETFASTINT (BVAR (&buffer_local_flags, bidi_display_reordering), idx); ++idx;
  4686   XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_direction), idx); ++idx;
  4687   XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_separate_re), idx); ++idx;
  4688   XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_start_re), idx); ++idx;
  4689   XSETFASTINT (BVAR (&buffer_local_flags, buffer_file_coding_system), idx);
  4690   /* Make this one a permanent local.  */
  4691   buffer_permanent_local_flags[idx++] = 1;
  4692   XSETFASTINT (BVAR (&buffer_local_flags, left_margin_cols), idx); ++idx;
  4693   XSETFASTINT (BVAR (&buffer_local_flags, right_margin_cols), idx); ++idx;
  4694   XSETFASTINT (BVAR (&buffer_local_flags, left_fringe_width), idx); ++idx;
  4695   XSETFASTINT (BVAR (&buffer_local_flags, right_fringe_width), idx); ++idx;
  4696   XSETFASTINT (BVAR (&buffer_local_flags, fringes_outside_margins), idx); ++idx;
  4697   XSETFASTINT (BVAR (&buffer_local_flags, scroll_bar_width), idx); ++idx;
  4698   XSETFASTINT (BVAR (&buffer_local_flags, scroll_bar_height), idx); ++idx;
  4699   XSETFASTINT (BVAR (&buffer_local_flags, vertical_scroll_bar_type), idx); ++idx;
  4700   XSETFASTINT (BVAR (&buffer_local_flags, horizontal_scroll_bar_type), idx); ++idx;
  4701   XSETFASTINT (BVAR (&buffer_local_flags, indicate_empty_lines), idx); ++idx;
  4702   XSETFASTINT (BVAR (&buffer_local_flags, indicate_buffer_boundaries), idx); ++idx;
  4703   XSETFASTINT (BVAR (&buffer_local_flags, fringe_indicator_alist), idx); ++idx;
  4704   XSETFASTINT (BVAR (&buffer_local_flags, fringe_cursor_alist), idx); ++idx;
  4705   XSETFASTINT (BVAR (&buffer_local_flags, scroll_up_aggressively), idx); ++idx;
  4706   XSETFASTINT (BVAR (&buffer_local_flags, scroll_down_aggressively), idx); ++idx;
  4707   XSETFASTINT (BVAR (&buffer_local_flags, header_line_format), idx); ++idx;
  4708   XSETFASTINT (BVAR (&buffer_local_flags, tab_line_format), idx); ++idx;
  4709   XSETFASTINT (BVAR (&buffer_local_flags, cursor_type), idx); ++idx;
  4710   XSETFASTINT (BVAR (&buffer_local_flags, extra_line_spacing), idx); ++idx;
  4711 #ifdef HAVE_TREE_SITTER
  4712   XSETFASTINT (BVAR (&buffer_local_flags, ts_parser_list), idx); ++idx;
  4713 #endif
  4714   XSETFASTINT (BVAR (&buffer_local_flags, cursor_in_non_selected_windows), idx); ++idx;
  4715 
  4716   /* buffer_local_flags contains no pointers, so it's safe to treat it
  4717      as a blob for pdumper.  */
  4718   PDUMPER_REMEMBER_SCALAR (buffer_local_flags);
  4719 
  4720   /* Need more room? */
  4721   if (idx >= MAX_PER_BUFFER_VARS)
  4722     emacs_abort ();
  4723   last_per_buffer_idx = idx;
  4724   PDUMPER_REMEMBER_SCALAR (last_per_buffer_idx);
  4725 
  4726   /* Make sure all markable slots in buffer_defaults
  4727      are initialized reasonably, so mark_buffer won't choke.  */
  4728   reset_buffer (&buffer_defaults);
  4729   eassert (NILP (BVAR (&buffer_defaults, name)));
  4730   reset_buffer_local_variables (&buffer_defaults, 1);
  4731   eassert (NILP (BVAR (&buffer_local_symbols, name)));
  4732   reset_buffer (&buffer_local_symbols);
  4733   reset_buffer_local_variables (&buffer_local_symbols, 1);
  4734   /* Prevent GC from getting confused.  */
  4735   buffer_defaults.text = &buffer_defaults.own_text;
  4736   buffer_local_symbols.text = &buffer_local_symbols.own_text;
  4737   /* No one will share the text with these buffers, but let's play it safe.  */
  4738   buffer_defaults.indirections = 0;
  4739   buffer_local_symbols.indirections = 0;
  4740   /* Likewise no one will display them.  */
  4741   buffer_defaults.window_count = 0;
  4742   buffer_local_symbols.window_count = 0;
  4743   set_buffer_intervals (&buffer_defaults, NULL);
  4744   set_buffer_intervals (&buffer_local_symbols, NULL);
  4745   /* This is not strictly necessary, but let's make them initialized.  */
  4746   bset_name (&buffer_defaults, build_pure_c_string (" *buffer-defaults*"));
  4747   bset_name (&buffer_local_symbols, build_pure_c_string (" *buffer-local-symbols*"));
  4748   BUFFER_PVEC_INIT (&buffer_defaults);
  4749   BUFFER_PVEC_INIT (&buffer_local_symbols);
  4750 
  4751   /* Set up the default values of various buffer slots.  */
  4752   /* Must do these before making the first buffer! */
  4753 
  4754   /* real setup is done in bindings.el */
  4755   bset_mode_line_format (&buffer_defaults, build_pure_c_string ("%-"));
  4756   bset_header_line_format (&buffer_defaults, Qnil);
  4757   bset_tab_line_format (&buffer_defaults, Qnil);
  4758   bset_abbrev_mode (&buffer_defaults, Qnil);
  4759   bset_overwrite_mode (&buffer_defaults, Qnil);
  4760   bset_case_fold_search (&buffer_defaults, Qt);
  4761   bset_auto_fill_function (&buffer_defaults, Qnil);
  4762   bset_selective_display (&buffer_defaults, Qnil);
  4763   bset_selective_display_ellipses (&buffer_defaults, Qt);
  4764   bset_abbrev_table (&buffer_defaults, Qnil);
  4765   bset_display_table (&buffer_defaults, Qnil);
  4766   bset_undo_list (&buffer_defaults, Qnil);
  4767   bset_mark_active (&buffer_defaults, Qnil);
  4768   bset_file_format (&buffer_defaults, Qnil);
  4769   bset_auto_save_file_format (&buffer_defaults, Qt);
  4770   buffer_defaults.overlays = NULL;
  4771 
  4772   XSETFASTINT (BVAR (&buffer_defaults, tab_width), 8);
  4773   bset_truncate_lines (&buffer_defaults, Qnil);
  4774   bset_word_wrap (&buffer_defaults, Qnil);
  4775   bset_ctl_arrow (&buffer_defaults, Qt);
  4776   bset_bidi_display_reordering (&buffer_defaults, Qt);
  4777   bset_bidi_paragraph_direction (&buffer_defaults, Qnil);
  4778   bset_bidi_paragraph_start_re (&buffer_defaults, Qnil);
  4779   bset_bidi_paragraph_separate_re (&buffer_defaults, Qnil);
  4780   bset_cursor_type (&buffer_defaults, Qt);
  4781   bset_extra_line_spacing (&buffer_defaults, Qnil);
  4782 #ifdef HAVE_TREE_SITTER
  4783   bset_ts_parser_list (&buffer_defaults, Qnil);
  4784 #endif
  4785   bset_cursor_in_non_selected_windows (&buffer_defaults, Qt);
  4786 
  4787   bset_enable_multibyte_characters (&buffer_defaults, Qt);
  4788   bset_buffer_file_coding_system (&buffer_defaults, Qnil);
  4789   XSETFASTINT (BVAR (&buffer_defaults, fill_column), 70);
  4790   XSETFASTINT (BVAR (&buffer_defaults, left_margin), 0);
  4791   bset_cache_long_scans (&buffer_defaults, Qt);
  4792   bset_file_truename (&buffer_defaults, Qnil);
  4793   XSETFASTINT (BVAR (&buffer_defaults, display_count), 0);
  4794   XSETFASTINT (BVAR (&buffer_defaults, left_margin_cols), 0);
  4795   XSETFASTINT (BVAR (&buffer_defaults, right_margin_cols), 0);
  4796   bset_left_fringe_width (&buffer_defaults, Qnil);
  4797   bset_right_fringe_width (&buffer_defaults, Qnil);
  4798   bset_fringes_outside_margins (&buffer_defaults, Qnil);
  4799   bset_scroll_bar_width (&buffer_defaults, Qnil);
  4800   bset_scroll_bar_height (&buffer_defaults, Qnil);
  4801   bset_vertical_scroll_bar_type (&buffer_defaults, Qt);
  4802   bset_horizontal_scroll_bar_type (&buffer_defaults, Qt);
  4803   bset_indicate_empty_lines (&buffer_defaults, Qnil);
  4804   bset_indicate_buffer_boundaries (&buffer_defaults, Qnil);
  4805   bset_fringe_indicator_alist (&buffer_defaults, Qnil);
  4806   bset_fringe_cursor_alist (&buffer_defaults, Qnil);
  4807   bset_scroll_up_aggressively (&buffer_defaults, Qnil);
  4808   bset_scroll_down_aggressively (&buffer_defaults, Qnil);
  4809   bset_display_time (&buffer_defaults, Qnil);
  4810 
  4811   /* Assign the local-flags to the slots that have default values.
  4812      The local flag is a bit that is used in the buffer
  4813      to say that it has its own local value for the slot.
  4814      The local flag bits are in the local_var_flags slot of the buffer.  */
  4815 
  4816   /* Nothing can work if this isn't true.  */
  4817   { verify (sizeof (EMACS_INT) == word_size); }
  4818 
  4819   Vbuffer_alist = Qnil;
  4820   current_buffer = 0;
  4821   pdumper_remember_lv_ptr_raw (&current_buffer, Lisp_Vectorlike);
  4822 
  4823   QSFundamental = build_pure_c_string ("Fundamental");
  4824 
  4825   DEFSYM (Qfundamental_mode, "fundamental-mode");
  4826   bset_major_mode (&buffer_defaults, Qfundamental_mode);
  4827 
  4828   DEFSYM (Qmode_class, "mode-class");
  4829   DEFSYM (Qprotected_field, "protected-field");
  4830 
  4831   DEFSYM (Qpermanent_local, "permanent-local");
  4832   DEFSYM (Qkill_buffer_hook, "kill-buffer-hook");
  4833   Fput (Qkill_buffer_hook, Qpermanent_local, Qt);
  4834 
  4835   /* Super-magic invisible buffer.  */
  4836   Vprin1_to_string_buffer =
  4837     Fget_buffer_create (build_pure_c_string (" prin1"), Qt);
  4838   Vbuffer_alist = Qnil;
  4839 
  4840   Fset_buffer (Fget_buffer_create (build_pure_c_string ("*scratch*"), Qnil));
  4841 
  4842   inhibit_modification_hooks = 0;
  4843 }
  4844 
  4845 void
  4846 init_buffer (void)
  4847 {
  4848   Lisp_Object temp;
  4849 
  4850 #ifdef USE_MMAP_FOR_BUFFERS
  4851   if (dumped_with_unexec_p ())
  4852     {
  4853       Lisp_Object tail, buffer;
  4854 
  4855 #ifndef WINDOWSNT
  4856       /* These must be reset in the dumped Emacs, to avoid stale
  4857          references to mmap'ed memory from before the dump.
  4858 
  4859          WINDOWSNT doesn't need this because it doesn't track mmap'ed
  4860          regions by hand (see w32heap.c, which uses system APIs for
  4861          that purpose), and thus doesn't use mmap_regions.  */
  4862       mmap_regions = NULL;
  4863       mmap_fd = -1;
  4864 #endif
  4865 
  4866       /* The dumped buffers reference addresses of buffer text
  4867          recorded by temacs, that cannot be used by the dumped Emacs.
  4868          We map new memory for their text here.
  4869 
  4870          Implementation notes: the buffers we carry from temacs are:
  4871          " prin1", "*scratch*", " *Minibuf-0*", "*Messages*", and
  4872          " *code-conversion-work*".  They are created by
  4873          init_buffer_once and init_window_once (which are not called
  4874          in the dumped Emacs), and by the first call to coding.c
  4875          routines.  Since FOR_EACH_LIVE_BUFFER only walks the buffers
  4876          in Vbuffer_alist, any buffer we carry from temacs that is
  4877          not in the alist (a.k.a. "magic invisible buffers") should
  4878          be handled here explicitly.  */
  4879       FOR_EACH_LIVE_BUFFER (tail, buffer)
  4880         {
  4881           struct buffer *b = XBUFFER (buffer);
  4882           b->text->beg = NULL;
  4883           enlarge_buffer_text (b, 0);
  4884         }
  4885       /* The " prin1" buffer is not in Vbuffer_alist.  */
  4886       XBUFFER (Vprin1_to_string_buffer)->text->beg = NULL;
  4887       enlarge_buffer_text (XBUFFER (Vprin1_to_string_buffer), 0);
  4888     }
  4889 #endif /* USE_MMAP_FOR_BUFFERS */
  4890 
  4891   AUTO_STRING (scratch, "*scratch*");
  4892   Fset_buffer (Fget_buffer_create (scratch, Qnil));
  4893   if (NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
  4894     Fset_buffer_multibyte (Qnil);
  4895 
  4896   char const *pwd = emacs_wd;
  4897 
  4898   if (!pwd)
  4899     {
  4900       fprintf (stderr, "Error getting directory: %s\n",
  4901                emacs_strerror (errno));
  4902       bset_directory (current_buffer, Qnil);
  4903     }
  4904   else
  4905     {
  4906       /* Maybe this should really use some standard subroutine
  4907          whose definition is filename syntax dependent.  */
  4908       ptrdiff_t len = strlen (pwd);
  4909       bool add_slash = ! IS_DIRECTORY_SEP (pwd[len - 1]);
  4910 
  4911       /* At this moment, we still don't know how to decode the directory
  4912          name.  So, we keep the bytes in unibyte form so that file I/O
  4913          routines correctly get the original bytes.  */
  4914       Lisp_Object dirname = make_unibyte_string (pwd, len + add_slash);
  4915       if (add_slash)
  4916         SSET (dirname, len, DIRECTORY_SEP);
  4917       bset_directory (current_buffer, dirname);
  4918 
  4919       /* Add /: to the front of the name
  4920          if it would otherwise be treated as magic.  */
  4921       temp = Ffind_file_name_handler (BVAR (current_buffer, directory), Qt);
  4922       if (! NILP (temp)
  4923           /* If the default dir is just /, TEMP is non-nil
  4924              because of the ange-ftp completion handler.
  4925              However, it is not necessary to turn / into /:/.
  4926              So avoid doing that.  */
  4927           && strcmp ("/", SSDATA (BVAR (current_buffer, directory))))
  4928         {
  4929           AUTO_STRING (slash_colon, "/:");
  4930           bset_directory (current_buffer,
  4931                           concat2 (slash_colon,
  4932                                    BVAR (current_buffer, directory)));
  4933         }
  4934     }
  4935 
  4936   temp = get_minibuffer (0);
  4937   bset_directory (XBUFFER (temp), BVAR (current_buffer, directory));
  4938 }
  4939 
  4940 /* Similar to defvar_lisp but define a variable whose value is the
  4941    Lisp_Object stored in the current buffer.  LNAME is the Lisp-level
  4942    variable name.  VNAME is the name of the buffer slot.  PREDICATE
  4943    is nil for a general Lisp variable.  If PREDICATE is non-nil, then
  4944    only Lisp values that satisfies the PREDICATE are allowed (except
  4945    that nil is allowed too).  DOC is a dummy where you write the doc
  4946    string as a comment.  */
  4947 
  4948 #define DEFVAR_PER_BUFFER(lname, vname, predicate, doc)         \
  4949   do {                                                          \
  4950     static struct Lisp_Buffer_Objfwd bo_fwd;                    \
  4951     defvar_per_buffer (&bo_fwd, lname, vname, predicate);       \
  4952   } while (0)
  4953 
  4954 static void
  4955 defvar_per_buffer (struct Lisp_Buffer_Objfwd *bo_fwd, const char *namestring,
  4956                    Lisp_Object *address, Lisp_Object predicate)
  4957 {
  4958   struct Lisp_Symbol *sym;
  4959   int offset;
  4960 
  4961   sym = XSYMBOL (intern (namestring));
  4962   offset = (char *)address - (char *)current_buffer;
  4963 
  4964   bo_fwd->type = Lisp_Fwd_Buffer_Obj;
  4965   bo_fwd->offset = offset;
  4966   bo_fwd->predicate = predicate;
  4967   sym->u.s.declared_special = true;
  4968   sym->u.s.redirect = SYMBOL_FORWARDED;
  4969   SET_SYMBOL_FWD (sym, bo_fwd);
  4970   XSETSYMBOL (PER_BUFFER_SYMBOL (offset), sym);
  4971 
  4972   if (PER_BUFFER_IDX (offset) == 0)
  4973     /* Did a DEFVAR_PER_BUFFER without initializing the corresponding
  4974        slot of buffer_local_flags.  */
  4975     emacs_abort ();
  4976 }
  4977 
  4978 #ifdef ITREE_DEBUG
  4979 static Lisp_Object
  4980 make_lispy_itree_node (const struct itree_node *node)
  4981 {
  4982   return listn (12,
  4983                 intern (":begin"),
  4984                 make_fixnum (node->begin),
  4985                 intern (":end"),
  4986                 make_fixnum (node->end),
  4987                 intern (":limit"),
  4988                 make_fixnum (node->limit),
  4989                 intern (":offset"),
  4990                 make_fixnum (node->offset),
  4991                 intern (":rear-advance"),
  4992                 node->rear_advance ? Qt : Qnil,
  4993                 intern (":front-advance"),
  4994                 node->front_advance ? Qt : Qnil);
  4995 }
  4996 
  4997 static Lisp_Object
  4998 overlay_tree (const struct itree_tree *tree,
  4999               const struct itree_node *node)
  5000 {
  5001   if (node == ITREE_NULL)
  5002     return Qnil;
  5003   return list3 (make_lispy_itree_node (node),
  5004                 overlay_tree (tree, node->left),
  5005                 overlay_tree (tree, node->right));
  5006 }
  5007 
  5008 DEFUN ("overlay-tree", Foverlay_tree, Soverlay_tree, 0, 1, 0,
  5009        doc: /* Get the overlay tree for BUFFER.  */)
  5010      (Lisp_Object buffer)
  5011 {
  5012   struct buffer *b = decode_buffer (buffer);
  5013   if (! b->overlays)
  5014     return Qnil;
  5015   return overlay_tree (b->overlays, b->overlays->root);
  5016 }
  5017 #endif
  5018 
  5019 
  5020 
  5021 /* Initialize the buffer routines.  */
  5022 void
  5023 syms_of_buffer (void)
  5024 {
  5025   staticpro (&last_overlay_modification_hooks);
  5026   last_overlay_modification_hooks = make_nil_vector (10);
  5027 
  5028   staticpro (&QSFundamental);
  5029   staticpro (&Vbuffer_alist);
  5030 
  5031   DEFSYM (Qchoice, "choice");
  5032   DEFSYM (Qleft, "left");
  5033   DEFSYM (Qright, "right");
  5034   DEFSYM (Qrange, "range");
  5035 
  5036   DEFSYM (Qpermanent_local_hook, "permanent-local-hook");
  5037   DEFSYM (Qoverlayp, "overlayp");
  5038   DEFSYM (Qevaporate, "evaporate");
  5039   DEFSYM (Qmodification_hooks, "modification-hooks");
  5040   DEFSYM (Qinsert_in_front_hooks, "insert-in-front-hooks");
  5041   DEFSYM (Qinsert_behind_hooks, "insert-behind-hooks");
  5042   DEFSYM (Qget_file_buffer, "get-file-buffer");
  5043   DEFSYM (Qpriority, "priority");
  5044   DEFSYM (Qbefore_string, "before-string");
  5045   DEFSYM (Qafter_string, "after-string");
  5046   DEFSYM (Qfirst_change_hook, "first-change-hook");
  5047   DEFSYM (Qbefore_change_functions, "before-change-functions");
  5048   DEFSYM (Qafter_change_functions, "after-change-functions");
  5049   DEFSYM (Qkill_buffer_query_functions, "kill-buffer-query-functions");
  5050   DEFSYM (Qget_scratch_buffer_create, "get-scratch-buffer-create");
  5051 
  5052   DEFSYM (Qvertical_scroll_bar, "vertical-scroll-bar");
  5053   Fput (Qvertical_scroll_bar, Qchoice, list4 (Qnil, Qt, Qleft, Qright));
  5054   DEFSYM (Qhorizontal_scroll_bar, "horizontal-scroll-bar");
  5055 
  5056   DEFSYM (Qfraction, "fraction");
  5057   Fput (Qfraction, Qrange, Fcons (make_float (0.0), make_float (1.0)));
  5058 
  5059   DEFSYM (Qoverwrite_mode, "overwrite-mode");
  5060   Fput (Qoverwrite_mode, Qchoice,
  5061         list3 (Qnil, intern ("overwrite-mode-textual"),
  5062                Qoverwrite_mode_binary));
  5063 
  5064   Fput (Qprotected_field, Qerror_conditions,
  5065         pure_list (Qprotected_field, Qerror));
  5066   Fput (Qprotected_field, Qerror_message,
  5067         build_pure_c_string ("Attempt to modify a protected field"));
  5068 
  5069   DEFSYM (Qclone_indirect_buffer_hook, "clone-indirect-buffer-hook");
  5070 
  5071   DEFVAR_PER_BUFFER ("tab-line-format",
  5072                      &BVAR (current_buffer, tab_line_format),
  5073                      Qnil,
  5074                      doc: /* Analogous to `mode-line-format', but controls the tab line.
  5075 The tab line appears, optionally, at the top of a window;
  5076 the mode line appears at the bottom.  */);
  5077 
  5078   DEFVAR_PER_BUFFER ("header-line-format",
  5079                      &BVAR (current_buffer, header_line_format),
  5080                      Qnil,
  5081                      doc: /* Analogous to `mode-line-format', but controls the header line.
  5082 The header line appears, optionally, at the top of a window; the mode
  5083 line appears at the bottom.
  5084 
  5085 Also see `header-line-indent-mode' if `display-line-numbers-mode' is
  5086 turned on and header-line text should be aligned with buffer text.  */);
  5087 
  5088   DEFVAR_PER_BUFFER ("mode-line-format", &BVAR (current_buffer, mode_line_format),
  5089                      Qnil,
  5090                      doc: /* Template for displaying mode line for a window's buffer.
  5091 
  5092 The value may be nil, a string, a symbol or a list.
  5093 
  5094 A value of nil means don't display a mode line.
  5095 
  5096 For any symbol other than t or nil, the symbol's value is processed as
  5097  a mode line construct.  As a special exception, if that value is a
  5098  string, the string is processed verbatim, without handling any
  5099  %-constructs (see below).  Also, unless the symbol has a non-nil
  5100  `risky-local-variable' property, all properties in any strings, as
  5101  well as all :eval and :propertize forms in the value, are ignored.
  5102 
  5103 When the value is processed, the window's buffer is temporarily the
  5104 current buffer.
  5105 
  5106 A list whose car is a string or list is processed by processing each
  5107  of the list elements recursively, as separate mode line constructs,
  5108  and concatenating the results.
  5109 
  5110 A list of the form `(:eval FORM)' is processed by evaluating FORM and
  5111  using the result as a mode line construct.  Be careful--FORM should
  5112  not load any files, because that can cause an infinite recursion.
  5113 
  5114 A list of the form `(:propertize ELT PROPS...)' is processed by
  5115  processing ELT as the mode line construct, and adding the text
  5116  properties PROPS to the result.
  5117 
  5118 A list whose car is a symbol is processed by examining the symbol's
  5119  value, and, if that value is non-nil, processing the cadr of the list
  5120  recursively; and if that value is nil, processing the caddr of the
  5121  list recursively.
  5122 
  5123 A list whose car is an integer is processed by processing the cadr of
  5124  the list, and padding (if the number is positive) or truncating (if
  5125  negative) to the width specified by that number.
  5126 
  5127 A string is printed verbatim in the mode line except for %-constructs:
  5128   %b -- print buffer name.      %f -- print visited file name.
  5129   %F -- print frame name.
  5130   %* -- print %, * or hyphen.   %+ -- print *, % or hyphen.
  5131         %& is like %*, but ignore read-only-ness.
  5132         % means buffer is read-only and * means it is modified.
  5133         For a modified read-only buffer, %* gives % and %+ gives *.
  5134   %s -- print process status.   %l -- print the current line number.
  5135   %c -- print the current column number (this makes editing slower).
  5136         Columns are numbered starting from the left margin, and the
  5137         leftmost column is displayed as zero.
  5138         To make the column number update correctly in all cases,
  5139         `column-number-mode' must be non-nil.
  5140   %C -- Like %c, but the leftmost column is displayed as one.
  5141   %i -- print the size of the buffer.
  5142   %I -- like %i, but use k, M, G, etc., to abbreviate.
  5143   %o -- print percent of window travel through buffer, or Top, Bot or All.
  5144   %p -- print percent of buffer above top of window, or Top, Bot or All.
  5145   %P -- print percent of buffer above bottom of window, perhaps plus Top,
  5146         or print Bottom or All.
  5147   %q -- print percent of buffer above both the top and the bottom of the
  5148         window, separated by ‘-’, or ‘All’.
  5149   %n -- print Narrow if appropriate.
  5150   %z -- print mnemonics of keyboard, terminal, and buffer coding systems.
  5151   %Z -- like %z, but including the end-of-line format.
  5152   %e -- print error message about full memory.
  5153   %@ -- print @ or hyphen.  @ means that default-directory is on a
  5154         remote machine.
  5155   %[ -- print one [ for each recursive editing level.  %] similar.
  5156   %% -- print %.   %- -- print infinitely many dashes.
  5157 Decimal digits after the % specify field width to which to pad.  */);
  5158 
  5159   DEFVAR_PER_BUFFER ("major-mode", &BVAR (current_buffer, major_mode),
  5160                      Qsymbolp,
  5161                      doc: /* Symbol for current buffer's major mode.
  5162 The default value (normally `fundamental-mode') affects new buffers.
  5163 A value of nil means to use the current buffer's major mode, provided
  5164 it is not marked as "special".  */);
  5165 
  5166   DEFVAR_PER_BUFFER ("local-minor-modes",
  5167                      &BVAR (current_buffer, local_minor_modes),
  5168                      Qnil,
  5169                      doc: /* Minor modes currently active in the current buffer.
  5170 This is a list of symbols, or nil if there are no minor modes active.  */);
  5171 
  5172   DEFVAR_PER_BUFFER ("mode-name", &BVAR (current_buffer, mode_name),
  5173                      Qnil,
  5174                      doc: /* Pretty name of current buffer's major mode.
  5175 Usually a string, but can use any of the constructs for `mode-line-format',
  5176 which see.
  5177 Format with `format-mode-line' to produce a string value.  */);
  5178 
  5179   DEFVAR_PER_BUFFER ("local-abbrev-table", &BVAR (current_buffer, abbrev_table), Qnil,
  5180                      doc: /* Local (mode-specific) abbrev table of current buffer.  */);
  5181 
  5182   DEFVAR_PER_BUFFER ("abbrev-mode", &BVAR (current_buffer, abbrev_mode), Qnil,
  5183                      doc: /*  Non-nil if Abbrev mode is enabled.
  5184 Use the command `abbrev-mode' to change this variable.  */);
  5185 
  5186   DEFVAR_PER_BUFFER ("case-fold-search", &BVAR (current_buffer, case_fold_search),
  5187                      Qnil,
  5188                      doc: /* Non-nil if searches and matches should ignore case.  */);
  5189 
  5190   DEFVAR_PER_BUFFER ("fill-column", &BVAR (current_buffer, fill_column),
  5191                      Qintegerp,
  5192                      doc: /* Column beyond which automatic line-wrapping should happen.
  5193 It is used by filling commands, such as `fill-region' and `fill-paragraph',
  5194 and by `auto-fill-mode', which see.
  5195 See also `current-fill-column'.
  5196 Interactively, you can set the buffer local value using \\[set-fill-column].  */);
  5197 
  5198   DEFVAR_PER_BUFFER ("left-margin", &BVAR (current_buffer, left_margin),
  5199                      Qintegerp,
  5200                      doc: /* Column for the default `indent-line-function' to indent to.
  5201 Linefeed indents to this column in Fundamental mode.  */);
  5202 
  5203   DEFVAR_PER_BUFFER ("tab-width", &BVAR (current_buffer, tab_width),
  5204                      Qintegerp,
  5205                      doc: /* Distance between tab stops (for display of tab characters), in columns.
  5206 This controls the width of a TAB character on display.
  5207 The value should be a positive integer.
  5208 Note that this variable doesn't necessarily affect the size of the
  5209 indentation step.  However, if the major mode's indentation facility
  5210 inserts one or more TAB characters, this variable will affect the
  5211 indentation step as well, even if `indent-tabs-mode' is non-nil.  */);
  5212 
  5213   DEFVAR_PER_BUFFER ("ctl-arrow", &BVAR (current_buffer, ctl_arrow), Qnil,
  5214                      doc: /* Non-nil means display control chars with uparrow `^'.
  5215 A value of nil means use backslash `\\' and octal digits.
  5216 This variable does not apply to characters whose display is specified in
  5217 the current display table (if there is one; see `standard-display-table').  */);
  5218 
  5219   DEFVAR_PER_BUFFER ("enable-multibyte-characters",
  5220                      &BVAR (current_buffer, enable_multibyte_characters),
  5221                      Qnil,
  5222                      doc: /* Non-nil means the buffer contents are regarded as multi-byte characters.
  5223 Otherwise they are regarded as unibyte.  This affects the display,
  5224 file I/O and the behavior of various editing commands.
  5225 
  5226 This variable is buffer-local but you cannot set it directly;
  5227 use the function `set-buffer-multibyte' to change a buffer's representation.
  5228 To prevent any attempts to set it or make it buffer-local, Emacs will
  5229 signal an error in those cases.
  5230 See also Info node `(elisp)Text Representations'.  */);
  5231   make_symbol_constant (intern_c_string ("enable-multibyte-characters"));
  5232 
  5233   DEFVAR_PER_BUFFER ("buffer-file-coding-system",
  5234                      &BVAR (current_buffer, buffer_file_coding_system), Qnil,
  5235                      doc: /* Coding system to be used for encoding the buffer contents on saving.
  5236 This variable applies to saving the buffer, and also to `write-region'
  5237 and other functions that use `write-region'.
  5238 It does not apply to sending output to subprocesses, however.
  5239 
  5240 If this is nil, the buffer is saved without any code conversion
  5241 unless some coding system is specified in `file-coding-system-alist'
  5242 for the buffer file.
  5243 
  5244 If the text to be saved cannot be encoded as specified by this variable,
  5245 an alternative encoding is selected by `select-safe-coding-system', which see.
  5246 
  5247 The variable `coding-system-for-write', if non-nil, overrides this variable.
  5248 
  5249 This variable is never applied to a way of decoding a file while reading it.  */);
  5250 
  5251   DEFVAR_PER_BUFFER ("bidi-display-reordering",
  5252                      &BVAR (current_buffer, bidi_display_reordering), Qnil,
  5253                      doc: /* Non-nil means reorder bidirectional text for display in the visual order.
  5254 Setting this to nil is intended for use in debugging the display code.
  5255 Don't set to nil in normal sessions, as that is not supported.
  5256 See also `bidi-paragraph-direction'; setting that non-nil might
  5257 speed up redisplay.  */);
  5258 
  5259   DEFVAR_PER_BUFFER ("bidi-paragraph-start-re",
  5260                      &BVAR (current_buffer, bidi_paragraph_start_re), Qnil,
  5261                      doc: /* If non-nil, a regexp matching a line that starts OR separates paragraphs.
  5262 
  5263 The value of nil means to use empty lines as lines that start and
  5264 separate paragraphs.
  5265 
  5266 When Emacs displays bidirectional text, it by default computes
  5267 the base paragraph direction separately for each paragraph.
  5268 Setting this variable changes the places where paragraph base
  5269 direction is recomputed.
  5270 
  5271 The regexp is always matched after a newline, so it is best to
  5272 anchor it by beginning it with a "^".
  5273 
  5274 If you change the value of this variable, be sure to change
  5275 the value of `bidi-paragraph-separate-re' accordingly.  For
  5276 example, to have a single newline behave as a paragraph separator,
  5277 set both these variables to "^".
  5278 
  5279 See also `bidi-paragraph-direction'.  */);
  5280 
  5281   DEFVAR_PER_BUFFER ("bidi-paragraph-separate-re",
  5282                      &BVAR (current_buffer, bidi_paragraph_separate_re), Qnil,
  5283                      doc: /* If non-nil, a regexp matching a line that separates paragraphs.
  5284 
  5285 The value of nil means to use empty lines as paragraph separators.
  5286 
  5287 When Emacs displays bidirectional text, it by default computes
  5288 the base paragraph direction separately for each paragraph.
  5289 Setting this variable changes the places where paragraph base
  5290 direction is recomputed.
  5291 
  5292 The regexp is always matched after a newline, so it is best to
  5293 anchor it by beginning it with a "^".
  5294 
  5295 If you change the value of this variable, be sure to change
  5296 the value of `bidi-paragraph-start-re' accordingly.  For
  5297 example, to have a single newline behave as a paragraph separator,
  5298 set both these variables to "^".
  5299 
  5300 See also `bidi-paragraph-direction'.  */);
  5301 
  5302   DEFVAR_PER_BUFFER ("bidi-paragraph-direction",
  5303                      &BVAR (current_buffer, bidi_paragraph_direction), Qnil,
  5304                      doc: /* If non-nil, forces directionality of text paragraphs in the buffer.
  5305 
  5306 If this is nil (the default), the direction of each paragraph is
  5307 determined by the first strong directional character of its text.
  5308 The values of `right-to-left' and `left-to-right' override that.
  5309 Any other value is treated as nil.
  5310 
  5311 This variable has no effect unless the buffer's value of
  5312 `bidi-display-reordering' is non-nil.  */);
  5313 
  5314  DEFVAR_PER_BUFFER ("truncate-lines", &BVAR (current_buffer, truncate_lines), Qnil,
  5315                      doc: /* Non-nil means do not display continuation lines.
  5316 Instead, give each line of text just one screen line.
  5317 
  5318 Note that this is overridden by the variable
  5319 `truncate-partial-width-windows' if that variable is non-nil
  5320 and this buffer is not full-frame width.
  5321 
  5322 Minibuffers set this variable to nil.
  5323 
  5324 Don't set this to a non-nil value when `visual-line-mode' is
  5325 turned on, as it could produce confusing results.   */);
  5326 
  5327   DEFVAR_PER_BUFFER ("word-wrap", &BVAR (current_buffer, word_wrap), Qnil,
  5328                      doc: /* Non-nil means to use word-wrapping for continuation lines.
  5329 When word-wrapping is on, continuation lines are wrapped at the space
  5330 or tab character nearest to the right window edge.
  5331 If nil, continuation lines are wrapped at the right screen edge.
  5332 
  5333 This variable has no effect if long lines are truncated (see
  5334 `truncate-lines' and `truncate-partial-width-windows').  If you use
  5335 word-wrapping, you might want to reduce the value of
  5336 `truncate-partial-width-windows', since wrapping can make text readable
  5337 in narrower windows.
  5338 
  5339 Instead of setting this variable directly, most users should use
  5340 Visual Line mode.  Visual Line mode, when enabled, sets `word-wrap'
  5341 to t, and additionally redefines simple editing commands to act on
  5342 visual lines rather than logical lines.  See the documentation of
  5343 `visual-line-mode'.  */);
  5344 
  5345   DEFVAR_PER_BUFFER ("default-directory", &BVAR (current_buffer, directory),
  5346                      Qstringp,
  5347                      doc: /* Name of default directory of current buffer.
  5348 It should be an absolute directory name; on GNU and Unix systems,
  5349 these names start with `/' or `~' and end with `/'.
  5350 To interactively change the default directory, use command `cd'. */);
  5351 
  5352   DEFVAR_PER_BUFFER ("auto-fill-function", &BVAR (current_buffer, auto_fill_function),
  5353                      Qnil,
  5354                      doc: /* Function called (if non-nil) to perform auto-fill.
  5355 It is called after self-inserting any character specified in
  5356 the `auto-fill-chars' table.
  5357 NOTE: This variable is not a hook;
  5358 its value may not be a list of functions.  */);
  5359 
  5360   DEFVAR_PER_BUFFER ("buffer-file-name", &BVAR (current_buffer, filename),
  5361                      Qstringp,
  5362                      doc: /* Name of file visited in current buffer, or nil if not visiting a file.
  5363 This should be an absolute file name.  */);
  5364 
  5365   DEFVAR_PER_BUFFER ("buffer-file-truename", &BVAR (current_buffer, file_truename),
  5366                      Qstringp,
  5367                      doc: /* Abbreviated truename of file visited in current buffer, or nil if none.
  5368 The truename of a file is calculated by `file-truename'
  5369 and then abbreviated with `abbreviate-file-name'.  */);
  5370 
  5371   DEFVAR_PER_BUFFER ("buffer-auto-save-file-name",
  5372                      &BVAR (current_buffer, auto_save_file_name),
  5373                      Qstringp,
  5374                      doc: /* Name of file for auto-saving current buffer.
  5375 If it is nil, that means don't auto-save this buffer.  */);
  5376 
  5377   DEFVAR_PER_BUFFER ("buffer-read-only", &BVAR (current_buffer, read_only), Qnil,
  5378                      doc: /* Non-nil if this buffer is read-only.  */);
  5379 
  5380   DEFVAR_PER_BUFFER ("buffer-backed-up", &BVAR (current_buffer, backed_up), Qnil,
  5381                      doc: /* Non-nil if this buffer's file has been backed up.
  5382 Backing up is done before the first time the file is saved.  */);
  5383 
  5384   DEFVAR_PER_BUFFER ("buffer-saved-size", &BVAR (current_buffer, save_length),
  5385                      Qintegerp,
  5386                      doc: /* Length of current buffer when last read in, saved or auto-saved.
  5387 0 initially.
  5388 -1 means auto-saving turned off until next real save.
  5389 
  5390 If you set this to -2, that means don't turn off auto-saving in this buffer
  5391 if its text size shrinks.   If you use `buffer-swap-text' on a buffer,
  5392 you probably should set this to -2 in that buffer.  */);
  5393 
  5394   DEFVAR_PER_BUFFER ("selective-display", &BVAR (current_buffer, selective_display),
  5395                      Qnil,
  5396                      doc: /* Non-nil enables selective display.
  5397 
  5398 An integer N as value means display only lines
  5399 that start with less than N columns of space.
  5400 
  5401 A value of t means that the character ^M makes itself and
  5402 all the rest of the line invisible; also, when saving the buffer
  5403 in a file, save the ^M as a newline.  This usage is obsolete; use
  5404 overlays or text properties instead.  */);
  5405 
  5406   DEFVAR_PER_BUFFER ("selective-display-ellipses",
  5407                      &BVAR (current_buffer, selective_display_ellipses),
  5408                      Qnil,
  5409                      doc: /* Non-nil means display ... on previous line when a line is invisible.  */);
  5410 
  5411   DEFVAR_PER_BUFFER ("overwrite-mode", &BVAR (current_buffer, overwrite_mode),
  5412                      Qoverwrite_mode,
  5413                      doc: /* Non-nil if self-insertion should replace existing text.
  5414 The value should be one of `overwrite-mode-textual',
  5415 `overwrite-mode-binary', or nil.
  5416 If it is `overwrite-mode-textual', self-insertion still
  5417 inserts at the end of a line, and inserts when point is before a tab,
  5418 until the tab is filled in.
  5419 If `overwrite-mode-binary', self-insertion replaces newlines and tabs too.  */);
  5420 
  5421   DEFVAR_PER_BUFFER ("buffer-display-table", &BVAR (current_buffer, display_table),
  5422                      Qnil,
  5423                      doc: /* Display table that controls display of the contents of current buffer.
  5424 
  5425 If this variable is nil, the value of `standard-display-table' is used.
  5426 Each window can have its own, overriding display table, see
  5427 `set-window-display-table' and `window-display-table'.
  5428 
  5429 The display table is a char-table created with `make-display-table'.
  5430 A char-table is an array indexed by character codes.  Normal array
  5431 primitives `aref' and `aset' can be used to access elements of a char-table.
  5432 
  5433 Each of the char-table elements control how to display the corresponding
  5434 text character: the element at index C in the table says how to display
  5435 the character whose code is C.  Each element should be a vector of
  5436 characters or nil.  The value nil means display the character in the
  5437 default fashion; otherwise, the characters from the vector are delivered
  5438 to the screen instead of the original character.
  5439 
  5440 For example, (aset buffer-display-table ?X [?Y]) tells Emacs
  5441 to display a capital Y instead of each X character.
  5442 
  5443 In addition, a char-table has six extra slots to control the display of:
  5444 
  5445   the end of a truncated screen line (extra-slot 0, a single character);
  5446   the end of a continued line (extra-slot 1, a single character);
  5447   the escape character used to display character codes in octal
  5448     (extra-slot 2, a single character);
  5449   the character used as an arrow for control characters (extra-slot 3,
  5450     a single character);
  5451   the decoration indicating the presence of invisible lines (extra-slot 4,
  5452     a vector of characters);
  5453   the character used to draw the border between side-by-side windows
  5454     (extra-slot 5, a single character).
  5455 
  5456 See also the functions `display-table-slot' and `set-display-table-slot'.  */);
  5457 
  5458   DEFVAR_PER_BUFFER ("left-margin-width", &BVAR (current_buffer, left_margin_cols),
  5459                      Qintegerp,
  5460                      doc: /* Width in columns of left marginal area for display of a buffer.
  5461 A value of nil means no marginal area.
  5462 
  5463 Setting this variable does not take effect until a new buffer is displayed
  5464 in a window.  To make the change take effect, call `set-window-buffer'.  */);
  5465 
  5466   DEFVAR_PER_BUFFER ("right-margin-width", &BVAR (current_buffer, right_margin_cols),
  5467                      Qintegerp,
  5468                      doc: /* Width in columns of right marginal area for display of a buffer.
  5469 A value of nil means no marginal area.
  5470 
  5471 Setting this variable does not take effect until a new buffer is displayed
  5472 in a window.  To make the change take effect, call `set-window-buffer'.  */);
  5473 
  5474   DEFVAR_PER_BUFFER ("left-fringe-width", &BVAR (current_buffer, left_fringe_width),
  5475                      Qintegerp,
  5476                      doc: /* Width of this buffer's left fringe (in pixels).
  5477 A value of 0 means no left fringe is shown in this buffer's window.
  5478 A value of nil means to use the left fringe width from the window's frame.
  5479 
  5480 Setting this variable does not take effect until a new buffer is displayed
  5481 in a window.  To make the change take effect, call `set-window-buffer'.  */);
  5482 
  5483   DEFVAR_PER_BUFFER ("right-fringe-width", &BVAR (current_buffer, right_fringe_width),
  5484                      Qintegerp,
  5485                      doc: /* Width of this buffer's right fringe (in pixels).
  5486 A value of 0 means no right fringe is shown in this buffer's window.
  5487 A value of nil means to use the right fringe width from the window's frame.
  5488 
  5489 Setting this variable does not take effect until a new buffer is displayed
  5490 in a window.  To make the change take effect, call `set-window-buffer'.  */);
  5491 
  5492   DEFVAR_PER_BUFFER ("fringes-outside-margins", &BVAR (current_buffer, fringes_outside_margins),
  5493                      Qnil,
  5494                      doc: /* Non-nil means to display fringes outside display margins.
  5495 A value of nil means to display fringes between margins and buffer text.
  5496 
  5497 Setting this variable does not take effect until a new buffer is displayed
  5498 in a window.  To make the change take effect, call `set-window-buffer'.  */);
  5499 
  5500   DEFVAR_PER_BUFFER ("scroll-bar-width", &BVAR (current_buffer, scroll_bar_width),
  5501                      Qintegerp,
  5502                      doc: /* Width of this buffer's vertical scroll bars in pixels.
  5503 A value of nil means to use the scroll bar width from the window's frame.  */);
  5504 
  5505   DEFVAR_PER_BUFFER ("scroll-bar-height", &BVAR (current_buffer, scroll_bar_height),
  5506                      Qintegerp,
  5507                      doc: /* Height of this buffer's horizontal scroll bars in pixels.
  5508 A value of nil means to use the scroll bar height from the window's frame.  */);
  5509 
  5510   DEFVAR_PER_BUFFER ("vertical-scroll-bar", &BVAR (current_buffer, vertical_scroll_bar_type),
  5511                      Qvertical_scroll_bar,
  5512                      doc: /* Position of this buffer's vertical scroll bar.
  5513 The value takes effect whenever you tell a window to display this buffer;
  5514 for instance, with `set-window-buffer' or when `display-buffer' displays it.
  5515 
  5516 A value of `left' or `right' means put the vertical scroll bar at that side
  5517 of the window; a value of nil means don't show any vertical scroll bars.
  5518 A value of t (the default) means do whatever the window's frame specifies.  */);
  5519 
  5520   DEFVAR_PER_BUFFER ("horizontal-scroll-bar", &BVAR (current_buffer, horizontal_scroll_bar_type),
  5521                      Qnil,
  5522                      doc: /* Position of this buffer's horizontal scroll bar.
  5523 The value takes effect whenever you tell a window to display this buffer;
  5524 for instance, with `set-window-buffer' or when `display-buffer' displays it.
  5525 
  5526 A value of `bottom' means put the horizontal scroll bar at the bottom of
  5527 the window; a value of nil means don't show any horizontal scroll bars.
  5528 A value of t (the default) means do whatever the window's frame
  5529 specifies.  */);
  5530 
  5531   DEFVAR_PER_BUFFER ("indicate-empty-lines",
  5532                      &BVAR (current_buffer, indicate_empty_lines), Qnil,
  5533                      doc: /* Visually indicate unused ("empty") screen lines after the buffer end.
  5534 If non-nil, a bitmap is displayed in the left fringe of a window
  5535 on graphical displays for each screen line that doesn't correspond
  5536 to any buffer text.  */);
  5537 
  5538   DEFVAR_PER_BUFFER ("indicate-buffer-boundaries",
  5539                      &BVAR (current_buffer, indicate_buffer_boundaries), Qnil,
  5540                      doc: /* Visually indicate buffer boundaries and scrolling.
  5541 If non-nil, the first and last line of the buffer are marked in the fringe
  5542 of a window on graphical displays with angle bitmaps, or if the window can be
  5543 scrolled, the top and bottom line of the window are marked with up and down
  5544 arrow bitmaps.
  5545 
  5546 If value is a symbol `left' or `right', both angle and arrow bitmaps
  5547 are displayed in the left or right fringe, resp.  Any other value
  5548 that doesn't look like an alist means display the angle bitmaps in
  5549 the left fringe but no arrows.
  5550 
  5551 You can exercise more precise control by using an alist as the
  5552 value.  Each alist element (INDICATOR . POSITION) specifies
  5553 where to show one of the indicators.  INDICATOR is one of `top',
  5554 `bottom', `up', `down', or t, which specifies the default position,
  5555 and POSITION is one of `left', `right', or nil, meaning do not show
  5556 this indicator.
  5557 
  5558 For example, ((top . left) (t . right)) places the top angle bitmap in
  5559 left fringe, the bottom angle bitmap in right fringe, and both arrow
  5560 bitmaps in right fringe.  To show just the angle bitmaps in the left
  5561 fringe, but no arrow bitmaps, use ((top .  left) (bottom . left)).  */);
  5562 
  5563   DEFVAR_PER_BUFFER ("fringe-indicator-alist",
  5564                      &BVAR (current_buffer, fringe_indicator_alist), Qnil,
  5565                      doc: /* Mapping from logical to physical fringe indicator bitmaps.
  5566 The value is an alist where each element (INDICATOR . BITMAPS)
  5567 specifies the fringe bitmaps used to display a specific logical
  5568 fringe indicator.
  5569 
  5570 INDICATOR specifies the logical indicator type which is one of the
  5571 following symbols: `truncation' , `continuation', `overlay-arrow',
  5572 `top', `bottom', `top-bottom', `up', `down', empty-line', or `unknown'.
  5573 
  5574 BITMAPS is a list of symbols (LEFT RIGHT [LEFT1 RIGHT1]) which specifies
  5575 the actual bitmap shown in the left or right fringe for the logical
  5576 indicator.  LEFT and RIGHT are the bitmaps shown in the left and/or
  5577 right fringe for the specific indicator.  The LEFT1 or RIGHT1 bitmaps
  5578 are used only for the `bottom' and `top-bottom' indicators when the
  5579 last (only) line has no final newline.  BITMAPS may also be a single
  5580 symbol which is used in both left and right fringes.  */);
  5581 
  5582   DEFVAR_PER_BUFFER ("fringe-cursor-alist",
  5583                      &BVAR (current_buffer, fringe_cursor_alist), Qnil,
  5584                      doc: /* Mapping from logical to physical fringe cursor bitmaps.
  5585 The value is an alist where each element (CURSOR . BITMAP)
  5586 specifies the fringe bitmaps used to display a specific logical
  5587 cursor type in the fringe.
  5588 
  5589 CURSOR specifies the logical cursor type which is one of the following
  5590 symbols: `box' , `hollow', `bar', `hbar', or `hollow-small'.  The last
  5591 one is used to show a hollow cursor on narrow lines display lines
  5592 where the normal hollow cursor will not fit.
  5593 
  5594 BITMAP is the corresponding fringe bitmap shown for the logical
  5595 cursor type.  */);
  5596 
  5597   DEFVAR_PER_BUFFER ("scroll-up-aggressively",
  5598                      &BVAR (current_buffer, scroll_up_aggressively), Qfraction,
  5599                      doc: /* How far to scroll windows upward.
  5600 If you move point off the bottom, the window scrolls automatically.
  5601 This variable controls how far it scrolls.  The value nil, the default,
  5602 means scroll to center point.  A fraction means scroll to put point
  5603 that fraction of the window's height from the bottom of the window.
  5604 When the value is 0.0, point goes at the bottom line, which in the
  5605 simple case that you moved off with C-f means scrolling just one line.
  5606 1.0 means point goes at the top, so that in that simple case, the
  5607 window scrolls by a full window height.  Meaningful values are
  5608 between 0.0 and 1.0, inclusive.  */);
  5609 
  5610   DEFVAR_PER_BUFFER ("scroll-down-aggressively",
  5611                      &BVAR (current_buffer, scroll_down_aggressively), Qfraction,
  5612                      doc: /* How far to scroll windows downward.
  5613 If you move point off the top, the window scrolls automatically.
  5614 This variable controls how far it scrolls.  The value nil, the default,
  5615 means scroll to center point.  A fraction means scroll to put point
  5616 that fraction of the window's height from the top of the window.
  5617 When the value is 0.0, point goes at the top line, which in the
  5618 simple case that you moved off with C-b means scrolling just one line.
  5619 1.0 means point goes at the bottom, so that in that simple case, the
  5620 window scrolls by a full window height.  Meaningful values are
  5621 between 0.0 and 1.0, inclusive.  */);
  5622 
  5623   DEFVAR_LISP ("before-change-functions", Vbefore_change_functions,
  5624                doc: /* List of functions to call before each text change.
  5625 Two arguments are passed to each function: the positions of
  5626 the beginning and end of the range of old text to be changed.
  5627 \(For an insertion, the beginning and end are at the same place.)
  5628 No information is given about the length of the text after the change.
  5629 
  5630 Buffer changes made while executing the `before-change-functions'
  5631 don't call any before-change or after-change functions.
  5632 That's because `inhibit-modification-hooks' is temporarily set non-nil.
  5633 
  5634 If an unhandled error happens in running these functions,
  5635 the variable's value remains nil.  That prevents the error
  5636 from happening repeatedly and making Emacs nonfunctional.  */);
  5637   Vbefore_change_functions = Qnil;
  5638 
  5639   DEFVAR_LISP ("after-change-functions", Vafter_change_functions,
  5640                doc: /* List of functions to call after each text change.
  5641 Three arguments are passed to each function: the positions of
  5642 the beginning and end of the range of changed text,
  5643 and the length in chars of the pre-change text replaced by that range.
  5644 \(For an insertion, the pre-change length is zero;
  5645 for a deletion, that length is the number of chars deleted,
  5646 and the post-change beginning and end are at the same place.)
  5647 
  5648 Buffer changes made while executing the `after-change-functions'
  5649 don't call any before-change or after-change functions.
  5650 That's because `inhibit-modification-hooks' is temporarily set non-nil.
  5651 
  5652 If an unhandled error happens in running these functions,
  5653 the variable's value remains nil.  That prevents the error
  5654 from happening repeatedly and making Emacs nonfunctional.  */);
  5655   Vafter_change_functions = Qnil;
  5656 
  5657   DEFVAR_LISP ("first-change-hook", Vfirst_change_hook,
  5658                doc: /* A list of functions to call before changing a buffer which is unmodified.
  5659 The functions are run using the `run-hooks' function.  */);
  5660   Vfirst_change_hook = Qnil;
  5661 
  5662   DEFVAR_PER_BUFFER ("buffer-undo-list", &BVAR (current_buffer, undo_list), Qnil,
  5663                      doc: /* List of undo entries in current buffer.
  5664 Recent changes come first; older changes follow newer.
  5665 
  5666 An entry (BEG . END) represents an insertion which begins at
  5667 position BEG and ends at position END.
  5668 
  5669 An entry (TEXT . POSITION) represents the deletion of the string TEXT
  5670 from (abs POSITION).  If POSITION is positive, point was at the front
  5671 of the text being deleted; if negative, point was at the end.
  5672 
  5673 An entry (t . TIMESTAMP), where TIMESTAMP is in the style of
  5674 `current-time', indicates that the buffer was previously unmodified;
  5675 TIMESTAMP is the visited file's modification time, as of that time.
  5676 If the modification time of the most recent save is different, this
  5677 entry is obsolete.
  5678 
  5679 An entry (t . 0) means the buffer was previously unmodified but
  5680 its time stamp was unknown because it was not associated with a file.
  5681 An entry (t . -1) is similar, except that it means the buffer's visited
  5682 file did not exist.
  5683 
  5684 An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
  5685 was modified between BEG and END.  PROPERTY is the property name,
  5686 and VALUE is the old value.
  5687 
  5688 An entry (apply FUN-NAME . ARGS) means undo the change with
  5689 \(apply FUN-NAME ARGS).
  5690 
  5691 An entry (apply DELTA BEG END FUN-NAME . ARGS) supports selective undo
  5692 in the active region.  BEG and END is the range affected by this entry
  5693 and DELTA is the number of characters added or deleted in that range by
  5694 this change.
  5695 
  5696 An entry (MARKER . DISTANCE) indicates that the marker MARKER
  5697 was adjusted in position by the offset DISTANCE (an integer).
  5698 
  5699 An entry of the form POSITION indicates that point was at the buffer
  5700 location given by the integer.  Undoing an entry of this form places
  5701 point at POSITION.
  5702 
  5703 Entries with value nil mark undo boundaries.  The undo command treats
  5704 the changes between two undo boundaries as a single step to be undone.
  5705 
  5706 If the value of the variable is t, undo information is not recorded.  */);
  5707 
  5708   DEFVAR_PER_BUFFER ("mark-active", &BVAR (current_buffer, mark_active), Qnil,
  5709                      doc: /* Non-nil means the mark and region are currently active in this buffer.  */);
  5710 
  5711   DEFVAR_PER_BUFFER ("cache-long-scans", &BVAR (current_buffer, cache_long_scans), Qnil,
  5712                      doc: /* Non-nil means that Emacs should use caches in attempt to speedup buffer scans.
  5713 
  5714 There is no reason to set this to nil except for debugging purposes.
  5715 
  5716 Normally, the line-motion functions work by scanning the buffer for
  5717 newlines.  Columnar operations (like `move-to-column' and
  5718 `compute-motion') also work by scanning the buffer, summing character
  5719 widths as they go.  This works well for ordinary text, but if the
  5720 buffer's lines are very long (say, more than 500 characters), these
  5721 motion functions will take longer to execute.  Emacs may also take
  5722 longer to update the display.
  5723 
  5724 If `cache-long-scans' is non-nil, these motion functions cache the
  5725 results of their scans, and consult the cache to avoid rescanning
  5726 regions of the buffer until the text is modified.  The caches are most
  5727 beneficial when they prevent the most searching---that is, when the
  5728 buffer contains long lines and large regions of characters with the
  5729 same, fixed screen width.
  5730 
  5731 When `cache-long-scans' is non-nil, processing short lines will
  5732 become slightly slower (because of the overhead of consulting the
  5733 cache), and the caches will use memory roughly proportional to the
  5734 number of newlines and characters whose screen width varies.
  5735 
  5736 Bidirectional editing also requires buffer scans to find paragraph
  5737 separators.  If you have large paragraphs or no paragraph separators
  5738 at all, these scans may be slow.  If `cache-long-scans' is non-nil,
  5739 results of these scans are cached.  This doesn't help too much if
  5740 paragraphs are of the reasonable (few thousands of characters) size.
  5741 
  5742 The caches require no explicit maintenance; their accuracy is
  5743 maintained internally by the Emacs primitives.  Enabling or disabling
  5744 the cache should not affect the behavior of any of the motion
  5745 functions; it should only affect their performance.  */);
  5746 
  5747   DEFVAR_PER_BUFFER ("point-before-scroll", &BVAR (current_buffer, point_before_scroll), Qnil,
  5748                      doc: /* Value of point before the last series of scroll operations, or nil.  */);
  5749 
  5750   DEFVAR_PER_BUFFER ("buffer-file-format", &BVAR (current_buffer, file_format), Qnil,
  5751                      doc: /* List of formats to use when saving this buffer.
  5752 Formats are defined by `format-alist'.  This variable is
  5753 set when a file is visited.  */);
  5754 
  5755   DEFVAR_PER_BUFFER ("buffer-auto-save-file-format",
  5756                      &BVAR (current_buffer, auto_save_file_format), Qnil,
  5757                      doc: /* Format in which to write auto-save files.
  5758 Should be a list of symbols naming formats that are defined in `format-alist'.
  5759 If it is t, which is the default, auto-save files are written in the
  5760 same format as a regular save would use.  */);
  5761 
  5762   DEFVAR_PER_BUFFER ("buffer-invisibility-spec",
  5763                      &BVAR (current_buffer, invisibility_spec), Qnil,
  5764                      doc: /* Invisibility spec of this buffer.
  5765 The default is t, which means that text is invisible if it has a non-nil
  5766 `invisible' property.
  5767 This variable can also be a list.  The list can have two kinds of elements:
  5768 `ATOM' and `(ATOM . ELLIPSIS)'.  A text character is invisible if its
  5769 `invisible' property is `ATOM', or has an `invisible' property that is a list
  5770 that contains `ATOM'.
  5771 If the `(ATOM . ELLIPSIS)' form is used, and `ELLIPSIS' is non-nil, an
  5772 ellipsis will be displayed after the invisible characters.
  5773 Setting this variable is very fast, much faster than scanning all the text in
  5774 the buffer looking for properties to change.  */);
  5775 
  5776   DEFVAR_PER_BUFFER ("buffer-display-count",
  5777                      &BVAR (current_buffer, display_count), Qintegerp,
  5778                      doc: /* A number incremented each time this buffer is displayed in a window.
  5779 The function `set-window-buffer' increments it.  */);
  5780 
  5781   DEFVAR_PER_BUFFER ("buffer-display-time",
  5782                      &BVAR (current_buffer, display_time), Qnil,
  5783                      doc: /* Time stamp updated each time this buffer is displayed in a window.
  5784 The function `set-window-buffer' updates this variable
  5785 to the value obtained by calling `current-time'.
  5786 If the buffer has never been shown in a window, the value is nil.  */);
  5787 
  5788   DEFVAR_LISP ("transient-mark-mode", Vtransient_mark_mode,
  5789                doc: /*  Non-nil if Transient Mark mode is enabled.
  5790 See the command `transient-mark-mode' for a description of this minor mode.
  5791 
  5792 Non-nil also enables highlighting of the region whenever the mark is active.
  5793 The region is highlighted with the `region' face.
  5794 The variable `highlight-nonselected-windows' controls whether to highlight
  5795 all windows or just the selected window.
  5796 
  5797 Lisp programs may give this variable certain special values:
  5798 
  5799 - The symbol `lambda' enables Transient Mark mode temporarily.
  5800   The mode is disabled again after any subsequent action that would
  5801   normally deactivate the mark (e.g. buffer modification).
  5802 
  5803 - The pair (only . OLDVAL) enables Transient Mark mode
  5804   temporarily.  After any subsequent point motion command that is
  5805   not shift-translated, or any other action that would normally
  5806   deactivate the mark (e.g. buffer modification), the value of
  5807   `transient-mark-mode' is set to OLDVAL.  */);
  5808   Vtransient_mark_mode = Qnil;
  5809 
  5810   DEFVAR_LISP ("inhibit-read-only", Vinhibit_read_only,
  5811                doc: /* Non-nil means disregard read-only status of buffers or characters.
  5812 A non-nil value that is a list means disregard `buffer-read-only' status,
  5813 and disregard a `read-only' text property if the property value is a
  5814 member of the list.  Any other non-nil value means disregard `buffer-read-only'
  5815 and all `read-only' text properties.  */);
  5816   Vinhibit_read_only = Qnil;
  5817 
  5818   DEFVAR_PER_BUFFER ("cursor-type", &BVAR (current_buffer, cursor_type), Qnil,
  5819                      doc: /* Cursor to use when this buffer is in the selected window.
  5820 Values are interpreted as follows:
  5821 
  5822   t               use the cursor specified for the frame
  5823   nil             don't display a cursor
  5824   box             display a filled box cursor
  5825   (box . SIZE)    display a filled box cursor, but make it
  5826                   hollow if cursor is under masked image larger than
  5827                   SIZE pixels in either dimension.
  5828   hollow          display a hollow box cursor
  5829   bar             display a vertical bar cursor with default width
  5830   (bar . WIDTH)   display a vertical bar cursor with width WIDTH
  5831   hbar            display a horizontal bar cursor with default height
  5832   (hbar . HEIGHT) display a horizontal bar cursor with height HEIGHT
  5833   ANYTHING ELSE   display a hollow box cursor
  5834 
  5835 WIDTH and HEIGHT can't exceed the frame's canonical character size.
  5836 
  5837 When the buffer is displayed in a non-selected window, the
  5838 cursor's appearance is instead controlled by the variable
  5839 `cursor-in-non-selected-windows'.  */);
  5840 
  5841   DEFVAR_PER_BUFFER ("line-spacing",
  5842                      &BVAR (current_buffer, extra_line_spacing), Qnumberp,
  5843                      doc: /* Additional space to put between lines when displaying a buffer.
  5844 The space is measured in pixels, and put below lines on graphic displays,
  5845 see `display-graphic-p'.
  5846 If value is a floating point number, it specifies the spacing relative
  5847 to the default frame line height.  A value of nil means add no extra space.  */);
  5848 
  5849   DEFVAR_PER_BUFFER ("cursor-in-non-selected-windows",
  5850                      &BVAR (current_buffer, cursor_in_non_selected_windows), Qnil,
  5851                      doc: /* Non-nil means show a cursor in non-selected windows.
  5852 If nil, only shows a cursor in the selected window.
  5853 If t, displays a cursor related to the usual cursor type
  5854 \(a solid box becomes hollow, a bar becomes a narrower bar).
  5855 You can also specify the cursor type as in the `cursor-type' variable.
  5856 Use Custom to set this variable and update the display.  */);
  5857 
  5858   DEFVAR_LISP ("kill-buffer-query-functions", Vkill_buffer_query_functions,
  5859                doc: /* List of functions called with no args to query before killing a buffer.
  5860 The buffer being killed will be current while the functions are running.
  5861 See `kill-buffer'.
  5862 
  5863 If any of them returns nil, the buffer is not killed.  Functions run by
  5864 this hook are supposed to not change the current buffer.
  5865 
  5866 This hook is not run for internal or temporary buffers created by
  5867 `get-buffer-create' or `generate-new-buffer' with argument
  5868 INHIBIT-BUFFER-HOOKS non-nil.  */);
  5869   Vkill_buffer_query_functions = Qnil;
  5870 
  5871   DEFVAR_LISP ("change-major-mode-hook", Vchange_major_mode_hook,
  5872                doc: /* Normal hook run before changing the major mode of a buffer.
  5873 The function `kill-all-local-variables' runs this before doing anything else.  */);
  5874   Vchange_major_mode_hook = Qnil;
  5875   DEFSYM (Qchange_major_mode_hook, "change-major-mode-hook");
  5876 
  5877   DEFVAR_LISP ("buffer-list-update-hook", Vbuffer_list_update_hook,
  5878                doc: /* Hook run when the buffer list changes.
  5879 Functions (implicitly) running this hook are `get-buffer-create',
  5880 `make-indirect-buffer', `rename-buffer', `kill-buffer', `bury-buffer'
  5881 and `select-window'.  This hook is not run for internal or temporary
  5882 buffers created by `get-buffer-create' or `generate-new-buffer' with
  5883 argument INHIBIT-BUFFER-HOOKS non-nil.
  5884 
  5885 Functions run by this hook should avoid calling `select-window' with a
  5886 nil NORECORD argument since it may lead to infinite recursion.  */);
  5887   Vbuffer_list_update_hook = Qnil;
  5888   DEFSYM (Qbuffer_list_update_hook, "buffer-list-update-hook");
  5889 
  5890   DEFVAR_BOOL ("kill-buffer-delete-auto-save-files",
  5891                kill_buffer_delete_auto_save_files,
  5892                doc: /* If non-nil, offer to delete any autosave file when killing a buffer.
  5893 
  5894 If `delete-auto-save-files' is nil, any autosave deletion is inhibited.  */);
  5895   kill_buffer_delete_auto_save_files = 0;
  5896 
  5897   DEFVAR_BOOL ("delete-auto-save-files", delete_auto_save_files,
  5898                doc: /* Non-nil means delete auto-save file when a buffer is saved.
  5899 This is the default.  If nil, auto-save file deletion is inhibited.  */);
  5900   delete_auto_save_files = 1;
  5901 
  5902   DEFVAR_LISP ("clone-indirect-buffer-hook", Vclone_indirect_buffer_hook,
  5903                doc: /* Normal hook to run in the new buffer at the end of `make-indirect-buffer'.
  5904 
  5905 Since `clone-indirect-buffer' calls `make-indirect-buffer', this hook
  5906 will run for `clone-indirect-buffer' calls as well.  */);
  5907   Vclone_indirect_buffer_hook = Qnil;
  5908 
  5909   DEFVAR_LISP ("long-line-threshold", Vlong_line_threshold,
  5910     doc: /* Line length above which to use redisplay shortcuts.
  5911 
  5912 The value should be a positive integer or nil.
  5913 If the value is an integer, shortcuts in the display code intended
  5914 to speed up redisplay for long lines will automatically be enabled
  5915 in buffers which contain one or more lines whose length is above
  5916 this threshold.
  5917 If nil, these display shortcuts will always remain disabled.
  5918 
  5919 There is no reason to change that value except for debugging purposes.  */);
  5920   XSETFASTINT (Vlong_line_threshold, 50000);
  5921 
  5922   DEFVAR_INT ("long-line-optimizations-region-size",
  5923               long_line_optimizations_region_size,
  5924               doc: /* Region size for narrowing in buffers with long lines.
  5925 
  5926 This variable has effect only in buffers in which
  5927 `long-line-optimizations-p' is non-nil.  For performance reasons, in
  5928 such buffers, the `fontification-functions', `pre-command-hook' and
  5929 `post-command-hook' hooks are executed on a narrowed buffer around
  5930 point, as if they were called in a `with-restriction' form with a label.
  5931 This variable specifies the size of the narrowed region around point.
  5932 
  5933 To disable that narrowing, set this variable to 0.
  5934 
  5935 See also `long-line-optimizations-bol-search-limit'.
  5936 
  5937 There is no reason to change that value except for debugging purposes.  */);
  5938   long_line_optimizations_region_size = 500000;
  5939 
  5940   DEFVAR_INT ("long-line-optimizations-bol-search-limit",
  5941               long_line_optimizations_bol_search_limit,
  5942               doc: /* Limit for beginning of line search in buffers with long lines.
  5943 
  5944 This variable has effect only in buffers in which
  5945 `long-line-optimizations-p' is non-nil.  For performance reasons, in
  5946 such buffers, the `fontification-functions', `pre-command-hook' and
  5947 `post-command-hook' hooks are executed on a narrowed buffer around
  5948 point, as if they were called in a `with-restriction' form with a label.
  5949 The variable `long-line-optimizations-region-size' specifies the
  5950 size of the narrowed region around point.  This variable, which should
  5951 be a small integer, specifies the number of characters by which that
  5952 region can be extended backwards to make it start at the beginning of
  5953 a line.
  5954 
  5955 There is no reason to change that value except for debugging purposes.  */);
  5956   long_line_optimizations_bol_search_limit = 128;
  5957 
  5958   DEFVAR_INT ("large-hscroll-threshold", large_hscroll_threshold,
  5959     doc: /* Horizontal scroll of truncated lines above which to use redisplay shortcuts.
  5960 
  5961 The value should be a positive integer.
  5962 
  5963 Shortcuts in the display code intended to speed up redisplay for long
  5964 and truncated lines will automatically be enabled when a line's
  5965 horizontal scroll amount is or about to become larger than the value
  5966 of this variable.
  5967 
  5968 This variable has effect only in buffers which contain one or more
  5969 lines whose length is above `long-line-threshold', which see.
  5970 To disable redisplay shortcuts for long truncated line, set this
  5971 variable to `most-positive-fixnum'.
  5972 
  5973 There is no reason to change that value except for debugging purposes.  */);
  5974   large_hscroll_threshold = 10000;
  5975 
  5976   defsubr (&Sbuffer_live_p);
  5977   defsubr (&Sbuffer_list);
  5978   defsubr (&Sget_buffer);
  5979   defsubr (&Sget_file_buffer);
  5980   defsubr (&Sget_buffer_create);
  5981   defsubr (&Smake_indirect_buffer);
  5982   defsubr (&Sgenerate_new_buffer_name);
  5983   defsubr (&Sbuffer_name);
  5984   defsubr (&Sbuffer_file_name);
  5985   defsubr (&Sbuffer_base_buffer);
  5986   defsubr (&Sbuffer_local_value);
  5987   defsubr (&Sbuffer_local_variables);
  5988   defsubr (&Sbuffer_modified_p);
  5989   defsubr (&Sforce_mode_line_update);
  5990   defsubr (&Sset_buffer_modified_p);
  5991   defsubr (&Sbuffer_modified_tick);
  5992   defsubr (&Sinternal__set_buffer_modified_tick);
  5993   defsubr (&Sbuffer_chars_modified_tick);
  5994   defsubr (&Srename_buffer);
  5995   defsubr (&Sother_buffer);
  5996   defsubr (&Sbuffer_enable_undo);
  5997   defsubr (&Skill_buffer);
  5998   defsubr (&Sbury_buffer_internal);
  5999   defsubr (&Sset_buffer_major_mode);
  6000   defsubr (&Scurrent_buffer);
  6001   defsubr (&Sset_buffer);
  6002   defsubr (&Sbarf_if_buffer_read_only);
  6003   defsubr (&Serase_buffer);
  6004   defsubr (&Sbuffer_swap_text);
  6005   defsubr (&Sset_buffer_multibyte);
  6006   defsubr (&Skill_all_local_variables);
  6007 
  6008   defsubr (&Soverlayp);
  6009   defsubr (&Smake_overlay);
  6010   defsubr (&Sdelete_overlay);
  6011   defsubr (&Sdelete_all_overlays);
  6012   defsubr (&Smove_overlay);
  6013   defsubr (&Soverlay_start);
  6014   defsubr (&Soverlay_end);
  6015   defsubr (&Soverlay_buffer);
  6016   defsubr (&Soverlay_properties);
  6017   defsubr (&Soverlays_at);
  6018   defsubr (&Soverlays_in);
  6019   defsubr (&Snext_overlay_change);
  6020   defsubr (&Sprevious_overlay_change);
  6021   defsubr (&Soverlay_recenter);
  6022   defsubr (&Soverlay_lists);
  6023   defsubr (&Soverlay_get);
  6024   defsubr (&Soverlay_put);
  6025   defsubr (&Srestore_buffer_modified_p);
  6026 
  6027   DEFSYM (Qautosaved, "autosaved");
  6028 
  6029 #ifdef ITREE_DEBUG
  6030   defsubr (&Soverlay_tree);
  6031 #endif
  6032 
  6033   DEFSYM (Qkill_buffer__possibly_save, "kill-buffer--possibly-save");
  6034 
  6035   DEFSYM (Qbuffer_stale_function, "buffer-stale-function");
  6036 
  6037   Fput (intern_c_string ("erase-buffer"), Qdisabled, Qt);
  6038 }

/* [<][>][^][v][top][bottom][index][help] */