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