Merge from emacs-24; up to 2013-01-03T02:37:57Z!rgm@gnu.org
[emacs.git] / src / buffer.c
blob61b685ea5c5f7f534a4ce845ce5c654b46ac7113
1 /* Buffer manipulation primitives for GNU Emacs.
3 Copyright (C) 1985-1989, 1993-1995, 1997-2013 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/param.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <unistd.h>
30 #include <verify.h>
32 #include "lisp.h"
33 #include "intervals.h"
34 #include "window.h"
35 #include "commands.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "region-cache.h"
39 #include "indent.h"
40 #include "blockinput.h"
41 #include "keyboard.h"
42 #include "keymap.h"
43 #include "frame.h"
45 struct buffer *current_buffer; /* The current buffer. */
47 /* First buffer in chain of all buffers (in reverse order of creation).
48 Threaded through ->header.next.buffer. */
50 struct buffer *all_buffers;
52 /* This structure holds the default values of the buffer-local variables
53 defined with DEFVAR_PER_BUFFER, that have special slots in each buffer.
54 The default value occupies the same slot in this structure
55 as an individual buffer's value occupies in that buffer.
56 Setting the default value also goes through the alist of buffers
57 and stores into each buffer that does not say it has a local value. */
59 struct buffer alignas (GCALIGNMENT) buffer_defaults;
61 /* This structure marks which slots in a buffer have corresponding
62 default values in buffer_defaults.
63 Each such slot has a nonzero value in this structure.
64 The value has only one nonzero bit.
66 When a buffer has its own local value for a slot,
67 the entry for that slot (found in the same slot in this structure)
68 is turned on in the buffer's local_flags array.
70 If a slot in this structure is -1, then even though there may
71 be a DEFVAR_PER_BUFFER for the slot, there is no default value for it;
72 and the corresponding slot in buffer_defaults is not used.
74 If a slot in this structure corresponding to a DEFVAR_PER_BUFFER is
75 zero, that is a bug. */
77 struct buffer buffer_local_flags;
79 /* This structure holds the names of symbols whose values may be
80 buffer-local. It is indexed and accessed in the same way as the above. */
82 struct buffer alignas (GCALIGNMENT) buffer_local_symbols;
84 /* Return the symbol of the per-buffer variable at offset OFFSET in
85 the buffer structure. */
87 #define PER_BUFFER_SYMBOL(OFFSET) \
88 (*(Lisp_Object *)((OFFSET) + (char *) &buffer_local_symbols))
90 /* Maximum length of an overlay vector. */
91 #define OVERLAY_COUNT_MAX \
92 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, \
93 min (PTRDIFF_MAX, SIZE_MAX) / word_size))
95 /* Flags indicating which built-in buffer-local variables
96 are permanent locals. */
97 static char buffer_permanent_local_flags[MAX_PER_BUFFER_VARS];
99 /* Number of per-buffer variables used. */
101 int last_per_buffer_idx;
103 static void call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay,
104 bool after, Lisp_Object arg1,
105 Lisp_Object arg2, Lisp_Object arg3);
106 static void swap_out_buffer_local_variables (struct buffer *b);
107 static void reset_buffer_local_variables (struct buffer *, bool);
109 /* Alist of all buffer names vs the buffers. This used to be
110 a Lisp-visible variable, but is no longer, to prevent lossage
111 due to user rplac'ing this alist or its elements. */
112 Lisp_Object Vbuffer_alist;
114 static Lisp_Object Qkill_buffer_query_functions;
116 /* Hook run before changing a major mode. */
117 static Lisp_Object Qchange_major_mode_hook;
119 Lisp_Object Qfirst_change_hook;
120 Lisp_Object Qbefore_change_functions;
121 Lisp_Object Qafter_change_functions;
123 static Lisp_Object Qfundamental_mode, Qmode_class, Qpermanent_local;
124 static Lisp_Object Qpermanent_local_hook;
126 static Lisp_Object Qprotected_field;
128 static Lisp_Object QSFundamental; /* A string "Fundamental". */
130 static Lisp_Object Qkill_buffer_hook;
131 static Lisp_Object Qbuffer_list_update_hook;
133 static Lisp_Object Qget_file_buffer;
135 static Lisp_Object Qoverlayp;
137 Lisp_Object Qpriority, Qbefore_string, Qafter_string;
139 static Lisp_Object Qevaporate;
141 Lisp_Object Qmodification_hooks;
142 Lisp_Object Qinsert_in_front_hooks;
143 Lisp_Object Qinsert_behind_hooks;
145 static void alloc_buffer_text (struct buffer *, ptrdiff_t);
146 static void free_buffer_text (struct buffer *b);
147 static struct Lisp_Overlay * copy_overlays (struct buffer *, struct Lisp_Overlay *);
148 static void modify_overlay (struct buffer *, ptrdiff_t, ptrdiff_t);
149 static Lisp_Object buffer_lisp_local_variables (struct buffer *, bool);
151 static void
152 CHECK_OVERLAY (Lisp_Object x)
154 CHECK_TYPE (OVERLAYP (x), Qoverlayp, x);
157 /* These setters are used only in this file, so they can be private.
158 The public setters are inline functions defined in buffer.h. */
159 static void
160 bset_abbrev_mode (struct buffer *b, Lisp_Object val)
162 b->INTERNAL_FIELD (abbrev_mode) = val;
164 static void
165 bset_abbrev_table (struct buffer *b, Lisp_Object val)
167 b->INTERNAL_FIELD (abbrev_table) = val;
169 static void
170 bset_auto_fill_function (struct buffer *b, Lisp_Object val)
172 b->INTERNAL_FIELD (auto_fill_function) = val;
174 static void
175 bset_auto_save_file_format (struct buffer *b, Lisp_Object val)
177 b->INTERNAL_FIELD (auto_save_file_format) = val;
179 static void
180 bset_auto_save_file_name (struct buffer *b, Lisp_Object val)
182 b->INTERNAL_FIELD (auto_save_file_name) = val;
184 static void
185 bset_backed_up (struct buffer *b, Lisp_Object val)
187 b->INTERNAL_FIELD (backed_up) = val;
189 static void
190 bset_begv_marker (struct buffer *b, Lisp_Object val)
192 b->INTERNAL_FIELD (begv_marker) = val;
194 static void
195 bset_bidi_display_reordering (struct buffer *b, Lisp_Object val)
197 b->INTERNAL_FIELD (bidi_display_reordering) = val;
199 static void
200 bset_buffer_file_coding_system (struct buffer *b, Lisp_Object val)
202 b->INTERNAL_FIELD (buffer_file_coding_system) = val;
204 static void
205 bset_case_fold_search (struct buffer *b, Lisp_Object val)
207 b->INTERNAL_FIELD (case_fold_search) = val;
209 static void
210 bset_ctl_arrow (struct buffer *b, Lisp_Object val)
212 b->INTERNAL_FIELD (ctl_arrow) = val;
214 static void
215 bset_cursor_in_non_selected_windows (struct buffer *b, Lisp_Object val)
217 b->INTERNAL_FIELD (cursor_in_non_selected_windows) = val;
219 static void
220 bset_cursor_type (struct buffer *b, Lisp_Object val)
222 b->INTERNAL_FIELD (cursor_type) = val;
224 static void
225 bset_display_table (struct buffer *b, Lisp_Object val)
227 b->INTERNAL_FIELD (display_table) = val;
229 static void
230 bset_extra_line_spacing (struct buffer *b, Lisp_Object val)
232 b->INTERNAL_FIELD (extra_line_spacing) = val;
234 static void
235 bset_file_format (struct buffer *b, Lisp_Object val)
237 b->INTERNAL_FIELD (file_format) = val;
239 static void
240 bset_file_truename (struct buffer *b, Lisp_Object val)
242 b->INTERNAL_FIELD (file_truename) = val;
244 static void
245 bset_fringe_cursor_alist (struct buffer *b, Lisp_Object val)
247 b->INTERNAL_FIELD (fringe_cursor_alist) = val;
249 static void
250 bset_fringe_indicator_alist (struct buffer *b, Lisp_Object val)
252 b->INTERNAL_FIELD (fringe_indicator_alist) = val;
254 static void
255 bset_fringes_outside_margins (struct buffer *b, Lisp_Object val)
257 b->INTERNAL_FIELD (fringes_outside_margins) = val;
259 static void
260 bset_header_line_format (struct buffer *b, Lisp_Object val)
262 b->INTERNAL_FIELD (header_line_format) = val;
264 static void
265 bset_indicate_buffer_boundaries (struct buffer *b, Lisp_Object val)
267 b->INTERNAL_FIELD (indicate_buffer_boundaries) = val;
269 static void
270 bset_indicate_empty_lines (struct buffer *b, Lisp_Object val)
272 b->INTERNAL_FIELD (indicate_empty_lines) = val;
274 static void
275 bset_invisibility_spec (struct buffer *b, Lisp_Object val)
277 b->INTERNAL_FIELD (invisibility_spec) = val;
279 static void
280 bset_left_fringe_width (struct buffer *b, Lisp_Object val)
282 b->INTERNAL_FIELD (left_fringe_width) = val;
284 static void
285 bset_major_mode (struct buffer *b, Lisp_Object val)
287 b->INTERNAL_FIELD (major_mode) = val;
289 static void
290 bset_mark (struct buffer *b, Lisp_Object val)
292 b->INTERNAL_FIELD (mark) = val;
294 static void
295 bset_minor_modes (struct buffer *b, Lisp_Object val)
297 b->INTERNAL_FIELD (minor_modes) = val;
299 static void
300 bset_mode_line_format (struct buffer *b, Lisp_Object val)
302 b->INTERNAL_FIELD (mode_line_format) = val;
304 static void
305 bset_mode_name (struct buffer *b, Lisp_Object val)
307 b->INTERNAL_FIELD (mode_name) = val;
309 static void
310 bset_name (struct buffer *b, Lisp_Object val)
312 b->INTERNAL_FIELD (name) = val;
314 static void
315 bset_overwrite_mode (struct buffer *b, Lisp_Object val)
317 b->INTERNAL_FIELD (overwrite_mode) = val;
319 static void
320 bset_pt_marker (struct buffer *b, Lisp_Object val)
322 b->INTERNAL_FIELD (pt_marker) = val;
324 static void
325 bset_right_fringe_width (struct buffer *b, Lisp_Object val)
327 b->INTERNAL_FIELD (right_fringe_width) = val;
329 static void
330 bset_save_length (struct buffer *b, Lisp_Object val)
332 b->INTERNAL_FIELD (save_length) = val;
334 static void
335 bset_scroll_bar_width (struct buffer *b, Lisp_Object val)
337 b->INTERNAL_FIELD (scroll_bar_width) = val;
339 static void
340 bset_scroll_down_aggressively (struct buffer *b, Lisp_Object val)
342 b->INTERNAL_FIELD (scroll_down_aggressively) = val;
344 static void
345 bset_scroll_up_aggressively (struct buffer *b, Lisp_Object val)
347 b->INTERNAL_FIELD (scroll_up_aggressively) = val;
349 static void
350 bset_selective_display (struct buffer *b, Lisp_Object val)
352 b->INTERNAL_FIELD (selective_display) = val;
354 static void
355 bset_selective_display_ellipses (struct buffer *b, Lisp_Object val)
357 b->INTERNAL_FIELD (selective_display_ellipses) = val;
359 static void
360 bset_vertical_scroll_bar_type (struct buffer *b, Lisp_Object val)
362 b->INTERNAL_FIELD (vertical_scroll_bar_type) = val;
364 static void
365 bset_word_wrap (struct buffer *b, Lisp_Object val)
367 b->INTERNAL_FIELD (word_wrap) = val;
369 static void
370 bset_zv_marker (struct buffer *b, Lisp_Object val)
372 b->INTERNAL_FIELD (zv_marker) = val;
375 void
376 nsberror (Lisp_Object spec)
378 if (STRINGP (spec))
379 error ("No buffer named %s", SDATA (spec));
380 error ("Invalid buffer argument");
383 DEFUN ("buffer-live-p", Fbuffer_live_p, Sbuffer_live_p, 1, 1, 0,
384 doc: /* Return non-nil if OBJECT is a buffer which has not been killed.
385 Value is nil if OBJECT is not a buffer or if it has been killed. */)
386 (Lisp_Object object)
388 return ((BUFFERP (object) && BUFFER_LIVE_P (XBUFFER (object)))
389 ? Qt : Qnil);
392 DEFUN ("buffer-list", Fbuffer_list, Sbuffer_list, 0, 1, 0,
393 doc: /* Return a list of all existing live buffers.
394 If the optional arg FRAME is a frame, we return the buffer list in the
395 proper order for that frame: the buffers show in FRAME come first,
396 followed by the rest of the buffers. */)
397 (Lisp_Object frame)
399 Lisp_Object general;
400 general = Fmapcar (Qcdr, Vbuffer_alist);
402 if (FRAMEP (frame))
404 Lisp_Object framelist, prevlist, tail;
405 Lisp_Object args[3];
407 framelist = Fcopy_sequence (XFRAME (frame)->buffer_list);
408 prevlist = Fnreverse (Fcopy_sequence
409 (XFRAME (frame)->buried_buffer_list));
411 /* Remove from GENERAL any buffer that duplicates one in
412 FRAMELIST or PREVLIST. */
413 tail = framelist;
414 while (CONSP (tail))
416 general = Fdelq (XCAR (tail), general);
417 tail = XCDR (tail);
419 tail = prevlist;
420 while (CONSP (tail))
422 general = Fdelq (XCAR (tail), general);
423 tail = XCDR (tail);
426 args[0] = framelist;
427 args[1] = general;
428 args[2] = prevlist;
429 return Fnconc (3, args);
431 else
432 return general;
435 /* Like Fassoc, but use Fstring_equal to compare
436 (which ignores text properties),
437 and don't ever QUIT. */
439 static Lisp_Object
440 assoc_ignore_text_properties (register Lisp_Object key, Lisp_Object list)
442 register Lisp_Object tail;
443 for (tail = list; CONSP (tail); tail = XCDR (tail))
445 register Lisp_Object elt, tem;
446 elt = XCAR (tail);
447 tem = Fstring_equal (Fcar (elt), key);
448 if (!NILP (tem))
449 return elt;
451 return Qnil;
454 DEFUN ("get-buffer", Fget_buffer, Sget_buffer, 1, 1, 0,
455 doc: /* Return the buffer named BUFFER-OR-NAME.
456 BUFFER-OR-NAME must be either a string or a buffer. If BUFFER-OR-NAME
457 is a string and there is no buffer with that name, return nil. If
458 BUFFER-OR-NAME is a buffer, return it as given. */)
459 (register Lisp_Object buffer_or_name)
461 if (BUFFERP (buffer_or_name))
462 return buffer_or_name;
463 CHECK_STRING (buffer_or_name);
465 return Fcdr (assoc_ignore_text_properties (buffer_or_name, Vbuffer_alist));
468 DEFUN ("get-file-buffer", Fget_file_buffer, Sget_file_buffer, 1, 1, 0,
469 doc: /* Return the buffer visiting file FILENAME (a string).
470 The buffer's `buffer-file-name' must match exactly the expansion of FILENAME.
471 If there is no such live buffer, return nil.
472 See also `find-buffer-visiting'. */)
473 (register Lisp_Object filename)
475 register Lisp_Object tail, buf, handler;
477 CHECK_STRING (filename);
478 filename = Fexpand_file_name (filename, Qnil);
480 /* If the file name has special constructs in it,
481 call the corresponding file handler. */
482 handler = Ffind_file_name_handler (filename, Qget_file_buffer);
483 if (!NILP (handler))
485 Lisp_Object handled_buf = call2 (handler, Qget_file_buffer,
486 filename);
487 return BUFFERP (handled_buf) ? handled_buf : Qnil;
490 FOR_EACH_LIVE_BUFFER (tail, buf)
492 if (!STRINGP (BVAR (XBUFFER (buf), filename))) continue;
493 if (!NILP (Fstring_equal (BVAR (XBUFFER (buf), filename), filename)))
494 return buf;
496 return Qnil;
499 Lisp_Object
500 get_truename_buffer (register Lisp_Object filename)
502 register Lisp_Object tail, buf;
504 FOR_EACH_LIVE_BUFFER (tail, buf)
506 if (!STRINGP (BVAR (XBUFFER (buf), file_truename))) continue;
507 if (!NILP (Fstring_equal (BVAR (XBUFFER (buf), file_truename), filename)))
508 return buf;
510 return Qnil;
513 DEFUN ("get-buffer-create", Fget_buffer_create, Sget_buffer_create, 1, 1, 0,
514 doc: /* Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.
515 If BUFFER-OR-NAME is a string and a live buffer with that name exists,
516 return that buffer. If no such buffer exists, create a new buffer with
517 that name and return it. If BUFFER-OR-NAME starts with a space, the new
518 buffer does not keep undo information.
520 If BUFFER-OR-NAME is a buffer instead of a string, return it as given,
521 even if it is dead. The return value is never nil. */)
522 (register Lisp_Object buffer_or_name)
524 register Lisp_Object buffer, name;
525 register struct buffer *b;
527 buffer = Fget_buffer (buffer_or_name);
528 if (!NILP (buffer))
529 return buffer;
531 if (SCHARS (buffer_or_name) == 0)
532 error ("Empty string for buffer name is not allowed");
534 b = allocate_buffer ();
536 /* An ordinary buffer uses its own struct buffer_text. */
537 b->text = &b->own_text;
538 b->base_buffer = NULL;
539 /* No one shares the text with us now. */
540 b->indirections = 0;
541 /* No one shows us now. */
542 b->window_count = 0;
544 BUF_GAP_SIZE (b) = 20;
545 block_input ();
546 /* We allocate extra 1-byte at the tail and keep it always '\0' for
547 anchoring a search. */
548 alloc_buffer_text (b, BUF_GAP_SIZE (b) + 1);
549 unblock_input ();
550 if (! BUF_BEG_ADDR (b))
551 buffer_memory_full (BUF_GAP_SIZE (b) + 1);
553 b->pt = BEG;
554 b->begv = BEG;
555 b->zv = BEG;
556 b->pt_byte = BEG_BYTE;
557 b->begv_byte = BEG_BYTE;
558 b->zv_byte = BEG_BYTE;
560 BUF_GPT (b) = BEG;
561 BUF_GPT_BYTE (b) = BEG_BYTE;
563 BUF_Z (b) = BEG;
564 BUF_Z_BYTE (b) = BEG_BYTE;
565 BUF_MODIFF (b) = 1;
566 BUF_CHARS_MODIFF (b) = 1;
567 BUF_OVERLAY_MODIFF (b) = 1;
568 BUF_SAVE_MODIFF (b) = 1;
569 BUF_COMPACT (b) = 1;
570 set_buffer_intervals (b, NULL);
571 BUF_UNCHANGED_MODIFIED (b) = 1;
572 BUF_OVERLAY_UNCHANGED_MODIFIED (b) = 1;
573 BUF_END_UNCHANGED (b) = 0;
574 BUF_BEG_UNCHANGED (b) = 0;
575 *(BUF_GPT_ADDR (b)) = *(BUF_Z_ADDR (b)) = 0; /* Put an anchor '\0'. */
576 b->text->inhibit_shrinking = 0;
578 b->newline_cache = 0;
579 b->width_run_cache = 0;
580 b->bidi_paragraph_cache = 0;
581 bset_width_table (b, Qnil);
582 b->prevent_redisplay_optimizations_p = 1;
584 /* An ordinary buffer normally doesn't need markers
585 to handle BEGV and ZV. */
586 bset_pt_marker (b, Qnil);
587 bset_begv_marker (b, Qnil);
588 bset_zv_marker (b, Qnil);
590 name = Fcopy_sequence (buffer_or_name);
591 set_string_intervals (name, NULL);
592 bset_name (b, name);
594 bset_undo_list (b, SREF (name, 0) != ' ' ? Qnil : Qt);
596 reset_buffer (b);
597 reset_buffer_local_variables (b, 1);
599 bset_mark (b, Fmake_marker ());
600 BUF_MARKERS (b) = NULL;
602 /* Put this in the alist of all live buffers. */
603 XSETBUFFER (buffer, b);
604 Vbuffer_alist = nconc2 (Vbuffer_alist, list1 (Fcons (name, buffer)));
605 /* And run buffer-list-update-hook. */
606 if (!NILP (Vrun_hooks))
607 call1 (Vrun_hooks, Qbuffer_list_update_hook);
609 return buffer;
613 /* Return a list of overlays which is a copy of the overlay list
614 LIST, but for buffer B. */
616 static struct Lisp_Overlay *
617 copy_overlays (struct buffer *b, struct Lisp_Overlay *list)
619 struct Lisp_Overlay *result = NULL, *tail = NULL;
621 for (; list; list = list->next)
623 Lisp_Object overlay, start, end;
624 struct Lisp_Marker *m;
626 eassert (MARKERP (list->start));
627 m = XMARKER (list->start);
628 start = build_marker (b, m->charpos, m->bytepos);
629 XMARKER (start)->insertion_type = m->insertion_type;
631 eassert (MARKERP (list->end));
632 m = XMARKER (list->end);
633 end = build_marker (b, m->charpos, m->bytepos);
634 XMARKER (end)->insertion_type = m->insertion_type;
636 overlay = build_overlay (start, end, Fcopy_sequence (list->plist));
637 if (tail)
638 tail = tail->next = XOVERLAY (overlay);
639 else
640 result = tail = XOVERLAY (overlay);
643 return result;
646 /* Set an appropriate overlay of B. */
648 static void
649 set_buffer_overlays_before (struct buffer *b, struct Lisp_Overlay *o)
651 b->overlays_before = o;
654 static void
655 set_buffer_overlays_after (struct buffer *b, struct Lisp_Overlay *o)
657 b->overlays_after = o;
660 /* Clone per-buffer values of buffer FROM.
662 Buffer TO gets the same per-buffer values as FROM, with the
663 following exceptions: (1) TO's name is left untouched, (2) markers
664 are copied and made to refer to TO, and (3) overlay lists are
665 copied. */
667 static void
668 clone_per_buffer_values (struct buffer *from, struct buffer *to)
670 int offset;
672 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
674 Lisp_Object obj;
676 /* Don't touch the `name' which should be unique for every buffer. */
677 if (offset == PER_BUFFER_VAR_OFFSET (name))
678 continue;
680 obj = per_buffer_value (from, offset);
681 if (MARKERP (obj) && XMARKER (obj)->buffer == from)
683 struct Lisp_Marker *m = XMARKER (obj);
685 obj = build_marker (to, m->charpos, m->bytepos);
686 XMARKER (obj)->insertion_type = m->insertion_type;
689 set_per_buffer_value (to, offset, obj);
692 memcpy (to->local_flags, from->local_flags, sizeof to->local_flags);
694 set_buffer_overlays_before (to, copy_overlays (to, from->overlays_before));
695 set_buffer_overlays_after (to, copy_overlays (to, from->overlays_after));
697 /* Get (a copy of) the alist of Lisp-level local variables of FROM
698 and install that in TO. */
699 bset_local_var_alist (to, buffer_lisp_local_variables (from, 1));
703 /* If buffer B has markers to record PT, BEGV and ZV when it is not
704 current, update these markers. */
706 static void
707 record_buffer_markers (struct buffer *b)
709 if (! NILP (BVAR (b, pt_marker)))
711 Lisp_Object buffer;
713 eassert (!NILP (BVAR (b, begv_marker)));
714 eassert (!NILP (BVAR (b, zv_marker)));
716 XSETBUFFER (buffer, b);
717 set_marker_both (BVAR (b, pt_marker), buffer, b->pt, b->pt_byte);
718 set_marker_both (BVAR (b, begv_marker), buffer, b->begv, b->begv_byte);
719 set_marker_both (BVAR (b, zv_marker), buffer, b->zv, b->zv_byte);
724 /* If buffer B has markers to record PT, BEGV and ZV when it is not
725 current, fetch these values into B->begv etc. */
727 static void
728 fetch_buffer_markers (struct buffer *b)
730 if (! NILP (BVAR (b, pt_marker)))
732 Lisp_Object m;
734 eassert (!NILP (BVAR (b, begv_marker)));
735 eassert (!NILP (BVAR (b, zv_marker)));
737 m = BVAR (b, pt_marker);
738 SET_BUF_PT_BOTH (b, marker_position (m), marker_byte_position (m));
740 m = BVAR (b, begv_marker);
741 SET_BUF_BEGV_BOTH (b, marker_position (m), marker_byte_position (m));
743 m = BVAR (b, zv_marker);
744 SET_BUF_ZV_BOTH (b, marker_position (m), marker_byte_position (m));
749 DEFUN ("make-indirect-buffer", Fmake_indirect_buffer, Smake_indirect_buffer,
750 2, 3,
751 "bMake indirect buffer (to buffer): \nBName of indirect buffer: ",
752 doc: /* Create and return an indirect buffer for buffer BASE-BUFFER, named NAME.
753 BASE-BUFFER should be a live buffer, or the name of an existing buffer.
754 NAME should be a string which is not the name of an existing buffer.
755 Optional argument CLONE non-nil means preserve BASE-BUFFER's state,
756 such as major and minor modes, in the indirect buffer.
757 CLONE nil means the indirect buffer's state is reset to default values. */)
758 (Lisp_Object base_buffer, Lisp_Object name, Lisp_Object clone)
760 Lisp_Object buf, tem;
761 struct buffer *b;
763 CHECK_STRING (name);
764 buf = Fget_buffer (name);
765 if (!NILP (buf))
766 error ("Buffer name `%s' is in use", SDATA (name));
768 tem = base_buffer;
769 base_buffer = Fget_buffer (base_buffer);
770 if (NILP (base_buffer))
771 error ("No such buffer: `%s'", SDATA (tem));
772 if (!BUFFER_LIVE_P (XBUFFER (base_buffer)))
773 error ("Base buffer has been killed");
775 if (SCHARS (name) == 0)
776 error ("Empty string for buffer name is not allowed");
778 b = allocate_buffer ();
780 /* No double indirection - if base buffer is indirect,
781 new buffer becomes an indirect to base's base. */
782 b->base_buffer = (XBUFFER (base_buffer)->base_buffer
783 ? XBUFFER (base_buffer)->base_buffer
784 : XBUFFER (base_buffer));
786 /* Use the base buffer's text object. */
787 b->text = b->base_buffer->text;
788 /* We have no own text. */
789 b->indirections = -1;
790 /* Notify base buffer that we share the text now. */
791 b->base_buffer->indirections++;
792 /* Always -1 for an indirect buffer. */
793 b->window_count = -1;
795 b->pt = b->base_buffer->pt;
796 b->begv = b->base_buffer->begv;
797 b->zv = b->base_buffer->zv;
798 b->pt_byte = b->base_buffer->pt_byte;
799 b->begv_byte = b->base_buffer->begv_byte;
800 b->zv_byte = b->base_buffer->zv_byte;
802 b->newline_cache = 0;
803 b->width_run_cache = 0;
804 b->bidi_paragraph_cache = 0;
805 bset_width_table (b, Qnil);
807 name = Fcopy_sequence (name);
808 set_string_intervals (name, NULL);
809 bset_name (b, name);
811 reset_buffer (b);
812 reset_buffer_local_variables (b, 1);
814 /* Put this in the alist of all live buffers. */
815 XSETBUFFER (buf, b);
816 Vbuffer_alist = nconc2 (Vbuffer_alist, list1 (Fcons (name, buf)));
818 bset_mark (b, Fmake_marker ());
820 /* The multibyte status belongs to the base buffer. */
821 bset_enable_multibyte_characters
822 (b, BVAR (b->base_buffer, enable_multibyte_characters));
824 /* Make sure the base buffer has markers for its narrowing. */
825 if (NILP (BVAR (b->base_buffer, pt_marker)))
827 eassert (NILP (BVAR (b->base_buffer, begv_marker)));
828 eassert (NILP (BVAR (b->base_buffer, zv_marker)));
830 bset_pt_marker (b->base_buffer,
831 build_marker (b->base_buffer, b->base_buffer->pt,
832 b->base_buffer->pt_byte));
834 bset_begv_marker (b->base_buffer,
835 build_marker (b->base_buffer, b->base_buffer->begv,
836 b->base_buffer->begv_byte));
838 bset_zv_marker (b->base_buffer,
839 build_marker (b->base_buffer, b->base_buffer->zv,
840 b->base_buffer->zv_byte));
842 XMARKER (BVAR (b->base_buffer, zv_marker))->insertion_type = 1;
845 if (NILP (clone))
847 /* Give the indirect buffer markers for its narrowing. */
848 bset_pt_marker (b, build_marker (b, b->pt, b->pt_byte));
849 bset_begv_marker (b, build_marker (b, b->begv, b->begv_byte));
850 bset_zv_marker (b, build_marker (b, b->zv, b->zv_byte));
851 XMARKER (BVAR (b, zv_marker))->insertion_type = 1;
853 else
855 struct buffer *old_b = current_buffer;
857 clone_per_buffer_values (b->base_buffer, b);
858 bset_filename (b, Qnil);
859 bset_file_truename (b, Qnil);
860 bset_display_count (b, make_number (0));
861 bset_backed_up (b, Qnil);
862 bset_auto_save_file_name (b, Qnil);
863 set_buffer_internal_1 (b);
864 Fset (intern ("buffer-save-without-query"), Qnil);
865 Fset (intern ("buffer-file-number"), Qnil);
866 Fset (intern ("buffer-stale-function"), Qnil);
867 set_buffer_internal_1 (old_b);
870 /* Run buffer-list-update-hook. */
871 if (!NILP (Vrun_hooks))
872 call1 (Vrun_hooks, Qbuffer_list_update_hook);
874 return buf;
877 /* Mark OV as no longer associated with B. */
879 static void
880 drop_overlay (struct buffer *b, struct Lisp_Overlay *ov)
882 eassert (b == XBUFFER (Fmarker_buffer (ov->start)));
883 modify_overlay (b, marker_position (ov->start),
884 marker_position (ov->end));
885 unchain_marker (XMARKER (ov->start));
886 unchain_marker (XMARKER (ov->end));
890 /* Delete all overlays of B and reset it's overlay lists. */
892 void
893 delete_all_overlays (struct buffer *b)
895 struct Lisp_Overlay *ov, *next;
897 /* FIXME: Since each drop_overlay will scan BUF_MARKERS to unlink its
898 markers, we have an unneeded O(N^2) behavior here. */
899 for (ov = b->overlays_before; ov; ov = next)
901 drop_overlay (b, ov);
902 next = ov->next;
903 ov->next = NULL;
906 for (ov = b->overlays_after; ov; ov = next)
908 drop_overlay (b, ov);
909 next = ov->next;
910 ov->next = NULL;
913 set_buffer_overlays_before (b, NULL);
914 set_buffer_overlays_after (b, NULL);
917 /* Reinitialize everything about a buffer except its name and contents
918 and local variables.
919 If called on an already-initialized buffer, the list of overlays
920 should be deleted before calling this function, otherwise we end up
921 with overlays that claim to belong to the buffer but the buffer
922 claims it doesn't belong to it. */
924 void
925 reset_buffer (register struct buffer *b)
927 bset_filename (b, Qnil);
928 bset_file_truename (b, Qnil);
929 bset_directory (b, current_buffer ? BVAR (current_buffer, directory) : Qnil);
930 b->modtime = make_timespec (0, UNKNOWN_MODTIME_NSECS);
931 b->modtime_size = -1;
932 XSETFASTINT (BVAR (b, save_length), 0);
933 b->last_window_start = 1;
934 /* It is more conservative to start out "changed" than "unchanged". */
935 b->clip_changed = 0;
936 b->prevent_redisplay_optimizations_p = 1;
937 bset_backed_up (b, Qnil);
938 BUF_AUTOSAVE_MODIFF (b) = 0;
939 b->auto_save_failure_time = 0;
940 bset_auto_save_file_name (b, Qnil);
941 bset_read_only (b, Qnil);
942 set_buffer_overlays_before (b, NULL);
943 set_buffer_overlays_after (b, NULL);
944 b->overlay_center = BEG;
945 bset_mark_active (b, Qnil);
946 bset_point_before_scroll (b, Qnil);
947 bset_file_format (b, Qnil);
948 bset_auto_save_file_format (b, Qt);
949 bset_last_selected_window (b, Qnil);
950 bset_display_count (b, make_number (0));
951 bset_display_time (b, Qnil);
952 bset_enable_multibyte_characters
953 (b, BVAR (&buffer_defaults, enable_multibyte_characters));
954 bset_cursor_type (b, BVAR (&buffer_defaults, cursor_type));
955 bset_extra_line_spacing (b, BVAR (&buffer_defaults, extra_line_spacing));
957 b->display_error_modiff = 0;
960 /* Reset buffer B's local variables info.
961 Don't use this on a buffer that has already been in use;
962 it does not treat permanent locals consistently.
963 Instead, use Fkill_all_local_variables.
965 If PERMANENT_TOO, reset permanent buffer-local variables.
966 If not, preserve those. */
968 static void
969 reset_buffer_local_variables (struct buffer *b, bool permanent_too)
971 int offset, i;
973 /* Reset the major mode to Fundamental, together with all the
974 things that depend on the major mode.
975 default-major-mode is handled at a higher level.
976 We ignore it here. */
977 bset_major_mode (b, Qfundamental_mode);
978 bset_keymap (b, Qnil);
979 bset_mode_name (b, QSFundamental);
980 bset_minor_modes (b, Qnil);
982 /* If the standard case table has been altered and invalidated,
983 fix up its insides first. */
984 if (! (CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[0])
985 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[1])
986 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[2])))
987 Fset_standard_case_table (Vascii_downcase_table);
989 bset_downcase_table (b, Vascii_downcase_table);
990 bset_upcase_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[0]);
991 bset_case_canon_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[1]);
992 bset_case_eqv_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[2]);
993 bset_invisibility_spec (b, Qt);
995 /* Reset all (or most) per-buffer variables to their defaults. */
996 if (permanent_too)
997 bset_local_var_alist (b, Qnil);
998 else
1000 Lisp_Object tmp, prop, last = Qnil;
1001 for (tmp = BVAR (b, local_var_alist); CONSP (tmp); tmp = XCDR (tmp))
1002 if (!NILP (prop = Fget (XCAR (XCAR (tmp)), Qpermanent_local)))
1004 /* If permanent-local, keep it. */
1005 last = tmp;
1006 if (EQ (prop, Qpermanent_local_hook))
1008 /* This is a partially permanent hook variable.
1009 Preserve only the elements that want to be preserved. */
1010 Lisp_Object list, newlist;
1011 list = XCDR (XCAR (tmp));
1012 if (!CONSP (list))
1013 newlist = list;
1014 else
1015 for (newlist = Qnil; CONSP (list); list = XCDR (list))
1017 Lisp_Object elt = XCAR (list);
1018 /* Preserve element ELT if it's t,
1019 if it is a function with a `permanent-local-hook' property,
1020 or if it's not a symbol. */
1021 if (! SYMBOLP (elt)
1022 || EQ (elt, Qt)
1023 || !NILP (Fget (elt, Qpermanent_local_hook)))
1024 newlist = Fcons (elt, newlist);
1026 XSETCDR (XCAR (tmp), Fnreverse (newlist));
1029 /* Delete this local variable. */
1030 else if (NILP (last))
1031 bset_local_var_alist (b, XCDR (tmp));
1032 else
1033 XSETCDR (last, XCDR (tmp));
1036 for (i = 0; i < last_per_buffer_idx; ++i)
1037 if (permanent_too || buffer_permanent_local_flags[i] == 0)
1038 SET_PER_BUFFER_VALUE_P (b, i, 0);
1040 /* For each slot that has a default value, copy that into the slot. */
1041 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
1043 int idx = PER_BUFFER_IDX (offset);
1044 if ((idx > 0
1045 && (permanent_too
1046 || buffer_permanent_local_flags[idx] == 0)))
1047 set_per_buffer_value (b, offset, per_buffer_default (offset));
1051 /* We split this away from generate-new-buffer, because rename-buffer
1052 and set-visited-file-name ought to be able to use this to really
1053 rename the buffer properly. */
1055 DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name,
1056 Sgenerate_new_buffer_name, 1, 2, 0,
1057 doc: /* Return a string that is the name of no existing buffer based on NAME.
1058 If there is no live buffer named NAME, then return NAME.
1059 Otherwise modify name by appending `<NUMBER>', incrementing NUMBER
1060 \(starting at 2) until an unused name is found, and then return that name.
1061 Optional second argument IGNORE specifies a name that is okay to use (if
1062 it is in the sequence to be tried) even if a buffer with that name exists.
1064 If NAME begins with a space (i.e., a buffer that is not normally
1065 visible to users), then if buffer NAME already exists a random number
1066 is first appended to NAME, to speed up finding a non-existent buffer. */)
1067 (register Lisp_Object name, Lisp_Object ignore)
1069 register Lisp_Object gentemp, tem, tem2;
1070 ptrdiff_t count;
1071 char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
1073 CHECK_STRING (name);
1075 tem = Fstring_equal (name, ignore);
1076 if (!NILP (tem))
1077 return name;
1078 tem = Fget_buffer (name);
1079 if (NILP (tem))
1080 return name;
1082 if (!strncmp (SSDATA (name), " ", 1)) /* see bug#1229 */
1084 /* Note fileio.c:make_temp_name does random differently. */
1085 tem2 = concat2 (name, make_formatted_string
1086 (number, "-%"pI"d",
1087 XFASTINT (Frandom (make_number (999999)))));
1088 tem = Fget_buffer (tem2);
1089 if (NILP (tem))
1090 return tem2;
1092 else
1093 tem2 = name;
1095 count = 1;
1096 while (1)
1098 gentemp = concat2 (tem2, make_formatted_string
1099 (number, "<%"pD"d>", ++count));
1100 tem = Fstring_equal (gentemp, ignore);
1101 if (!NILP (tem))
1102 return gentemp;
1103 tem = Fget_buffer (gentemp);
1104 if (NILP (tem))
1105 return gentemp;
1110 DEFUN ("buffer-name", Fbuffer_name, Sbuffer_name, 0, 1, 0,
1111 doc: /* Return the name of BUFFER, as a string.
1112 BUFFER defaults to the current buffer.
1113 Return nil if BUFFER has been killed. */)
1114 (register Lisp_Object buffer)
1116 if (NILP (buffer))
1117 return BVAR (current_buffer, name);
1118 CHECK_BUFFER (buffer);
1119 return BVAR (XBUFFER (buffer), name);
1122 DEFUN ("buffer-file-name", Fbuffer_file_name, Sbuffer_file_name, 0, 1, 0,
1123 doc: /* Return name of file BUFFER is visiting, or nil if none.
1124 No argument or nil as argument means use the current buffer. */)
1125 (register Lisp_Object buffer)
1127 if (NILP (buffer))
1128 return BVAR (current_buffer, filename);
1129 CHECK_BUFFER (buffer);
1130 return BVAR (XBUFFER (buffer), filename);
1133 DEFUN ("buffer-base-buffer", Fbuffer_base_buffer, Sbuffer_base_buffer,
1134 0, 1, 0,
1135 doc: /* Return the base buffer of indirect buffer BUFFER.
1136 If BUFFER is not indirect, return nil.
1137 BUFFER defaults to the current buffer. */)
1138 (register Lisp_Object buffer)
1140 struct buffer *base;
1141 Lisp_Object base_buffer;
1143 if (NILP (buffer))
1144 base = current_buffer->base_buffer;
1145 else
1147 CHECK_BUFFER (buffer);
1148 base = XBUFFER (buffer)->base_buffer;
1151 if (! base)
1152 return Qnil;
1153 XSETBUFFER (base_buffer, base);
1154 return base_buffer;
1157 DEFUN ("buffer-local-value", Fbuffer_local_value,
1158 Sbuffer_local_value, 2, 2, 0,
1159 doc: /* Return the value of VARIABLE in BUFFER.
1160 If VARIABLE does not have a buffer-local binding in BUFFER, the value
1161 is the default binding of the variable. */)
1162 (register Lisp_Object variable, register Lisp_Object buffer)
1164 register Lisp_Object result = buffer_local_value_1 (variable, buffer);
1166 if (EQ (result, Qunbound))
1167 xsignal1 (Qvoid_variable, variable);
1169 return result;
1173 /* Like Fbuffer_local_value, but return Qunbound if the variable is
1174 locally unbound. */
1176 Lisp_Object
1177 buffer_local_value_1 (Lisp_Object variable, Lisp_Object buffer)
1179 register struct buffer *buf;
1180 register Lisp_Object result;
1181 struct Lisp_Symbol *sym;
1183 CHECK_SYMBOL (variable);
1184 CHECK_BUFFER (buffer);
1185 buf = XBUFFER (buffer);
1186 sym = XSYMBOL (variable);
1188 start:
1189 switch (sym->redirect)
1191 case SYMBOL_VARALIAS: sym = indirect_variable (sym); goto start;
1192 case SYMBOL_PLAINVAL: result = SYMBOL_VAL (sym); break;
1193 case SYMBOL_LOCALIZED:
1194 { /* Look in local_var_alist. */
1195 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
1196 XSETSYMBOL (variable, sym); /* Update In case of aliasing. */
1197 result = Fassoc (variable, BVAR (buf, local_var_alist));
1198 if (!NILP (result))
1200 if (blv->fwd)
1201 { /* What binding is loaded right now? */
1202 Lisp_Object current_alist_element = blv->valcell;
1204 /* The value of the currently loaded binding is not
1205 stored in it, but rather in the realvalue slot.
1206 Store that value into the binding it belongs to
1207 in case that is the one we are about to use. */
1209 XSETCDR (current_alist_element,
1210 do_symval_forwarding (blv->fwd));
1212 /* Now get the (perhaps updated) value out of the binding. */
1213 result = XCDR (result);
1215 else
1216 result = Fdefault_value (variable);
1217 break;
1219 case SYMBOL_FORWARDED:
1221 union Lisp_Fwd *fwd = SYMBOL_FWD (sym);
1222 if (BUFFER_OBJFWDP (fwd))
1223 result = per_buffer_value (buf, XBUFFER_OBJFWD (fwd)->offset);
1224 else
1225 result = Fdefault_value (variable);
1226 break;
1228 default: emacs_abort ();
1231 return result;
1234 /* Return an alist of the Lisp-level buffer-local bindings of
1235 buffer BUF. That is, don't include the variables maintained
1236 in special slots in the buffer object.
1237 If not CLONE, replace elements of the form (VAR . unbound)
1238 by VAR. */
1240 static Lisp_Object
1241 buffer_lisp_local_variables (struct buffer *buf, bool clone)
1243 Lisp_Object result = Qnil;
1244 Lisp_Object tail;
1245 for (tail = BVAR (buf, local_var_alist); CONSP (tail); tail = XCDR (tail))
1247 Lisp_Object val, elt;
1249 elt = XCAR (tail);
1251 /* Reference each variable in the alist in buf.
1252 If inquiring about the current buffer, this gets the current values,
1253 so store them into the alist so the alist is up to date.
1254 If inquiring about some other buffer, this swaps out any values
1255 for that buffer, making the alist up to date automatically. */
1256 val = find_symbol_value (XCAR (elt));
1257 /* Use the current buffer value only if buf is the current buffer. */
1258 if (buf != current_buffer)
1259 val = XCDR (elt);
1261 result = Fcons (!clone && EQ (val, Qunbound)
1262 ? XCAR (elt)
1263 : Fcons (XCAR (elt), val),
1264 result);
1267 return result;
1270 DEFUN ("buffer-local-variables", Fbuffer_local_variables,
1271 Sbuffer_local_variables, 0, 1, 0,
1272 doc: /* Return an alist of variables that are buffer-local in BUFFER.
1273 Most elements look like (SYMBOL . VALUE), describing one variable.
1274 For a symbol that is locally unbound, just the symbol appears in the value.
1275 Note that storing new VALUEs in these elements doesn't change the variables.
1276 No argument or nil as argument means use current buffer as BUFFER. */)
1277 (register Lisp_Object buffer)
1279 register struct buffer *buf;
1280 register Lisp_Object result;
1282 if (NILP (buffer))
1283 buf = current_buffer;
1284 else
1286 CHECK_BUFFER (buffer);
1287 buf = XBUFFER (buffer);
1290 result = buffer_lisp_local_variables (buf, 0);
1292 /* Add on all the variables stored in special slots. */
1294 int offset, idx;
1296 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
1298 idx = PER_BUFFER_IDX (offset);
1299 if ((idx == -1 || PER_BUFFER_VALUE_P (buf, idx))
1300 && SYMBOLP (PER_BUFFER_SYMBOL (offset)))
1302 Lisp_Object sym = PER_BUFFER_SYMBOL (offset);
1303 Lisp_Object val = per_buffer_value (buf, offset);
1304 result = Fcons (EQ (val, Qunbound) ? sym : Fcons (sym, val),
1305 result);
1310 return result;
1313 DEFUN ("buffer-modified-p", Fbuffer_modified_p, Sbuffer_modified_p,
1314 0, 1, 0,
1315 doc: /* Return t if BUFFER was modified since its file was last read or saved.
1316 No argument or nil as argument means use current buffer as BUFFER. */)
1317 (register Lisp_Object buffer)
1319 register struct buffer *buf;
1320 if (NILP (buffer))
1321 buf = current_buffer;
1322 else
1324 CHECK_BUFFER (buffer);
1325 buf = XBUFFER (buffer);
1328 return BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf) ? Qt : Qnil;
1331 DEFUN ("force-mode-line-update", Fforce_mode_line_update,
1332 Sforce_mode_line_update, 0, 1, 0,
1333 doc: /* Force redisplay of the current buffer's mode line and header line.
1334 With optional non-nil ALL, force redisplay of all mode lines and
1335 header lines. This function also forces recomputation of the
1336 menu bar menus and the frame title. */)
1337 (Lisp_Object all)
1339 if (!NILP (all) || buffer_window_count (current_buffer))
1341 update_mode_lines = 10;
1342 current_buffer->prevent_redisplay_optimizations_p = 1;
1344 return all;
1347 DEFUN ("set-buffer-modified-p", Fset_buffer_modified_p, Sset_buffer_modified_p,
1348 1, 1, 0,
1349 doc: /* Mark current buffer as modified or unmodified according to FLAG.
1350 A non-nil FLAG means mark the buffer modified. */)
1351 (Lisp_Object flag)
1353 Frestore_buffer_modified_p (flag);
1355 /* Set update_mode_lines only if buffer is displayed in some window.
1356 Packages like jit-lock or lazy-lock preserve a buffer's modified
1357 state by recording/restoring the state around blocks of code.
1358 Setting update_mode_lines makes redisplay consider all windows
1359 (on all frames). Stealth fontification of buffers not displayed
1360 would incur additional redisplay costs if we'd set
1361 update_modes_lines unconditionally.
1363 Ideally, I think there should be another mechanism for fontifying
1364 buffers without "modifying" buffers, or redisplay should be
1365 smarter about updating the `*' in mode lines. --gerd */
1366 return Fforce_mode_line_update (Qnil);
1369 DEFUN ("restore-buffer-modified-p", Frestore_buffer_modified_p,
1370 Srestore_buffer_modified_p, 1, 1, 0,
1371 doc: /* Like `set-buffer-modified-p', with a difference concerning redisplay.
1372 It is not ensured that mode lines will be updated to show the modified
1373 state of the current buffer. Use with care. */)
1374 (Lisp_Object flag)
1376 #ifdef CLASH_DETECTION
1377 Lisp_Object fn;
1379 /* If buffer becoming modified, lock the file.
1380 If buffer becoming unmodified, unlock the file. */
1382 struct buffer *b = current_buffer->base_buffer
1383 ? current_buffer->base_buffer
1384 : current_buffer;
1386 fn = BVAR (b, file_truename);
1387 /* Test buffer-file-name so that binding it to nil is effective. */
1388 if (!NILP (fn) && ! NILP (BVAR (b, filename)))
1390 bool already = SAVE_MODIFF < MODIFF;
1391 if (!already && !NILP (flag))
1392 lock_file (fn);
1393 else if (already && NILP (flag))
1394 unlock_file (fn);
1396 #endif /* CLASH_DETECTION */
1398 /* Here we have a problem. SAVE_MODIFF is used here to encode
1399 buffer-modified-p (as SAVE_MODIFF<MODIFF) as well as
1400 recent-auto-save-p (as SAVE_MODIFF<auto_save_modified). So if we
1401 modify SAVE_MODIFF to affect one, we may affect the other
1402 as well.
1403 E.g. if FLAG is nil we need to set SAVE_MODIFF to MODIFF, but
1404 if SAVE_MODIFF<auto_save_modified that means we risk changing
1405 recent-auto-save-p from t to nil.
1406 Vice versa, if FLAG is non-nil and SAVE_MODIFF>=auto_save_modified
1407 we risk changing recent-auto-save-p from nil to t. */
1408 SAVE_MODIFF = (NILP (flag)
1409 /* FIXME: This unavoidably sets recent-auto-save-p to nil. */
1410 ? MODIFF
1411 /* Let's try to preserve recent-auto-save-p. */
1412 : SAVE_MODIFF < MODIFF ? SAVE_MODIFF
1413 /* If SAVE_MODIFF == auto_save_modified == MODIFF,
1414 we can either decrease SAVE_MODIFF and auto_save_modified
1415 or increase MODIFF. */
1416 : MODIFF++);
1418 return flag;
1421 DEFUN ("buffer-modified-tick", Fbuffer_modified_tick, Sbuffer_modified_tick,
1422 0, 1, 0,
1423 doc: /* Return BUFFER's tick counter, incremented for each change in text.
1424 Each buffer has a tick counter which is incremented each time the
1425 text in that buffer is changed. It wraps around occasionally.
1426 No argument or nil as argument means use current buffer as BUFFER. */)
1427 (register Lisp_Object buffer)
1429 register struct buffer *buf;
1430 if (NILP (buffer))
1431 buf = current_buffer;
1432 else
1434 CHECK_BUFFER (buffer);
1435 buf = XBUFFER (buffer);
1438 return make_number (BUF_MODIFF (buf));
1441 DEFUN ("buffer-chars-modified-tick", Fbuffer_chars_modified_tick,
1442 Sbuffer_chars_modified_tick, 0, 1, 0,
1443 doc: /* Return BUFFER's character-change tick counter.
1444 Each buffer has a character-change tick counter, which is set to the
1445 value of the buffer's tick counter \(see `buffer-modified-tick'), each
1446 time text in that buffer is inserted or deleted. By comparing the
1447 values returned by two individual calls of `buffer-chars-modified-tick',
1448 you can tell whether a character change occurred in that buffer in
1449 between these calls. No argument or nil as argument means use current
1450 buffer as BUFFER. */)
1451 (register Lisp_Object buffer)
1453 register struct buffer *buf;
1454 if (NILP (buffer))
1455 buf = current_buffer;
1456 else
1458 CHECK_BUFFER (buffer);
1459 buf = XBUFFER (buffer);
1462 return make_number (BUF_CHARS_MODIFF (buf));
1465 DEFUN ("rename-buffer", Frename_buffer, Srename_buffer, 1, 2,
1466 "(list (read-string \"Rename buffer (to new name): \" \
1467 nil 'buffer-name-history (buffer-name (current-buffer))) \
1468 current-prefix-arg)",
1469 doc: /* Change current buffer's name to NEWNAME (a string).
1470 If second arg UNIQUE is nil or omitted, it is an error if a
1471 buffer named NEWNAME already exists.
1472 If UNIQUE is non-nil, come up with a new name using
1473 `generate-new-buffer-name'.
1474 Interactively, you can set UNIQUE with a prefix argument.
1475 We return the name we actually gave the buffer.
1476 This does not change the name of the visited file (if any). */)
1477 (register Lisp_Object newname, Lisp_Object unique)
1479 register Lisp_Object tem, buf;
1481 CHECK_STRING (newname);
1483 if (SCHARS (newname) == 0)
1484 error ("Empty string is invalid as a buffer name");
1486 tem = Fget_buffer (newname);
1487 if (!NILP (tem))
1489 /* Don't short-circuit if UNIQUE is t. That is a useful way to
1490 rename the buffer automatically so you can create another
1491 with the original name. It makes UNIQUE equivalent to
1492 (rename-buffer (generate-new-buffer-name NEWNAME)). */
1493 if (NILP (unique) && XBUFFER (tem) == current_buffer)
1494 return BVAR (current_buffer, name);
1495 if (!NILP (unique))
1496 newname = Fgenerate_new_buffer_name (newname, BVAR (current_buffer, name));
1497 else
1498 error ("Buffer name `%s' is in use", SDATA (newname));
1501 bset_name (current_buffer, newname);
1503 /* Catch redisplay's attention. Unless we do this, the mode lines for
1504 any windows displaying current_buffer will stay unchanged. */
1505 update_mode_lines = 11;
1507 XSETBUFFER (buf, current_buffer);
1508 Fsetcar (Frassq (buf, Vbuffer_alist), newname);
1509 if (NILP (BVAR (current_buffer, filename))
1510 && !NILP (BVAR (current_buffer, auto_save_file_name)))
1511 call0 (intern ("rename-auto-save-file"));
1513 /* Run buffer-list-update-hook. */
1514 if (!NILP (Vrun_hooks))
1515 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1517 /* Refetch since that last call may have done GC. */
1518 return BVAR (current_buffer, name);
1521 /* True if B can be used as 'other-than-BUFFER' buffer. */
1523 static bool
1524 candidate_buffer (Lisp_Object b, Lisp_Object buffer)
1526 return (BUFFERP (b) && !EQ (b, buffer)
1527 && BUFFER_LIVE_P (XBUFFER (b))
1528 && !BUFFER_HIDDEN_P (XBUFFER (b)));
1531 DEFUN ("other-buffer", Fother_buffer, Sother_buffer, 0, 3, 0,
1532 doc: /* Return most recently selected buffer other than BUFFER.
1533 Buffers not visible in windows are preferred to visible buffers, unless
1534 optional second argument VISIBLE-OK is non-nil. Ignore the argument
1535 BUFFER unless it denotes a live buffer. If the optional third argument
1536 FRAME is non-nil, use that frame's buffer list instead of the selected
1537 frame's buffer list.
1539 The buffer is found by scanning the selected or specified frame's buffer
1540 list first, followed by the list of all buffers. If no other buffer
1541 exists, return the buffer `*scratch*' (creating it if necessary). */)
1542 (register Lisp_Object buffer, Lisp_Object visible_ok, Lisp_Object frame)
1544 struct frame *f = decode_any_frame (frame);
1545 Lisp_Object tail = f->buffer_list, pred = f->buffer_predicate;
1546 Lisp_Object buf, notsogood = Qnil;
1548 /* Consider buffers that have been seen in the frame first. */
1549 for (; CONSP (tail); tail = XCDR (tail))
1551 buf = XCAR (tail);
1552 if (candidate_buffer (buf, buffer)
1553 /* If the frame has a buffer_predicate, disregard buffers that
1554 don't fit the predicate. */
1555 && (NILP (pred) || !NILP (call1 (pred, buf))))
1557 if (!NILP (visible_ok)
1558 || NILP (Fget_buffer_window (buf, Qvisible)))
1559 return buf;
1560 else if (NILP (notsogood))
1561 notsogood = buf;
1565 /* Consider alist of all buffers next. */
1566 FOR_EACH_LIVE_BUFFER (tail, buf)
1568 if (candidate_buffer (buf, buffer)
1569 /* If the frame has a buffer_predicate, disregard buffers that
1570 don't fit the predicate. */
1571 && (NILP (pred) || !NILP (call1 (pred, buf))))
1573 if (!NILP (visible_ok)
1574 || NILP (Fget_buffer_window (buf, Qvisible)))
1575 return buf;
1576 else if (NILP (notsogood))
1577 notsogood = buf;
1581 if (!NILP (notsogood))
1582 return notsogood;
1583 else
1585 buf = Fget_buffer (build_string ("*scratch*"));
1586 if (NILP (buf))
1588 buf = Fget_buffer_create (build_string ("*scratch*"));
1589 Fset_buffer_major_mode (buf);
1591 return buf;
1595 /* The following function is a safe variant of Fother_buffer: It doesn't
1596 pay attention to any frame-local buffer lists, doesn't care about
1597 visibility of buffers, and doesn't evaluate any frame predicates. */
1599 Lisp_Object
1600 other_buffer_safely (Lisp_Object buffer)
1602 Lisp_Object tail, buf;
1604 FOR_EACH_LIVE_BUFFER (tail, buf)
1605 if (candidate_buffer (buf, buffer))
1606 return buf;
1608 buf = Fget_buffer (build_string ("*scratch*"));
1609 if (NILP (buf))
1611 buf = Fget_buffer_create (build_string ("*scratch*"));
1612 Fset_buffer_major_mode (buf);
1615 return buf;
1618 DEFUN ("buffer-enable-undo", Fbuffer_enable_undo, Sbuffer_enable_undo,
1619 0, 1, "",
1620 doc: /* Start keeping undo information for buffer BUFFER.
1621 No argument or nil as argument means do this for the current buffer. */)
1622 (register Lisp_Object buffer)
1624 Lisp_Object real_buffer;
1626 if (NILP (buffer))
1627 XSETBUFFER (real_buffer, current_buffer);
1628 else
1630 real_buffer = Fget_buffer (buffer);
1631 if (NILP (real_buffer))
1632 nsberror (buffer);
1635 if (EQ (BVAR (XBUFFER (real_buffer), undo_list), Qt))
1636 bset_undo_list (XBUFFER (real_buffer), Qnil);
1638 return Qnil;
1641 /* Truncate undo list and shrink the gap of BUFFER. */
1643 void
1644 compact_buffer (struct buffer *buffer)
1646 BUFFER_CHECK_INDIRECTION (buffer);
1648 /* Skip dead buffers, indirect buffers and buffers
1649 which aren't changed since last compaction. */
1650 if (BUFFER_LIVE_P (buffer)
1651 && (buffer->base_buffer == NULL)
1652 && (BUF_COMPACT (buffer) != BUF_MODIFF (buffer)))
1654 /* If a buffer's undo list is Qt, that means that undo is
1655 turned off in that buffer. Calling truncate_undo_list on
1656 Qt tends to return NULL, which effectively turns undo back on.
1657 So don't call truncate_undo_list if undo_list is Qt. */
1658 if (!EQ (buffer->INTERNAL_FIELD (undo_list), Qt))
1659 truncate_undo_list (buffer);
1661 /* Shrink buffer gaps. */
1662 if (!buffer->text->inhibit_shrinking)
1664 /* If a buffer's gap size is more than 10% of the buffer
1665 size, or larger than GAP_BYTES_DFL bytes, then shrink it
1666 accordingly. Keep a minimum size of GAP_BYTES_MIN bytes. */
1667 ptrdiff_t size = clip_to_bounds (GAP_BYTES_MIN,
1668 BUF_Z_BYTE (buffer) / 10,
1669 GAP_BYTES_DFL);
1670 if (BUF_GAP_SIZE (buffer) > size)
1671 make_gap_1 (buffer, -(BUF_GAP_SIZE (buffer) - size));
1673 BUF_COMPACT (buffer) = BUF_MODIFF (buffer);
1677 DEFUN ("kill-buffer", Fkill_buffer, Skill_buffer, 0, 1, "bKill buffer: ",
1678 doc: /* Kill the buffer specified by BUFFER-OR-NAME.
1679 The argument may be a buffer or the name of an existing buffer.
1680 Argument nil or omitted means kill the current buffer. Return t if the
1681 buffer is actually killed, nil otherwise.
1683 The functions in `kill-buffer-query-functions' are called with the
1684 buffer to be killed as the current buffer. If any of them returns nil,
1685 the buffer is not killed. The hook `kill-buffer-hook' is run before the
1686 buffer is actually killed. The buffer being killed will be current
1687 while the hook is running. Functions called by any of these hooks are
1688 supposed to not change the current buffer.
1690 Any processes that have this buffer as the `process-buffer' are killed
1691 with SIGHUP. This function calls `replace-buffer-in-windows' for
1692 cleaning up all windows currently displaying the buffer to be killed. */)
1693 (Lisp_Object buffer_or_name)
1695 Lisp_Object buffer;
1696 register struct buffer *b;
1697 register Lisp_Object tem;
1698 register struct Lisp_Marker *m;
1699 struct gcpro gcpro1;
1701 if (NILP (buffer_or_name))
1702 buffer = Fcurrent_buffer ();
1703 else
1704 buffer = Fget_buffer (buffer_or_name);
1705 if (NILP (buffer))
1706 nsberror (buffer_or_name);
1708 b = XBUFFER (buffer);
1710 /* Avoid trouble for buffer already dead. */
1711 if (!BUFFER_LIVE_P (b))
1712 return Qnil;
1714 /* Run hooks with the buffer to be killed the current buffer. */
1716 ptrdiff_t count = SPECPDL_INDEX ();
1717 Lisp_Object arglist[1];
1719 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1720 set_buffer_internal (b);
1722 /* First run the query functions; if any query is answered no,
1723 don't kill the buffer. */
1724 arglist[0] = Qkill_buffer_query_functions;
1725 tem = Frun_hook_with_args_until_failure (1, arglist);
1726 if (NILP (tem))
1727 return unbind_to (count, Qnil);
1729 /* Query if the buffer is still modified. */
1730 if (INTERACTIVE && !NILP (BVAR (b, filename))
1731 && BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
1733 GCPRO1 (buffer);
1734 tem = do_yes_or_no_p (format2 ("Buffer %s modified; kill anyway? ",
1735 BVAR (b, name), make_number (0)));
1736 UNGCPRO;
1737 if (NILP (tem))
1738 return unbind_to (count, Qnil);
1741 /* If the hooks have killed the buffer, exit now. */
1742 if (!BUFFER_LIVE_P (b))
1743 return unbind_to (count, Qt);
1745 /* Then run the hooks. */
1746 Frun_hooks (1, &Qkill_buffer_hook);
1747 unbind_to (count, Qnil);
1750 /* If the hooks have killed the buffer, exit now. */
1751 if (!BUFFER_LIVE_P (b))
1752 return Qt;
1754 /* We have no more questions to ask. Verify that it is valid
1755 to kill the buffer. This must be done after the questions
1756 since anything can happen within do_yes_or_no_p. */
1758 /* Don't kill the minibuffer now current. */
1759 if (EQ (buffer, XWINDOW (minibuf_window)->contents))
1760 return Qnil;
1762 /* When we kill an ordinary buffer which shares it's buffer text
1763 with indirect buffer(s), we must kill indirect buffer(s) too.
1764 We do it at this stage so nothing terrible happens if they
1765 ask questions or their hooks get errors. */
1766 if (!b->base_buffer && b->indirections > 0)
1768 struct buffer *other;
1770 GCPRO1 (buffer);
1772 FOR_EACH_BUFFER (other)
1773 if (other->base_buffer == b)
1775 Lisp_Object buf;
1776 XSETBUFFER (buf, other);
1777 Fkill_buffer (buf);
1780 UNGCPRO;
1782 /* Exit if we now have killed the base buffer (Bug#11665). */
1783 if (!BUFFER_LIVE_P (b))
1784 return Qt;
1787 /* Run replace_buffer_in_windows before making another buffer current
1788 since set-window-buffer-start-and-point will refuse to make another
1789 buffer current if the selected window does not show the current
1790 buffer (bug#10114). */
1791 replace_buffer_in_windows (buffer);
1793 /* Exit if replacing the buffer in windows has killed our buffer. */
1794 if (!BUFFER_LIVE_P (b))
1795 return Qt;
1797 /* Make this buffer not be current. Exit if it is the sole visible
1798 buffer. */
1799 if (b == current_buffer)
1801 tem = Fother_buffer (buffer, Qnil, Qnil);
1802 Fset_buffer (tem);
1803 if (b == current_buffer)
1804 return Qnil;
1807 /* If the buffer now current is shown in the minibuffer and our buffer
1808 is the sole other buffer give up. */
1809 XSETBUFFER (tem, current_buffer);
1810 if (EQ (tem, XWINDOW (minibuf_window)->contents)
1811 && EQ (buffer, Fother_buffer (buffer, Qnil, Qnil)))
1812 return Qnil;
1814 /* Now there is no question: we can kill the buffer. */
1816 #ifdef CLASH_DETECTION
1817 /* Unlock this buffer's file, if it is locked. */
1818 unlock_buffer (b);
1819 #endif /* CLASH_DETECTION */
1821 GCPRO1 (buffer);
1822 kill_buffer_processes (buffer);
1823 UNGCPRO;
1825 /* Killing buffer processes may run sentinels which may have killed
1826 our buffer. */
1827 if (!BUFFER_LIVE_P (b))
1828 return Qt;
1830 /* These may run Lisp code and into infinite loops (if someone
1831 insisted on circular lists) so allow quitting here. */
1832 frames_discard_buffer (buffer);
1834 clear_charpos_cache (b);
1836 tem = Vinhibit_quit;
1837 Vinhibit_quit = Qt;
1838 /* Remove the buffer from the list of all buffers. */
1839 Vbuffer_alist = Fdelq (Frassq (buffer, Vbuffer_alist), Vbuffer_alist);
1840 /* If replace_buffer_in_windows didn't do its job fix that now. */
1841 replace_buffer_in_windows_safely (buffer);
1842 Vinhibit_quit = tem;
1844 /* Delete any auto-save file, if we saved it in this session.
1845 But not if the buffer is modified. */
1846 if (STRINGP (BVAR (b, auto_save_file_name))
1847 && BUF_AUTOSAVE_MODIFF (b) != 0
1848 && BUF_SAVE_MODIFF (b) < BUF_AUTOSAVE_MODIFF (b)
1849 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
1850 && NILP (Fsymbol_value (intern ("auto-save-visited-file-name"))))
1852 Lisp_Object delete;
1853 delete = Fsymbol_value (intern ("delete-auto-save-files"));
1854 if (! NILP (delete))
1855 internal_delete_file (BVAR (b, auto_save_file_name));
1858 /* Deleting an auto-save file could have killed our buffer. */
1859 if (!BUFFER_LIVE_P (b))
1860 return Qt;
1862 if (b->base_buffer)
1864 /* Unchain all markers that belong to this indirect buffer.
1865 Don't unchain the markers that belong to the base buffer
1866 or its other indirect buffers. */
1867 struct Lisp_Marker **mp = &BUF_MARKERS (b);
1868 while ((m = *mp))
1870 if (m->buffer == b)
1872 m->buffer = NULL;
1873 *mp = m->next;
1875 else
1876 mp = &m->next;
1879 else
1881 /* Unchain all markers of this buffer and its indirect buffers.
1882 and leave them pointing nowhere. */
1883 for (m = BUF_MARKERS (b); m; )
1885 struct Lisp_Marker *next = m->next;
1886 m->buffer = 0;
1887 m->next = NULL;
1888 m = next;
1890 BUF_MARKERS (b) = NULL;
1891 set_buffer_intervals (b, NULL);
1893 /* Perhaps we should explicitly free the interval tree here... */
1895 /* Since we've unlinked the markers, the overlays can't be here any more
1896 either. */
1897 b->overlays_before = NULL;
1898 b->overlays_after = NULL;
1900 /* Reset the local variables, so that this buffer's local values
1901 won't be protected from GC. They would be protected
1902 if they happened to remain cached in their symbols.
1903 This gets rid of them for certain. */
1904 swap_out_buffer_local_variables (b);
1905 reset_buffer_local_variables (b, 1);
1907 bset_name (b, Qnil);
1909 block_input ();
1910 if (b->base_buffer)
1912 /* Notify our base buffer that we don't share the text anymore. */
1913 eassert (b->indirections == -1);
1914 b->base_buffer->indirections--;
1915 eassert (b->base_buffer->indirections >= 0);
1916 /* Make sure that we wasn't confused. */
1917 eassert (b->window_count == -1);
1919 else
1921 /* Make sure that no one shows us. */
1922 eassert (b->window_count == 0);
1923 /* No one shares our buffer text, can free it. */
1924 free_buffer_text (b);
1927 if (b->newline_cache)
1929 free_region_cache (b->newline_cache);
1930 b->newline_cache = 0;
1932 if (b->width_run_cache)
1934 free_region_cache (b->width_run_cache);
1935 b->width_run_cache = 0;
1937 if (b->bidi_paragraph_cache)
1939 free_region_cache (b->bidi_paragraph_cache);
1940 b->bidi_paragraph_cache = 0;
1942 bset_width_table (b, Qnil);
1943 unblock_input ();
1944 bset_undo_list (b, Qnil);
1946 /* Run buffer-list-update-hook. */
1947 if (!NILP (Vrun_hooks))
1948 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1950 return Qt;
1953 /* Move association for BUFFER to the front of buffer (a)lists. Since
1954 we do this each time BUFFER is selected visibly, the more recently
1955 selected buffers are always closer to the front of those lists. This
1956 means that other_buffer is more likely to choose a relevant buffer.
1958 Note that this moves BUFFER to the front of the buffer lists of the
1959 selected frame even if BUFFER is not shown there. If BUFFER is not
1960 shown in the selected frame, consider the present behavior a feature.
1961 `select-window' gets this right since it shows BUFFER in the selected
1962 window when calling us. */
1964 void
1965 record_buffer (Lisp_Object buffer)
1967 Lisp_Object aelt, aelt_cons, tem;
1968 register struct frame *f = XFRAME (selected_frame);
1970 CHECK_BUFFER (buffer);
1972 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
1973 Don't allow quitting since this might leave the buffer list in an
1974 inconsistent state. */
1975 tem = Vinhibit_quit;
1976 Vinhibit_quit = Qt;
1977 aelt = Frassq (buffer, Vbuffer_alist);
1978 aelt_cons = Fmemq (aelt, Vbuffer_alist);
1979 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
1980 XSETCDR (aelt_cons, Vbuffer_alist);
1981 Vbuffer_alist = aelt_cons;
1982 Vinhibit_quit = tem;
1984 /* Update buffer list of selected frame. */
1985 fset_buffer_list (f, Fcons (buffer, Fdelq (buffer, f->buffer_list)));
1986 fset_buried_buffer_list (f, Fdelq (buffer, f->buried_buffer_list));
1988 /* Run buffer-list-update-hook. */
1989 if (!NILP (Vrun_hooks))
1990 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1994 /* Move BUFFER to the end of the buffer (a)lists. Do nothing if the
1995 buffer is killed. For the selected frame's buffer list this moves
1996 BUFFER to its end even if it was never shown in that frame. If
1997 this happens we have a feature, hence `bury-buffer-internal' should be
1998 called only when BUFFER was shown in the selected frame. */
2000 DEFUN ("bury-buffer-internal", Fbury_buffer_internal, Sbury_buffer_internal,
2001 1, 1, 0,
2002 doc: /* Move BUFFER to the end of the buffer list. */)
2003 (Lisp_Object buffer)
2005 Lisp_Object aelt, aelt_cons, tem;
2006 register struct frame *f = XFRAME (selected_frame);
2008 CHECK_BUFFER (buffer);
2010 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
2011 Don't allow quitting since this might leave the buffer list in an
2012 inconsistent state. */
2013 tem = Vinhibit_quit;
2014 Vinhibit_quit = Qt;
2015 aelt = Frassq (buffer, Vbuffer_alist);
2016 aelt_cons = Fmemq (aelt, Vbuffer_alist);
2017 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
2018 XSETCDR (aelt_cons, Qnil);
2019 Vbuffer_alist = nconc2 (Vbuffer_alist, aelt_cons);
2020 Vinhibit_quit = tem;
2022 /* Update buffer lists of selected frame. */
2023 fset_buffer_list (f, Fdelq (buffer, f->buffer_list));
2024 fset_buried_buffer_list
2025 (f, Fcons (buffer, Fdelq (buffer, f->buried_buffer_list)));
2027 /* Run buffer-list-update-hook. */
2028 if (!NILP (Vrun_hooks))
2029 call1 (Vrun_hooks, Qbuffer_list_update_hook);
2031 return Qnil;
2034 DEFUN ("set-buffer-major-mode", Fset_buffer_major_mode, Sset_buffer_major_mode, 1, 1, 0,
2035 doc: /* Set an appropriate major mode for BUFFER.
2036 For the *scratch* buffer, use `initial-major-mode', otherwise choose a mode
2037 according to the default value of `major-mode'.
2038 Use this function before selecting the buffer, since it may need to inspect
2039 the current buffer's major mode. */)
2040 (Lisp_Object buffer)
2042 ptrdiff_t count;
2043 Lisp_Object function;
2045 CHECK_BUFFER (buffer);
2047 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
2048 error ("Attempt to set major mode for a dead buffer");
2050 if (strcmp (SSDATA (BVAR (XBUFFER (buffer), name)), "*scratch*") == 0)
2051 function = find_symbol_value (intern ("initial-major-mode"));
2052 else
2054 function = BVAR (&buffer_defaults, major_mode);
2055 if (NILP (function)
2056 && NILP (Fget (BVAR (current_buffer, major_mode), Qmode_class)))
2057 function = BVAR (current_buffer, major_mode);
2060 if (NILP (function) || EQ (function, Qfundamental_mode))
2061 return Qnil;
2063 count = SPECPDL_INDEX ();
2065 /* To select a nonfundamental mode,
2066 select the buffer temporarily and then call the mode function. */
2068 record_unwind_protect (save_excursion_restore, save_excursion_save ());
2070 Fset_buffer (buffer);
2071 call0 (function);
2073 return unbind_to (count, Qnil);
2076 DEFUN ("current-buffer", Fcurrent_buffer, Scurrent_buffer, 0, 0, 0,
2077 doc: /* Return the current buffer as a Lisp object. */)
2078 (void)
2080 register Lisp_Object buf;
2081 XSETBUFFER (buf, current_buffer);
2082 return buf;
2085 /* Set the current buffer to B, and do not set windows_or_buffers_changed.
2086 This is used by redisplay. */
2088 void
2089 set_buffer_internal_1 (register struct buffer *b)
2091 register struct buffer *old_buf;
2092 register Lisp_Object tail;
2094 #ifdef USE_MMAP_FOR_BUFFERS
2095 if (b->text->beg == NULL)
2096 enlarge_buffer_text (b, 0);
2097 #endif /* USE_MMAP_FOR_BUFFERS */
2099 if (current_buffer == b)
2100 return;
2102 BUFFER_CHECK_INDIRECTION (b);
2104 old_buf = current_buffer;
2105 current_buffer = b;
2106 last_known_column_point = -1; /* Invalidate indentation cache. */
2108 if (old_buf)
2110 /* Put the undo list back in the base buffer, so that it appears
2111 that an indirect buffer shares the undo list of its base. */
2112 if (old_buf->base_buffer)
2113 bset_undo_list (old_buf->base_buffer, BVAR (old_buf, undo_list));
2115 /* If the old current buffer has markers to record PT, BEGV and ZV
2116 when it is not current, update them now. */
2117 record_buffer_markers (old_buf);
2120 /* Get the undo list from the base buffer, so that it appears
2121 that an indirect buffer shares the undo list of its base. */
2122 if (b->base_buffer)
2123 bset_undo_list (b, BVAR (b->base_buffer, undo_list));
2125 /* If the new current buffer has markers to record PT, BEGV and ZV
2126 when it is not current, fetch them now. */
2127 fetch_buffer_markers (b);
2129 /* Look down buffer's list of local Lisp variables
2130 to find and update any that forward into C variables. */
2134 for (tail = BVAR (b, local_var_alist); CONSP (tail); tail = XCDR (tail))
2136 Lisp_Object var = XCAR (XCAR (tail));
2137 struct Lisp_Symbol *sym = XSYMBOL (var);
2138 if (sym->redirect == SYMBOL_LOCALIZED /* Just to be sure. */
2139 && SYMBOL_BLV (sym)->fwd)
2140 /* Just reference the variable
2141 to cause it to become set for this buffer. */
2142 Fsymbol_value (var);
2145 /* Do the same with any others that were local to the previous buffer */
2146 while (b != old_buf && (b = old_buf, b));
2149 /* Switch to buffer B temporarily for redisplay purposes.
2150 This avoids certain things that don't need to be done within redisplay. */
2152 void
2153 set_buffer_temp (struct buffer *b)
2155 register struct buffer *old_buf;
2157 if (current_buffer == b)
2158 return;
2160 old_buf = current_buffer;
2161 current_buffer = b;
2163 /* If the old current buffer has markers to record PT, BEGV and ZV
2164 when it is not current, update them now. */
2165 record_buffer_markers (old_buf);
2167 /* If the new current buffer has markers to record PT, BEGV and ZV
2168 when it is not current, fetch them now. */
2169 fetch_buffer_markers (b);
2172 DEFUN ("set-buffer", Fset_buffer, Sset_buffer, 1, 1, 0,
2173 doc: /* Make buffer BUFFER-OR-NAME current for editing operations.
2174 BUFFER-OR-NAME may be a buffer or the name of an existing buffer. See
2175 also `with-current-buffer' when you want to make a buffer current
2176 temporarily. This function does not display the buffer, so its effect
2177 ends when the current command terminates. Use `switch-to-buffer' or
2178 `pop-to-buffer' to switch buffers permanently. */)
2179 (register Lisp_Object buffer_or_name)
2181 register Lisp_Object buffer;
2182 buffer = Fget_buffer (buffer_or_name);
2183 if (NILP (buffer))
2184 nsberror (buffer_or_name);
2185 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
2186 error ("Selecting deleted buffer");
2187 set_buffer_internal (XBUFFER (buffer));
2188 return buffer;
2191 void
2192 restore_buffer (Lisp_Object buffer_or_name)
2194 Fset_buffer (buffer_or_name);
2197 /* Set the current buffer to BUFFER provided if it is alive. */
2199 void
2200 set_buffer_if_live (Lisp_Object buffer)
2202 if (BUFFER_LIVE_P (XBUFFER (buffer)))
2203 set_buffer_internal (XBUFFER (buffer));
2206 DEFUN ("barf-if-buffer-read-only", Fbarf_if_buffer_read_only,
2207 Sbarf_if_buffer_read_only, 0, 0, 0,
2208 doc: /* Signal a `buffer-read-only' error if the current buffer is read-only. */)
2209 (void)
2211 if (!NILP (BVAR (current_buffer, read_only))
2212 && NILP (Vinhibit_read_only))
2213 xsignal1 (Qbuffer_read_only, Fcurrent_buffer ());
2214 return Qnil;
2217 DEFUN ("erase-buffer", Ferase_buffer, Serase_buffer, 0, 0, "*",
2218 doc: /* Delete the entire contents of the current buffer.
2219 Any narrowing restriction in effect (see `narrow-to-region') is removed,
2220 so the buffer is truly empty after this. */)
2221 (void)
2223 Fwiden ();
2225 del_range (BEG, Z);
2227 current_buffer->last_window_start = 1;
2228 /* Prevent warnings, or suspension of auto saving, that would happen
2229 if future size is less than past size. Use of erase-buffer
2230 implies that the future text is not really related to the past text. */
2231 XSETFASTINT (BVAR (current_buffer, save_length), 0);
2232 return Qnil;
2235 void
2236 validate_region (register Lisp_Object *b, register Lisp_Object *e)
2238 CHECK_NUMBER_COERCE_MARKER (*b);
2239 CHECK_NUMBER_COERCE_MARKER (*e);
2241 if (XINT (*b) > XINT (*e))
2243 Lisp_Object tem;
2244 tem = *b; *b = *e; *e = tem;
2247 if (! (BEGV <= XINT (*b) && XINT (*e) <= ZV))
2248 args_out_of_range (*b, *e);
2251 /* Advance BYTE_POS up to a character boundary
2252 and return the adjusted position. */
2254 static ptrdiff_t
2255 advance_to_char_boundary (ptrdiff_t byte_pos)
2257 int c;
2259 if (byte_pos == BEG)
2260 /* Beginning of buffer is always a character boundary. */
2261 return BEG;
2263 c = FETCH_BYTE (byte_pos);
2264 if (! CHAR_HEAD_P (c))
2266 /* We should advance BYTE_POS only when C is a constituent of a
2267 multibyte sequence. */
2268 ptrdiff_t orig_byte_pos = byte_pos;
2272 byte_pos--;
2273 c = FETCH_BYTE (byte_pos);
2275 while (! CHAR_HEAD_P (c) && byte_pos > BEG);
2276 INC_POS (byte_pos);
2277 if (byte_pos < orig_byte_pos)
2278 byte_pos = orig_byte_pos;
2279 /* If C is a constituent of a multibyte sequence, BYTE_POS was
2280 surely advance to the correct character boundary. If C is
2281 not, BYTE_POS was unchanged. */
2284 return byte_pos;
2287 DEFUN ("buffer-swap-text", Fbuffer_swap_text, Sbuffer_swap_text,
2288 1, 1, 0,
2289 doc: /* Swap the text between current buffer and BUFFER. */)
2290 (Lisp_Object buffer)
2292 struct buffer *other_buffer;
2293 CHECK_BUFFER (buffer);
2294 other_buffer = XBUFFER (buffer);
2296 if (!BUFFER_LIVE_P (other_buffer))
2297 error ("Cannot swap a dead buffer's text");
2299 /* Actually, it probably works just fine.
2300 * if (other_buffer == current_buffer)
2301 * error ("Cannot swap a buffer's text with itself"); */
2303 /* Actually, this may be workable as well, tho probably only if they're
2304 *both* indirect. */
2305 if (other_buffer->base_buffer
2306 || current_buffer->base_buffer)
2307 error ("Cannot swap indirect buffers's text");
2309 { /* This is probably harder to make work. */
2310 struct buffer *other;
2311 FOR_EACH_BUFFER (other)
2312 if (other->base_buffer == other_buffer
2313 || other->base_buffer == current_buffer)
2314 error ("One of the buffers to swap has indirect buffers");
2317 #define swapfield(field, type) \
2318 do { \
2319 type tmp##field = other_buffer->field; \
2320 other_buffer->field = current_buffer->field; \
2321 current_buffer->field = tmp##field; \
2322 } while (0)
2323 #define swapfield_(field, type) \
2324 do { \
2325 type tmp##field = BVAR (other_buffer, field); \
2326 bset_##field (other_buffer, BVAR (current_buffer, field)); \
2327 bset_##field (current_buffer, tmp##field); \
2328 } while (0)
2330 swapfield (own_text, struct buffer_text);
2331 eassert (current_buffer->text == &current_buffer->own_text);
2332 eassert (other_buffer->text == &other_buffer->own_text);
2333 #ifdef REL_ALLOC
2334 r_alloc_reset_variable ((void **) &current_buffer->own_text.beg,
2335 (void **) &other_buffer->own_text.beg);
2336 r_alloc_reset_variable ((void **) &other_buffer->own_text.beg,
2337 (void **) &current_buffer->own_text.beg);
2338 #endif /* REL_ALLOC */
2340 swapfield (pt, ptrdiff_t);
2341 swapfield (pt_byte, ptrdiff_t);
2342 swapfield (begv, ptrdiff_t);
2343 swapfield (begv_byte, ptrdiff_t);
2344 swapfield (zv, ptrdiff_t);
2345 swapfield (zv_byte, ptrdiff_t);
2346 eassert (!current_buffer->base_buffer);
2347 eassert (!other_buffer->base_buffer);
2348 swapfield (indirections, ptrdiff_t);
2349 current_buffer->clip_changed = 1; other_buffer->clip_changed = 1;
2350 swapfield (newline_cache, struct region_cache *);
2351 swapfield (width_run_cache, struct region_cache *);
2352 swapfield (bidi_paragraph_cache, struct region_cache *);
2353 current_buffer->prevent_redisplay_optimizations_p = 1;
2354 other_buffer->prevent_redisplay_optimizations_p = 1;
2355 swapfield (overlays_before, struct Lisp_Overlay *);
2356 swapfield (overlays_after, struct Lisp_Overlay *);
2357 swapfield (overlay_center, ptrdiff_t);
2358 swapfield_ (undo_list, Lisp_Object);
2359 swapfield_ (mark, Lisp_Object);
2360 swapfield_ (enable_multibyte_characters, Lisp_Object);
2361 swapfield_ (bidi_display_reordering, Lisp_Object);
2362 swapfield_ (bidi_paragraph_direction, Lisp_Object);
2363 /* FIXME: Not sure what we should do with these *_marker fields.
2364 Hopefully they're just nil anyway. */
2365 swapfield_ (pt_marker, Lisp_Object);
2366 swapfield_ (begv_marker, Lisp_Object);
2367 swapfield_ (zv_marker, Lisp_Object);
2368 bset_point_before_scroll (current_buffer, Qnil);
2369 bset_point_before_scroll (other_buffer, Qnil);
2371 current_buffer->text->modiff++; other_buffer->text->modiff++;
2372 current_buffer->text->chars_modiff++; other_buffer->text->chars_modiff++;
2373 current_buffer->text->overlay_modiff++; other_buffer->text->overlay_modiff++;
2374 current_buffer->text->beg_unchanged = current_buffer->text->gpt;
2375 current_buffer->text->end_unchanged = current_buffer->text->gpt;
2376 other_buffer->text->beg_unchanged = other_buffer->text->gpt;
2377 other_buffer->text->end_unchanged = other_buffer->text->gpt;
2379 struct Lisp_Marker *m;
2380 for (m = BUF_MARKERS (current_buffer); m; m = m->next)
2381 if (m->buffer == other_buffer)
2382 m->buffer = current_buffer;
2383 else
2384 /* Since there's no indirect buffer in sight, markers on
2385 BUF_MARKERS(buf) should either be for `buf' or dead. */
2386 eassert (!m->buffer);
2387 for (m = BUF_MARKERS (other_buffer); m; m = m->next)
2388 if (m->buffer == current_buffer)
2389 m->buffer = other_buffer;
2390 else
2391 /* Since there's no indirect buffer in sight, markers on
2392 BUF_MARKERS(buf) should either be for `buf' or dead. */
2393 eassert (!m->buffer);
2395 { /* Some of the C code expects that both window markers of a
2396 live window points to that window's buffer. So since we
2397 just swapped the markers between the two buffers, we need
2398 to undo the effect of this swap for window markers. */
2399 Lisp_Object w = selected_window, ws = Qnil;
2400 Lisp_Object buf1, buf2;
2401 XSETBUFFER (buf1, current_buffer); XSETBUFFER (buf2, other_buffer);
2403 while (NILP (Fmemq (w, ws)))
2405 ws = Fcons (w, ws);
2406 if (MARKERP (XWINDOW (w)->pointm)
2407 && (EQ (XWINDOW (w)->contents, buf1)
2408 || EQ (XWINDOW (w)->contents, buf2)))
2409 Fset_marker (XWINDOW (w)->pointm,
2410 make_number
2411 (BUF_BEGV (XBUFFER (XWINDOW (w)->contents))),
2412 XWINDOW (w)->contents);
2413 if (MARKERP (XWINDOW (w)->start)
2414 && (EQ (XWINDOW (w)->contents, buf1)
2415 || EQ (XWINDOW (w)->contents, buf2)))
2416 Fset_marker (XWINDOW (w)->start,
2417 make_number
2418 (XBUFFER (XWINDOW (w)->contents)->last_window_start),
2419 XWINDOW (w)->contents);
2420 w = Fnext_window (w, Qt, Qt);
2424 if (current_buffer->text->intervals)
2425 (eassert (EQ (current_buffer->text->intervals->up.obj, buffer)),
2426 XSETBUFFER (current_buffer->text->intervals->up.obj, current_buffer));
2427 if (other_buffer->text->intervals)
2428 (eassert (EQ (other_buffer->text->intervals->up.obj, Fcurrent_buffer ())),
2429 XSETBUFFER (other_buffer->text->intervals->up.obj, other_buffer));
2431 return Qnil;
2434 DEFUN ("set-buffer-multibyte", Fset_buffer_multibyte, Sset_buffer_multibyte,
2435 1, 1, 0,
2436 doc: /* Set the multibyte flag of the current buffer to FLAG.
2437 If FLAG is t, this makes the buffer a multibyte buffer.
2438 If FLAG is nil, this makes the buffer a single-byte buffer.
2439 In these cases, the buffer contents remain unchanged as a sequence of
2440 bytes but the contents viewed as characters do change.
2441 If FLAG is `to', this makes the buffer a multibyte buffer by changing
2442 all eight-bit bytes to eight-bit characters.
2443 If the multibyte flag was really changed, undo information of the
2444 current buffer is cleared. */)
2445 (Lisp_Object flag)
2447 struct Lisp_Marker *tail, *markers;
2448 struct buffer *other;
2449 ptrdiff_t begv, zv;
2450 bool narrowed = (BEG != BEGV || Z != ZV);
2451 bool modified_p = !NILP (Fbuffer_modified_p (Qnil));
2452 Lisp_Object old_undo = BVAR (current_buffer, undo_list);
2453 struct gcpro gcpro1;
2455 if (current_buffer->base_buffer)
2456 error ("Cannot do `set-buffer-multibyte' on an indirect buffer");
2458 /* Do nothing if nothing actually changes. */
2459 if (NILP (flag) == NILP (BVAR (current_buffer, enable_multibyte_characters)))
2460 return flag;
2462 GCPRO1 (old_undo);
2464 /* Don't record these buffer changes. We will put a special undo entry
2465 instead. */
2466 bset_undo_list (current_buffer, Qt);
2468 /* If the cached position is for this buffer, clear it out. */
2469 clear_charpos_cache (current_buffer);
2471 if (NILP (flag))
2472 begv = BEGV_BYTE, zv = ZV_BYTE;
2473 else
2474 begv = BEGV, zv = ZV;
2476 if (narrowed)
2477 error ("Changing multibyteness in a narrowed buffer");
2479 if (NILP (flag))
2481 ptrdiff_t pos, stop;
2482 unsigned char *p;
2484 /* Do this first, so it can use CHAR_TO_BYTE
2485 to calculate the old correspondences. */
2486 set_intervals_multibyte (0);
2488 bset_enable_multibyte_characters (current_buffer, Qnil);
2490 Z = Z_BYTE;
2491 BEGV = BEGV_BYTE;
2492 ZV = ZV_BYTE;
2493 GPT = GPT_BYTE;
2494 TEMP_SET_PT_BOTH (PT_BYTE, PT_BYTE);
2497 for (tail = BUF_MARKERS (current_buffer); tail; tail = tail->next)
2498 tail->charpos = tail->bytepos;
2500 /* Convert multibyte form of 8-bit characters to unibyte. */
2501 pos = BEG;
2502 stop = GPT;
2503 p = BEG_ADDR;
2504 while (1)
2506 int c, bytes;
2508 if (pos == stop)
2510 if (pos == Z)
2511 break;
2512 p = GAP_END_ADDR;
2513 stop = Z;
2515 if (ASCII_BYTE_P (*p))
2516 p++, pos++;
2517 else if (CHAR_BYTE8_HEAD_P (*p))
2519 c = STRING_CHAR_AND_LENGTH (p, bytes);
2520 /* Delete all bytes for this 8-bit character but the
2521 last one, and change the last one to the character
2522 code. */
2523 bytes--;
2524 del_range_2 (pos, pos, pos + bytes, pos + bytes, 0);
2525 p = GAP_END_ADDR;
2526 *p++ = c;
2527 pos++;
2528 if (begv > pos)
2529 begv -= bytes;
2530 if (zv > pos)
2531 zv -= bytes;
2532 stop = Z;
2534 else
2536 bytes = BYTES_BY_CHAR_HEAD (*p);
2537 p += bytes, pos += bytes;
2540 if (narrowed)
2541 Fnarrow_to_region (make_number (begv), make_number (zv));
2543 else
2545 ptrdiff_t pt = PT;
2546 ptrdiff_t pos, stop;
2547 unsigned char *p, *pend;
2549 /* Be sure not to have a multibyte sequence striding over the GAP.
2550 Ex: We change this: "...abc\302 _GAP_ \241def..."
2551 to: "...abc _GAP_ \302\241def..." */
2553 if (EQ (flag, Qt)
2554 && GPT_BYTE > 1 && GPT_BYTE < Z_BYTE
2555 && ! CHAR_HEAD_P (*(GAP_END_ADDR)))
2557 unsigned char *q = GPT_ADDR - 1;
2559 while (! CHAR_HEAD_P (*q) && q > BEG_ADDR) q--;
2560 if (LEADING_CODE_P (*q))
2562 ptrdiff_t new_gpt = GPT_BYTE - (GPT_ADDR - q);
2564 move_gap_both (new_gpt, new_gpt);
2568 /* Make the buffer contents valid as multibyte by converting
2569 8-bit characters to multibyte form. */
2570 pos = BEG;
2571 stop = GPT;
2572 p = BEG_ADDR;
2573 pend = GPT_ADDR;
2574 while (1)
2576 int bytes;
2578 if (pos == stop)
2580 if (pos == Z)
2581 break;
2582 p = GAP_END_ADDR;
2583 pend = Z_ADDR;
2584 stop = Z;
2587 if (ASCII_BYTE_P (*p))
2588 p++, pos++;
2589 else if (EQ (flag, Qt)
2590 && ! CHAR_BYTE8_HEAD_P (*p)
2591 && (bytes = MULTIBYTE_LENGTH (p, pend)) > 0)
2592 p += bytes, pos += bytes;
2593 else
2595 unsigned char tmp[MAX_MULTIBYTE_LENGTH];
2596 int c;
2598 c = BYTE8_TO_CHAR (*p);
2599 bytes = CHAR_STRING (c, tmp);
2600 *p = tmp[0];
2601 TEMP_SET_PT_BOTH (pos + 1, pos + 1);
2602 bytes--;
2603 insert_1_both ((char *) tmp + 1, bytes, bytes, 1, 0, 0);
2604 /* Now the gap is after the just inserted data. */
2605 pos = GPT;
2606 p = GAP_END_ADDR;
2607 if (pos <= begv)
2608 begv += bytes;
2609 if (pos <= zv)
2610 zv += bytes;
2611 if (pos <= pt)
2612 pt += bytes;
2613 pend = Z_ADDR;
2614 stop = Z;
2618 if (pt != PT)
2619 TEMP_SET_PT (pt);
2621 if (narrowed)
2622 Fnarrow_to_region (make_number (begv), make_number (zv));
2624 /* Do this first, so that chars_in_text asks the right question.
2625 set_intervals_multibyte needs it too. */
2626 bset_enable_multibyte_characters (current_buffer, Qt);
2628 GPT_BYTE = advance_to_char_boundary (GPT_BYTE);
2629 GPT = chars_in_text (BEG_ADDR, GPT_BYTE - BEG_BYTE) + BEG;
2631 Z = chars_in_text (GAP_END_ADDR, Z_BYTE - GPT_BYTE) + GPT;
2633 BEGV_BYTE = advance_to_char_boundary (BEGV_BYTE);
2634 if (BEGV_BYTE > GPT_BYTE)
2635 BEGV = chars_in_text (GAP_END_ADDR, BEGV_BYTE - GPT_BYTE) + GPT;
2636 else
2637 BEGV = chars_in_text (BEG_ADDR, BEGV_BYTE - BEG_BYTE) + BEG;
2639 ZV_BYTE = advance_to_char_boundary (ZV_BYTE);
2640 if (ZV_BYTE > GPT_BYTE)
2641 ZV = chars_in_text (GAP_END_ADDR, ZV_BYTE - GPT_BYTE) + GPT;
2642 else
2643 ZV = chars_in_text (BEG_ADDR, ZV_BYTE - BEG_BYTE) + BEG;
2646 ptrdiff_t byte = advance_to_char_boundary (PT_BYTE);
2647 ptrdiff_t position;
2649 if (byte > GPT_BYTE)
2650 position = chars_in_text (GAP_END_ADDR, byte - GPT_BYTE) + GPT;
2651 else
2652 position = chars_in_text (BEG_ADDR, byte - BEG_BYTE) + BEG;
2653 TEMP_SET_PT_BOTH (position, byte);
2656 tail = markers = BUF_MARKERS (current_buffer);
2658 /* This prevents BYTE_TO_CHAR (that is, buf_bytepos_to_charpos) from
2659 getting confused by the markers that have not yet been updated.
2660 It is also a signal that it should never create a marker. */
2661 BUF_MARKERS (current_buffer) = NULL;
2663 for (; tail; tail = tail->next)
2665 tail->bytepos = advance_to_char_boundary (tail->bytepos);
2666 tail->charpos = BYTE_TO_CHAR (tail->bytepos);
2669 /* Make sure no markers were put on the chain
2670 while the chain value was incorrect. */
2671 if (BUF_MARKERS (current_buffer))
2672 emacs_abort ();
2674 BUF_MARKERS (current_buffer) = markers;
2676 /* Do this last, so it can calculate the new correspondences
2677 between chars and bytes. */
2678 set_intervals_multibyte (1);
2681 if (!EQ (old_undo, Qt))
2683 /* Represent all the above changes by a special undo entry. */
2684 bset_undo_list (current_buffer,
2685 Fcons (list3 (Qapply,
2686 intern ("set-buffer-multibyte"),
2687 NILP (flag) ? Qt : Qnil),
2688 old_undo));
2691 UNGCPRO;
2693 current_buffer->prevent_redisplay_optimizations_p = 1;
2695 /* If buffer is shown in a window, let redisplay consider other windows. */
2696 if (buffer_window_count (current_buffer))
2697 windows_or_buffers_changed = 10;
2699 /* Copy this buffer's new multibyte status
2700 into all of its indirect buffers. */
2701 FOR_EACH_BUFFER (other)
2702 if (other->base_buffer == current_buffer && BUFFER_LIVE_P (other))
2704 BVAR (other, enable_multibyte_characters)
2705 = BVAR (current_buffer, enable_multibyte_characters);
2706 other->prevent_redisplay_optimizations_p = 1;
2709 /* Restore the modifiedness of the buffer. */
2710 if (!modified_p && !NILP (Fbuffer_modified_p (Qnil)))
2711 Fset_buffer_modified_p (Qnil);
2713 /* Update coding systems of this buffer's process (if any). */
2715 Lisp_Object process;
2717 process = Fget_buffer_process (Fcurrent_buffer ());
2718 if (PROCESSP (process))
2719 setup_process_coding_systems (process);
2722 return flag;
2725 DEFUN ("kill-all-local-variables", Fkill_all_local_variables,
2726 Skill_all_local_variables, 0, 0, 0,
2727 doc: /* Switch to Fundamental mode by killing current buffer's local variables.
2728 Most local variable bindings are eliminated so that the default values
2729 become effective once more. Also, the syntax table is set from
2730 `standard-syntax-table', the local keymap is set to nil,
2731 and the abbrev table from `fundamental-mode-abbrev-table'.
2732 This function also forces redisplay of the mode line.
2734 Every function to select a new major mode starts by
2735 calling this function.
2737 As a special exception, local variables whose names have
2738 a non-nil `permanent-local' property are not eliminated by this function.
2740 The first thing this function does is run
2741 the normal hook `change-major-mode-hook'. */)
2742 (void)
2744 Frun_hooks (1, &Qchange_major_mode_hook);
2746 /* Make sure none of the bindings in local_var_alist
2747 remain swapped in, in their symbols. */
2749 swap_out_buffer_local_variables (current_buffer);
2751 /* Actually eliminate all local bindings of this buffer. */
2753 reset_buffer_local_variables (current_buffer, 0);
2755 /* Force mode-line redisplay. Useful here because all major mode
2756 commands call this function. */
2757 update_mode_lines = 12;
2759 return Qnil;
2762 /* Make sure no local variables remain set up with buffer B
2763 for their current values. */
2765 static void
2766 swap_out_buffer_local_variables (struct buffer *b)
2768 Lisp_Object oalist, alist, buffer;
2770 XSETBUFFER (buffer, b);
2771 oalist = BVAR (b, local_var_alist);
2773 for (alist = oalist; CONSP (alist); alist = XCDR (alist))
2775 Lisp_Object sym = XCAR (XCAR (alist));
2776 eassert (XSYMBOL (sym)->redirect == SYMBOL_LOCALIZED);
2777 /* Need not do anything if some other buffer's binding is
2778 now cached. */
2779 if (EQ (SYMBOL_BLV (XSYMBOL (sym))->where, buffer))
2781 /* Symbol is set up for this buffer's old local value:
2782 swap it out! */
2783 swap_in_global_binding (XSYMBOL (sym));
2788 /* Find all the overlays in the current buffer that contain position POS.
2789 Return the number found, and store them in a vector in *VEC_PTR.
2790 Store in *LEN_PTR the size allocated for the vector.
2791 Store in *NEXT_PTR the next position after POS where an overlay starts,
2792 or ZV if there are no more overlays between POS and ZV.
2793 Store in *PREV_PTR the previous position before POS where an overlay ends,
2794 or where an overlay starts which ends at or after POS;
2795 or BEGV if there are no such overlays from BEGV to POS.
2796 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2798 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2799 when this function is called.
2801 If EXTEND, make the vector bigger if necessary.
2802 If not, never extend the vector,
2803 and store only as many overlays as will fit.
2804 But still return the total number of overlays.
2806 If CHANGE_REQ, any position written into *PREV_PTR or
2807 *NEXT_PTR is guaranteed to be not equal to POS, unless it is the
2808 default (BEGV or ZV). */
2810 ptrdiff_t
2811 overlays_at (EMACS_INT pos, bool extend, Lisp_Object **vec_ptr,
2812 ptrdiff_t *len_ptr,
2813 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr, bool change_req)
2815 Lisp_Object overlay, start, end;
2816 struct Lisp_Overlay *tail;
2817 ptrdiff_t idx = 0;
2818 ptrdiff_t len = *len_ptr;
2819 Lisp_Object *vec = *vec_ptr;
2820 ptrdiff_t next = ZV;
2821 ptrdiff_t prev = BEGV;
2822 bool inhibit_storing = 0;
2824 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2826 ptrdiff_t startpos, endpos;
2828 XSETMISC (overlay, tail);
2830 start = OVERLAY_START (overlay);
2831 end = OVERLAY_END (overlay);
2832 endpos = OVERLAY_POSITION (end);
2833 if (endpos < pos)
2835 if (prev < endpos)
2836 prev = endpos;
2837 break;
2839 startpos = OVERLAY_POSITION (start);
2840 /* This one ends at or after POS
2841 so its start counts for PREV_PTR if it's before POS. */
2842 if (prev < startpos && startpos < pos)
2843 prev = startpos;
2844 if (endpos == pos)
2845 continue;
2846 if (startpos <= pos)
2848 if (idx == len)
2850 /* The supplied vector is full.
2851 Either make it bigger, or don't store any more in it. */
2852 if (extend)
2854 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2855 sizeof *vec);
2856 *vec_ptr = vec;
2857 len = *len_ptr;
2859 else
2860 inhibit_storing = 1;
2863 if (!inhibit_storing)
2864 vec[idx] = overlay;
2865 /* Keep counting overlays even if we can't return them all. */
2866 idx++;
2868 else if (startpos < next)
2869 next = startpos;
2872 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2874 ptrdiff_t startpos, endpos;
2876 XSETMISC (overlay, tail);
2878 start = OVERLAY_START (overlay);
2879 end = OVERLAY_END (overlay);
2880 startpos = OVERLAY_POSITION (start);
2881 if (pos < startpos)
2883 if (startpos < next)
2884 next = startpos;
2885 break;
2887 endpos = OVERLAY_POSITION (end);
2888 if (pos < endpos)
2890 if (idx == len)
2892 if (extend)
2894 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2895 sizeof *vec);
2896 *vec_ptr = vec;
2897 len = *len_ptr;
2899 else
2900 inhibit_storing = 1;
2903 if (!inhibit_storing)
2904 vec[idx] = overlay;
2905 idx++;
2907 if (startpos < pos && startpos > prev)
2908 prev = startpos;
2910 else if (endpos < pos && endpos > prev)
2911 prev = endpos;
2912 else if (endpos == pos && startpos > prev
2913 && (!change_req || startpos < pos))
2914 prev = startpos;
2917 if (next_ptr)
2918 *next_ptr = next;
2919 if (prev_ptr)
2920 *prev_ptr = prev;
2921 return idx;
2924 /* Find all the overlays in the current buffer that overlap the range
2925 BEG-END, or are empty at BEG, or are empty at END provided END
2926 denotes the position at the end of the current buffer.
2928 Return the number found, and store them in a vector in *VEC_PTR.
2929 Store in *LEN_PTR the size allocated for the vector.
2930 Store in *NEXT_PTR the next position after POS where an overlay starts,
2931 or ZV if there are no more overlays.
2932 Store in *PREV_PTR the previous position before POS where an overlay ends,
2933 or BEGV if there are no previous overlays.
2934 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2936 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2937 when this function is called.
2939 If EXTEND, make the vector bigger if necessary.
2940 If not, never extend the vector,
2941 and store only as many overlays as will fit.
2942 But still return the total number of overlays. */
2944 static ptrdiff_t
2945 overlays_in (EMACS_INT beg, EMACS_INT end, bool extend,
2946 Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
2947 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr)
2949 Lisp_Object overlay, ostart, oend;
2950 struct Lisp_Overlay *tail;
2951 ptrdiff_t idx = 0;
2952 ptrdiff_t len = *len_ptr;
2953 Lisp_Object *vec = *vec_ptr;
2954 ptrdiff_t next = ZV;
2955 ptrdiff_t prev = BEGV;
2956 bool inhibit_storing = 0;
2957 bool end_is_Z = end == Z;
2959 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2961 ptrdiff_t startpos, endpos;
2963 XSETMISC (overlay, tail);
2965 ostart = OVERLAY_START (overlay);
2966 oend = OVERLAY_END (overlay);
2967 endpos = OVERLAY_POSITION (oend);
2968 if (endpos < beg)
2970 if (prev < endpos)
2971 prev = endpos;
2972 break;
2974 startpos = OVERLAY_POSITION (ostart);
2975 /* Count an interval if it overlaps the range, is empty at the
2976 start of the range, or is empty at END provided END denotes the
2977 end of the buffer. */
2978 if ((beg < endpos && startpos < end)
2979 || (startpos == endpos
2980 && (beg == endpos || (end_is_Z && endpos == end))))
2982 if (idx == len)
2984 /* The supplied vector is full.
2985 Either make it bigger, or don't store any more in it. */
2986 if (extend)
2988 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2989 sizeof *vec);
2990 *vec_ptr = vec;
2991 len = *len_ptr;
2993 else
2994 inhibit_storing = 1;
2997 if (!inhibit_storing)
2998 vec[idx] = overlay;
2999 /* Keep counting overlays even if we can't return them all. */
3000 idx++;
3002 else if (startpos < next)
3003 next = startpos;
3006 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
3008 ptrdiff_t startpos, endpos;
3010 XSETMISC (overlay, tail);
3012 ostart = OVERLAY_START (overlay);
3013 oend = OVERLAY_END (overlay);
3014 startpos = OVERLAY_POSITION (ostart);
3015 if (end < startpos)
3017 if (startpos < next)
3018 next = startpos;
3019 break;
3021 endpos = OVERLAY_POSITION (oend);
3022 /* Count an interval if it overlaps the range, is empty at the
3023 start of the range, or is empty at END provided END denotes the
3024 end of the buffer. */
3025 if ((beg < endpos && startpos < end)
3026 || (startpos == endpos
3027 && (beg == endpos || (end_is_Z && endpos == end))))
3029 if (idx == len)
3031 if (extend)
3033 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
3034 sizeof *vec);
3035 *vec_ptr = vec;
3036 len = *len_ptr;
3038 else
3039 inhibit_storing = 1;
3042 if (!inhibit_storing)
3043 vec[idx] = overlay;
3044 idx++;
3046 else if (endpos < beg && endpos > prev)
3047 prev = endpos;
3050 if (next_ptr)
3051 *next_ptr = next;
3052 if (prev_ptr)
3053 *prev_ptr = prev;
3054 return idx;
3058 /* Return true if there exists an overlay with a non-nil
3059 `mouse-face' property overlapping OVERLAY. */
3061 bool
3062 mouse_face_overlay_overlaps (Lisp_Object overlay)
3064 ptrdiff_t start = OVERLAY_POSITION (OVERLAY_START (overlay));
3065 ptrdiff_t end = OVERLAY_POSITION (OVERLAY_END (overlay));
3066 ptrdiff_t n, i, size;
3067 Lisp_Object *v, tem;
3069 size = 10;
3070 v = alloca (size * sizeof *v);
3071 n = overlays_in (start, end, 0, &v, &size, NULL, NULL);
3072 if (n > size)
3074 v = alloca (n * sizeof *v);
3075 overlays_in (start, end, 0, &v, &n, NULL, NULL);
3078 for (i = 0; i < n; ++i)
3079 if (!EQ (v[i], overlay)
3080 && (tem = Foverlay_get (overlay, Qmouse_face),
3081 !NILP (tem)))
3082 break;
3084 return i < n;
3089 /* Fast function to just test if we're at an overlay boundary. */
3090 bool
3091 overlay_touches_p (ptrdiff_t pos)
3093 Lisp_Object overlay;
3094 struct Lisp_Overlay *tail;
3096 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
3098 ptrdiff_t endpos;
3100 XSETMISC (overlay ,tail);
3101 eassert (OVERLAYP (overlay));
3103 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3104 if (endpos < pos)
3105 break;
3106 if (endpos == pos || OVERLAY_POSITION (OVERLAY_START (overlay)) == pos)
3107 return 1;
3110 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
3112 ptrdiff_t startpos;
3114 XSETMISC (overlay, tail);
3115 eassert (OVERLAYP (overlay));
3117 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3118 if (pos < startpos)
3119 break;
3120 if (startpos == pos || OVERLAY_POSITION (OVERLAY_END (overlay)) == pos)
3121 return 1;
3123 return 0;
3126 struct sortvec
3128 Lisp_Object overlay;
3129 ptrdiff_t beg, end;
3130 EMACS_INT priority;
3133 static int
3134 compare_overlays (const void *v1, const void *v2)
3136 const struct sortvec *s1 = v1;
3137 const struct sortvec *s2 = v2;
3138 if (s1->priority != s2->priority)
3139 return s1->priority < s2->priority ? -1 : 1;
3140 if (s1->beg != s2->beg)
3141 return s1->beg < s2->beg ? -1 : 1;
3142 if (s1->end != s2->end)
3143 return s2->end < s1->end ? -1 : 1;
3144 /* Avoid the non-determinism of qsort by choosing an arbitrary ordering
3145 between "equal" overlays. The result can still change between
3146 invocations of Emacs, but it won't change in the middle of
3147 `find_field' (bug#6830). */
3148 if (!EQ (s1->overlay, s2->overlay))
3149 return XLI (s1->overlay) < XLI (s2->overlay) ? -1 : 1;
3150 return 0;
3153 /* Sort an array of overlays by priority. The array is modified in place.
3154 The return value is the new size; this may be smaller than the original
3155 size if some of the overlays were invalid or were window-specific. */
3156 ptrdiff_t
3157 sort_overlays (Lisp_Object *overlay_vec, ptrdiff_t noverlays, struct window *w)
3159 ptrdiff_t i, j;
3160 USE_SAFE_ALLOCA;
3161 struct sortvec *sortvec;
3163 SAFE_NALLOCA (sortvec, 1, noverlays);
3165 /* Put the valid and relevant overlays into sortvec. */
3167 for (i = 0, j = 0; i < noverlays; i++)
3169 Lisp_Object tem;
3170 Lisp_Object overlay;
3172 overlay = overlay_vec[i];
3173 if (OVERLAYP (overlay)
3174 && OVERLAY_POSITION (OVERLAY_START (overlay)) > 0
3175 && OVERLAY_POSITION (OVERLAY_END (overlay)) > 0)
3177 /* If we're interested in a specific window, then ignore
3178 overlays that are limited to some other window. */
3179 if (w)
3181 Lisp_Object window;
3183 window = Foverlay_get (overlay, Qwindow);
3184 if (WINDOWP (window) && XWINDOW (window) != w)
3185 continue;
3188 /* This overlay is good and counts: put it into sortvec. */
3189 sortvec[j].overlay = overlay;
3190 sortvec[j].beg = OVERLAY_POSITION (OVERLAY_START (overlay));
3191 sortvec[j].end = OVERLAY_POSITION (OVERLAY_END (overlay));
3192 tem = Foverlay_get (overlay, Qpriority);
3193 if (INTEGERP (tem))
3194 sortvec[j].priority = XINT (tem);
3195 else
3196 sortvec[j].priority = 0;
3197 j++;
3200 noverlays = j;
3202 /* Sort the overlays into the proper order: increasing priority. */
3204 if (noverlays > 1)
3205 qsort (sortvec, noverlays, sizeof (struct sortvec), compare_overlays);
3207 for (i = 0; i < noverlays; i++)
3208 overlay_vec[i] = sortvec[i].overlay;
3210 SAFE_FREE ();
3211 return (noverlays);
3214 struct sortstr
3216 Lisp_Object string, string2;
3217 ptrdiff_t size;
3218 EMACS_INT priority;
3221 struct sortstrlist
3223 struct sortstr *buf; /* An array that expands as needed; never freed. */
3224 ptrdiff_t size; /* Allocated length of that array. */
3225 ptrdiff_t used; /* How much of the array is currently in use. */
3226 ptrdiff_t bytes; /* Total length of the strings in buf. */
3229 /* Buffers for storing information about the overlays touching a given
3230 position. These could be automatic variables in overlay_strings, but
3231 it's more efficient to hold onto the memory instead of repeatedly
3232 allocating and freeing it. */
3233 static struct sortstrlist overlay_heads, overlay_tails;
3234 static unsigned char *overlay_str_buf;
3236 /* Allocated length of overlay_str_buf. */
3237 static ptrdiff_t overlay_str_len;
3239 /* A comparison function suitable for passing to qsort. */
3240 static int
3241 cmp_for_strings (const void *as1, const void *as2)
3243 struct sortstr const *s1 = as1;
3244 struct sortstr const *s2 = as2;
3245 if (s1->size != s2->size)
3246 return s2->size < s1->size ? -1 : 1;
3247 if (s1->priority != s2->priority)
3248 return s1->priority < s2->priority ? -1 : 1;
3249 return 0;
3252 static void
3253 record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
3254 Lisp_Object str2, Lisp_Object pri, ptrdiff_t size)
3256 ptrdiff_t nbytes;
3258 if (ssl->used == ssl->size)
3259 ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
3260 ssl->buf[ssl->used].string = str;
3261 ssl->buf[ssl->used].string2 = str2;
3262 ssl->buf[ssl->used].size = size;
3263 ssl->buf[ssl->used].priority = (INTEGERP (pri) ? XINT (pri) : 0);
3264 ssl->used++;
3266 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3267 nbytes = SCHARS (str);
3268 else if (! STRING_MULTIBYTE (str))
3269 nbytes = count_size_as_multibyte (SDATA (str),
3270 SBYTES (str));
3271 else
3272 nbytes = SBYTES (str);
3274 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3275 memory_full (SIZE_MAX);
3276 ssl->bytes += nbytes;
3278 if (STRINGP (str2))
3280 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3281 nbytes = SCHARS (str2);
3282 else if (! STRING_MULTIBYTE (str2))
3283 nbytes = count_size_as_multibyte (SDATA (str2),
3284 SBYTES (str2));
3285 else
3286 nbytes = SBYTES (str2);
3288 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3289 memory_full (SIZE_MAX);
3290 ssl->bytes += nbytes;
3294 /* Return the concatenation of the strings associated with overlays that
3295 begin or end at POS, ignoring overlays that are specific to a window
3296 other than W. The strings are concatenated in the appropriate order:
3297 shorter overlays nest inside longer ones, and higher priority inside
3298 lower. Normally all of the after-strings come first, but zero-sized
3299 overlays have their after-strings ride along with the before-strings
3300 because it would look strange to print them inside-out.
3302 Returns the string length, and stores the contents indirectly through
3303 PSTR, if that variable is non-null. The string may be overwritten by
3304 subsequent calls. */
3306 ptrdiff_t
3307 overlay_strings (ptrdiff_t pos, struct window *w, unsigned char **pstr)
3309 Lisp_Object overlay, window, str;
3310 struct Lisp_Overlay *ov;
3311 ptrdiff_t startpos, endpos;
3312 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3314 overlay_heads.used = overlay_heads.bytes = 0;
3315 overlay_tails.used = overlay_tails.bytes = 0;
3316 for (ov = current_buffer->overlays_before; ov; ov = ov->next)
3318 XSETMISC (overlay, ov);
3319 eassert (OVERLAYP (overlay));
3321 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3322 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3323 if (endpos < pos)
3324 break;
3325 if (endpos != pos && startpos != pos)
3326 continue;
3327 window = Foverlay_get (overlay, Qwindow);
3328 if (WINDOWP (window) && XWINDOW (window) != w)
3329 continue;
3330 if (startpos == pos
3331 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3332 record_overlay_string (&overlay_heads, str,
3333 (startpos == endpos
3334 ? Foverlay_get (overlay, Qafter_string)
3335 : Qnil),
3336 Foverlay_get (overlay, Qpriority),
3337 endpos - startpos);
3338 else if (endpos == pos
3339 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3340 record_overlay_string (&overlay_tails, str, Qnil,
3341 Foverlay_get (overlay, Qpriority),
3342 endpos - startpos);
3344 for (ov = current_buffer->overlays_after; ov; ov = ov->next)
3346 XSETMISC (overlay, ov);
3347 eassert (OVERLAYP (overlay));
3349 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3350 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3351 if (startpos > pos)
3352 break;
3353 if (endpos != pos && startpos != pos)
3354 continue;
3355 window = Foverlay_get (overlay, Qwindow);
3356 if (WINDOWP (window) && XWINDOW (window) != w)
3357 continue;
3358 if (startpos == pos
3359 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3360 record_overlay_string (&overlay_heads, str,
3361 (startpos == endpos
3362 ? Foverlay_get (overlay, Qafter_string)
3363 : Qnil),
3364 Foverlay_get (overlay, Qpriority),
3365 endpos - startpos);
3366 else if (endpos == pos
3367 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3368 record_overlay_string (&overlay_tails, str, Qnil,
3369 Foverlay_get (overlay, Qpriority),
3370 endpos - startpos);
3372 if (overlay_tails.used > 1)
3373 qsort (overlay_tails.buf, overlay_tails.used, sizeof (struct sortstr),
3374 cmp_for_strings);
3375 if (overlay_heads.used > 1)
3376 qsort (overlay_heads.buf, overlay_heads.used, sizeof (struct sortstr),
3377 cmp_for_strings);
3378 if (overlay_heads.bytes || overlay_tails.bytes)
3380 Lisp_Object tem;
3381 ptrdiff_t i;
3382 unsigned char *p;
3383 ptrdiff_t total;
3385 if (INT_ADD_OVERFLOW (overlay_heads.bytes, overlay_tails.bytes))
3386 memory_full (SIZE_MAX);
3387 total = overlay_heads.bytes + overlay_tails.bytes;
3388 if (total > overlay_str_len)
3389 overlay_str_buf = xpalloc (overlay_str_buf, &overlay_str_len,
3390 total - overlay_str_len, -1, 1);
3392 p = overlay_str_buf;
3393 for (i = overlay_tails.used; --i >= 0;)
3395 ptrdiff_t nbytes;
3396 tem = overlay_tails.buf[i].string;
3397 nbytes = copy_text (SDATA (tem), p,
3398 SBYTES (tem),
3399 STRING_MULTIBYTE (tem), multibyte);
3400 p += nbytes;
3402 for (i = 0; i < overlay_heads.used; ++i)
3404 ptrdiff_t nbytes;
3405 tem = overlay_heads.buf[i].string;
3406 nbytes = copy_text (SDATA (tem), p,
3407 SBYTES (tem),
3408 STRING_MULTIBYTE (tem), multibyte);
3409 p += nbytes;
3410 tem = overlay_heads.buf[i].string2;
3411 if (STRINGP (tem))
3413 nbytes = copy_text (SDATA (tem), p,
3414 SBYTES (tem),
3415 STRING_MULTIBYTE (tem), multibyte);
3416 p += nbytes;
3419 if (p != overlay_str_buf + total)
3420 emacs_abort ();
3421 if (pstr)
3422 *pstr = overlay_str_buf;
3423 return total;
3425 return 0;
3428 /* Shift overlays in BUF's overlay lists, to center the lists at POS. */
3430 void
3431 recenter_overlay_lists (struct buffer *buf, ptrdiff_t pos)
3433 Lisp_Object overlay, beg, end;
3434 struct Lisp_Overlay *prev, *tail, *next;
3436 /* See if anything in overlays_before should move to overlays_after. */
3438 /* We don't strictly need prev in this loop; it should always be nil.
3439 But we use it for symmetry and in case that should cease to be true
3440 with some future change. */
3441 prev = NULL;
3442 for (tail = buf->overlays_before; tail; prev = tail, tail = next)
3444 next = tail->next;
3445 XSETMISC (overlay, tail);
3446 eassert (OVERLAYP (overlay));
3448 beg = OVERLAY_START (overlay);
3449 end = OVERLAY_END (overlay);
3451 if (OVERLAY_POSITION (end) > pos)
3453 /* OVERLAY needs to be moved. */
3454 ptrdiff_t where = OVERLAY_POSITION (beg);
3455 struct Lisp_Overlay *other, *other_prev;
3457 /* Splice the cons cell TAIL out of overlays_before. */
3458 if (prev)
3459 prev->next = next;
3460 else
3461 set_buffer_overlays_before (buf, next);
3463 /* Search thru overlays_after for where to put it. */
3464 other_prev = NULL;
3465 for (other = buf->overlays_after; other;
3466 other_prev = other, other = other->next)
3468 Lisp_Object otherbeg, otheroverlay;
3470 XSETMISC (otheroverlay, other);
3471 eassert (OVERLAYP (otheroverlay));
3473 otherbeg = OVERLAY_START (otheroverlay);
3474 if (OVERLAY_POSITION (otherbeg) >= where)
3475 break;
3478 /* Add TAIL to overlays_after before OTHER. */
3479 tail->next = other;
3480 if (other_prev)
3481 other_prev->next = tail;
3482 else
3483 set_buffer_overlays_after (buf, tail);
3484 tail = prev;
3486 else
3487 /* We've reached the things that should stay in overlays_before.
3488 All the rest of overlays_before must end even earlier,
3489 so stop now. */
3490 break;
3493 /* See if anything in overlays_after should be in overlays_before. */
3494 prev = NULL;
3495 for (tail = buf->overlays_after; tail; prev = tail, tail = next)
3497 next = tail->next;
3498 XSETMISC (overlay, tail);
3499 eassert (OVERLAYP (overlay));
3501 beg = OVERLAY_START (overlay);
3502 end = OVERLAY_END (overlay);
3504 /* Stop looking, when we know that nothing further
3505 can possibly end before POS. */
3506 if (OVERLAY_POSITION (beg) > pos)
3507 break;
3509 if (OVERLAY_POSITION (end) <= pos)
3511 /* OVERLAY needs to be moved. */
3512 ptrdiff_t where = OVERLAY_POSITION (end);
3513 struct Lisp_Overlay *other, *other_prev;
3515 /* Splice the cons cell TAIL out of overlays_after. */
3516 if (prev)
3517 prev->next = next;
3518 else
3519 set_buffer_overlays_after (buf, next);
3521 /* Search thru overlays_before for where to put it. */
3522 other_prev = NULL;
3523 for (other = buf->overlays_before; other;
3524 other_prev = other, other = other->next)
3526 Lisp_Object otherend, otheroverlay;
3528 XSETMISC (otheroverlay, other);
3529 eassert (OVERLAYP (otheroverlay));
3531 otherend = OVERLAY_END (otheroverlay);
3532 if (OVERLAY_POSITION (otherend) <= where)
3533 break;
3536 /* Add TAIL to overlays_before before OTHER. */
3537 tail->next = other;
3538 if (other_prev)
3539 other_prev->next = tail;
3540 else
3541 set_buffer_overlays_before (buf, tail);
3542 tail = prev;
3546 buf->overlay_center = pos;
3549 void
3550 adjust_overlays_for_insert (ptrdiff_t pos, ptrdiff_t length)
3552 /* After an insertion, the lists are still sorted properly,
3553 but we may need to update the value of the overlay center. */
3554 if (current_buffer->overlay_center >= pos)
3555 current_buffer->overlay_center += length;
3558 void
3559 adjust_overlays_for_delete (ptrdiff_t pos, ptrdiff_t length)
3561 if (current_buffer->overlay_center < pos)
3562 /* The deletion was to our right. No change needed; the before- and
3563 after-lists are still consistent. */
3565 else if (current_buffer->overlay_center - pos > length)
3566 /* The deletion was to our left. We need to adjust the center value
3567 to account for the change in position, but the lists are consistent
3568 given the new value. */
3569 current_buffer->overlay_center -= length;
3570 else
3571 /* We're right in the middle. There might be things on the after-list
3572 that now belong on the before-list. Recentering will move them,
3573 and also update the center point. */
3574 recenter_overlay_lists (current_buffer, pos);
3577 /* Fix up overlays that were garbled as a result of permuting markers
3578 in the range START through END. Any overlay with at least one
3579 endpoint in this range will need to be unlinked from the overlay
3580 list and reinserted in its proper place.
3581 Such an overlay might even have negative size at this point.
3582 If so, we'll make the overlay empty. */
3583 void
3584 fix_start_end_in_overlays (register ptrdiff_t start, register ptrdiff_t end)
3586 Lisp_Object overlay;
3587 struct Lisp_Overlay *before_list IF_LINT (= NULL);
3588 struct Lisp_Overlay *after_list IF_LINT (= NULL);
3589 /* These are either nil, indicating that before_list or after_list
3590 should be assigned, or the cons cell the cdr of which should be
3591 assigned. */
3592 struct Lisp_Overlay *beforep = NULL, *afterp = NULL;
3593 /* 'Parent', likewise, indicates a cons cell or
3594 current_buffer->overlays_before or overlays_after, depending
3595 which loop we're in. */
3596 struct Lisp_Overlay *tail, *parent;
3597 ptrdiff_t startpos, endpos;
3599 /* This algorithm shifts links around instead of consing and GCing.
3600 The loop invariant is that before_list (resp. after_list) is a
3601 well-formed list except that its last element, the CDR of beforep
3602 (resp. afterp) if beforep (afterp) isn't nil or before_list
3603 (after_list) if it is, is still uninitialized. So it's not a bug
3604 that before_list isn't initialized, although it may look
3605 strange. */
3606 for (parent = NULL, tail = current_buffer->overlays_before; tail;)
3608 XSETMISC (overlay, tail);
3610 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3611 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3613 /* If the overlay is backwards, make it empty. */
3614 if (endpos < startpos)
3616 startpos = endpos;
3617 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3618 Qnil);
3621 if (endpos < start)
3622 break;
3624 if (endpos < end
3625 || (startpos >= start && startpos < end))
3627 /* Add it to the end of the wrong list. Later on,
3628 recenter_overlay_lists will move it to the right place. */
3629 if (endpos < current_buffer->overlay_center)
3631 if (!afterp)
3632 after_list = tail;
3633 else
3634 afterp->next = tail;
3635 afterp = tail;
3637 else
3639 if (!beforep)
3640 before_list = tail;
3641 else
3642 beforep->next = tail;
3643 beforep = tail;
3645 if (!parent)
3646 set_buffer_overlays_before (current_buffer, tail->next);
3647 else
3648 parent->next = tail->next;
3649 tail = tail->next;
3651 else
3652 parent = tail, tail = parent->next;
3654 for (parent = NULL, tail = current_buffer->overlays_after; tail;)
3656 XSETMISC (overlay, tail);
3658 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3659 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3661 /* If the overlay is backwards, make it empty. */
3662 if (endpos < startpos)
3664 startpos = endpos;
3665 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3666 Qnil);
3669 if (startpos >= end)
3670 break;
3672 if (startpos >= start
3673 || (endpos >= start && endpos < end))
3675 if (endpos < current_buffer->overlay_center)
3677 if (!afterp)
3678 after_list = tail;
3679 else
3680 afterp->next = tail;
3681 afterp = tail;
3683 else
3685 if (!beforep)
3686 before_list = tail;
3687 else
3688 beforep->next = tail;
3689 beforep = tail;
3691 if (!parent)
3692 set_buffer_overlays_after (current_buffer, tail->next);
3693 else
3694 parent->next = tail->next;
3695 tail = tail->next;
3697 else
3698 parent = tail, tail = parent->next;
3701 /* Splice the constructed (wrong) lists into the buffer's lists,
3702 and let the recenter function make it sane again. */
3703 if (beforep)
3705 beforep->next = current_buffer->overlays_before;
3706 set_buffer_overlays_before (current_buffer, before_list);
3709 if (afterp)
3711 afterp->next = current_buffer->overlays_after;
3712 set_buffer_overlays_after (current_buffer, after_list);
3714 recenter_overlay_lists (current_buffer, current_buffer->overlay_center);
3717 /* We have two types of overlay: the one whose ending marker is
3718 after-insertion-marker (this is the usual case) and the one whose
3719 ending marker is before-insertion-marker. When `overlays_before'
3720 contains overlays of the latter type and the former type in this
3721 order and both overlays end at inserting position, inserting a text
3722 increases only the ending marker of the latter type, which results
3723 in incorrect ordering of `overlays_before'.
3725 This function fixes ordering of overlays in the slot
3726 `overlays_before' of the buffer *BP. Before the insertion, `point'
3727 was at PREV, and now is at POS. */
3729 void
3730 fix_overlays_before (struct buffer *bp, ptrdiff_t prev, ptrdiff_t pos)
3732 /* If parent is nil, replace overlays_before; otherwise, parent->next. */
3733 struct Lisp_Overlay *tail = bp->overlays_before, *parent = NULL, *right_pair;
3734 Lisp_Object tem;
3735 ptrdiff_t end IF_LINT (= 0);
3737 /* After the insertion, the several overlays may be in incorrect
3738 order. The possibility is that, in the list `overlays_before',
3739 an overlay which ends at POS appears after an overlay which ends
3740 at PREV. Since POS is greater than PREV, we must fix the
3741 ordering of these overlays, by moving overlays ends at POS before
3742 the overlays ends at PREV. */
3744 /* At first, find a place where disordered overlays should be linked
3745 in. It is where an overlay which end before POS exists. (i.e. an
3746 overlay whose ending marker is after-insertion-marker if disorder
3747 exists). */
3748 while (tail
3749 && (XSETMISC (tem, tail),
3750 (end = OVERLAY_POSITION (OVERLAY_END (tem))) >= pos))
3752 parent = tail;
3753 tail = tail->next;
3756 /* If we don't find such an overlay,
3757 or the found one ends before PREV,
3758 or the found one is the last one in the list,
3759 we don't have to fix anything. */
3760 if (!tail || end < prev || !tail->next)
3761 return;
3763 right_pair = parent;
3764 parent = tail;
3765 tail = tail->next;
3767 /* Now, end position of overlays in the list TAIL should be before
3768 or equal to PREV. In the loop, an overlay which ends at POS is
3769 moved ahead to the place indicated by the CDR of RIGHT_PAIR. If
3770 we found an overlay which ends before PREV, the remaining
3771 overlays are in correct order. */
3772 while (tail)
3774 XSETMISC (tem, tail);
3775 end = OVERLAY_POSITION (OVERLAY_END (tem));
3777 if (end == pos)
3778 { /* This overlay is disordered. */
3779 struct Lisp_Overlay *found = tail;
3781 /* Unlink the found overlay. */
3782 tail = found->next;
3783 parent->next = tail;
3784 /* Move an overlay at RIGHT_PLACE to the next of the found one,
3785 and link it into the right place. */
3786 if (!right_pair)
3788 found->next = bp->overlays_before;
3789 set_buffer_overlays_before (bp, found);
3791 else
3793 found->next = right_pair->next;
3794 right_pair->next = found;
3797 else if (end == prev)
3799 parent = tail;
3800 tail = tail->next;
3802 else /* No more disordered overlay. */
3803 break;
3807 DEFUN ("overlayp", Foverlayp, Soverlayp, 1, 1, 0,
3808 doc: /* Return t if OBJECT is an overlay. */)
3809 (Lisp_Object object)
3811 return (OVERLAYP (object) ? Qt : Qnil);
3814 DEFUN ("make-overlay", Fmake_overlay, Smake_overlay, 2, 5, 0,
3815 doc: /* Create a new overlay with range BEG to END in BUFFER.
3816 If omitted, BUFFER defaults to the current buffer.
3817 BEG and END may be integers or markers.
3818 The fourth arg FRONT-ADVANCE, if non-nil, makes the marker
3819 for the front of the overlay advance when text is inserted there
3820 \(which means the text *is not* included in the overlay).
3821 The fifth arg REAR-ADVANCE, if non-nil, makes the marker
3822 for the rear of the overlay advance when text is inserted there
3823 \(which means the text *is* included in the overlay). */)
3824 (Lisp_Object beg, Lisp_Object end, Lisp_Object buffer,
3825 Lisp_Object front_advance, Lisp_Object rear_advance)
3827 Lisp_Object overlay;
3828 struct buffer *b;
3830 if (NILP (buffer))
3831 XSETBUFFER (buffer, current_buffer);
3832 else
3833 CHECK_BUFFER (buffer);
3835 if (MARKERP (beg) && !EQ (Fmarker_buffer (beg), buffer))
3836 signal_error ("Marker points into wrong buffer", beg);
3837 if (MARKERP (end) && !EQ (Fmarker_buffer (end), buffer))
3838 signal_error ("Marker points into wrong buffer", end);
3840 CHECK_NUMBER_COERCE_MARKER (beg);
3841 CHECK_NUMBER_COERCE_MARKER (end);
3843 if (XINT (beg) > XINT (end))
3845 Lisp_Object temp;
3846 temp = beg; beg = end; end = temp;
3849 b = XBUFFER (buffer);
3851 beg = Fset_marker (Fmake_marker (), beg, buffer);
3852 end = Fset_marker (Fmake_marker (), end, buffer);
3854 if (!NILP (front_advance))
3855 XMARKER (beg)->insertion_type = 1;
3856 if (!NILP (rear_advance))
3857 XMARKER (end)->insertion_type = 1;
3859 overlay = build_overlay (beg, end, Qnil);
3861 /* Put the new overlay on the wrong list. */
3862 end = OVERLAY_END (overlay);
3863 if (OVERLAY_POSITION (end) < b->overlay_center)
3865 eassert (b->overlays_after || (XOVERLAY (overlay)->next == NULL));
3866 XOVERLAY (overlay)->next = b->overlays_after;
3867 set_buffer_overlays_after (b, XOVERLAY (overlay));
3869 else
3871 eassert (b->overlays_before || (XOVERLAY (overlay)->next == NULL));
3872 XOVERLAY (overlay)->next = b->overlays_before;
3873 set_buffer_overlays_before (b, XOVERLAY (overlay));
3875 /* This puts it in the right list, and in the right order. */
3876 recenter_overlay_lists (b, b->overlay_center);
3878 /* We don't need to redisplay the region covered by the overlay, because
3879 the overlay has no properties at the moment. */
3881 return overlay;
3884 /* Mark a section of BUF as needing redisplay because of overlays changes. */
3886 static void
3887 modify_overlay (struct buffer *buf, ptrdiff_t start, ptrdiff_t end)
3889 if (start > end)
3891 ptrdiff_t temp = start;
3892 start = end;
3893 end = temp;
3896 BUF_COMPUTE_UNCHANGED (buf, start, end);
3898 /* If BUF is visible, consider updating the display if ... */
3899 if (buffer_window_count (buf) > 0)
3901 /* ... it's visible in other window than selected, */
3902 if (buf != XBUFFER (XWINDOW (selected_window)->contents))
3903 windows_or_buffers_changed = 11;
3904 /* ... or if we modify an overlay at the end of the buffer
3905 and so we cannot be sure that window end is still valid. */
3906 else if (end >= ZV && start <= ZV)
3907 windows_or_buffers_changed = 12;
3910 ++BUF_OVERLAY_MODIFF (buf);
3913 /* Remove OVERLAY from LIST. */
3915 static struct Lisp_Overlay *
3916 unchain_overlay (struct Lisp_Overlay *list, struct Lisp_Overlay *overlay)
3918 register struct Lisp_Overlay *tail, **prev = &list;
3920 for (tail = list; tail; prev = &tail->next, tail = *prev)
3921 if (tail == overlay)
3923 *prev = overlay->next;
3924 overlay->next = NULL;
3925 break;
3927 return list;
3930 /* Remove OVERLAY from both overlay lists of B. */
3932 static void
3933 unchain_both (struct buffer *b, Lisp_Object overlay)
3935 struct Lisp_Overlay *ov = XOVERLAY (overlay);
3937 set_buffer_overlays_before (b, unchain_overlay (b->overlays_before, ov));
3938 set_buffer_overlays_after (b, unchain_overlay (b->overlays_after, ov));
3939 eassert (XOVERLAY (overlay)->next == NULL);
3942 DEFUN ("move-overlay", Fmove_overlay, Smove_overlay, 3, 4, 0,
3943 doc: /* Set the endpoints of OVERLAY to BEG and END in BUFFER.
3944 If BUFFER is omitted, leave OVERLAY in the same buffer it inhabits now.
3945 If BUFFER is omitted, and OVERLAY is in no buffer, put it in the current
3946 buffer. */)
3947 (Lisp_Object overlay, Lisp_Object beg, Lisp_Object end, Lisp_Object buffer)
3949 struct buffer *b, *ob = 0;
3950 Lisp_Object obuffer;
3951 ptrdiff_t count = SPECPDL_INDEX ();
3952 ptrdiff_t n_beg, n_end, o_beg IF_LINT (= 0), o_end IF_LINT (= 0);
3954 CHECK_OVERLAY (overlay);
3955 if (NILP (buffer))
3956 buffer = Fmarker_buffer (OVERLAY_START (overlay));
3957 if (NILP (buffer))
3958 XSETBUFFER (buffer, current_buffer);
3959 CHECK_BUFFER (buffer);
3961 if (NILP (Fbuffer_live_p (buffer)))
3962 error ("Attempt to move overlay to a dead buffer");
3964 if (MARKERP (beg) && !EQ (Fmarker_buffer (beg), buffer))
3965 signal_error ("Marker points into wrong buffer", beg);
3966 if (MARKERP (end) && !EQ (Fmarker_buffer (end), buffer))
3967 signal_error ("Marker points into wrong buffer", end);
3969 CHECK_NUMBER_COERCE_MARKER (beg);
3970 CHECK_NUMBER_COERCE_MARKER (end);
3972 if (XINT (beg) > XINT (end))
3974 Lisp_Object temp;
3975 temp = beg; beg = end; end = temp;
3978 specbind (Qinhibit_quit, Qt);
3980 obuffer = Fmarker_buffer (OVERLAY_START (overlay));
3981 b = XBUFFER (buffer);
3983 if (!NILP (obuffer))
3985 ob = XBUFFER (obuffer);
3987 o_beg = OVERLAY_POSITION (OVERLAY_START (overlay));
3988 o_end = OVERLAY_POSITION (OVERLAY_END (overlay));
3990 unchain_both (ob, overlay);
3993 /* Set the overlay boundaries, which may clip them. */
3994 Fset_marker (OVERLAY_START (overlay), beg, buffer);
3995 Fset_marker (OVERLAY_END (overlay), end, buffer);
3997 n_beg = marker_position (OVERLAY_START (overlay));
3998 n_end = marker_position (OVERLAY_END (overlay));
4000 /* If the overlay has changed buffers, do a thorough redisplay. */
4001 if (!EQ (buffer, obuffer))
4003 /* Redisplay where the overlay was. */
4004 if (ob)
4005 modify_overlay (ob, o_beg, o_end);
4007 /* Redisplay where the overlay is going to be. */
4008 modify_overlay (b, n_beg, n_end);
4010 else
4011 /* Redisplay the area the overlay has just left, or just enclosed. */
4013 if (o_beg == n_beg)
4014 modify_overlay (b, o_end, n_end);
4015 else if (o_end == n_end)
4016 modify_overlay (b, o_beg, n_beg);
4017 else
4018 modify_overlay (b, min (o_beg, n_beg), max (o_end, n_end));
4021 /* Delete the overlay if it is empty after clipping and has the
4022 evaporate property. */
4023 if (n_beg == n_end && !NILP (Foverlay_get (overlay, Qevaporate)))
4024 return unbind_to (count, Fdelete_overlay (overlay));
4026 /* Put the overlay into the new buffer's overlay lists, first on the
4027 wrong list. */
4028 if (n_end < b->overlay_center)
4030 XOVERLAY (overlay)->next = b->overlays_after;
4031 set_buffer_overlays_after (b, XOVERLAY (overlay));
4033 else
4035 XOVERLAY (overlay)->next = b->overlays_before;
4036 set_buffer_overlays_before (b, XOVERLAY (overlay));
4039 /* This puts it in the right list, and in the right order. */
4040 recenter_overlay_lists (b, b->overlay_center);
4042 return unbind_to (count, overlay);
4045 DEFUN ("delete-overlay", Fdelete_overlay, Sdelete_overlay, 1, 1, 0,
4046 doc: /* Delete the overlay OVERLAY from its buffer. */)
4047 (Lisp_Object overlay)
4049 Lisp_Object buffer;
4050 struct buffer *b;
4051 ptrdiff_t count = SPECPDL_INDEX ();
4053 CHECK_OVERLAY (overlay);
4055 buffer = Fmarker_buffer (OVERLAY_START (overlay));
4056 if (NILP (buffer))
4057 return Qnil;
4059 b = XBUFFER (buffer);
4060 specbind (Qinhibit_quit, Qt);
4062 unchain_both (b, overlay);
4063 drop_overlay (b, XOVERLAY (overlay));
4065 /* When deleting an overlay with before or after strings, turn off
4066 display optimizations for the affected buffer, on the basis that
4067 these strings may contain newlines. This is easier to do than to
4068 check for that situation during redisplay. */
4069 if (!windows_or_buffers_changed
4070 && (!NILP (Foverlay_get (overlay, Qbefore_string))
4071 || !NILP (Foverlay_get (overlay, Qafter_string))))
4072 b->prevent_redisplay_optimizations_p = 1;
4074 return unbind_to (count, Qnil);
4077 DEFUN ("delete-all-overlays", Fdelete_all_overlays, Sdelete_all_overlays, 0, 1, 0,
4078 doc: /* Delete all overlays of BUFFER.
4079 BUFFER omitted or nil means delete all overlays of the current
4080 buffer. */)
4081 (Lisp_Object buffer)
4083 register struct buffer *buf;
4085 if (NILP (buffer))
4086 buf = current_buffer;
4087 else
4089 CHECK_BUFFER (buffer);
4090 buf = XBUFFER (buffer);
4093 delete_all_overlays (buf);
4094 return Qnil;
4097 /* Overlay dissection functions. */
4099 DEFUN ("overlay-start", Foverlay_start, Soverlay_start, 1, 1, 0,
4100 doc: /* Return the position at which OVERLAY starts. */)
4101 (Lisp_Object overlay)
4103 CHECK_OVERLAY (overlay);
4105 return (Fmarker_position (OVERLAY_START (overlay)));
4108 DEFUN ("overlay-end", Foverlay_end, Soverlay_end, 1, 1, 0,
4109 doc: /* Return the position at which OVERLAY ends. */)
4110 (Lisp_Object overlay)
4112 CHECK_OVERLAY (overlay);
4114 return (Fmarker_position (OVERLAY_END (overlay)));
4117 DEFUN ("overlay-buffer", Foverlay_buffer, Soverlay_buffer, 1, 1, 0,
4118 doc: /* Return the buffer OVERLAY belongs to.
4119 Return nil if OVERLAY has been deleted. */)
4120 (Lisp_Object overlay)
4122 CHECK_OVERLAY (overlay);
4124 return Fmarker_buffer (OVERLAY_START (overlay));
4127 DEFUN ("overlay-properties", Foverlay_properties, Soverlay_properties, 1, 1, 0,
4128 doc: /* Return a list of the properties on OVERLAY.
4129 This is a copy of OVERLAY's plist; modifying its conses has no effect on
4130 OVERLAY. */)
4131 (Lisp_Object overlay)
4133 CHECK_OVERLAY (overlay);
4135 return Fcopy_sequence (XOVERLAY (overlay)->plist);
4139 DEFUN ("overlays-at", Foverlays_at, Soverlays_at, 1, 1, 0,
4140 doc: /* Return a list of the overlays that contain the character at POS. */)
4141 (Lisp_Object pos)
4143 ptrdiff_t len, noverlays;
4144 Lisp_Object *overlay_vec;
4145 Lisp_Object result;
4147 CHECK_NUMBER_COERCE_MARKER (pos);
4149 if (!buffer_has_overlays ())
4150 return Qnil;
4152 len = 10;
4153 /* We can't use alloca here because overlays_at can call xrealloc. */
4154 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4156 /* Put all the overlays we want in a vector in overlay_vec.
4157 Store the length in len. */
4158 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
4159 NULL, NULL, 0);
4161 /* Make a list of them all. */
4162 result = Flist (noverlays, overlay_vec);
4164 xfree (overlay_vec);
4165 return result;
4168 DEFUN ("overlays-in", Foverlays_in, Soverlays_in, 2, 2, 0,
4169 doc: /* Return a list of the overlays that overlap the region BEG ... END.
4170 Overlap means that at least one character is contained within the overlay
4171 and also contained within the specified region.
4172 Empty overlays are included in the result if they are located at BEG,
4173 between BEG and END, or at END provided END denotes the position at the
4174 end of the buffer. */)
4175 (Lisp_Object beg, Lisp_Object end)
4177 ptrdiff_t len, noverlays;
4178 Lisp_Object *overlay_vec;
4179 Lisp_Object result;
4181 CHECK_NUMBER_COERCE_MARKER (beg);
4182 CHECK_NUMBER_COERCE_MARKER (end);
4184 if (!buffer_has_overlays ())
4185 return Qnil;
4187 len = 10;
4188 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4190 /* Put all the overlays we want in a vector in overlay_vec.
4191 Store the length in len. */
4192 noverlays = overlays_in (XINT (beg), XINT (end), 1, &overlay_vec, &len,
4193 NULL, NULL);
4195 /* Make a list of them all. */
4196 result = Flist (noverlays, overlay_vec);
4198 xfree (overlay_vec);
4199 return result;
4202 DEFUN ("next-overlay-change", Fnext_overlay_change, Snext_overlay_change,
4203 1, 1, 0,
4204 doc: /* Return the next position after POS where an overlay starts or ends.
4205 If there are no overlay boundaries from POS to (point-max),
4206 the value is (point-max). */)
4207 (Lisp_Object pos)
4209 ptrdiff_t i, len, noverlays;
4210 ptrdiff_t endpos;
4211 Lisp_Object *overlay_vec;
4213 CHECK_NUMBER_COERCE_MARKER (pos);
4215 if (!buffer_has_overlays ())
4216 return make_number (ZV);
4218 len = 10;
4219 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4221 /* Put all the overlays we want in a vector in overlay_vec.
4222 Store the length in len.
4223 endpos gets the position where the next overlay starts. */
4224 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
4225 &endpos, 0, 1);
4227 /* If any of these overlays ends before endpos,
4228 use its ending point instead. */
4229 for (i = 0; i < noverlays; i++)
4231 Lisp_Object oend;
4232 ptrdiff_t oendpos;
4234 oend = OVERLAY_END (overlay_vec[i]);
4235 oendpos = OVERLAY_POSITION (oend);
4236 if (oendpos < endpos)
4237 endpos = oendpos;
4240 xfree (overlay_vec);
4241 return make_number (endpos);
4244 DEFUN ("previous-overlay-change", Fprevious_overlay_change,
4245 Sprevious_overlay_change, 1, 1, 0,
4246 doc: /* Return the previous position before POS where an overlay starts or ends.
4247 If there are no overlay boundaries from (point-min) to POS,
4248 the value is (point-min). */)
4249 (Lisp_Object pos)
4251 ptrdiff_t prevpos;
4252 Lisp_Object *overlay_vec;
4253 ptrdiff_t len;
4255 CHECK_NUMBER_COERCE_MARKER (pos);
4257 if (!buffer_has_overlays ())
4258 return make_number (BEGV);
4260 /* At beginning of buffer, we know the answer;
4261 avoid bug subtracting 1 below. */
4262 if (XINT (pos) == BEGV)
4263 return pos;
4265 len = 10;
4266 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4268 /* Put all the overlays we want in a vector in overlay_vec.
4269 Store the length in len.
4270 prevpos gets the position of the previous change. */
4271 overlays_at (XINT (pos), 1, &overlay_vec, &len,
4272 0, &prevpos, 1);
4274 xfree (overlay_vec);
4275 return make_number (prevpos);
4278 /* These functions are for debugging overlays. */
4280 DEFUN ("overlay-lists", Foverlay_lists, Soverlay_lists, 0, 0, 0,
4281 doc: /* Return a pair of lists giving all the overlays of the current buffer.
4282 The car has all the overlays before the overlay center;
4283 the cdr has all the overlays after the overlay center.
4284 Recentering overlays moves overlays between these lists.
4285 The lists you get are copies, so that changing them has no effect.
4286 However, the overlays you get are the real objects that the buffer uses. */)
4287 (void)
4289 struct Lisp_Overlay *ol;
4290 Lisp_Object before = Qnil, after = Qnil, tmp;
4292 for (ol = current_buffer->overlays_before; ol; ol = ol->next)
4294 XSETMISC (tmp, ol);
4295 before = Fcons (tmp, before);
4297 for (ol = current_buffer->overlays_after; ol; ol = ol->next)
4299 XSETMISC (tmp, ol);
4300 after = Fcons (tmp, after);
4303 return Fcons (Fnreverse (before), Fnreverse (after));
4306 DEFUN ("overlay-recenter", Foverlay_recenter, Soverlay_recenter, 1, 1, 0,
4307 doc: /* Recenter the overlays of the current buffer around position POS.
4308 That makes overlay lookup faster for positions near POS (but perhaps slower
4309 for positions far away from POS). */)
4310 (Lisp_Object pos)
4312 ptrdiff_t p;
4313 CHECK_NUMBER_COERCE_MARKER (pos);
4315 p = clip_to_bounds (PTRDIFF_MIN, XINT (pos), PTRDIFF_MAX);
4316 recenter_overlay_lists (current_buffer, p);
4317 return Qnil;
4320 DEFUN ("overlay-get", Foverlay_get, Soverlay_get, 2, 2, 0,
4321 doc: /* Get the property of overlay OVERLAY with property name PROP. */)
4322 (Lisp_Object overlay, Lisp_Object prop)
4324 CHECK_OVERLAY (overlay);
4325 return lookup_char_property (XOVERLAY (overlay)->plist, prop, 0);
4328 DEFUN ("overlay-put", Foverlay_put, Soverlay_put, 3, 3, 0,
4329 doc: /* Set one property of overlay OVERLAY: give property PROP value VALUE.
4330 VALUE will be returned.*/)
4331 (Lisp_Object overlay, Lisp_Object prop, Lisp_Object value)
4333 Lisp_Object tail, buffer;
4334 bool changed;
4336 CHECK_OVERLAY (overlay);
4338 buffer = Fmarker_buffer (OVERLAY_START (overlay));
4340 for (tail = XOVERLAY (overlay)->plist;
4341 CONSP (tail) && CONSP (XCDR (tail));
4342 tail = XCDR (XCDR (tail)))
4343 if (EQ (XCAR (tail), prop))
4345 changed = !EQ (XCAR (XCDR (tail)), value);
4346 XSETCAR (XCDR (tail), value);
4347 goto found;
4349 /* It wasn't in the list, so add it to the front. */
4350 changed = !NILP (value);
4351 set_overlay_plist
4352 (overlay, Fcons (prop, Fcons (value, XOVERLAY (overlay)->plist)));
4353 found:
4354 if (! NILP (buffer))
4356 if (changed)
4357 modify_overlay (XBUFFER (buffer),
4358 marker_position (OVERLAY_START (overlay)),
4359 marker_position (OVERLAY_END (overlay)));
4360 if (EQ (prop, Qevaporate) && ! NILP (value)
4361 && (OVERLAY_POSITION (OVERLAY_START (overlay))
4362 == OVERLAY_POSITION (OVERLAY_END (overlay))))
4363 Fdelete_overlay (overlay);
4366 return value;
4369 /* Subroutine of report_overlay_modification. */
4371 /* Lisp vector holding overlay hook functions to call.
4372 Vector elements come in pairs.
4373 Each even-index element is a list of hook functions.
4374 The following odd-index element is the overlay they came from.
4376 Before the buffer change, we fill in this vector
4377 as we call overlay hook functions.
4378 After the buffer change, we get the functions to call from this vector.
4379 This way we always call the same functions before and after the change. */
4380 static Lisp_Object last_overlay_modification_hooks;
4382 /* Number of elements actually used in last_overlay_modification_hooks. */
4383 static ptrdiff_t last_overlay_modification_hooks_used;
4385 /* Add one functionlist/overlay pair
4386 to the end of last_overlay_modification_hooks. */
4388 static void
4389 add_overlay_mod_hooklist (Lisp_Object functionlist, Lisp_Object overlay)
4391 ptrdiff_t oldsize = ASIZE (last_overlay_modification_hooks);
4393 if (oldsize - 1 <= last_overlay_modification_hooks_used)
4394 last_overlay_modification_hooks =
4395 larger_vector (last_overlay_modification_hooks, 2, -1);
4396 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4397 functionlist); last_overlay_modification_hooks_used++;
4398 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4399 overlay); last_overlay_modification_hooks_used++;
4402 /* Run the modification-hooks of overlays that include
4403 any part of the text in START to END.
4404 If this change is an insertion, also
4405 run the insert-before-hooks of overlay starting at END,
4406 and the insert-after-hooks of overlay ending at START.
4408 This is called both before and after the modification.
4409 AFTER is true when we call after the modification.
4411 ARG1, ARG2, ARG3 are arguments to pass to the hook functions.
4412 When AFTER is nonzero, they are the start position,
4413 the position after the inserted new text,
4414 and the length of deleted or replaced old text. */
4416 void
4417 report_overlay_modification (Lisp_Object start, Lisp_Object end, bool after,
4418 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4420 Lisp_Object prop, overlay;
4421 struct Lisp_Overlay *tail;
4422 /* True if this change is an insertion. */
4423 bool insertion = (after ? XFASTINT (arg3) == 0 : EQ (start, end));
4424 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4426 overlay = Qnil;
4427 tail = NULL;
4429 /* We used to run the functions as soon as we found them and only register
4430 them in last_overlay_modification_hooks for the purpose of the `after'
4431 case. But running elisp code as we traverse the list of overlays is
4432 painful because the list can be modified by the elisp code so we had to
4433 copy at several places. We now simply do a read-only traversal that
4434 only collects the functions to run and we run them afterwards. It's
4435 simpler, especially since all the code was already there. -stef */
4437 if (!after)
4439 /* We are being called before a change.
4440 Scan the overlays to find the functions to call. */
4441 last_overlay_modification_hooks_used = 0;
4442 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4444 ptrdiff_t startpos, endpos;
4445 Lisp_Object ostart, oend;
4447 XSETMISC (overlay, tail);
4449 ostart = OVERLAY_START (overlay);
4450 oend = OVERLAY_END (overlay);
4451 endpos = OVERLAY_POSITION (oend);
4452 if (XFASTINT (start) > endpos)
4453 break;
4454 startpos = OVERLAY_POSITION (ostart);
4455 if (insertion && (XFASTINT (start) == startpos
4456 || XFASTINT (end) == startpos))
4458 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4459 if (!NILP (prop))
4460 add_overlay_mod_hooklist (prop, overlay);
4462 if (insertion && (XFASTINT (start) == endpos
4463 || XFASTINT (end) == endpos))
4465 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4466 if (!NILP (prop))
4467 add_overlay_mod_hooklist (prop, overlay);
4469 /* Test for intersecting intervals. This does the right thing
4470 for both insertion and deletion. */
4471 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4473 prop = Foverlay_get (overlay, Qmodification_hooks);
4474 if (!NILP (prop))
4475 add_overlay_mod_hooklist (prop, overlay);
4479 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4481 ptrdiff_t startpos, endpos;
4482 Lisp_Object ostart, oend;
4484 XSETMISC (overlay, tail);
4486 ostart = OVERLAY_START (overlay);
4487 oend = OVERLAY_END (overlay);
4488 startpos = OVERLAY_POSITION (ostart);
4489 endpos = OVERLAY_POSITION (oend);
4490 if (XFASTINT (end) < startpos)
4491 break;
4492 if (insertion && (XFASTINT (start) == startpos
4493 || XFASTINT (end) == startpos))
4495 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4496 if (!NILP (prop))
4497 add_overlay_mod_hooklist (prop, overlay);
4499 if (insertion && (XFASTINT (start) == endpos
4500 || XFASTINT (end) == endpos))
4502 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4503 if (!NILP (prop))
4504 add_overlay_mod_hooklist (prop, overlay);
4506 /* Test for intersecting intervals. This does the right thing
4507 for both insertion and deletion. */
4508 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4510 prop = Foverlay_get (overlay, Qmodification_hooks);
4511 if (!NILP (prop))
4512 add_overlay_mod_hooklist (prop, overlay);
4517 GCPRO4 (overlay, arg1, arg2, arg3);
4519 /* Call the functions recorded in last_overlay_modification_hooks.
4520 First copy the vector contents, in case some of these hooks
4521 do subsequent modification of the buffer. */
4522 ptrdiff_t size = last_overlay_modification_hooks_used;
4523 Lisp_Object *copy = alloca (size * sizeof *copy);
4524 ptrdiff_t i;
4526 memcpy (copy, XVECTOR (last_overlay_modification_hooks)->contents,
4527 size * word_size);
4528 gcpro1.var = copy;
4529 gcpro1.nvars = size;
4531 for (i = 0; i < size;)
4533 Lisp_Object prop_i, overlay_i;
4534 prop_i = copy[i++];
4535 overlay_i = copy[i++];
4536 call_overlay_mod_hooks (prop_i, overlay_i, after, arg1, arg2, arg3);
4539 UNGCPRO;
4542 static void
4543 call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay, bool after,
4544 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4546 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4548 GCPRO4 (list, arg1, arg2, arg3);
4550 while (CONSP (list))
4552 if (NILP (arg3))
4553 call4 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2);
4554 else
4555 call5 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2, arg3);
4556 list = XCDR (list);
4558 UNGCPRO;
4561 /* Delete any zero-sized overlays at position POS, if the `evaporate'
4562 property is set. */
4563 void
4564 evaporate_overlays (ptrdiff_t pos)
4566 Lisp_Object overlay, hit_list;
4567 struct Lisp_Overlay *tail;
4569 hit_list = Qnil;
4570 if (pos <= current_buffer->overlay_center)
4571 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4573 ptrdiff_t endpos;
4574 XSETMISC (overlay, tail);
4575 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
4576 if (endpos < pos)
4577 break;
4578 if (endpos == pos && OVERLAY_POSITION (OVERLAY_START (overlay)) == pos
4579 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4580 hit_list = Fcons (overlay, hit_list);
4582 else
4583 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4585 ptrdiff_t startpos;
4586 XSETMISC (overlay, tail);
4587 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
4588 if (startpos > pos)
4589 break;
4590 if (startpos == pos && OVERLAY_POSITION (OVERLAY_END (overlay)) == pos
4591 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4592 hit_list = Fcons (overlay, hit_list);
4594 for (; CONSP (hit_list); hit_list = XCDR (hit_list))
4595 Fdelete_overlay (XCAR (hit_list));
4598 /***********************************************************************
4599 Allocation with mmap
4600 ***********************************************************************/
4602 #ifdef USE_MMAP_FOR_BUFFERS
4604 #include <sys/mman.h>
4606 #ifndef MAP_ANON
4607 #ifdef MAP_ANONYMOUS
4608 #define MAP_ANON MAP_ANONYMOUS
4609 #else
4610 #define MAP_ANON 0
4611 #endif
4612 #endif
4614 #ifndef MAP_FAILED
4615 #define MAP_FAILED ((void *) -1)
4616 #endif
4618 #if MAP_ANON == 0
4619 #include <fcntl.h>
4620 #endif
4622 #include "coding.h"
4625 /* Memory is allocated in regions which are mapped using mmap(2).
4626 The current implementation lets the system select mapped
4627 addresses; we're not using MAP_FIXED in general, except when
4628 trying to enlarge regions.
4630 Each mapped region starts with a mmap_region structure, the user
4631 area starts after that structure, aligned to MEM_ALIGN.
4633 +-----------------------+
4634 | struct mmap_info + |
4635 | padding |
4636 +-----------------------+
4637 | user data |
4640 +-----------------------+ */
4642 struct mmap_region
4644 /* User-specified size. */
4645 size_t nbytes_specified;
4647 /* Number of bytes mapped */
4648 size_t nbytes_mapped;
4650 /* Pointer to the location holding the address of the memory
4651 allocated with the mmap'd block. The variable actually points
4652 after this structure. */
4653 void **var;
4655 /* Next and previous in list of all mmap'd regions. */
4656 struct mmap_region *next, *prev;
4659 /* Doubly-linked list of mmap'd regions. */
4661 static struct mmap_region *mmap_regions;
4663 /* File descriptor for mmap. If we don't have anonymous mapping,
4664 /dev/zero will be opened on it. */
4666 static int mmap_fd;
4668 /* Temporary storage for mmap_set_vars, see there. */
4670 static struct mmap_region *mmap_regions_1;
4671 static int mmap_fd_1;
4673 /* Page size on this system. */
4675 static int mmap_page_size;
4677 /* 1 means mmap has been initialized. */
4679 static bool mmap_initialized_p;
4681 /* Value is X rounded up to the next multiple of N. */
4683 #define ROUND(X, N) (((X) + (N) - 1) / (N) * (N))
4685 /* Size of mmap_region structure plus padding. */
4687 #define MMAP_REGION_STRUCT_SIZE \
4688 ROUND (sizeof (struct mmap_region), MEM_ALIGN)
4690 /* Given a pointer P to the start of the user-visible part of a mapped
4691 region, return a pointer to the start of the region. */
4693 #define MMAP_REGION(P) \
4694 ((struct mmap_region *) ((char *) (P) - MMAP_REGION_STRUCT_SIZE))
4696 /* Given a pointer P to the start of a mapped region, return a pointer
4697 to the start of the user-visible part of the region. */
4699 #define MMAP_USER_AREA(P) \
4700 ((void *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
4702 #define MEM_ALIGN sizeof (double)
4704 /* Predicate returning true if part of the address range [START .. END]
4705 is currently mapped. Used to prevent overwriting an existing
4706 memory mapping.
4708 Default is to conservatively assume the address range is occupied by
4709 something else. This can be overridden by system configuration
4710 files if system-specific means to determine this exists. */
4712 #ifndef MMAP_ALLOCATED_P
4713 #define MMAP_ALLOCATED_P(start, end) 1
4714 #endif
4716 /* Perform necessary initializations for the use of mmap. */
4718 static void
4719 mmap_init (void)
4721 #if MAP_ANON == 0
4722 /* The value of mmap_fd is initially 0 in temacs, and -1
4723 in a dumped Emacs. */
4724 if (mmap_fd <= 0)
4726 /* No anonymous mmap -- we need the file descriptor. */
4727 mmap_fd = emacs_open ("/dev/zero", O_RDONLY, 0);
4728 if (mmap_fd == -1)
4729 fatal ("Cannot open /dev/zero: %s", emacs_strerror (errno));
4731 #endif /* MAP_ANON == 0 */
4733 if (mmap_initialized_p)
4734 return;
4735 mmap_initialized_p = 1;
4737 #if MAP_ANON != 0
4738 mmap_fd = -1;
4739 #endif
4741 mmap_page_size = getpagesize ();
4744 /* Return a region overlapping address range START...END, or null if
4745 none. END is not including, i.e. the last byte in the range
4746 is at END - 1. */
4748 static struct mmap_region *
4749 mmap_find (void *start, void *end)
4751 struct mmap_region *r;
4752 char *s = start, *e = end;
4754 for (r = mmap_regions; r; r = r->next)
4756 char *rstart = (char *) r;
4757 char *rend = rstart + r->nbytes_mapped;
4759 if (/* First byte of range, i.e. START, in this region? */
4760 (s >= rstart && s < rend)
4761 /* Last byte of range, i.e. END - 1, in this region? */
4762 || (e > rstart && e <= rend)
4763 /* First byte of this region in the range? */
4764 || (rstart >= s && rstart < e)
4765 /* Last byte of this region in the range? */
4766 || (rend > s && rend <= e))
4767 break;
4770 return r;
4774 /* Unmap a region. P is a pointer to the start of the user-araa of
4775 the region. */
4777 static void
4778 mmap_free_1 (struct mmap_region *r)
4780 if (r->next)
4781 r->next->prev = r->prev;
4782 if (r->prev)
4783 r->prev->next = r->next;
4784 else
4785 mmap_regions = r->next;
4787 if (munmap (r, r->nbytes_mapped) == -1)
4788 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4792 /* Enlarge region R by NPAGES pages. NPAGES < 0 means shrink R.
4793 Value is true if successful. */
4795 static bool
4796 mmap_enlarge (struct mmap_region *r, int npages)
4798 char *region_end = (char *) r + r->nbytes_mapped;
4799 size_t nbytes;
4800 bool success = 0;
4802 if (npages < 0)
4804 /* Unmap pages at the end of the region. */
4805 nbytes = - npages * mmap_page_size;
4806 if (munmap (region_end - nbytes, nbytes) == -1)
4807 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4808 else
4810 r->nbytes_mapped -= nbytes;
4811 success = 1;
4814 else if (npages > 0)
4816 nbytes = npages * mmap_page_size;
4818 /* Try to map additional pages at the end of the region. We
4819 cannot do this if the address range is already occupied by
4820 something else because mmap deletes any previous mapping.
4821 I'm not sure this is worth doing, let's see. */
4822 if (!MMAP_ALLOCATED_P (region_end, region_end + nbytes))
4824 void *p;
4826 p = mmap (region_end, nbytes, PROT_READ | PROT_WRITE,
4827 MAP_ANON | MAP_PRIVATE | MAP_FIXED, mmap_fd, 0);
4828 if (p == MAP_FAILED)
4829 ; /* fprintf (stderr, "mmap: %s\n", emacs_strerror (errno)); */
4830 else if (p != region_end)
4832 /* Kernels are free to choose a different address. In
4833 that case, unmap what we've mapped above; we have
4834 no use for it. */
4835 if (munmap (p, nbytes) == -1)
4836 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4838 else
4840 r->nbytes_mapped += nbytes;
4841 success = 1;
4846 return success;
4850 /* Set or reset variables holding references to mapped regions.
4851 If not RESTORE_P, set all variables to null. If RESTORE_P, set all
4852 variables to the start of the user-areas of mapped regions.
4854 This function is called from Fdump_emacs to ensure that the dumped
4855 Emacs doesn't contain references to memory that won't be mapped
4856 when Emacs starts. */
4858 void
4859 mmap_set_vars (bool restore_p)
4861 struct mmap_region *r;
4863 if (restore_p)
4865 mmap_regions = mmap_regions_1;
4866 mmap_fd = mmap_fd_1;
4867 for (r = mmap_regions; r; r = r->next)
4868 *r->var = MMAP_USER_AREA (r);
4870 else
4872 for (r = mmap_regions; r; r = r->next)
4873 *r->var = NULL;
4874 mmap_regions_1 = mmap_regions;
4875 mmap_regions = NULL;
4876 mmap_fd_1 = mmap_fd;
4877 mmap_fd = -1;
4882 /* Allocate a block of storage large enough to hold NBYTES bytes of
4883 data. A pointer to the data is returned in *VAR. VAR is thus the
4884 address of some variable which will use the data area.
4886 The allocation of 0 bytes is valid.
4888 If we can't allocate the necessary memory, set *VAR to null, and
4889 return null. */
4891 static void *
4892 mmap_alloc (void **var, size_t nbytes)
4894 void *p;
4895 size_t map;
4897 mmap_init ();
4899 map = ROUND (nbytes + MMAP_REGION_STRUCT_SIZE, mmap_page_size);
4900 p = mmap (NULL, map, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
4901 mmap_fd, 0);
4903 if (p == MAP_FAILED)
4905 if (errno != ENOMEM)
4906 fprintf (stderr, "mmap: %s\n", emacs_strerror (errno));
4907 p = NULL;
4909 else
4911 struct mmap_region *r = p;
4913 r->nbytes_specified = nbytes;
4914 r->nbytes_mapped = map;
4915 r->var = var;
4916 r->prev = NULL;
4917 r->next = mmap_regions;
4918 if (r->next)
4919 r->next->prev = r;
4920 mmap_regions = r;
4922 p = MMAP_USER_AREA (p);
4925 return *var = p;
4929 /* Free a block of relocatable storage whose data is pointed to by
4930 PTR. Store 0 in *PTR to show there's no block allocated. */
4932 static void
4933 mmap_free (void **var)
4935 mmap_init ();
4937 if (*var)
4939 mmap_free_1 (MMAP_REGION (*var));
4940 *var = NULL;
4945 /* Given a pointer at address VAR to data allocated with mmap_alloc,
4946 resize it to size NBYTES. Change *VAR to reflect the new block,
4947 and return this value. If more memory cannot be allocated, then
4948 leave *VAR unchanged, and return null. */
4950 static void *
4951 mmap_realloc (void **var, size_t nbytes)
4953 void *result;
4955 mmap_init ();
4957 if (*var == NULL)
4958 result = mmap_alloc (var, nbytes);
4959 else if (nbytes == 0)
4961 mmap_free (var);
4962 result = mmap_alloc (var, nbytes);
4964 else
4966 struct mmap_region *r = MMAP_REGION (*var);
4967 size_t room = r->nbytes_mapped - MMAP_REGION_STRUCT_SIZE;
4969 if (room < nbytes)
4971 /* Must enlarge. */
4972 void *old_ptr = *var;
4974 /* Try to map additional pages at the end of the region.
4975 If that fails, allocate a new region, copy data
4976 from the old region, then free it. */
4977 if (mmap_enlarge (r, (ROUND (nbytes - room, mmap_page_size)
4978 / mmap_page_size)))
4980 r->nbytes_specified = nbytes;
4981 *var = result = old_ptr;
4983 else if (mmap_alloc (var, nbytes))
4985 memcpy (*var, old_ptr, r->nbytes_specified);
4986 mmap_free_1 (MMAP_REGION (old_ptr));
4987 result = *var;
4988 r = MMAP_REGION (result);
4989 r->nbytes_specified = nbytes;
4991 else
4993 *var = old_ptr;
4994 result = NULL;
4997 else if (room - nbytes >= mmap_page_size)
4999 /* Shrinking by at least a page. Let's give some
5000 memory back to the system.
5002 The extra parens are to make the division happens first,
5003 on positive values, so we know it will round towards
5004 zero. */
5005 mmap_enlarge (r, - ((room - nbytes) / mmap_page_size));
5006 result = *var;
5007 r->nbytes_specified = nbytes;
5009 else
5011 /* Leave it alone. */
5012 result = *var;
5013 r->nbytes_specified = nbytes;
5017 return result;
5021 #endif /* USE_MMAP_FOR_BUFFERS */
5025 /***********************************************************************
5026 Buffer-text Allocation
5027 ***********************************************************************/
5029 /* Allocate NBYTES bytes for buffer B's text buffer. */
5031 static void
5032 alloc_buffer_text (struct buffer *b, ptrdiff_t nbytes)
5034 void *p;
5036 block_input ();
5037 #if defined USE_MMAP_FOR_BUFFERS
5038 p = mmap_alloc ((void **) &b->text->beg, nbytes);
5039 #elif defined REL_ALLOC
5040 p = r_alloc ((void **) &b->text->beg, nbytes);
5041 #else
5042 p = xmalloc (nbytes);
5043 #endif
5045 if (p == NULL)
5047 unblock_input ();
5048 memory_full (nbytes);
5051 b->text->beg = p;
5052 unblock_input ();
5055 /* Enlarge buffer B's text buffer by DELTA bytes. DELTA < 0 means
5056 shrink it. */
5058 void
5059 enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
5061 void *p;
5062 ptrdiff_t nbytes = (BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1
5063 + delta);
5064 block_input ();
5065 #if defined USE_MMAP_FOR_BUFFERS
5066 p = mmap_realloc ((void **) &b->text->beg, nbytes);
5067 #elif defined REL_ALLOC
5068 p = r_re_alloc ((void **) &b->text->beg, nbytes);
5069 #else
5070 p = xrealloc (b->text->beg, nbytes);
5071 #endif
5073 if (p == NULL)
5075 unblock_input ();
5076 memory_full (nbytes);
5079 BUF_BEG_ADDR (b) = p;
5080 unblock_input ();
5084 /* Free buffer B's text buffer. */
5086 static void
5087 free_buffer_text (struct buffer *b)
5089 block_input ();
5091 #if defined USE_MMAP_FOR_BUFFERS
5092 mmap_free ((void **) &b->text->beg);
5093 #elif defined REL_ALLOC
5094 r_alloc_free ((void **) &b->text->beg);
5095 #else
5096 xfree (b->text->beg);
5097 #endif
5099 BUF_BEG_ADDR (b) = NULL;
5100 unblock_input ();
5105 /***********************************************************************
5106 Initialization
5107 ***********************************************************************/
5109 void
5110 init_buffer_once (void)
5112 int idx;
5114 memset (buffer_permanent_local_flags, 0, sizeof buffer_permanent_local_flags);
5116 /* Make sure all markable slots in buffer_defaults
5117 are initialized reasonably, so mark_buffer won't choke. */
5118 reset_buffer (&buffer_defaults);
5119 eassert (EQ (BVAR (&buffer_defaults, name), make_number (0)));
5120 reset_buffer_local_variables (&buffer_defaults, 1);
5121 eassert (EQ (BVAR (&buffer_local_symbols, name), make_number (0)));
5122 reset_buffer (&buffer_local_symbols);
5123 reset_buffer_local_variables (&buffer_local_symbols, 1);
5124 /* Prevent GC from getting confused. */
5125 buffer_defaults.text = &buffer_defaults.own_text;
5126 buffer_local_symbols.text = &buffer_local_symbols.own_text;
5127 /* No one will share the text with these buffers, but let's play it safe. */
5128 buffer_defaults.indirections = 0;
5129 buffer_local_symbols.indirections = 0;
5130 /* Likewise no one will display them. */
5131 buffer_defaults.window_count = 0;
5132 buffer_local_symbols.window_count = 0;
5133 set_buffer_intervals (&buffer_defaults, NULL);
5134 set_buffer_intervals (&buffer_local_symbols, NULL);
5135 /* This is not strictly necessary, but let's make them initialized. */
5136 bset_name (&buffer_defaults, build_pure_c_string (" *buffer-defaults*"));
5137 bset_name (&buffer_local_symbols, build_pure_c_string (" *buffer-local-symbols*"));
5138 BUFFER_PVEC_INIT (&buffer_defaults);
5139 BUFFER_PVEC_INIT (&buffer_local_symbols);
5141 /* Set up the default values of various buffer slots. */
5142 /* Must do these before making the first buffer! */
5144 /* real setup is done in bindings.el */
5145 bset_mode_line_format (&buffer_defaults, build_pure_c_string ("%-"));
5146 bset_header_line_format (&buffer_defaults, Qnil);
5147 bset_abbrev_mode (&buffer_defaults, Qnil);
5148 bset_overwrite_mode (&buffer_defaults, Qnil);
5149 bset_case_fold_search (&buffer_defaults, Qt);
5150 bset_auto_fill_function (&buffer_defaults, Qnil);
5151 bset_selective_display (&buffer_defaults, Qnil);
5152 bset_selective_display_ellipses (&buffer_defaults, Qt);
5153 bset_abbrev_table (&buffer_defaults, Qnil);
5154 bset_display_table (&buffer_defaults, Qnil);
5155 bset_undo_list (&buffer_defaults, Qnil);
5156 bset_mark_active (&buffer_defaults, Qnil);
5157 bset_file_format (&buffer_defaults, Qnil);
5158 bset_auto_save_file_format (&buffer_defaults, Qt);
5159 set_buffer_overlays_before (&buffer_defaults, NULL);
5160 set_buffer_overlays_after (&buffer_defaults, NULL);
5161 buffer_defaults.overlay_center = BEG;
5163 XSETFASTINT (BVAR (&buffer_defaults, tab_width), 8);
5164 bset_truncate_lines (&buffer_defaults, Qnil);
5165 bset_word_wrap (&buffer_defaults, Qnil);
5166 bset_ctl_arrow (&buffer_defaults, Qt);
5167 bset_bidi_display_reordering (&buffer_defaults, Qt);
5168 bset_bidi_paragraph_direction (&buffer_defaults, Qnil);
5169 bset_cursor_type (&buffer_defaults, Qt);
5170 bset_extra_line_spacing (&buffer_defaults, Qnil);
5171 bset_cursor_in_non_selected_windows (&buffer_defaults, Qt);
5173 bset_enable_multibyte_characters (&buffer_defaults, Qt);
5174 bset_buffer_file_coding_system (&buffer_defaults, Qnil);
5175 XSETFASTINT (BVAR (&buffer_defaults, fill_column), 70);
5176 XSETFASTINT (BVAR (&buffer_defaults, left_margin), 0);
5177 bset_cache_long_scans (&buffer_defaults, Qt);
5178 bset_file_truename (&buffer_defaults, Qnil);
5179 XSETFASTINT (BVAR (&buffer_defaults, display_count), 0);
5180 XSETFASTINT (BVAR (&buffer_defaults, left_margin_cols), 0);
5181 XSETFASTINT (BVAR (&buffer_defaults, right_margin_cols), 0);
5182 bset_left_fringe_width (&buffer_defaults, Qnil);
5183 bset_right_fringe_width (&buffer_defaults, Qnil);
5184 bset_fringes_outside_margins (&buffer_defaults, Qnil);
5185 bset_scroll_bar_width (&buffer_defaults, Qnil);
5186 bset_vertical_scroll_bar_type (&buffer_defaults, Qt);
5187 bset_indicate_empty_lines (&buffer_defaults, Qnil);
5188 bset_indicate_buffer_boundaries (&buffer_defaults, Qnil);
5189 bset_fringe_indicator_alist (&buffer_defaults, Qnil);
5190 bset_fringe_cursor_alist (&buffer_defaults, Qnil);
5191 bset_scroll_up_aggressively (&buffer_defaults, Qnil);
5192 bset_scroll_down_aggressively (&buffer_defaults, Qnil);
5193 bset_display_time (&buffer_defaults, Qnil);
5195 /* Assign the local-flags to the slots that have default values.
5196 The local flag is a bit that is used in the buffer
5197 to say that it has its own local value for the slot.
5198 The local flag bits are in the local_var_flags slot of the buffer. */
5200 /* Nothing can work if this isn't true */
5201 { verify (sizeof (EMACS_INT) == word_size); }
5203 /* 0 means not a lisp var, -1 means always local, else mask */
5204 memset (&buffer_local_flags, 0, sizeof buffer_local_flags);
5205 bset_filename (&buffer_local_flags, make_number (-1));
5206 bset_directory (&buffer_local_flags, make_number (-1));
5207 bset_backed_up (&buffer_local_flags, make_number (-1));
5208 bset_save_length (&buffer_local_flags, make_number (-1));
5209 bset_auto_save_file_name (&buffer_local_flags, make_number (-1));
5210 bset_read_only (&buffer_local_flags, make_number (-1));
5211 bset_major_mode (&buffer_local_flags, make_number (-1));
5212 bset_mode_name (&buffer_local_flags, make_number (-1));
5213 bset_undo_list (&buffer_local_flags, make_number (-1));
5214 bset_mark_active (&buffer_local_flags, make_number (-1));
5215 bset_point_before_scroll (&buffer_local_flags, make_number (-1));
5216 bset_file_truename (&buffer_local_flags, make_number (-1));
5217 bset_invisibility_spec (&buffer_local_flags, make_number (-1));
5218 bset_file_format (&buffer_local_flags, make_number (-1));
5219 bset_auto_save_file_format (&buffer_local_flags, make_number (-1));
5220 bset_display_count (&buffer_local_flags, make_number (-1));
5221 bset_display_time (&buffer_local_flags, make_number (-1));
5222 bset_enable_multibyte_characters (&buffer_local_flags, make_number (-1));
5224 idx = 1;
5225 XSETFASTINT (BVAR (&buffer_local_flags, mode_line_format), idx); ++idx;
5226 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_mode), idx); ++idx;
5227 XSETFASTINT (BVAR (&buffer_local_flags, overwrite_mode), idx); ++idx;
5228 XSETFASTINT (BVAR (&buffer_local_flags, case_fold_search), idx); ++idx;
5229 XSETFASTINT (BVAR (&buffer_local_flags, auto_fill_function), idx); ++idx;
5230 XSETFASTINT (BVAR (&buffer_local_flags, selective_display), idx); ++idx;
5231 XSETFASTINT (BVAR (&buffer_local_flags, selective_display_ellipses), idx); ++idx;
5232 XSETFASTINT (BVAR (&buffer_local_flags, tab_width), idx); ++idx;
5233 XSETFASTINT (BVAR (&buffer_local_flags, truncate_lines), idx); ++idx;
5234 XSETFASTINT (BVAR (&buffer_local_flags, word_wrap), idx); ++idx;
5235 XSETFASTINT (BVAR (&buffer_local_flags, ctl_arrow), idx); ++idx;
5236 XSETFASTINT (BVAR (&buffer_local_flags, fill_column), idx); ++idx;
5237 XSETFASTINT (BVAR (&buffer_local_flags, left_margin), idx); ++idx;
5238 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_table), idx); ++idx;
5239 XSETFASTINT (BVAR (&buffer_local_flags, display_table), idx); ++idx;
5240 XSETFASTINT (BVAR (&buffer_local_flags, syntax_table), idx); ++idx;
5241 XSETFASTINT (BVAR (&buffer_local_flags, cache_long_scans), idx); ++idx;
5242 XSETFASTINT (BVAR (&buffer_local_flags, category_table), idx); ++idx;
5243 XSETFASTINT (BVAR (&buffer_local_flags, bidi_display_reordering), idx); ++idx;
5244 XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_direction), idx); ++idx;
5245 XSETFASTINT (BVAR (&buffer_local_flags, buffer_file_coding_system), idx);
5246 /* Make this one a permanent local. */
5247 buffer_permanent_local_flags[idx++] = 1;
5248 XSETFASTINT (BVAR (&buffer_local_flags, left_margin_cols), idx); ++idx;
5249 XSETFASTINT (BVAR (&buffer_local_flags, right_margin_cols), idx); ++idx;
5250 XSETFASTINT (BVAR (&buffer_local_flags, left_fringe_width), idx); ++idx;
5251 XSETFASTINT (BVAR (&buffer_local_flags, right_fringe_width), idx); ++idx;
5252 XSETFASTINT (BVAR (&buffer_local_flags, fringes_outside_margins), idx); ++idx;
5253 XSETFASTINT (BVAR (&buffer_local_flags, scroll_bar_width), idx); ++idx;
5254 XSETFASTINT (BVAR (&buffer_local_flags, vertical_scroll_bar_type), idx); ++idx;
5255 XSETFASTINT (BVAR (&buffer_local_flags, indicate_empty_lines), idx); ++idx;
5256 XSETFASTINT (BVAR (&buffer_local_flags, indicate_buffer_boundaries), idx); ++idx;
5257 XSETFASTINT (BVAR (&buffer_local_flags, fringe_indicator_alist), idx); ++idx;
5258 XSETFASTINT (BVAR (&buffer_local_flags, fringe_cursor_alist), idx); ++idx;
5259 XSETFASTINT (BVAR (&buffer_local_flags, scroll_up_aggressively), idx); ++idx;
5260 XSETFASTINT (BVAR (&buffer_local_flags, scroll_down_aggressively), idx); ++idx;
5261 XSETFASTINT (BVAR (&buffer_local_flags, header_line_format), idx); ++idx;
5262 XSETFASTINT (BVAR (&buffer_local_flags, cursor_type), idx); ++idx;
5263 XSETFASTINT (BVAR (&buffer_local_flags, extra_line_spacing), idx); ++idx;
5264 XSETFASTINT (BVAR (&buffer_local_flags, cursor_in_non_selected_windows), idx); ++idx;
5266 /* Need more room? */
5267 if (idx >= MAX_PER_BUFFER_VARS)
5268 emacs_abort ();
5269 last_per_buffer_idx = idx;
5271 Vbuffer_alist = Qnil;
5272 current_buffer = 0;
5273 all_buffers = 0;
5275 QSFundamental = build_pure_c_string ("Fundamental");
5277 Qfundamental_mode = intern_c_string ("fundamental-mode");
5278 bset_major_mode (&buffer_defaults, Qfundamental_mode);
5280 Qmode_class = intern_c_string ("mode-class");
5282 Qprotected_field = intern_c_string ("protected-field");
5284 Qpermanent_local = intern_c_string ("permanent-local");
5286 Qkill_buffer_hook = intern_c_string ("kill-buffer-hook");
5287 Fput (Qkill_buffer_hook, Qpermanent_local, Qt);
5289 /* super-magic invisible buffer */
5290 Vprin1_to_string_buffer = Fget_buffer_create (build_pure_c_string (" prin1"));
5291 Vbuffer_alist = Qnil;
5293 Fset_buffer (Fget_buffer_create (build_pure_c_string ("*scratch*")));
5295 inhibit_modification_hooks = 0;
5298 void
5299 init_buffer (void)
5301 char *pwd;
5302 Lisp_Object temp;
5303 ptrdiff_t len;
5305 #ifdef USE_MMAP_FOR_BUFFERS
5307 /* When using the ralloc implementation based on mmap(2), buffer
5308 text pointers will have been set to null in the dumped Emacs.
5309 Map new memory. */
5310 struct buffer *b;
5312 FOR_EACH_BUFFER (b)
5313 if (b->text->beg == NULL)
5314 enlarge_buffer_text (b, 0);
5316 #endif /* USE_MMAP_FOR_BUFFERS */
5318 Fset_buffer (Fget_buffer_create (build_string ("*scratch*")));
5319 if (NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
5320 Fset_buffer_multibyte (Qnil);
5322 pwd = get_current_dir_name ();
5324 if (!pwd)
5325 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5327 /* Maybe this should really use some standard subroutine
5328 whose definition is filename syntax dependent. */
5329 len = strlen (pwd);
5330 if (!(IS_DIRECTORY_SEP (pwd[len - 1])))
5332 /* Grow buffer to add directory separator and '\0'. */
5333 pwd = realloc (pwd, len + 2);
5334 if (!pwd)
5335 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5336 pwd[len] = DIRECTORY_SEP;
5337 pwd[len + 1] = '\0';
5338 len++;
5341 /* At this moment, we still don't know how to decode the directory
5342 name. So, we keep the bytes in unibyte form so that file I/O
5343 routines correctly get the original bytes. */
5344 bset_directory (current_buffer, make_unibyte_string (pwd, len));
5346 /* Add /: to the front of the name
5347 if it would otherwise be treated as magic. */
5348 temp = Ffind_file_name_handler (BVAR (current_buffer, directory), Qt);
5349 if (! NILP (temp)
5350 /* If the default dir is just /, TEMP is non-nil
5351 because of the ange-ftp completion handler.
5352 However, it is not necessary to turn / into /:/.
5353 So avoid doing that. */
5354 && strcmp ("/", SSDATA (BVAR (current_buffer, directory))))
5355 bset_directory
5356 (current_buffer,
5357 concat2 (build_string ("/:"), BVAR (current_buffer, directory)));
5359 temp = get_minibuffer (0);
5360 bset_directory (XBUFFER (temp), BVAR (current_buffer, directory));
5362 free (pwd);
5365 /* Similar to defvar_lisp but define a variable whose value is the
5366 Lisp_Object stored in the current buffer. LNAME is the Lisp-level
5367 variable name. VNAME is the name of the buffer slot. PREDICATE
5368 is nil for a general Lisp variable. If PREDICATE is non-nil, then
5369 only Lisp values that satisfies the PREDICATE are allowed (except
5370 that nil is allowed too). DOC is a dummy where you write the doc
5371 string as a comment. */
5373 #define DEFVAR_PER_BUFFER(lname, vname, predicate, doc) \
5374 do { \
5375 static struct Lisp_Buffer_Objfwd bo_fwd; \
5376 defvar_per_buffer (&bo_fwd, lname, vname, predicate); \
5377 } while (0)
5379 static void
5380 defvar_per_buffer (struct Lisp_Buffer_Objfwd *bo_fwd, const char *namestring,
5381 Lisp_Object *address, Lisp_Object predicate)
5383 struct Lisp_Symbol *sym;
5384 int offset;
5386 sym = XSYMBOL (intern (namestring));
5387 offset = (char *)address - (char *)current_buffer;
5389 bo_fwd->type = Lisp_Fwd_Buffer_Obj;
5390 bo_fwd->offset = offset;
5391 bo_fwd->predicate = predicate;
5392 sym->declared_special = 1;
5393 sym->redirect = SYMBOL_FORWARDED;
5394 SET_SYMBOL_FWD (sym, (union Lisp_Fwd *) bo_fwd);
5395 XSETSYMBOL (PER_BUFFER_SYMBOL (offset), sym);
5397 if (PER_BUFFER_IDX (offset) == 0)
5398 /* Did a DEFVAR_PER_BUFFER without initializing the corresponding
5399 slot of buffer_local_flags. */
5400 emacs_abort ();
5404 /* Initialize the buffer routines. */
5405 void
5406 syms_of_buffer (void)
5408 staticpro (&last_overlay_modification_hooks);
5409 last_overlay_modification_hooks
5410 = Fmake_vector (make_number (10), Qnil);
5412 staticpro (&Qfundamental_mode);
5413 staticpro (&Qmode_class);
5414 staticpro (&QSFundamental);
5415 staticpro (&Vbuffer_alist);
5416 staticpro (&Qprotected_field);
5417 staticpro (&Qpermanent_local);
5418 staticpro (&Qkill_buffer_hook);
5420 DEFSYM (Qpermanent_local_hook, "permanent-local-hook");
5421 DEFSYM (Qoverlayp, "overlayp");
5422 DEFSYM (Qevaporate, "evaporate");
5423 DEFSYM (Qmodification_hooks, "modification-hooks");
5424 DEFSYM (Qinsert_in_front_hooks, "insert-in-front-hooks");
5425 DEFSYM (Qinsert_behind_hooks, "insert-behind-hooks");
5426 DEFSYM (Qget_file_buffer, "get-file-buffer");
5427 DEFSYM (Qpriority, "priority");
5428 DEFSYM (Qbefore_string, "before-string");
5429 DEFSYM (Qafter_string, "after-string");
5430 DEFSYM (Qfirst_change_hook, "first-change-hook");
5431 DEFSYM (Qbefore_change_functions, "before-change-functions");
5432 DEFSYM (Qafter_change_functions, "after-change-functions");
5433 DEFSYM (Qkill_buffer_query_functions, "kill-buffer-query-functions");
5435 Fput (Qprotected_field, Qerror_conditions,
5436 listn (CONSTYPE_PURE, 2, Qprotected_field, Qerror));
5437 Fput (Qprotected_field, Qerror_message,
5438 build_pure_c_string ("Attempt to modify a protected field"));
5440 DEFVAR_BUFFER_DEFAULTS ("default-mode-line-format",
5441 mode_line_format,
5442 doc: /* Default value of `mode-line-format' for buffers that don't override it.
5443 This is the same as (default-value 'mode-line-format). */);
5445 DEFVAR_BUFFER_DEFAULTS ("default-header-line-format",
5446 header_line_format,
5447 doc: /* Default value of `header-line-format' for buffers that don't override it.
5448 This is the same as (default-value 'header-line-format). */);
5450 DEFVAR_BUFFER_DEFAULTS ("default-cursor-type", cursor_type,
5451 doc: /* Default value of `cursor-type' for buffers that don't override it.
5452 This is the same as (default-value 'cursor-type). */);
5454 DEFVAR_BUFFER_DEFAULTS ("default-line-spacing",
5455 extra_line_spacing,
5456 doc: /* Default value of `line-spacing' for buffers that don't override it.
5457 This is the same as (default-value 'line-spacing). */);
5459 DEFVAR_BUFFER_DEFAULTS ("default-cursor-in-non-selected-windows",
5460 cursor_in_non_selected_windows,
5461 doc: /* Default value of `cursor-in-non-selected-windows'.
5462 This is the same as (default-value 'cursor-in-non-selected-windows). */);
5464 DEFVAR_BUFFER_DEFAULTS ("default-abbrev-mode",
5465 abbrev_mode,
5466 doc: /* Default value of `abbrev-mode' for buffers that do not override it.
5467 This is the same as (default-value 'abbrev-mode). */);
5469 DEFVAR_BUFFER_DEFAULTS ("default-ctl-arrow",
5470 ctl_arrow,
5471 doc: /* Default value of `ctl-arrow' for buffers that do not override it.
5472 This is the same as (default-value 'ctl-arrow). */);
5474 DEFVAR_BUFFER_DEFAULTS ("default-enable-multibyte-characters",
5475 enable_multibyte_characters,
5476 doc: /* Default value of `enable-multibyte-characters' for buffers not overriding it.
5477 This is the same as (default-value 'enable-multibyte-characters). */);
5479 DEFVAR_BUFFER_DEFAULTS ("default-buffer-file-coding-system",
5480 buffer_file_coding_system,
5481 doc: /* Default value of `buffer-file-coding-system' for buffers not overriding it.
5482 This is the same as (default-value 'buffer-file-coding-system). */);
5484 DEFVAR_BUFFER_DEFAULTS ("default-truncate-lines",
5485 truncate_lines,
5486 doc: /* Default value of `truncate-lines' for buffers that do not override it.
5487 This is the same as (default-value 'truncate-lines). */);
5489 DEFVAR_BUFFER_DEFAULTS ("default-fill-column",
5490 fill_column,
5491 doc: /* Default value of `fill-column' for buffers that do not override it.
5492 This is the same as (default-value 'fill-column). */);
5494 DEFVAR_BUFFER_DEFAULTS ("default-left-margin",
5495 left_margin,
5496 doc: /* Default value of `left-margin' for buffers that do not override it.
5497 This is the same as (default-value 'left-margin). */);
5499 DEFVAR_BUFFER_DEFAULTS ("default-tab-width",
5500 tab_width,
5501 doc: /* Default value of `tab-width' for buffers that do not override it.
5502 NOTE: This controls the display width of a TAB character, and not
5503 the size of an indentation step.
5504 This is the same as (default-value 'tab-width). */);
5506 DEFVAR_BUFFER_DEFAULTS ("default-case-fold-search",
5507 case_fold_search,
5508 doc: /* Default value of `case-fold-search' for buffers that don't override it.
5509 This is the same as (default-value 'case-fold-search). */);
5511 DEFVAR_BUFFER_DEFAULTS ("default-left-margin-width",
5512 left_margin_cols,
5513 doc: /* Default value of `left-margin-width' for buffers that don't override it.
5514 This is the same as (default-value 'left-margin-width). */);
5516 DEFVAR_BUFFER_DEFAULTS ("default-right-margin-width",
5517 right_margin_cols,
5518 doc: /* Default value of `right-margin-width' for buffers that don't override it.
5519 This is the same as (default-value 'right-margin-width). */);
5521 DEFVAR_BUFFER_DEFAULTS ("default-left-fringe-width",
5522 left_fringe_width,
5523 doc: /* Default value of `left-fringe-width' for buffers that don't override it.
5524 This is the same as (default-value 'left-fringe-width). */);
5526 DEFVAR_BUFFER_DEFAULTS ("default-right-fringe-width",
5527 right_fringe_width,
5528 doc: /* Default value of `right-fringe-width' for buffers that don't override it.
5529 This is the same as (default-value 'right-fringe-width). */);
5531 DEFVAR_BUFFER_DEFAULTS ("default-fringes-outside-margins",
5532 fringes_outside_margins,
5533 doc: /* Default value of `fringes-outside-margins' for buffers that don't override it.
5534 This is the same as (default-value 'fringes-outside-margins). */);
5536 DEFVAR_BUFFER_DEFAULTS ("default-scroll-bar-width",
5537 scroll_bar_width,
5538 doc: /* Default value of `scroll-bar-width' for buffers that don't override it.
5539 This is the same as (default-value 'scroll-bar-width). */);
5541 DEFVAR_BUFFER_DEFAULTS ("default-vertical-scroll-bar",
5542 vertical_scroll_bar_type,
5543 doc: /* Default value of `vertical-scroll-bar' for buffers that don't override it.
5544 This is the same as (default-value 'vertical-scroll-bar). */);
5546 DEFVAR_BUFFER_DEFAULTS ("default-indicate-empty-lines",
5547 indicate_empty_lines,
5548 doc: /* Default value of `indicate-empty-lines' for buffers that don't override it.
5549 This is the same as (default-value 'indicate-empty-lines). */);
5551 DEFVAR_BUFFER_DEFAULTS ("default-indicate-buffer-boundaries",
5552 indicate_buffer_boundaries,
5553 doc: /* Default value of `indicate-buffer-boundaries' for buffers that don't override it.
5554 This is the same as (default-value 'indicate-buffer-boundaries). */);
5556 DEFVAR_BUFFER_DEFAULTS ("default-fringe-indicator-alist",
5557 fringe_indicator_alist,
5558 doc: /* Default value of `fringe-indicator-alist' for buffers that don't override it.
5559 This is the same as (default-value 'fringe-indicator-alist'). */);
5561 DEFVAR_BUFFER_DEFAULTS ("default-fringe-cursor-alist",
5562 fringe_cursor_alist,
5563 doc: /* Default value of `fringe-cursor-alist' for buffers that don't override it.
5564 This is the same as (default-value 'fringe-cursor-alist'). */);
5566 DEFVAR_BUFFER_DEFAULTS ("default-scroll-up-aggressively",
5567 scroll_up_aggressively,
5568 doc: /* Default value of `scroll-up-aggressively'.
5569 This value applies in buffers that don't have their own local values.
5570 This is the same as (default-value 'scroll-up-aggressively). */);
5572 DEFVAR_BUFFER_DEFAULTS ("default-scroll-down-aggressively",
5573 scroll_down_aggressively,
5574 doc: /* Default value of `scroll-down-aggressively'.
5575 This value applies in buffers that don't have their own local values.
5576 This is the same as (default-value 'scroll-down-aggressively). */);
5578 DEFVAR_PER_BUFFER ("header-line-format",
5579 &BVAR (current_buffer, header_line_format),
5580 Qnil,
5581 doc: /* Analogous to `mode-line-format', but controls the header line.
5582 The header line appears, optionally, at the top of a window;
5583 the mode line appears at the bottom. */);
5585 DEFVAR_PER_BUFFER ("mode-line-format", &BVAR (current_buffer, mode_line_format),
5586 Qnil,
5587 doc: /* Template for displaying mode line for current buffer.
5589 The value may be nil, a string, a symbol or a list.
5591 A value of nil means don't display a mode line.
5593 For any symbol other than t or nil, the symbol's value is processed as
5594 a mode line construct. As a special exception, if that value is a
5595 string, the string is processed verbatim, without handling any
5596 %-constructs (see below). Also, unless the symbol has a non-nil
5597 `risky-local-variable' property, all properties in any strings, as
5598 well as all :eval and :propertize forms in the value, are ignored.
5600 A list whose car is a string or list is processed by processing each
5601 of the list elements recursively, as separate mode line constructs,
5602 and concatenating the results.
5604 A list of the form `(:eval FORM)' is processed by evaluating FORM and
5605 using the result as a mode line construct. Be careful--FORM should
5606 not load any files, because that can cause an infinite recursion.
5608 A list of the form `(:propertize ELT PROPS...)' is processed by
5609 processing ELT as the mode line construct, and adding the text
5610 properties PROPS to the result.
5612 A list whose car is a symbol is processed by examining the symbol's
5613 value, and, if that value is non-nil, processing the cadr of the list
5614 recursively; and if that value is nil, processing the caddr of the
5615 list recursively.
5617 A list whose car is an integer is processed by processing the cadr of
5618 the list, and padding (if the number is positive) or truncating (if
5619 negative) to the width specified by that number.
5621 A string is printed verbatim in the mode line except for %-constructs:
5622 %b -- print buffer name. %f -- print visited file name.
5623 %F -- print frame name.
5624 %* -- print %, * or hyphen. %+ -- print *, % or hyphen.
5625 %& is like %*, but ignore read-only-ness.
5626 % means buffer is read-only and * means it is modified.
5627 For a modified read-only buffer, %* gives % and %+ gives *.
5628 %s -- print process status. %l -- print the current line number.
5629 %c -- print the current column number (this makes editing slower).
5630 To make the column number update correctly in all cases,
5631 `column-number-mode' must be non-nil.
5632 %i -- print the size of the buffer.
5633 %I -- like %i, but use k, M, G, etc., to abbreviate.
5634 %p -- print percent of buffer above top of window, or Top, Bot or All.
5635 %P -- print percent of buffer above bottom of window, perhaps plus Top,
5636 or print Bottom or All.
5637 %n -- print Narrow if appropriate.
5638 %t -- visited file is text or binary (if OS supports this distinction).
5639 %z -- print mnemonics of keyboard, terminal, and buffer coding systems.
5640 %Z -- like %z, but including the end-of-line format.
5641 %e -- print error message about full memory.
5642 %@ -- print @ or hyphen. @ means that default-directory is on a
5643 remote machine.
5644 %[ -- print one [ for each recursive editing level. %] similar.
5645 %% -- print %. %- -- print infinitely many dashes.
5646 Decimal digits after the % specify field width to which to pad. */);
5648 DEFVAR_BUFFER_DEFAULTS ("default-major-mode", major_mode,
5649 doc: /* Value of `major-mode' for new buffers. */);
5651 DEFVAR_PER_BUFFER ("major-mode", &BVAR (current_buffer, major_mode),
5652 Qsymbolp,
5653 doc: /* Symbol for current buffer's major mode.
5654 The default value (normally `fundamental-mode') affects new buffers.
5655 A value of nil means to use the current buffer's major mode, provided
5656 it is not marked as "special".
5658 When a mode is used by default, `find-file' switches to it before it
5659 reads the contents into the buffer and before it finishes setting up
5660 the buffer. Thus, the mode and its hooks should not expect certain
5661 variables such as `buffer-read-only' and `buffer-file-coding-system'
5662 to be set up. */);
5664 DEFVAR_PER_BUFFER ("mode-name", &BVAR (current_buffer, mode_name),
5665 Qnil,
5666 doc: /* Pretty name of current buffer's major mode.
5667 Usually a string, but can use any of the constructs for `mode-line-format',
5668 which see.
5669 Format with `format-mode-line' to produce a string value. */);
5671 DEFVAR_PER_BUFFER ("local-abbrev-table", &BVAR (current_buffer, abbrev_table), Qnil,
5672 doc: /* Local (mode-specific) abbrev table of current buffer. */);
5674 DEFVAR_PER_BUFFER ("abbrev-mode", &BVAR (current_buffer, abbrev_mode), Qnil,
5675 doc: /* Non-nil if Abbrev mode is enabled.
5676 Use the command `abbrev-mode' to change this variable. */);
5678 DEFVAR_PER_BUFFER ("case-fold-search", &BVAR (current_buffer, case_fold_search),
5679 Qnil,
5680 doc: /* Non-nil if searches and matches should ignore case. */);
5682 DEFVAR_PER_BUFFER ("fill-column", &BVAR (current_buffer, fill_column),
5683 Qintegerp,
5684 doc: /* Column beyond which automatic line-wrapping should happen.
5685 Interactively, you can set the buffer local value using \\[set-fill-column]. */);
5687 DEFVAR_PER_BUFFER ("left-margin", &BVAR (current_buffer, left_margin),
5688 Qintegerp,
5689 doc: /* Column for the default `indent-line-function' to indent to.
5690 Linefeed indents to this column in Fundamental mode. */);
5692 DEFVAR_PER_BUFFER ("tab-width", &BVAR (current_buffer, tab_width),
5693 Qintegerp,
5694 doc: /* Distance between tab stops (for display of tab characters), in columns.
5695 NOTE: This controls the display width of a TAB character, and not
5696 the size of an indentation step.
5697 This should be an integer greater than zero. */);
5699 DEFVAR_PER_BUFFER ("ctl-arrow", &BVAR (current_buffer, ctl_arrow), Qnil,
5700 doc: /* Non-nil means display control chars with uparrow.
5701 A value of nil means use backslash and octal digits.
5702 This variable does not apply to characters whose display is specified
5703 in the current display table (if there is one). */);
5705 DEFVAR_PER_BUFFER ("enable-multibyte-characters",
5706 &BVAR (current_buffer, enable_multibyte_characters),
5707 Qnil,
5708 doc: /* Non-nil means the buffer contents are regarded as multi-byte characters.
5709 Otherwise they are regarded as unibyte. This affects the display,
5710 file I/O and the behavior of various editing commands.
5712 This variable is buffer-local but you cannot set it directly;
5713 use the function `set-buffer-multibyte' to change a buffer's representation.
5714 See also Info node `(elisp)Text Representations'. */);
5715 XSYMBOL (intern_c_string ("enable-multibyte-characters"))->constant = 1;
5717 DEFVAR_PER_BUFFER ("buffer-file-coding-system",
5718 &BVAR (current_buffer, buffer_file_coding_system), Qnil,
5719 doc: /* Coding system to be used for encoding the buffer contents on saving.
5720 This variable applies to saving the buffer, and also to `write-region'
5721 and other functions that use `write-region'.
5722 It does not apply to sending output to subprocesses, however.
5724 If this is nil, the buffer is saved without any code conversion
5725 unless some coding system is specified in `file-coding-system-alist'
5726 for the buffer file.
5728 If the text to be saved cannot be encoded as specified by this variable,
5729 an alternative encoding is selected by `select-safe-coding-system', which see.
5731 The variable `coding-system-for-write', if non-nil, overrides this variable.
5733 This variable is never applied to a way of decoding a file while reading it. */);
5735 DEFVAR_PER_BUFFER ("bidi-display-reordering",
5736 &BVAR (current_buffer, bidi_display_reordering), Qnil,
5737 doc: /* Non-nil means reorder bidirectional text for display in the visual order. */);
5739 DEFVAR_PER_BUFFER ("bidi-paragraph-direction",
5740 &BVAR (current_buffer, bidi_paragraph_direction), Qnil,
5741 doc: /* If non-nil, forces directionality of text paragraphs in the buffer.
5743 If this is nil (the default), the direction of each paragraph is
5744 determined by the first strong directional character of its text.
5745 The values of `right-to-left' and `left-to-right' override that.
5746 Any other value is treated as nil.
5748 This variable has no effect unless the buffer's value of
5749 \`bidi-display-reordering' is non-nil. */);
5751 DEFVAR_PER_BUFFER ("truncate-lines", &BVAR (current_buffer, truncate_lines), Qnil,
5752 doc: /* Non-nil means do not display continuation lines.
5753 Instead, give each line of text just one screen line.
5755 Note that this is overridden by the variable
5756 `truncate-partial-width-windows' if that variable is non-nil
5757 and this buffer is not full-frame width.
5759 Minibuffers set this variable to nil. */);
5761 DEFVAR_PER_BUFFER ("word-wrap", &BVAR (current_buffer, word_wrap), Qnil,
5762 doc: /* Non-nil means to use word-wrapping for continuation lines.
5763 When word-wrapping is on, continuation lines are wrapped at the space
5764 or tab character nearest to the right window edge.
5765 If nil, continuation lines are wrapped at the right screen edge.
5767 This variable has no effect if long lines are truncated (see
5768 `truncate-lines' and `truncate-partial-width-windows'). If you use
5769 word-wrapping, you might want to reduce the value of
5770 `truncate-partial-width-windows', since wrapping can make text readable
5771 in narrower windows.
5773 Instead of setting this variable directly, most users should use
5774 Visual Line mode . Visual Line mode, when enabled, sets `word-wrap'
5775 to t, and additionally redefines simple editing commands to act on
5776 visual lines rather than logical lines. See the documentation of
5777 `visual-line-mode'. */);
5779 DEFVAR_PER_BUFFER ("default-directory", &BVAR (current_buffer, directory),
5780 Qstringp,
5781 doc: /* Name of default directory of current buffer. Should end with slash.
5782 To interactively change the default directory, use command `cd'. */);
5784 DEFVAR_PER_BUFFER ("auto-fill-function", &BVAR (current_buffer, auto_fill_function),
5785 Qnil,
5786 doc: /* Function called (if non-nil) to perform auto-fill.
5787 It is called after self-inserting any character specified in
5788 the `auto-fill-chars' table.
5789 NOTE: This variable is not a hook;
5790 its value may not be a list of functions. */);
5792 DEFVAR_PER_BUFFER ("buffer-file-name", &BVAR (current_buffer, filename),
5793 Qstringp,
5794 doc: /* Name of file visited in current buffer, or nil if not visiting a file.
5795 This should be an absolute file name. */);
5797 DEFVAR_PER_BUFFER ("buffer-file-truename", &BVAR (current_buffer, file_truename),
5798 Qstringp,
5799 doc: /* Abbreviated truename of file visited in current buffer, or nil if none.
5800 The truename of a file is calculated by `file-truename'
5801 and then abbreviated with `abbreviate-file-name'. */);
5803 DEFVAR_PER_BUFFER ("buffer-auto-save-file-name",
5804 &BVAR (current_buffer, auto_save_file_name),
5805 Qstringp,
5806 doc: /* Name of file for auto-saving current buffer.
5807 If it is nil, that means don't auto-save this buffer. */);
5809 DEFVAR_PER_BUFFER ("buffer-read-only", &BVAR (current_buffer, read_only), Qnil,
5810 doc: /* Non-nil if this buffer is read-only. */);
5812 DEFVAR_PER_BUFFER ("buffer-backed-up", &BVAR (current_buffer, backed_up), Qnil,
5813 doc: /* Non-nil if this buffer's file has been backed up.
5814 Backing up is done before the first time the file is saved. */);
5816 DEFVAR_PER_BUFFER ("buffer-saved-size", &BVAR (current_buffer, save_length),
5817 Qintegerp,
5818 doc: /* Length of current buffer when last read in, saved or auto-saved.
5819 0 initially.
5820 -1 means auto-saving turned off until next real save.
5822 If you set this to -2, that means don't turn off auto-saving in this buffer
5823 if its text size shrinks. If you use `buffer-swap-text' on a buffer,
5824 you probably should set this to -2 in that buffer. */);
5826 DEFVAR_PER_BUFFER ("selective-display", &BVAR (current_buffer, selective_display),
5827 Qnil,
5828 doc: /* Non-nil enables selective display.
5829 An integer N as value means display only lines
5830 that start with less than N columns of space.
5831 A value of t means that the character ^M makes itself and
5832 all the rest of the line invisible; also, when saving the buffer
5833 in a file, save the ^M as a newline. */);
5835 DEFVAR_PER_BUFFER ("selective-display-ellipses",
5836 &BVAR (current_buffer, selective_display_ellipses),
5837 Qnil,
5838 doc: /* Non-nil means display ... on previous line when a line is invisible. */);
5840 DEFVAR_PER_BUFFER ("overwrite-mode", &BVAR (current_buffer, overwrite_mode), Qnil,
5841 doc: /* Non-nil if self-insertion should replace existing text.
5842 The value should be one of `overwrite-mode-textual',
5843 `overwrite-mode-binary', or nil.
5844 If it is `overwrite-mode-textual', self-insertion still
5845 inserts at the end of a line, and inserts when point is before a tab,
5846 until the tab is filled in.
5847 If `overwrite-mode-binary', self-insertion replaces newlines and tabs too. */);
5849 DEFVAR_PER_BUFFER ("buffer-display-table", &BVAR (current_buffer, display_table),
5850 Qnil,
5851 doc: /* Display table that controls display of the contents of current buffer.
5853 If this variable is nil, the value of `standard-display-table' is used.
5854 Each window can have its own, overriding display table, see
5855 `set-window-display-table' and `window-display-table'.
5857 The display table is a char-table created with `make-display-table'.
5858 A char-table is an array indexed by character codes. Normal array
5859 primitives `aref' and `aset' can be used to access elements of a char-table.
5861 Each of the char-table elements control how to display the corresponding
5862 text character: the element at index C in the table says how to display
5863 the character whose code is C. Each element should be a vector of
5864 characters or nil. The value nil means display the character in the
5865 default fashion; otherwise, the characters from the vector are delivered
5866 to the screen instead of the original character.
5868 For example, (aset buffer-display-table ?X [?Y]) tells Emacs
5869 to display a capital Y instead of each X character.
5871 In addition, a char-table has six extra slots to control the display of:
5873 the end of a truncated screen line (extra-slot 0, a single character);
5874 the end of a continued line (extra-slot 1, a single character);
5875 the escape character used to display character codes in octal
5876 (extra-slot 2, a single character);
5877 the character used as an arrow for control characters (extra-slot 3,
5878 a single character);
5879 the decoration indicating the presence of invisible lines (extra-slot 4,
5880 a vector of characters);
5881 the character used to draw the border between side-by-side windows
5882 (extra-slot 5, a single character).
5884 See also the functions `display-table-slot' and `set-display-table-slot'. */);
5886 DEFVAR_PER_BUFFER ("left-margin-width", &BVAR (current_buffer, left_margin_cols),
5887 Qintegerp,
5888 doc: /* Width in columns of left marginal area for display of a buffer.
5889 A value of nil means no marginal area.
5891 Setting this variable does not take effect until a new buffer is displayed
5892 in a window. To make the change take effect, call `set-window-buffer'. */);
5894 DEFVAR_PER_BUFFER ("right-margin-width", &BVAR (current_buffer, right_margin_cols),
5895 Qintegerp,
5896 doc: /* Width in columns of right marginal area for display of a buffer.
5897 A value of nil means no marginal area.
5899 Setting this variable does not take effect until a new buffer is displayed
5900 in a window. To make the change take effect, call `set-window-buffer'. */);
5902 DEFVAR_PER_BUFFER ("left-fringe-width", &BVAR (current_buffer, left_fringe_width),
5903 Qintegerp,
5904 doc: /* Width of this buffer's left fringe (in pixels).
5905 A value of 0 means no left fringe is shown in this buffer's window.
5906 A value of nil means to use the left fringe width from the window's frame.
5908 Setting this variable does not take effect until a new buffer is displayed
5909 in a window. To make the change take effect, call `set-window-buffer'. */);
5911 DEFVAR_PER_BUFFER ("right-fringe-width", &BVAR (current_buffer, right_fringe_width),
5912 Qintegerp,
5913 doc: /* Width of this buffer's right fringe (in pixels).
5914 A value of 0 means no right fringe is shown in this buffer's window.
5915 A value of nil means to use the right fringe width from the window's frame.
5917 Setting this variable does not take effect until a new buffer is displayed
5918 in a window. To make the change take effect, call `set-window-buffer'. */);
5920 DEFVAR_PER_BUFFER ("fringes-outside-margins", &BVAR (current_buffer, fringes_outside_margins),
5921 Qnil,
5922 doc: /* Non-nil means to display fringes outside display margins.
5923 A value of nil means to display fringes between margins and buffer text.
5925 Setting this variable does not take effect until a new buffer is displayed
5926 in a window. To make the change take effect, call `set-window-buffer'. */);
5928 DEFVAR_PER_BUFFER ("scroll-bar-width", &BVAR (current_buffer, scroll_bar_width),
5929 Qintegerp,
5930 doc: /* Width of this buffer's scroll bars in pixels.
5931 A value of nil means to use the scroll bar width from the window's frame. */);
5933 DEFVAR_PER_BUFFER ("vertical-scroll-bar", &BVAR (current_buffer, vertical_scroll_bar_type),
5934 Qnil,
5935 doc: /* Position of this buffer's vertical scroll bar.
5936 The value takes effect whenever you tell a window to display this buffer;
5937 for instance, with `set-window-buffer' or when `display-buffer' displays it.
5939 A value of `left' or `right' means put the vertical scroll bar at that side
5940 of the window; a value of nil means don't show any vertical scroll bars.
5941 A value of t (the default) means do whatever the window's frame specifies. */);
5943 DEFVAR_PER_BUFFER ("indicate-empty-lines",
5944 &BVAR (current_buffer, indicate_empty_lines), Qnil,
5945 doc: /* Visually indicate empty lines after the buffer end.
5946 If non-nil, a bitmap is displayed in the left fringe of a window on
5947 window-systems. */);
5949 DEFVAR_PER_BUFFER ("indicate-buffer-boundaries",
5950 &BVAR (current_buffer, indicate_buffer_boundaries), Qnil,
5951 doc: /* Visually indicate buffer boundaries and scrolling.
5952 If non-nil, the first and last line of the buffer are marked in the fringe
5953 of a window on window-systems with angle bitmaps, or if the window can be
5954 scrolled, the top and bottom line of the window are marked with up and down
5955 arrow bitmaps.
5957 If value is a symbol `left' or `right', both angle and arrow bitmaps
5958 are displayed in the left or right fringe, resp. Any other value
5959 that doesn't look like an alist means display the angle bitmaps in
5960 the left fringe but no arrows.
5962 You can exercise more precise control by using an alist as the
5963 value. Each alist element (INDICATOR . POSITION) specifies
5964 where to show one of the indicators. INDICATOR is one of `top',
5965 `bottom', `up', `down', or t, which specifies the default position,
5966 and POSITION is one of `left', `right', or nil, meaning do not show
5967 this indicator.
5969 For example, ((top . left) (t . right)) places the top angle bitmap in
5970 left fringe, the bottom angle bitmap in right fringe, and both arrow
5971 bitmaps in right fringe. To show just the angle bitmaps in the left
5972 fringe, but no arrow bitmaps, use ((top . left) (bottom . left)). */);
5974 DEFVAR_PER_BUFFER ("fringe-indicator-alist",
5975 &BVAR (current_buffer, fringe_indicator_alist), Qnil,
5976 doc: /* Mapping from logical to physical fringe indicator bitmaps.
5977 The value is an alist where each element (INDICATOR . BITMAPS)
5978 specifies the fringe bitmaps used to display a specific logical
5979 fringe indicator.
5981 INDICATOR specifies the logical indicator type which is one of the
5982 following symbols: `truncation' , `continuation', `overlay-arrow',
5983 `top', `bottom', `top-bottom', `up', `down', empty-line', or `unknown'.
5985 BITMAPS is a list of symbols (LEFT RIGHT [LEFT1 RIGHT1]) which specifies
5986 the actual bitmap shown in the left or right fringe for the logical
5987 indicator. LEFT and RIGHT are the bitmaps shown in the left and/or
5988 right fringe for the specific indicator. The LEFT1 or RIGHT1 bitmaps
5989 are used only for the `bottom' and `top-bottom' indicators when the
5990 last (only) line has no final newline. BITMAPS may also be a single
5991 symbol which is used in both left and right fringes. */);
5993 DEFVAR_PER_BUFFER ("fringe-cursor-alist",
5994 &BVAR (current_buffer, fringe_cursor_alist), Qnil,
5995 doc: /* Mapping from logical to physical fringe cursor bitmaps.
5996 The value is an alist where each element (CURSOR . BITMAP)
5997 specifies the fringe bitmaps used to display a specific logical
5998 cursor type in the fringe.
6000 CURSOR specifies the logical cursor type which is one of the following
6001 symbols: `box' , `hollow', `bar', `hbar', or `hollow-small'. The last
6002 one is used to show a hollow cursor on narrow lines display lines
6003 where the normal hollow cursor will not fit.
6005 BITMAP is the corresponding fringe bitmap shown for the logical
6006 cursor type. */);
6008 DEFVAR_PER_BUFFER ("scroll-up-aggressively",
6009 &BVAR (current_buffer, scroll_up_aggressively), Qfloatp,
6010 doc: /* How far to scroll windows upward.
6011 If you move point off the bottom, the window scrolls automatically.
6012 This variable controls how far it scrolls. The value nil, the default,
6013 means scroll to center point. A fraction means scroll to put point
6014 that fraction of the window's height from the bottom of the window.
6015 When the value is 0.0, point goes at the bottom line, which in the
6016 simple case that you moved off with C-f means scrolling just one line.
6017 1.0 means point goes at the top, so that in that simple case, the
6018 window scrolls by a full window height. Meaningful values are
6019 between 0.0 and 1.0, inclusive. */);
6021 DEFVAR_PER_BUFFER ("scroll-down-aggressively",
6022 &BVAR (current_buffer, scroll_down_aggressively), Qfloatp,
6023 doc: /* How far to scroll windows downward.
6024 If you move point off the top, the window scrolls automatically.
6025 This variable controls how far it scrolls. The value nil, the default,
6026 means scroll to center point. A fraction means scroll to put point
6027 that fraction of the window's height from the top of the window.
6028 When the value is 0.0, point goes at the top line, which in the
6029 simple case that you moved off with C-b means scrolling just one line.
6030 1.0 means point goes at the bottom, so that in that simple case, the
6031 window scrolls by a full window height. Meaningful values are
6032 between 0.0 and 1.0, inclusive. */);
6034 DEFVAR_LISP ("before-change-functions", Vbefore_change_functions,
6035 doc: /* List of functions to call before each text change.
6036 Two arguments are passed to each function: the positions of
6037 the beginning and end of the range of old text to be changed.
6038 \(For an insertion, the beginning and end are at the same place.)
6039 No information is given about the length of the text after the change.
6041 Buffer changes made while executing the `before-change-functions'
6042 don't call any before-change or after-change functions.
6043 That's because `inhibit-modification-hooks' is temporarily set non-nil.
6045 If an unhandled error happens in running these functions,
6046 the variable's value remains nil. That prevents the error
6047 from happening repeatedly and making Emacs nonfunctional. */);
6048 Vbefore_change_functions = Qnil;
6050 DEFVAR_LISP ("after-change-functions", Vafter_change_functions,
6051 doc: /* List of functions to call after each text change.
6052 Three arguments are passed to each function: the positions of
6053 the beginning and end of the range of changed text,
6054 and the length in bytes of the pre-change text replaced by that range.
6055 \(For an insertion, the pre-change length is zero;
6056 for a deletion, that length is the number of bytes deleted,
6057 and the post-change beginning and end are at the same place.)
6059 Buffer changes made while executing the `after-change-functions'
6060 don't call any before-change or after-change functions.
6061 That's because `inhibit-modification-hooks' is temporarily set non-nil.
6063 If an unhandled error happens in running these functions,
6064 the variable's value remains nil. That prevents the error
6065 from happening repeatedly and making Emacs nonfunctional. */);
6066 Vafter_change_functions = Qnil;
6068 DEFVAR_LISP ("first-change-hook", Vfirst_change_hook,
6069 doc: /* A list of functions to call before changing a buffer which is unmodified.
6070 The functions are run using the `run-hooks' function. */);
6071 Vfirst_change_hook = Qnil;
6073 DEFVAR_PER_BUFFER ("buffer-undo-list", &BVAR (current_buffer, undo_list), Qnil,
6074 doc: /* List of undo entries in current buffer.
6075 Recent changes come first; older changes follow newer.
6077 An entry (BEG . END) represents an insertion which begins at
6078 position BEG and ends at position END.
6080 An entry (TEXT . POSITION) represents the deletion of the string TEXT
6081 from (abs POSITION). If POSITION is positive, point was at the front
6082 of the text being deleted; if negative, point was at the end.
6084 An entry (t HIGH LOW USEC PSEC) indicates that the buffer was previously
6085 unmodified; (HIGH LOW USEC PSEC) is in the same style as (current-time)
6086 and is the visited file's modification time, as of that time. If the
6087 modification time of the most recent save is different, this entry is
6088 obsolete.
6090 An entry (t . 0) means means the buffer was previously unmodified but
6091 its time stamp was unknown because it was not associated with a file.
6092 An entry (t . -1) is similar, except that it means the buffer's visited
6093 file did not exist.
6095 An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
6096 was modified between BEG and END. PROPERTY is the property name,
6097 and VALUE is the old value.
6099 An entry (apply FUN-NAME . ARGS) means undo the change with
6100 \(apply FUN-NAME ARGS).
6102 An entry (apply DELTA BEG END FUN-NAME . ARGS) supports selective undo
6103 in the active region. BEG and END is the range affected by this entry
6104 and DELTA is the number of characters added or deleted in that range by
6105 this change.
6107 An entry (MARKER . DISTANCE) indicates that the marker MARKER
6108 was adjusted in position by the offset DISTANCE (an integer).
6110 An entry of the form POSITION indicates that point was at the buffer
6111 location given by the integer. Undoing an entry of this form places
6112 point at POSITION.
6114 Entries with value `nil' mark undo boundaries. The undo command treats
6115 the changes between two undo boundaries as a single step to be undone.
6117 If the value of the variable is t, undo information is not recorded. */);
6119 DEFVAR_PER_BUFFER ("mark-active", &BVAR (current_buffer, mark_active), Qnil,
6120 doc: /* Non-nil means the mark and region are currently active in this buffer. */);
6122 DEFVAR_PER_BUFFER ("cache-long-scans", &BVAR (current_buffer, cache_long_scans), Qnil,
6123 doc: /* Non-nil means that Emacs should use caches in attempt to speedup buffer scans.
6125 Normally, the line-motion functions work by scanning the buffer for
6126 newlines. Columnar operations (like `move-to-column' and
6127 `compute-motion') also work by scanning the buffer, summing character
6128 widths as they go. This works well for ordinary text, but if the
6129 buffer's lines are very long (say, more than 500 characters), these
6130 motion functions will take longer to execute. Emacs may also take
6131 longer to update the display.
6133 If `cache-long-scans' is non-nil, these motion functions cache the
6134 results of their scans, and consult the cache to avoid rescanning
6135 regions of the buffer until the text is modified. The caches are most
6136 beneficial when they prevent the most searching---that is, when the
6137 buffer contains long lines and large regions of characters with the
6138 same, fixed screen width.
6140 When `cache-long-scans' is non-nil, processing short lines will
6141 become slightly slower (because of the overhead of consulting the
6142 cache), and the caches will use memory roughly proportional to the
6143 number of newlines and characters whose screen width varies.
6145 Bidirectional editing also requires buffer scans to find paragraph
6146 separators. If you have large paragraphs or no paragraph separators
6147 at all, these scans may be slow. If `cache-long-scans' is non-nil,
6148 results of these scans are cached. This doesn't help too much if
6149 paragraphs are of the reasonable (few thousands of characters) size.
6151 The caches require no explicit maintenance; their accuracy is
6152 maintained internally by the Emacs primitives. Enabling or disabling
6153 the cache should not affect the behavior of any of the motion
6154 functions; it should only affect their performance. */);
6156 DEFVAR_PER_BUFFER ("point-before-scroll", &BVAR (current_buffer, point_before_scroll), Qnil,
6157 doc: /* Value of point before the last series of scroll operations, or nil. */);
6159 DEFVAR_PER_BUFFER ("buffer-file-format", &BVAR (current_buffer, file_format), Qnil,
6160 doc: /* List of formats to use when saving this buffer.
6161 Formats are defined by `format-alist'. This variable is
6162 set when a file is visited. */);
6164 DEFVAR_PER_BUFFER ("buffer-auto-save-file-format",
6165 &BVAR (current_buffer, auto_save_file_format), Qnil,
6166 doc: /* Format in which to write auto-save files.
6167 Should be a list of symbols naming formats that are defined in `format-alist'.
6168 If it is t, which is the default, auto-save files are written in the
6169 same format as a regular save would use. */);
6171 DEFVAR_PER_BUFFER ("buffer-invisibility-spec",
6172 &BVAR (current_buffer, invisibility_spec), Qnil,
6173 doc: /* Invisibility spec of this buffer.
6174 The default is t, which means that text is invisible
6175 if it has a non-nil `invisible' property.
6176 If the value is a list, a text character is invisible if its `invisible'
6177 property is an element in that list (or is a list with members in common).
6178 If an element is a cons cell of the form (PROP . ELLIPSIS),
6179 then characters with property value PROP are invisible,
6180 and they have an ellipsis as well if ELLIPSIS is non-nil.
6181 Setting this variable is very fast, much faster than scanning all the
6182 text in the buffer looking for properties to change. */);
6184 DEFVAR_PER_BUFFER ("buffer-display-count",
6185 &BVAR (current_buffer, display_count), Qintegerp,
6186 doc: /* A number incremented each time this buffer is displayed in a window.
6187 The function `set-window-buffer' increments it. */);
6189 DEFVAR_PER_BUFFER ("buffer-display-time",
6190 &BVAR (current_buffer, display_time), Qnil,
6191 doc: /* Time stamp updated each time this buffer is displayed in a window.
6192 The function `set-window-buffer' updates this variable
6193 to the value obtained by calling `current-time'.
6194 If the buffer has never been shown in a window, the value is nil. */);
6196 DEFVAR_LISP ("transient-mark-mode", Vtransient_mark_mode,
6197 doc: /* Non-nil if Transient Mark mode is enabled.
6198 See the command `transient-mark-mode' for a description of this minor mode.
6200 Non-nil also enables highlighting of the region whenever the mark is active.
6201 The variable `highlight-nonselected-windows' controls whether to highlight
6202 all windows or just the selected window.
6204 Lisp programs may give this variable certain special values:
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).
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. */);
6215 Vtransient_mark_mode = Qnil;
6217 DEFVAR_LISP ("inhibit-read-only", Vinhibit_read_only,
6218 doc: /* Non-nil means disregard read-only status of buffers or characters.
6219 If the value is t, disregard `buffer-read-only' and all `read-only'
6220 text properties. If the value is a list, disregard `buffer-read-only'
6221 and disregard a `read-only' text property if the property value
6222 is a member of the list. */);
6223 Vinhibit_read_only = Qnil;
6225 DEFVAR_PER_BUFFER ("cursor-type", &BVAR (current_buffer, cursor_type), Qnil,
6226 doc: /* Cursor to use when this buffer is in the selected window.
6227 Values are interpreted as follows:
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
6236 (hbar . HEIGHT) display a horizontal bar cursor with height HEIGHT
6237 ANYTHING ELSE display a hollow box cursor
6239 When the buffer is displayed in a non-selected window, the
6240 cursor's appearance is instead controlled by the variable
6241 `cursor-in-non-selected-windows'. */);
6243 DEFVAR_PER_BUFFER ("line-spacing",
6244 &BVAR (current_buffer, extra_line_spacing), Qnumberp,
6245 doc: /* Additional space to put between lines when displaying a buffer.
6246 The space is measured in pixels, and put below lines on graphic displays,
6247 see `display-graphic-p'.
6248 If value is a floating point number, it specifies the spacing relative
6249 to the default frame line height. A value of nil means add no extra space. */);
6251 DEFVAR_PER_BUFFER ("cursor-in-non-selected-windows",
6252 &BVAR (current_buffer, cursor_in_non_selected_windows), Qnil,
6253 doc: /* Non-nil means show a cursor in non-selected windows.
6254 If nil, only shows a cursor in the selected window.
6255 If t, displays a cursor related to the usual cursor type
6256 \(a solid box becomes hollow, a bar becomes a narrower bar).
6257 You can also specify the cursor type as in the `cursor-type' variable.
6258 Use Custom to set this variable and update the display." */);
6260 DEFVAR_LISP ("kill-buffer-query-functions", Vkill_buffer_query_functions,
6261 doc: /* List of functions called with no args to query before killing a buffer.
6262 The buffer being killed will be current while the functions are running.
6264 If any of them returns nil, the buffer is not killed. Functions run by
6265 this hook are supposed to not change the current buffer. */);
6266 Vkill_buffer_query_functions = Qnil;
6268 DEFVAR_LISP ("change-major-mode-hook", Vchange_major_mode_hook,
6269 doc: /* Normal hook run before changing the major mode of a buffer.
6270 The function `kill-all-local-variables' runs this before doing anything else. */);
6271 Vchange_major_mode_hook = Qnil;
6272 DEFSYM (Qchange_major_mode_hook, "change-major-mode-hook");
6274 DEFVAR_LISP ("buffer-list-update-hook", Vbuffer_list_update_hook,
6275 doc: /* Hook run when the buffer list changes.
6276 Functions running this hook are `get-buffer-create',
6277 `make-indirect-buffer', `rename-buffer', `kill-buffer',
6278 and `bury-buffer-internal'. */);
6279 Vbuffer_list_update_hook = Qnil;
6280 DEFSYM (Qbuffer_list_update_hook, "buffer-list-update-hook");
6282 defsubr (&Sbuffer_live_p);
6283 defsubr (&Sbuffer_list);
6284 defsubr (&Sget_buffer);
6285 defsubr (&Sget_file_buffer);
6286 defsubr (&Sget_buffer_create);
6287 defsubr (&Smake_indirect_buffer);
6288 defsubr (&Sgenerate_new_buffer_name);
6289 defsubr (&Sbuffer_name);
6290 defsubr (&Sbuffer_file_name);
6291 defsubr (&Sbuffer_base_buffer);
6292 defsubr (&Sbuffer_local_value);
6293 defsubr (&Sbuffer_local_variables);
6294 defsubr (&Sbuffer_modified_p);
6295 defsubr (&Sforce_mode_line_update);
6296 defsubr (&Sset_buffer_modified_p);
6297 defsubr (&Sbuffer_modified_tick);
6298 defsubr (&Sbuffer_chars_modified_tick);
6299 defsubr (&Srename_buffer);
6300 defsubr (&Sother_buffer);
6301 defsubr (&Sbuffer_enable_undo);
6302 defsubr (&Skill_buffer);
6303 defsubr (&Sbury_buffer_internal);
6304 defsubr (&Sset_buffer_major_mode);
6305 defsubr (&Scurrent_buffer);
6306 defsubr (&Sset_buffer);
6307 defsubr (&Sbarf_if_buffer_read_only);
6308 defsubr (&Serase_buffer);
6309 defsubr (&Sbuffer_swap_text);
6310 defsubr (&Sset_buffer_multibyte);
6311 defsubr (&Skill_all_local_variables);
6313 defsubr (&Soverlayp);
6314 defsubr (&Smake_overlay);
6315 defsubr (&Sdelete_overlay);
6316 defsubr (&Sdelete_all_overlays);
6317 defsubr (&Smove_overlay);
6318 defsubr (&Soverlay_start);
6319 defsubr (&Soverlay_end);
6320 defsubr (&Soverlay_buffer);
6321 defsubr (&Soverlay_properties);
6322 defsubr (&Soverlays_at);
6323 defsubr (&Soverlays_in);
6324 defsubr (&Snext_overlay_change);
6325 defsubr (&Sprevious_overlay_change);
6326 defsubr (&Soverlay_recenter);
6327 defsubr (&Soverlay_lists);
6328 defsubr (&Soverlay_get);
6329 defsubr (&Soverlay_put);
6330 defsubr (&Srestore_buffer_modified_p);
6333 void
6334 keys_of_buffer (void)
6336 initial_define_key (control_x_map, 'b', "switch-to-buffer");
6337 initial_define_key (control_x_map, 'k', "kill-buffer");
6339 /* This must not be in syms_of_buffer, because Qdisabled is not
6340 initialized when that function gets called. */
6341 Fput (intern_c_string ("erase-buffer"), Qdisabled, Qt);