* minibuf.texi (Basic Completion): Clarify list form of completion table.
[emacs.git] / src / buffer.c
blob425d05ca790cd181096695ed0a1fa125a71d0e15
1 /* Buffer manipulation primitives for GNU Emacs.
3 Copyright (C) 1985-1989, 1993-1995, 1997-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #define BUFFER_INLINE EXTERN_INLINE
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/param.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <unistd.h>
31 #include <verify.h>
33 #include "lisp.h"
34 #include "intervals.h"
35 #include "window.h"
36 #include "commands.h"
37 #include "character.h"
38 #include "buffer.h"
39 #include "region-cache.h"
40 #include "indent.h"
41 #include "blockinput.h"
42 #include "keyboard.h"
43 #include "keymap.h"
44 #include "frame.h"
46 struct buffer *current_buffer; /* The current buffer. */
48 /* First buffer in chain of all buffers (in reverse order of creation).
49 Threaded through ->header.next.buffer. */
51 struct buffer *all_buffers;
53 /* This structure holds the default values of the buffer-local variables
54 defined with DEFVAR_PER_BUFFER, that have special slots in each buffer.
55 The default value occupies the same slot in this structure
56 as an individual buffer's value occupies in that buffer.
57 Setting the default value also goes through the alist of buffers
58 and stores into each buffer that does not say it has a local value. */
60 struct buffer alignas (GCALIGNMENT) buffer_defaults;
62 /* This structure marks which slots in a buffer have corresponding
63 default values in buffer_defaults.
64 Each such slot has a nonzero value in this structure.
65 The value has only one nonzero bit.
67 When a buffer has its own local value for a slot,
68 the entry for that slot (found in the same slot in this structure)
69 is turned on in the buffer's local_flags array.
71 If a slot in this structure is -1, then even though there may
72 be a DEFVAR_PER_BUFFER for the slot, there is no default value for it;
73 and the corresponding slot in buffer_defaults is not used.
75 If a slot in this structure corresponding to a DEFVAR_PER_BUFFER is
76 zero, that is a bug. */
78 struct buffer buffer_local_flags;
80 /* This structure holds the names of symbols whose values may be
81 buffer-local. It is indexed and accessed in the same way as the above. */
83 struct buffer alignas (GCALIGNMENT) buffer_local_symbols;
85 /* Return the symbol of the per-buffer variable at offset OFFSET in
86 the buffer structure. */
88 #define PER_BUFFER_SYMBOL(OFFSET) \
89 (*(Lisp_Object *)((OFFSET) + (char *) &buffer_local_symbols))
91 /* Maximum length of an overlay vector. */
92 #define OVERLAY_COUNT_MAX \
93 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, \
94 min (PTRDIFF_MAX, SIZE_MAX) / word_size))
96 /* Flags indicating which built-in buffer-local variables
97 are permanent locals. */
98 static char buffer_permanent_local_flags[MAX_PER_BUFFER_VARS];
100 /* Number of per-buffer variables used. */
102 int last_per_buffer_idx;
104 static void call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay,
105 bool after, Lisp_Object arg1,
106 Lisp_Object arg2, Lisp_Object arg3);
107 static void swap_out_buffer_local_variables (struct buffer *b);
108 static void reset_buffer_local_variables (struct buffer *, bool);
110 /* Alist of all buffer names vs the buffers. */
111 /* This used to be a variable, but is no longer,
112 to prevent lossage due to user rplac'ing this alist or its elements. */
113 Lisp_Object Vbuffer_alist;
115 static Lisp_Object Qkill_buffer_query_functions;
117 /* Hook run before changing a major mode. */
118 static Lisp_Object Qchange_major_mode_hook;
120 Lisp_Object Qfirst_change_hook;
121 Lisp_Object Qbefore_change_functions;
122 Lisp_Object Qafter_change_functions;
124 static Lisp_Object Qfundamental_mode, Qmode_class, Qpermanent_local;
125 static Lisp_Object Qpermanent_local_hook;
127 static Lisp_Object Qprotected_field;
129 static Lisp_Object QSFundamental; /* A string "Fundamental". */
131 static Lisp_Object Qkill_buffer_hook;
132 static Lisp_Object Qbuffer_list_update_hook;
134 static Lisp_Object Qget_file_buffer;
136 static Lisp_Object Qoverlayp;
138 Lisp_Object Qpriority, Qbefore_string, Qafter_string;
140 static Lisp_Object Qevaporate;
142 Lisp_Object Qmodification_hooks;
143 Lisp_Object Qinsert_in_front_hooks;
144 Lisp_Object Qinsert_behind_hooks;
146 static void alloc_buffer_text (struct buffer *, ptrdiff_t);
147 static void free_buffer_text (struct buffer *b);
148 static struct Lisp_Overlay * copy_overlays (struct buffer *, struct Lisp_Overlay *);
149 static void modify_overlay (struct buffer *, ptrdiff_t, ptrdiff_t);
150 static Lisp_Object buffer_lisp_local_variables (struct buffer *, bool);
152 /* These setters are used only in this file, so they can be private. */
153 static void
154 bset_abbrev_mode (struct buffer *b, Lisp_Object val)
156 b->INTERNAL_FIELD (abbrev_mode) = val;
158 static void
159 bset_abbrev_table (struct buffer *b, Lisp_Object val)
161 b->INTERNAL_FIELD (abbrev_table) = val;
163 static void
164 bset_auto_fill_function (struct buffer *b, Lisp_Object val)
166 b->INTERNAL_FIELD (auto_fill_function) = val;
168 static void
169 bset_auto_save_file_format (struct buffer *b, Lisp_Object val)
171 b->INTERNAL_FIELD (auto_save_file_format) = val;
173 static void
174 bset_auto_save_file_name (struct buffer *b, Lisp_Object val)
176 b->INTERNAL_FIELD (auto_save_file_name) = val;
178 static void
179 bset_backed_up (struct buffer *b, Lisp_Object val)
181 b->INTERNAL_FIELD (backed_up) = val;
183 static void
184 bset_begv_marker (struct buffer *b, Lisp_Object val)
186 b->INTERNAL_FIELD (begv_marker) = val;
188 static void
189 bset_bidi_display_reordering (struct buffer *b, Lisp_Object val)
191 b->INTERNAL_FIELD (bidi_display_reordering) = val;
193 static void
194 bset_buffer_file_coding_system (struct buffer *b, Lisp_Object val)
196 b->INTERNAL_FIELD (buffer_file_coding_system) = val;
198 static void
199 bset_cache_long_line_scans (struct buffer *b, Lisp_Object val)
201 b->INTERNAL_FIELD (cache_long_line_scans) = val;
203 static void
204 bset_case_fold_search (struct buffer *b, Lisp_Object val)
206 b->INTERNAL_FIELD (case_fold_search) = val;
208 static void
209 bset_ctl_arrow (struct buffer *b, Lisp_Object val)
211 b->INTERNAL_FIELD (ctl_arrow) = val;
213 static void
214 bset_cursor_in_non_selected_windows (struct buffer *b, Lisp_Object val)
216 b->INTERNAL_FIELD (cursor_in_non_selected_windows) = val;
218 static void
219 bset_cursor_type (struct buffer *b, Lisp_Object val)
221 b->INTERNAL_FIELD (cursor_type) = val;
223 static void
224 bset_display_table (struct buffer *b, Lisp_Object val)
226 b->INTERNAL_FIELD (display_table) = val;
228 static void
229 bset_extra_line_spacing (struct buffer *b, Lisp_Object val)
231 b->INTERNAL_FIELD (extra_line_spacing) = val;
233 static void
234 bset_file_format (struct buffer *b, Lisp_Object val)
236 b->INTERNAL_FIELD (file_format) = val;
238 static void
239 bset_file_truename (struct buffer *b, Lisp_Object val)
241 b->INTERNAL_FIELD (file_truename) = val;
243 static void
244 bset_fringe_cursor_alist (struct buffer *b, Lisp_Object val)
246 b->INTERNAL_FIELD (fringe_cursor_alist) = val;
248 static void
249 bset_fringe_indicator_alist (struct buffer *b, Lisp_Object val)
251 b->INTERNAL_FIELD (fringe_indicator_alist) = val;
253 static void
254 bset_fringes_outside_margins (struct buffer *b, Lisp_Object val)
256 b->INTERNAL_FIELD (fringes_outside_margins) = val;
258 static void
259 bset_header_line_format (struct buffer *b, Lisp_Object val)
261 b->INTERNAL_FIELD (header_line_format) = val;
263 static void
264 bset_indicate_buffer_boundaries (struct buffer *b, Lisp_Object val)
266 b->INTERNAL_FIELD (indicate_buffer_boundaries) = val;
268 static void
269 bset_indicate_empty_lines (struct buffer *b, Lisp_Object val)
271 b->INTERNAL_FIELD (indicate_empty_lines) = val;
273 static void
274 bset_invisibility_spec (struct buffer *b, Lisp_Object val)
276 b->INTERNAL_FIELD (invisibility_spec) = val;
278 static void
279 bset_left_fringe_width (struct buffer *b, Lisp_Object val)
281 b->INTERNAL_FIELD (left_fringe_width) = val;
283 static void
284 bset_major_mode (struct buffer *b, Lisp_Object val)
286 b->INTERNAL_FIELD (major_mode) = val;
288 static void
289 bset_mark (struct buffer *b, Lisp_Object val)
291 b->INTERNAL_FIELD (mark) = val;
293 static void
294 bset_minor_modes (struct buffer *b, Lisp_Object val)
296 b->INTERNAL_FIELD (minor_modes) = val;
298 static void
299 bset_mode_line_format (struct buffer *b, Lisp_Object val)
301 b->INTERNAL_FIELD (mode_line_format) = val;
303 static void
304 bset_mode_name (struct buffer *b, Lisp_Object val)
306 b->INTERNAL_FIELD (mode_name) = val;
308 static void
309 bset_name (struct buffer *b, Lisp_Object val)
311 b->INTERNAL_FIELD (name) = val;
313 static void
314 bset_overwrite_mode (struct buffer *b, Lisp_Object val)
316 b->INTERNAL_FIELD (overwrite_mode) = val;
318 static void
319 bset_pt_marker (struct buffer *b, Lisp_Object val)
321 b->INTERNAL_FIELD (pt_marker) = val;
323 static void
324 bset_right_fringe_width (struct buffer *b, Lisp_Object val)
326 b->INTERNAL_FIELD (right_fringe_width) = val;
328 static void
329 bset_save_length (struct buffer *b, Lisp_Object val)
331 b->INTERNAL_FIELD (save_length) = val;
333 static void
334 bset_scroll_bar_width (struct buffer *b, Lisp_Object val)
336 b->INTERNAL_FIELD (scroll_bar_width) = val;
338 static void
339 bset_scroll_down_aggressively (struct buffer *b, Lisp_Object val)
341 b->INTERNAL_FIELD (scroll_down_aggressively) = val;
343 static void
344 bset_scroll_up_aggressively (struct buffer *b, Lisp_Object val)
346 b->INTERNAL_FIELD (scroll_up_aggressively) = val;
348 static void
349 bset_selective_display (struct buffer *b, Lisp_Object val)
351 b->INTERNAL_FIELD (selective_display) = val;
353 static void
354 bset_selective_display_ellipses (struct buffer *b, Lisp_Object val)
356 b->INTERNAL_FIELD (selective_display_ellipses) = val;
358 static void
359 bset_vertical_scroll_bar_type (struct buffer *b, Lisp_Object val)
361 b->INTERNAL_FIELD (vertical_scroll_bar_type) = val;
363 static void
364 bset_word_wrap (struct buffer *b, Lisp_Object val)
366 b->INTERNAL_FIELD (word_wrap) = val;
368 static void
369 bset_zv_marker (struct buffer *b, Lisp_Object val)
371 b->INTERNAL_FIELD (zv_marker) = val;
374 /* For debugging; temporary. See set_buffer_internal. */
375 /* Lisp_Object Qlisp_mode, Vcheck_symbol; */
377 void
378 nsberror (Lisp_Object spec)
380 if (STRINGP (spec))
381 error ("No buffer named %s", SDATA (spec));
382 error ("Invalid buffer argument");
385 DEFUN ("buffer-live-p", Fbuffer_live_p, Sbuffer_live_p, 1, 1, 0,
386 doc: /* Return non-nil if OBJECT is a buffer which has not been killed.
387 Value is nil if OBJECT is not a buffer or if it has been killed. */)
388 (Lisp_Object object)
390 return ((BUFFERP (object) && BUFFER_LIVE_P (XBUFFER (object)))
391 ? Qt : Qnil);
394 DEFUN ("buffer-list", Fbuffer_list, Sbuffer_list, 0, 1, 0,
395 doc: /* Return a list of all existing live buffers.
396 If the optional arg FRAME is a frame, we return the buffer list in the
397 proper order for that frame: the buffers show in FRAME come first,
398 followed by the rest of the buffers. */)
399 (Lisp_Object frame)
401 Lisp_Object general;
402 general = Fmapcar (Qcdr, Vbuffer_alist);
404 if (FRAMEP (frame))
406 Lisp_Object framelist, prevlist, tail;
407 Lisp_Object args[3];
409 CHECK_FRAME (frame);
410 framelist = Fcopy_sequence (XFRAME (frame)->buffer_list);
411 prevlist = Fnreverse (Fcopy_sequence
412 (XFRAME (frame)->buried_buffer_list));
414 /* Remove from GENERAL any buffer that duplicates one in
415 FRAMELIST or PREVLIST. */
416 tail = framelist;
417 while (CONSP (tail))
419 general = Fdelq (XCAR (tail), general);
420 tail = XCDR (tail);
422 tail = prevlist;
423 while (CONSP (tail))
425 general = Fdelq (XCAR (tail), general);
426 tail = XCDR (tail);
429 args[0] = framelist;
430 args[1] = general;
431 args[2] = prevlist;
432 return Fnconc (3, args);
434 else
435 return general;
438 /* Like Fassoc, but use Fstring_equal to compare
439 (which ignores text properties),
440 and don't ever QUIT. */
442 static Lisp_Object
443 assoc_ignore_text_properties (register Lisp_Object key, Lisp_Object list)
445 register Lisp_Object tail;
446 for (tail = list; CONSP (tail); tail = XCDR (tail))
448 register Lisp_Object elt, tem;
449 elt = XCAR (tail);
450 tem = Fstring_equal (Fcar (elt), key);
451 if (!NILP (tem))
452 return elt;
454 return Qnil;
457 DEFUN ("get-buffer", Fget_buffer, Sget_buffer, 1, 1, 0,
458 doc: /* Return the buffer named BUFFER-OR-NAME.
459 BUFFER-OR-NAME must be either a string or a buffer. If BUFFER-OR-NAME
460 is a string and there is no buffer with that name, return nil. If
461 BUFFER-OR-NAME is a buffer, return it as given. */)
462 (register Lisp_Object buffer_or_name)
464 if (BUFFERP (buffer_or_name))
465 return buffer_or_name;
466 CHECK_STRING (buffer_or_name);
468 return Fcdr (assoc_ignore_text_properties (buffer_or_name, Vbuffer_alist));
471 DEFUN ("get-file-buffer", Fget_file_buffer, Sget_file_buffer, 1, 1, 0,
472 doc: /* Return the buffer visiting file FILENAME (a string).
473 The buffer's `buffer-file-name' must match exactly the expansion of FILENAME.
474 If there is no such live buffer, return nil.
475 See also `find-buffer-visiting'. */)
476 (register Lisp_Object filename)
478 register Lisp_Object tail, buf, tem;
479 Lisp_Object handler;
481 CHECK_STRING (filename);
482 filename = Fexpand_file_name (filename, Qnil);
484 /* If the file name has special constructs in it,
485 call the corresponding file handler. */
486 handler = Ffind_file_name_handler (filename, Qget_file_buffer);
487 if (!NILP (handler))
489 Lisp_Object handled_buf = call2 (handler, Qget_file_buffer,
490 filename);
491 return BUFFERP (handled_buf) ? handled_buf : Qnil;
494 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
496 buf = Fcdr (XCAR (tail));
497 if (!BUFFERP (buf)) continue;
498 if (!STRINGP (BVAR (XBUFFER (buf), filename))) continue;
499 tem = Fstring_equal (BVAR (XBUFFER (buf), filename), filename);
500 if (!NILP (tem))
501 return buf;
503 return Qnil;
506 Lisp_Object
507 get_truename_buffer (register Lisp_Object filename)
509 register Lisp_Object tail, buf, tem;
511 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
513 buf = Fcdr (XCAR (tail));
514 if (!BUFFERP (buf)) continue;
515 if (!STRINGP (BVAR (XBUFFER (buf), file_truename))) continue;
516 tem = Fstring_equal (BVAR (XBUFFER (buf), file_truename), filename);
517 if (!NILP (tem))
518 return buf;
520 return Qnil;
523 DEFUN ("get-buffer-create", Fget_buffer_create, Sget_buffer_create, 1, 1, 0,
524 doc: /* Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.
525 If BUFFER-OR-NAME is a string and a live buffer with that name exists,
526 return that buffer. If no such buffer exists, create a new buffer with
527 that name and return it. If BUFFER-OR-NAME starts with a space, the new
528 buffer does not keep undo information.
530 If BUFFER-OR-NAME is a buffer instead of a string, return it as given,
531 even if it is dead. The return value is never nil. */)
532 (register Lisp_Object buffer_or_name)
534 register Lisp_Object buffer, name;
535 register struct buffer *b;
537 buffer = Fget_buffer (buffer_or_name);
538 if (!NILP (buffer))
539 return buffer;
541 if (SCHARS (buffer_or_name) == 0)
542 error ("Empty string for buffer name is not allowed");
544 b = allocate_buffer ();
546 /* An ordinary buffer uses its own struct buffer_text. */
547 b->text = &b->own_text;
548 b->base_buffer = NULL;
549 /* No one shares the text with us now. */
550 b->indirections = 0;
552 BUF_GAP_SIZE (b) = 20;
553 block_input ();
554 /* We allocate extra 1-byte at the tail and keep it always '\0' for
555 anchoring a search. */
556 alloc_buffer_text (b, BUF_GAP_SIZE (b) + 1);
557 unblock_input ();
558 if (! BUF_BEG_ADDR (b))
559 buffer_memory_full (BUF_GAP_SIZE (b) + 1);
561 b->pt = BEG;
562 b->begv = BEG;
563 b->zv = BEG;
564 b->pt_byte = BEG_BYTE;
565 b->begv_byte = BEG_BYTE;
566 b->zv_byte = BEG_BYTE;
568 BUF_GPT (b) = BEG;
569 BUF_GPT_BYTE (b) = BEG_BYTE;
571 BUF_Z (b) = BEG;
572 BUF_Z_BYTE (b) = BEG_BYTE;
573 BUF_MODIFF (b) = 1;
574 BUF_CHARS_MODIFF (b) = 1;
575 BUF_OVERLAY_MODIFF (b) = 1;
576 BUF_SAVE_MODIFF (b) = 1;
577 set_buffer_intervals (b, NULL);
578 BUF_UNCHANGED_MODIFIED (b) = 1;
579 BUF_OVERLAY_UNCHANGED_MODIFIED (b) = 1;
580 BUF_END_UNCHANGED (b) = 0;
581 BUF_BEG_UNCHANGED (b) = 0;
582 *(BUF_GPT_ADDR (b)) = *(BUF_Z_ADDR (b)) = 0; /* Put an anchor '\0'. */
583 b->text->inhibit_shrinking = 0;
585 b->newline_cache = 0;
586 b->width_run_cache = 0;
587 bset_width_table (b, Qnil);
588 b->prevent_redisplay_optimizations_p = 1;
590 /* An ordinary buffer normally doesn't need markers
591 to handle BEGV and ZV. */
592 bset_pt_marker (b, Qnil);
593 bset_begv_marker (b, Qnil);
594 bset_zv_marker (b, Qnil);
596 name = Fcopy_sequence (buffer_or_name);
597 set_string_intervals (name, NULL);
598 bset_name (b, name);
600 bset_undo_list (b, SREF (name, 0) != ' ' ? Qnil : Qt);
602 reset_buffer (b);
603 reset_buffer_local_variables (b, 1);
605 bset_mark (b, Fmake_marker ());
606 BUF_MARKERS (b) = NULL;
608 /* Put this in the alist of all live buffers. */
609 XSETBUFFER (buffer, b);
610 Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (Fcons (name, buffer), Qnil));
611 /* And run buffer-list-update-hook. */
612 if (!NILP (Vrun_hooks))
613 call1 (Vrun_hooks, Qbuffer_list_update_hook);
615 return buffer;
619 /* Return a list of overlays which is a copy of the overlay list
620 LIST, but for buffer B. */
622 static struct Lisp_Overlay *
623 copy_overlays (struct buffer *b, struct Lisp_Overlay *list)
625 struct Lisp_Overlay *result = NULL, *tail = NULL;
627 for (; list; list = list->next)
629 Lisp_Object overlay, start, end;
630 struct Lisp_Marker *m;
632 eassert (MARKERP (list->start));
633 m = XMARKER (list->start);
634 start = build_marker (b, m->charpos, m->bytepos);
635 XMARKER (start)->insertion_type = m->insertion_type;
637 eassert (MARKERP (list->end));
638 m = XMARKER (list->end);
639 end = build_marker (b, m->charpos, m->bytepos);
640 XMARKER (end)->insertion_type = m->insertion_type;
642 overlay = build_overlay (start, end, Fcopy_sequence (list->plist));
643 if (tail)
644 tail = tail->next = XOVERLAY (overlay);
645 else
646 result = tail = XOVERLAY (overlay);
649 return result;
652 /* Set an appropriate overlay of B. */
654 static void
655 set_buffer_overlays_before (struct buffer *b, struct Lisp_Overlay *o)
657 b->overlays_before = o;
660 static void
661 set_buffer_overlays_after (struct buffer *b, struct Lisp_Overlay *o)
663 b->overlays_after = o;
666 /* Clone per-buffer values of buffer FROM.
668 Buffer TO gets the same per-buffer values as FROM, with the
669 following exceptions: (1) TO's name is left untouched, (2) markers
670 are copied and made to refer to TO, and (3) overlay lists are
671 copied. */
673 static void
674 clone_per_buffer_values (struct buffer *from, struct buffer *to)
676 int offset;
678 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
680 Lisp_Object obj;
682 /* Don't touch the `name' which should be unique for every buffer. */
683 if (offset == PER_BUFFER_VAR_OFFSET (name))
684 continue;
686 obj = per_buffer_value (from, offset);
687 if (MARKERP (obj) && XMARKER (obj)->buffer == from)
689 struct Lisp_Marker *m = XMARKER (obj);
691 obj = build_marker (to, m->charpos, m->bytepos);
692 XMARKER (obj)->insertion_type = m->insertion_type;
695 set_per_buffer_value (to, offset, obj);
698 memcpy (to->local_flags, from->local_flags, sizeof to->local_flags);
700 set_buffer_overlays_before (to, copy_overlays (to, from->overlays_before));
701 set_buffer_overlays_after (to, copy_overlays (to, from->overlays_after));
703 /* Get (a copy of) the alist of Lisp-level local variables of FROM
704 and install that in TO. */
705 bset_local_var_alist (to, buffer_lisp_local_variables (from, 1));
709 /* If buffer B has markers to record PT, BEGV and ZV when it is not
710 current, update these markers. */
712 static void
713 record_buffer_markers (struct buffer *b)
715 if (! NILP (BVAR (b, pt_marker)))
717 Lisp_Object buffer;
719 eassert (!NILP (BVAR (b, begv_marker)));
720 eassert (!NILP (BVAR (b, zv_marker)));
722 XSETBUFFER (buffer, b);
723 set_marker_both (BVAR (b, pt_marker), buffer, b->pt, b->pt_byte);
724 set_marker_both (BVAR (b, begv_marker), buffer, b->begv, b->begv_byte);
725 set_marker_both (BVAR (b, zv_marker), buffer, b->zv, b->zv_byte);
730 /* If buffer B has markers to record PT, BEGV and ZV when it is not
731 current, fetch these values into B->begv etc. */
733 static void
734 fetch_buffer_markers (struct buffer *b)
736 if (! NILP (BVAR (b, pt_marker)))
738 Lisp_Object m;
740 eassert (!NILP (BVAR (b, begv_marker)));
741 eassert (!NILP (BVAR (b, zv_marker)));
743 m = BVAR (b, pt_marker);
744 SET_BUF_PT_BOTH (b, marker_position (m), marker_byte_position (m));
746 m = BVAR (b, begv_marker);
747 SET_BUF_BEGV_BOTH (b, marker_position (m), marker_byte_position (m));
749 m = BVAR (b, zv_marker);
750 SET_BUF_ZV_BOTH (b, marker_position (m), marker_byte_position (m));
755 DEFUN ("make-indirect-buffer", Fmake_indirect_buffer, Smake_indirect_buffer,
756 2, 3,
757 "bMake indirect buffer (to buffer): \nBName of indirect buffer: ",
758 doc: /* Create and return an indirect buffer for buffer BASE-BUFFER, named NAME.
759 BASE-BUFFER should be a live buffer, or the name of an existing buffer.
760 NAME should be a string which is not the name of an existing buffer.
761 Optional argument CLONE non-nil means preserve BASE-BUFFER's state,
762 such as major and minor modes, in the indirect buffer.
763 CLONE nil means the indirect buffer's state is reset to default values. */)
764 (Lisp_Object base_buffer, Lisp_Object name, Lisp_Object clone)
766 Lisp_Object buf, tem;
767 struct buffer *b;
769 CHECK_STRING (name);
770 buf = Fget_buffer (name);
771 if (!NILP (buf))
772 error ("Buffer name `%s' is in use", SDATA (name));
774 tem = base_buffer;
775 base_buffer = Fget_buffer (base_buffer);
776 if (NILP (base_buffer))
777 error ("No such buffer: `%s'", SDATA (tem));
778 if (!BUFFER_LIVE_P (XBUFFER (base_buffer)))
779 error ("Base buffer has been killed");
781 if (SCHARS (name) == 0)
782 error ("Empty string for buffer name is not allowed");
784 b = allocate_buffer ();
786 /* No double indirection - if base buffer is indirect,
787 new buffer becomes an indirect to base's base. */
788 b->base_buffer = (XBUFFER (base_buffer)->base_buffer
789 ? XBUFFER (base_buffer)->base_buffer
790 : XBUFFER (base_buffer));
792 /* Use the base buffer's text object. */
793 b->text = b->base_buffer->text;
794 /* We have no own text. */
795 b->indirections = -1;
796 /* Notify base buffer that we share the text now. */
797 b->base_buffer->indirections++;
799 b->pt = b->base_buffer->pt;
800 b->begv = b->base_buffer->begv;
801 b->zv = b->base_buffer->zv;
802 b->pt_byte = b->base_buffer->pt_byte;
803 b->begv_byte = b->base_buffer->begv_byte;
804 b->zv_byte = b->base_buffer->zv_byte;
806 b->newline_cache = 0;
807 b->width_run_cache = 0;
808 bset_width_table (b, Qnil);
810 name = Fcopy_sequence (name);
811 set_string_intervals (name, NULL);
812 bset_name (b, name);
814 reset_buffer (b);
815 reset_buffer_local_variables (b, 1);
817 /* Put this in the alist of all live buffers. */
818 XSETBUFFER (buf, b);
819 Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (Fcons (name, buf), Qnil));
821 bset_mark (b, Fmake_marker ());
823 /* The multibyte status belongs to the base buffer. */
824 bset_enable_multibyte_characters
825 (b, BVAR (b->base_buffer, enable_multibyte_characters));
827 /* Make sure the base buffer has markers for its narrowing. */
828 if (NILP (BVAR (b->base_buffer, pt_marker)))
830 eassert (NILP (BVAR (b->base_buffer, begv_marker)));
831 eassert (NILP (BVAR (b->base_buffer, zv_marker)));
833 bset_pt_marker (b->base_buffer,
834 build_marker (b->base_buffer, b->base_buffer->pt,
835 b->base_buffer->pt_byte));
837 bset_begv_marker (b->base_buffer,
838 build_marker (b->base_buffer, b->base_buffer->begv,
839 b->base_buffer->begv_byte));
841 bset_zv_marker (b->base_buffer,
842 build_marker (b->base_buffer, b->base_buffer->zv,
843 b->base_buffer->zv_byte));
845 XMARKER (BVAR (b->base_buffer, zv_marker))->insertion_type = 1;
848 if (NILP (clone))
850 /* Give the indirect buffer markers for its narrowing. */
851 bset_pt_marker (b, build_marker (b, b->pt, b->pt_byte));
852 bset_begv_marker (b, build_marker (b, b->begv, b->begv_byte));
853 bset_zv_marker (b, build_marker (b, b->zv, b->zv_byte));
854 XMARKER (BVAR (b, zv_marker))->insertion_type = 1;
856 else
858 struct buffer *old_b = current_buffer;
860 clone_per_buffer_values (b->base_buffer, b);
861 bset_filename (b, Qnil);
862 bset_file_truename (b, Qnil);
863 bset_display_count (b, make_number (0));
864 bset_backed_up (b, Qnil);
865 bset_auto_save_file_name (b, Qnil);
866 set_buffer_internal_1 (b);
867 Fset (intern ("buffer-save-without-query"), Qnil);
868 Fset (intern ("buffer-file-number"), Qnil);
869 Fset (intern ("buffer-stale-function"), Qnil);
870 set_buffer_internal_1 (old_b);
873 /* Run buffer-list-update-hook. */
874 if (!NILP (Vrun_hooks))
875 call1 (Vrun_hooks, Qbuffer_list_update_hook);
877 return buf;
880 /* Mark OV as no longer associated with B. */
882 static void
883 drop_overlay (struct buffer *b, struct Lisp_Overlay *ov)
885 eassert (b == XBUFFER (Fmarker_buffer (ov->start)));
886 modify_overlay (b, marker_position (ov->start),
887 marker_position (ov->end));
888 Fset_marker (ov->start, Qnil, Qnil);
889 Fset_marker (ov->end, Qnil, Qnil);
893 /* Delete all overlays of B and reset it's overlay lists. */
895 void
896 delete_all_overlays (struct buffer *b)
898 struct Lisp_Overlay *ov, *next;
900 for (ov = b->overlays_before; ov; ov = next)
902 drop_overlay (b, ov);
903 next = ov->next;
904 ov->next = NULL;
907 for (ov = b->overlays_after; ov; ov = next)
909 drop_overlay (b, ov);
910 next = ov->next;
911 ov->next = NULL;
914 set_buffer_overlays_before (b, NULL);
915 set_buffer_overlays_after (b, NULL);
918 /* Reinitialize everything about a buffer except its name and contents
919 and local variables.
920 If called on an already-initialized buffer, the list of overlays
921 should be deleted before calling this function, otherwise we end up
922 with overlays that claim to belong to the buffer but the buffer
923 claims it doesn't belong to it. */
925 void
926 reset_buffer (register struct buffer *b)
928 bset_filename (b, Qnil);
929 bset_file_truename (b, Qnil);
930 bset_directory (b, current_buffer ? BVAR (current_buffer, directory) : Qnil);
931 b->modtime = make_emacs_time (0, UNKNOWN_MODTIME_NSECS);
932 b->modtime_size = -1;
933 XSETFASTINT (BVAR (b, save_length), 0);
934 b->last_window_start = 1;
935 /* It is more conservative to start out "changed" than "unchanged". */
936 b->clip_changed = 0;
937 b->prevent_redisplay_optimizations_p = 1;
938 bset_backed_up (b, Qnil);
939 BUF_AUTOSAVE_MODIFF (b) = 0;
940 b->auto_save_failure_time = 0;
941 bset_auto_save_file_name (b, Qnil);
942 bset_read_only (b, Qnil);
943 set_buffer_overlays_before (b, NULL);
944 set_buffer_overlays_after (b, NULL);
945 b->overlay_center = BEG;
946 bset_mark_active (b, Qnil);
947 bset_point_before_scroll (b, Qnil);
948 bset_file_format (b, Qnil);
949 bset_auto_save_file_format (b, Qt);
950 bset_last_selected_window (b, Qnil);
951 bset_display_count (b, make_number (0));
952 bset_display_time (b, Qnil);
953 bset_enable_multibyte_characters
954 (b, BVAR (&buffer_defaults, enable_multibyte_characters));
955 bset_cursor_type (b, BVAR (&buffer_defaults, cursor_type));
956 bset_extra_line_spacing (b, BVAR (&buffer_defaults, extra_line_spacing));
958 b->display_error_modiff = 0;
961 /* Reset buffer B's local variables info.
962 Don't use this on a buffer that has already been in use;
963 it does not treat permanent locals consistently.
964 Instead, use Fkill_all_local_variables.
966 If PERMANENT_TOO, reset permanent buffer-local variables.
967 If not, preserve those. */
969 static void
970 reset_buffer_local_variables (struct buffer *b, bool permanent_too)
972 int offset, i;
974 /* Reset the major mode to Fundamental, together with all the
975 things that depend on the major mode.
976 default-major-mode is handled at a higher level.
977 We ignore it here. */
978 bset_major_mode (b, Qfundamental_mode);
979 bset_keymap (b, Qnil);
980 bset_mode_name (b, QSFundamental);
981 bset_minor_modes (b, Qnil);
983 /* If the standard case table has been altered and invalidated,
984 fix up its insides first. */
985 if (! (CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[0])
986 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[1])
987 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[2])))
988 Fset_standard_case_table (Vascii_downcase_table);
990 bset_downcase_table (b, Vascii_downcase_table);
991 bset_upcase_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[0]);
992 bset_case_canon_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[1]);
993 bset_case_eqv_table (b, XCHAR_TABLE (Vascii_downcase_table)->extras[2]);
994 bset_invisibility_spec (b, Qt);
996 /* Reset all (or most) per-buffer variables to their defaults. */
997 if (permanent_too)
998 bset_local_var_alist (b, Qnil);
999 else
1001 Lisp_Object tmp, prop, last = Qnil;
1002 for (tmp = BVAR (b, local_var_alist); CONSP (tmp); tmp = XCDR (tmp))
1003 if (!NILP (prop = Fget (XCAR (XCAR (tmp)), Qpermanent_local)))
1005 /* If permanent-local, keep it. */
1006 last = tmp;
1007 if (EQ (prop, Qpermanent_local_hook))
1009 /* This is a partially permanent hook variable.
1010 Preserve only the elements that want to be preserved. */
1011 Lisp_Object list, newlist;
1012 list = XCDR (XCAR (tmp));
1013 if (!CONSP (list))
1014 newlist = list;
1015 else
1016 for (newlist = Qnil; CONSP (list); list = XCDR (list))
1018 Lisp_Object elt = XCAR (list);
1019 /* Preserve element ELT if it's t,
1020 if it is a function with a `permanent-local-hook' property,
1021 or if it's not a symbol. */
1022 if (! SYMBOLP (elt)
1023 || EQ (elt, Qt)
1024 || !NILP (Fget (elt, Qpermanent_local_hook)))
1025 newlist = Fcons (elt, newlist);
1027 XSETCDR (XCAR (tmp), Fnreverse (newlist));
1030 /* Delete this local variable. */
1031 else if (NILP (last))
1032 bset_local_var_alist (b, XCDR (tmp));
1033 else
1034 XSETCDR (last, XCDR (tmp));
1037 for (i = 0; i < last_per_buffer_idx; ++i)
1038 if (permanent_too || buffer_permanent_local_flags[i] == 0)
1039 SET_PER_BUFFER_VALUE_P (b, i, 0);
1041 /* For each slot that has a default value, copy that into the slot. */
1042 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
1044 int idx = PER_BUFFER_IDX (offset);
1045 if ((idx > 0
1046 && (permanent_too
1047 || buffer_permanent_local_flags[idx] == 0)))
1048 set_per_buffer_value (b, offset, per_buffer_default (offset));
1052 /* We split this away from generate-new-buffer, because rename-buffer
1053 and set-visited-file-name ought to be able to use this to really
1054 rename the buffer properly. */
1056 DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name,
1057 Sgenerate_new_buffer_name, 1, 2, 0,
1058 doc: /* Return a string that is the name of no existing buffer based on NAME.
1059 If there is no live buffer named NAME, then return NAME.
1060 Otherwise modify name by appending `<NUMBER>', incrementing NUMBER
1061 \(starting at 2) until an unused name is found, and then return that name.
1062 Optional second argument IGNORE specifies a name that is okay to use (if
1063 it is in the sequence to be tried) even if a buffer with that name exists.
1065 If NAME begins with a space (i.e., a buffer that is not normally
1066 visible to users), then if buffer NAME already exists a random number
1067 is first appended to NAME, to speed up finding a non-existent buffer. */)
1068 (register Lisp_Object name, Lisp_Object ignore)
1070 register Lisp_Object gentemp, tem, tem2;
1071 ptrdiff_t count;
1072 char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
1074 CHECK_STRING (name);
1076 tem = Fstring_equal (name, ignore);
1077 if (!NILP (tem))
1078 return name;
1079 tem = Fget_buffer (name);
1080 if (NILP (tem))
1081 return name;
1083 if (!strncmp (SSDATA (name), " ", 1)) /* see bug#1229 */
1085 /* Note fileio.c:make_temp_name does random differently. */
1086 tem2 = concat2 (name, make_formatted_string
1087 (number, "-%"pI"d",
1088 XFASTINT (Frandom (make_number (999999)))));
1089 tem = Fget_buffer (tem2);
1090 if (NILP (tem))
1091 return tem2;
1093 else
1094 tem2 = name;
1096 count = 1;
1097 while (1)
1099 gentemp = concat2 (tem2, make_formatted_string
1100 (number, "<%"pD"d>", ++count));
1101 tem = Fstring_equal (gentemp, ignore);
1102 if (!NILP (tem))
1103 return gentemp;
1104 tem = Fget_buffer (gentemp);
1105 if (NILP (tem))
1106 return gentemp;
1111 DEFUN ("buffer-name", Fbuffer_name, Sbuffer_name, 0, 1, 0,
1112 doc: /* Return the name of BUFFER, as a string.
1113 BUFFER defaults to the current buffer.
1114 Return nil if BUFFER has been killed. */)
1115 (register Lisp_Object buffer)
1117 if (NILP (buffer))
1118 return BVAR (current_buffer, name);
1119 CHECK_BUFFER (buffer);
1120 return BVAR (XBUFFER (buffer), name);
1123 DEFUN ("buffer-file-name", Fbuffer_file_name, Sbuffer_file_name, 0, 1, 0,
1124 doc: /* Return name of file BUFFER is visiting, or nil if none.
1125 No argument or nil as argument means use the current buffer. */)
1126 (register Lisp_Object buffer)
1128 if (NILP (buffer))
1129 return BVAR (current_buffer, filename);
1130 CHECK_BUFFER (buffer);
1131 return BVAR (XBUFFER (buffer), filename);
1134 DEFUN ("buffer-base-buffer", Fbuffer_base_buffer, Sbuffer_base_buffer,
1135 0, 1, 0,
1136 doc: /* Return the base buffer of indirect buffer BUFFER.
1137 If BUFFER is not indirect, return nil.
1138 BUFFER defaults to the current buffer. */)
1139 (register Lisp_Object buffer)
1141 struct buffer *base;
1142 Lisp_Object base_buffer;
1144 if (NILP (buffer))
1145 base = current_buffer->base_buffer;
1146 else
1148 CHECK_BUFFER (buffer);
1149 base = XBUFFER (buffer)->base_buffer;
1152 if (! base)
1153 return Qnil;
1154 XSETBUFFER (base_buffer, base);
1155 return base_buffer;
1158 DEFUN ("buffer-local-value", Fbuffer_local_value,
1159 Sbuffer_local_value, 2, 2, 0,
1160 doc: /* Return the value of VARIABLE in BUFFER.
1161 If VARIABLE does not have a buffer-local binding in BUFFER, the value
1162 is the default binding of the variable. */)
1163 (register Lisp_Object variable, register Lisp_Object buffer)
1165 register Lisp_Object result = buffer_local_value_1 (variable, buffer);
1167 if (EQ (result, Qunbound))
1168 xsignal1 (Qvoid_variable, variable);
1170 return result;
1174 /* Like Fbuffer_local_value, but return Qunbound if the variable is
1175 locally unbound. */
1177 Lisp_Object
1178 buffer_local_value_1 (Lisp_Object variable, Lisp_Object buffer)
1180 register struct buffer *buf;
1181 register Lisp_Object result;
1182 struct Lisp_Symbol *sym;
1184 CHECK_SYMBOL (variable);
1185 CHECK_BUFFER (buffer);
1186 buf = XBUFFER (buffer);
1187 sym = XSYMBOL (variable);
1189 start:
1190 switch (sym->redirect)
1192 case SYMBOL_VARALIAS: sym = indirect_variable (sym); goto start;
1193 case SYMBOL_PLAINVAL: result = SYMBOL_VAL (sym); break;
1194 case SYMBOL_LOCALIZED:
1195 { /* Look in local_var_alist. */
1196 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
1197 XSETSYMBOL (variable, sym); /* Update In case of aliasing. */
1198 result = Fassoc (variable, BVAR (buf, local_var_alist));
1199 if (!NILP (result))
1201 if (blv->fwd)
1202 { /* What binding is loaded right now? */
1203 Lisp_Object current_alist_element = blv->valcell;
1205 /* The value of the currently loaded binding is not
1206 stored in it, but rather in the realvalue slot.
1207 Store that value into the binding it belongs to
1208 in case that is the one we are about to use. */
1210 XSETCDR (current_alist_element,
1211 do_symval_forwarding (blv->fwd));
1213 /* Now get the (perhaps updated) value out of the binding. */
1214 result = XCDR (result);
1216 else
1217 result = Fdefault_value (variable);
1218 break;
1220 case SYMBOL_FORWARDED:
1222 union Lisp_Fwd *fwd = SYMBOL_FWD (sym);
1223 if (BUFFER_OBJFWDP (fwd))
1224 result = per_buffer_value (buf, XBUFFER_OBJFWD (fwd)->offset);
1225 else
1226 result = Fdefault_value (variable);
1227 break;
1229 default: emacs_abort ();
1232 return result;
1235 /* Return an alist of the Lisp-level buffer-local bindings of
1236 buffer BUF. That is, don't include the variables maintained
1237 in special slots in the buffer object.
1238 If not CLONE, replace elements of the form (VAR . unbound)
1239 by VAR. */
1241 static Lisp_Object
1242 buffer_lisp_local_variables (struct buffer *buf, bool clone)
1244 Lisp_Object result = Qnil;
1245 Lisp_Object tail;
1246 for (tail = BVAR (buf, local_var_alist); CONSP (tail); tail = XCDR (tail))
1248 Lisp_Object val, elt;
1250 elt = XCAR (tail);
1252 /* Reference each variable in the alist in buf.
1253 If inquiring about the current buffer, this gets the current values,
1254 so store them into the alist so the alist is up to date.
1255 If inquiring about some other buffer, this swaps out any values
1256 for that buffer, making the alist up to date automatically. */
1257 val = find_symbol_value (XCAR (elt));
1258 /* Use the current buffer value only if buf is the current buffer. */
1259 if (buf != current_buffer)
1260 val = XCDR (elt);
1262 result = Fcons (!clone && EQ (val, Qunbound)
1263 ? XCAR (elt)
1264 : Fcons (XCAR (elt), val),
1265 result);
1268 return result;
1271 DEFUN ("buffer-local-variables", Fbuffer_local_variables,
1272 Sbuffer_local_variables, 0, 1, 0,
1273 doc: /* Return an alist of variables that are buffer-local in BUFFER.
1274 Most elements look like (SYMBOL . VALUE), describing one variable.
1275 For a symbol that is locally unbound, just the symbol appears in the value.
1276 Note that storing new VALUEs in these elements doesn't change the variables.
1277 No argument or nil as argument means use current buffer as BUFFER. */)
1278 (register Lisp_Object buffer)
1280 register struct buffer *buf;
1281 register Lisp_Object result;
1283 if (NILP (buffer))
1284 buf = current_buffer;
1285 else
1287 CHECK_BUFFER (buffer);
1288 buf = XBUFFER (buffer);
1291 result = buffer_lisp_local_variables (buf, 0);
1293 /* Add on all the variables stored in special slots. */
1295 int offset, idx;
1297 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
1299 idx = PER_BUFFER_IDX (offset);
1300 if ((idx == -1 || PER_BUFFER_VALUE_P (buf, idx))
1301 && SYMBOLP (PER_BUFFER_SYMBOL (offset)))
1303 Lisp_Object sym = PER_BUFFER_SYMBOL (offset);
1304 Lisp_Object val = per_buffer_value (buf, offset);
1305 result = Fcons (EQ (val, Qunbound) ? sym : Fcons (sym, val),
1306 result);
1311 return result;
1314 DEFUN ("buffer-modified-p", Fbuffer_modified_p, Sbuffer_modified_p,
1315 0, 1, 0,
1316 doc: /* Return t if BUFFER was modified since its file was last read or saved.
1317 No argument or nil as argument means use current buffer as BUFFER. */)
1318 (register Lisp_Object buffer)
1320 register struct buffer *buf;
1321 if (NILP (buffer))
1322 buf = current_buffer;
1323 else
1325 CHECK_BUFFER (buffer);
1326 buf = XBUFFER (buffer);
1329 return BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf) ? Qt : Qnil;
1332 DEFUN ("set-buffer-modified-p", Fset_buffer_modified_p, Sset_buffer_modified_p,
1333 1, 1, 0,
1334 doc: /* Mark current buffer as modified or unmodified according to FLAG.
1335 A non-nil FLAG means mark the buffer modified. */)
1336 (Lisp_Object flag)
1338 Lisp_Object fn, buffer, window;
1340 #ifdef CLASH_DETECTION
1341 /* If buffer becoming modified, lock the file.
1342 If buffer becoming unmodified, unlock the file. */
1344 struct buffer *b = current_buffer->base_buffer
1345 ? current_buffer->base_buffer
1346 : current_buffer;
1348 fn = BVAR (b, file_truename);
1349 /* Test buffer-file-name so that binding it to nil is effective. */
1350 if (!NILP (fn) && ! NILP (BVAR (b, filename)))
1352 bool already = SAVE_MODIFF < MODIFF;
1353 if (!already && !NILP (flag))
1354 lock_file (fn);
1355 else if (already && NILP (flag))
1356 unlock_file (fn);
1358 #endif /* CLASH_DETECTION */
1360 /* Here we have a problem. SAVE_MODIFF is used here to encode
1361 buffer-modified-p (as SAVE_MODIFF<MODIFF) as well as
1362 recent-auto-save-p (as SAVE_MODIFF<auto_save_modified). So if we
1363 modify SAVE_MODIFF to affect one, we may affect the other
1364 as well.
1365 E.g. if FLAG is nil we need to set SAVE_MODIFF to MODIFF, but
1366 if SAVE_MODIFF<auto_save_modified that means we risk changing
1367 recent-auto-save-p from t to nil.
1368 Vice versa, if FLAG is non-nil and SAVE_MODIFF>=auto_save_modified
1369 we risk changing recent-auto-save-p from nil to t. */
1370 SAVE_MODIFF = (NILP (flag)
1371 /* FIXME: This unavoidably sets recent-auto-save-p to nil. */
1372 ? MODIFF
1373 /* Let's try to preserve recent-auto-save-p. */
1374 : SAVE_MODIFF < MODIFF ? SAVE_MODIFF
1375 /* If SAVE_MODIFF == auto_save_modified == MODIFF,
1376 we can either decrease SAVE_MODIFF and auto_save_modified
1377 or increase MODIFF. */
1378 : MODIFF++);
1380 /* Set update_mode_lines only if buffer is displayed in some window.
1381 Packages like jit-lock or lazy-lock preserve a buffer's modified
1382 state by recording/restoring the state around blocks of code.
1383 Setting update_mode_lines makes redisplay consider all windows
1384 (on all frames). Stealth fontification of buffers not displayed
1385 would incur additional redisplay costs if we'd set
1386 update_modes_lines unconditionally.
1388 Ideally, I think there should be another mechanism for fontifying
1389 buffers without "modifying" buffers, or redisplay should be
1390 smarter about updating the `*' in mode lines. --gerd */
1391 XSETBUFFER (buffer, current_buffer);
1392 window = Fget_buffer_window (buffer, Qt);
1393 if (WINDOWP (window))
1395 ++update_mode_lines;
1396 current_buffer->prevent_redisplay_optimizations_p = 1;
1399 return flag;
1402 DEFUN ("restore-buffer-modified-p", Frestore_buffer_modified_p,
1403 Srestore_buffer_modified_p, 1, 1, 0,
1404 doc: /* Like `set-buffer-modified-p', with a difference concerning redisplay.
1405 It is not ensured that mode lines will be updated to show the modified
1406 state of the current buffer. Use with care. */)
1407 (Lisp_Object flag)
1409 #ifdef CLASH_DETECTION
1410 Lisp_Object fn;
1412 /* If buffer becoming modified, lock the file.
1413 If buffer becoming unmodified, unlock the file. */
1415 fn = BVAR (current_buffer, file_truename);
1416 /* Test buffer-file-name so that binding it to nil is effective. */
1417 if (!NILP (fn) && ! NILP (BVAR (current_buffer, filename)))
1419 bool already = SAVE_MODIFF < MODIFF;
1420 if (!already && !NILP (flag))
1421 lock_file (fn);
1422 else if (already && NILP (flag))
1423 unlock_file (fn);
1425 #endif /* CLASH_DETECTION */
1427 SAVE_MODIFF = NILP (flag) ? MODIFF : 0;
1428 return flag;
1431 DEFUN ("buffer-modified-tick", Fbuffer_modified_tick, Sbuffer_modified_tick,
1432 0, 1, 0,
1433 doc: /* Return BUFFER's tick counter, incremented for each change in text.
1434 Each buffer has a tick counter which is incremented each time the
1435 text in that buffer is changed. It wraps around occasionally.
1436 No argument or nil as argument means use current buffer as BUFFER. */)
1437 (register Lisp_Object buffer)
1439 register struct buffer *buf;
1440 if (NILP (buffer))
1441 buf = current_buffer;
1442 else
1444 CHECK_BUFFER (buffer);
1445 buf = XBUFFER (buffer);
1448 return make_number (BUF_MODIFF (buf));
1451 DEFUN ("buffer-chars-modified-tick", Fbuffer_chars_modified_tick,
1452 Sbuffer_chars_modified_tick, 0, 1, 0,
1453 doc: /* Return BUFFER's character-change tick counter.
1454 Each buffer has a character-change tick counter, which is set to the
1455 value of the buffer's tick counter \(see `buffer-modified-tick'), each
1456 time text in that buffer is inserted or deleted. By comparing the
1457 values returned by two individual calls of `buffer-chars-modified-tick',
1458 you can tell whether a character change occurred in that buffer in
1459 between these calls. No argument or nil as argument means use current
1460 buffer as BUFFER. */)
1461 (register Lisp_Object buffer)
1463 register struct buffer *buf;
1464 if (NILP (buffer))
1465 buf = current_buffer;
1466 else
1468 CHECK_BUFFER (buffer);
1469 buf = XBUFFER (buffer);
1472 return make_number (BUF_CHARS_MODIFF (buf));
1475 DEFUN ("rename-buffer", Frename_buffer, Srename_buffer, 1, 2,
1476 "(list (read-string \"Rename buffer (to new name): \" \
1477 nil 'buffer-name-history (buffer-name (current-buffer))) \
1478 current-prefix-arg)",
1479 doc: /* Change current buffer's name to NEWNAME (a string).
1480 If second arg UNIQUE is nil or omitted, it is an error if a
1481 buffer named NEWNAME already exists.
1482 If UNIQUE is non-nil, come up with a new name using
1483 `generate-new-buffer-name'.
1484 Interactively, you can set UNIQUE with a prefix argument.
1485 We return the name we actually gave the buffer.
1486 This does not change the name of the visited file (if any). */)
1487 (register Lisp_Object newname, Lisp_Object unique)
1489 register Lisp_Object tem, buf;
1491 CHECK_STRING (newname);
1493 if (SCHARS (newname) == 0)
1494 error ("Empty string is invalid as a buffer name");
1496 tem = Fget_buffer (newname);
1497 if (!NILP (tem))
1499 /* Don't short-circuit if UNIQUE is t. That is a useful way to
1500 rename the buffer automatically so you can create another
1501 with the original name. It makes UNIQUE equivalent to
1502 (rename-buffer (generate-new-buffer-name NEWNAME)). */
1503 if (NILP (unique) && XBUFFER (tem) == current_buffer)
1504 return BVAR (current_buffer, name);
1505 if (!NILP (unique))
1506 newname = Fgenerate_new_buffer_name (newname, BVAR (current_buffer, name));
1507 else
1508 error ("Buffer name `%s' is in use", SDATA (newname));
1511 bset_name (current_buffer, newname);
1513 /* Catch redisplay's attention. Unless we do this, the mode lines for
1514 any windows displaying current_buffer will stay unchanged. */
1515 update_mode_lines++;
1517 XSETBUFFER (buf, current_buffer);
1518 Fsetcar (Frassq (buf, Vbuffer_alist), newname);
1519 if (NILP (BVAR (current_buffer, filename))
1520 && !NILP (BVAR (current_buffer, auto_save_file_name)))
1521 call0 (intern ("rename-auto-save-file"));
1523 /* Run buffer-list-update-hook. */
1524 if (!NILP (Vrun_hooks))
1525 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1527 /* Refetch since that last call may have done GC. */
1528 return BVAR (current_buffer, name);
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 Lisp_Object tail, buf, pred;
1545 Lisp_Object notsogood = Qnil;
1547 if (NILP (frame))
1548 frame = selected_frame;
1550 CHECK_FRAME (frame);
1552 pred = frame_buffer_predicate (frame);
1553 /* Consider buffers that have been seen in the frame first. */
1554 tail = XFRAME (frame)->buffer_list;
1555 for (; CONSP (tail); tail = XCDR (tail))
1557 buf = XCAR (tail);
1558 if (BUFFERP (buf) && !EQ (buf, buffer)
1559 && BUFFER_LIVE_P (XBUFFER (buf))
1560 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' ')
1561 /* If the frame has a buffer_predicate, disregard buffers that
1562 don't fit the predicate. */
1563 && (NILP (pred) || !NILP (call1 (pred, buf))))
1565 if (!NILP (visible_ok)
1566 || NILP (Fget_buffer_window (buf, Qvisible)))
1567 return buf;
1568 else if (NILP (notsogood))
1569 notsogood = buf;
1573 /* Consider alist of all buffers next. */
1574 tail = Vbuffer_alist;
1575 for (; CONSP (tail); tail = XCDR (tail))
1577 buf = Fcdr (XCAR (tail));
1578 if (BUFFERP (buf) && !EQ (buf, buffer)
1579 && BUFFER_LIVE_P (XBUFFER (buf))
1580 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' ')
1581 /* If the frame has a buffer_predicate, disregard buffers that
1582 don't fit the predicate. */
1583 && (NILP (pred) || !NILP (call1 (pred, buf))))
1585 if (!NILP (visible_ok)
1586 || NILP (Fget_buffer_window (buf, Qvisible)))
1587 return buf;
1588 else if (NILP (notsogood))
1589 notsogood = buf;
1593 if (!NILP (notsogood))
1594 return notsogood;
1595 else
1597 buf = Fget_buffer (build_string ("*scratch*"));
1598 if (NILP (buf))
1600 buf = Fget_buffer_create (build_string ("*scratch*"));
1601 Fset_buffer_major_mode (buf);
1603 return buf;
1607 /* The following function is a safe variant of Fother_buffer: It doesn't
1608 pay attention to any frame-local buffer lists, doesn't care about
1609 visibility of buffers, and doesn't evaluate any frame predicates. */
1611 Lisp_Object
1612 other_buffer_safely (Lisp_Object buffer)
1614 Lisp_Object tail, buf;
1616 tail = Vbuffer_alist;
1617 for (; CONSP (tail); tail = XCDR (tail))
1619 buf = Fcdr (XCAR (tail));
1620 if (BUFFERP (buf) && !EQ (buf, buffer)
1621 && BUFFER_LIVE_P (XBUFFER (buf))
1622 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' '))
1623 return buf;
1626 buf = Fget_buffer (build_string ("*scratch*"));
1627 if (NILP (buf))
1629 buf = Fget_buffer_create (build_string ("*scratch*"));
1630 Fset_buffer_major_mode (buf);
1633 return buf;
1636 DEFUN ("buffer-enable-undo", Fbuffer_enable_undo, Sbuffer_enable_undo,
1637 0, 1, "",
1638 doc: /* Start keeping undo information for buffer BUFFER.
1639 No argument or nil as argument means do this for the current buffer. */)
1640 (register Lisp_Object buffer)
1642 Lisp_Object real_buffer;
1644 if (NILP (buffer))
1645 XSETBUFFER (real_buffer, current_buffer);
1646 else
1648 real_buffer = Fget_buffer (buffer);
1649 if (NILP (real_buffer))
1650 nsberror (buffer);
1653 if (EQ (BVAR (XBUFFER (real_buffer), undo_list), Qt))
1654 bset_undo_list (XBUFFER (real_buffer), Qnil);
1656 return Qnil;
1659 /* Truncate undo list and shrink the gap of BUFFER. */
1661 void
1662 compact_buffer (struct buffer *buffer)
1664 /* Verify indirection counters. */
1665 if (buffer->base_buffer)
1667 eassert (buffer->indirections == -1);
1668 eassert (buffer->base_buffer->indirections > 0);
1670 else
1671 eassert (buffer->indirections >= 0);
1673 /* Skip dead buffers, indirect buffers and buffers
1674 which aren't changed since last compaction. */
1675 if (!NILP (buffer->INTERNAL_FIELD (name))
1676 && (buffer->base_buffer == NULL)
1677 && (buffer->text->compact != buffer->text->modiff))
1679 /* If a buffer's undo list is Qt, that means that undo is
1680 turned off in that buffer. Calling truncate_undo_list on
1681 Qt tends to return NULL, which effectively turns undo back on.
1682 So don't call truncate_undo_list if undo_list is Qt. */
1683 if (!EQ (buffer->INTERNAL_FIELD (undo_list), Qt))
1684 truncate_undo_list (buffer);
1686 /* Shrink buffer gaps. */
1687 if (!buffer->text->inhibit_shrinking)
1689 /* If a buffer's gap size is more than 10% of the buffer
1690 size, or larger than 2000 bytes, then shrink it
1691 accordingly. Keep a minimum size of 20 bytes. */
1692 int size = min (2000, max (20, (buffer->text->z_byte / 10)));
1694 if (buffer->text->gap_size > size)
1696 struct buffer *save_current = current_buffer;
1697 current_buffer = buffer;
1698 make_gap (-(buffer->text->gap_size - size));
1699 current_buffer = save_current;
1702 buffer->text->compact = buffer->text->modiff;
1706 DEFUN ("kill-buffer", Fkill_buffer, Skill_buffer, 0, 1, "bKill buffer: ",
1707 doc: /* Kill the buffer specified by BUFFER-OR-NAME.
1708 The argument may be a buffer or the name of an existing buffer.
1709 Argument nil or omitted means kill the current buffer. Return t if the
1710 buffer is actually killed, nil otherwise.
1712 The functions in `kill-buffer-query-functions' are called with the
1713 buffer to be killed as the current buffer. If any of them returns nil,
1714 the buffer is not killed. The hook `kill-buffer-hook' is run before the
1715 buffer is actually killed. The buffer being killed will be current
1716 while the hook is running. Functions called by any of these hooks are
1717 supposed to not change the current buffer.
1719 Any processes that have this buffer as the `process-buffer' are killed
1720 with SIGHUP. This function calls `replace-buffer-in-windows' for
1721 cleaning up all windows currently displaying the buffer to be killed. */)
1722 (Lisp_Object buffer_or_name)
1724 Lisp_Object buffer;
1725 register struct buffer *b;
1726 register Lisp_Object tem;
1727 register struct Lisp_Marker *m;
1728 struct gcpro gcpro1;
1730 if (NILP (buffer_or_name))
1731 buffer = Fcurrent_buffer ();
1732 else
1733 buffer = Fget_buffer (buffer_or_name);
1734 if (NILP (buffer))
1735 nsberror (buffer_or_name);
1737 b = XBUFFER (buffer);
1739 /* Avoid trouble for buffer already dead. */
1740 if (!BUFFER_LIVE_P (b))
1741 return Qnil;
1743 /* Query if the buffer is still modified. */
1744 if (INTERACTIVE && !NILP (BVAR (b, filename))
1745 && BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
1747 GCPRO1 (buffer);
1748 tem = do_yes_or_no_p (format2 ("Buffer %s modified; kill anyway? ",
1749 BVAR (b, name), make_number (0)));
1750 UNGCPRO;
1751 if (NILP (tem))
1752 return Qnil;
1755 /* Run hooks with the buffer to be killed the current buffer. */
1757 ptrdiff_t count = SPECPDL_INDEX ();
1758 Lisp_Object arglist[1];
1760 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1761 set_buffer_internal (b);
1763 /* First run the query functions; if any query is answered no,
1764 don't kill the buffer. */
1765 arglist[0] = Qkill_buffer_query_functions;
1766 tem = Frun_hook_with_args_until_failure (1, arglist);
1767 if (NILP (tem))
1768 return unbind_to (count, Qnil);
1770 /* Then run the hooks. */
1771 Frun_hooks (1, &Qkill_buffer_hook);
1772 unbind_to (count, Qnil);
1775 /* If the hooks have killed the buffer, exit now. */
1776 if (!BUFFER_LIVE_P (b))
1777 return Qt;
1779 /* We have no more questions to ask. Verify that it is valid
1780 to kill the buffer. This must be done after the questions
1781 since anything can happen within do_yes_or_no_p. */
1783 /* Don't kill the minibuffer now current. */
1784 if (EQ (buffer, XWINDOW (minibuf_window)->buffer))
1785 return Qnil;
1787 /* When we kill an ordinary buffer which shares it's buffer text
1788 with indirect buffer(s), we must kill indirect buffer(s) too.
1789 We do it at this stage so nothing terrible happens if they
1790 ask questions or their hooks get errors. */
1791 if (!b->base_buffer && b->indirections > 0)
1793 struct buffer *other;
1795 GCPRO1 (buffer);
1797 FOR_EACH_BUFFER (other)
1798 if (other->base_buffer == b)
1800 Lisp_Object buf;
1801 XSETBUFFER (buf, other);
1802 Fkill_buffer (buf);
1805 UNGCPRO;
1807 /* Exit if we now have killed the base buffer (Bug#11665). */
1808 if (!BUFFER_LIVE_P (b))
1809 return Qt;
1812 /* Run replace_buffer_in_windows before making another buffer current
1813 since set-window-buffer-start-and-point will refuse to make another
1814 buffer current if the selected window does not show the current
1815 buffer. (Bug#10114) */
1816 replace_buffer_in_windows (buffer);
1818 /* Exit if replacing the buffer in windows has killed our buffer. */
1819 if (!BUFFER_LIVE_P (b))
1820 return Qt;
1822 /* Make this buffer not be current. Exit if it is the sole visible
1823 buffer. */
1824 if (b == current_buffer)
1826 tem = Fother_buffer (buffer, Qnil, Qnil);
1827 Fset_buffer (tem);
1828 if (b == current_buffer)
1829 return Qnil;
1832 /* If the buffer now current is shown in the minibuffer and our buffer
1833 is the sole other buffer give up. */
1834 XSETBUFFER (tem, current_buffer);
1835 if (EQ (tem, XWINDOW (minibuf_window)->buffer)
1836 && EQ (buffer, Fother_buffer (buffer, Qnil, Qnil)))
1837 return Qnil;
1839 /* Now there is no question: we can kill the buffer. */
1841 #ifdef CLASH_DETECTION
1842 /* Unlock this buffer's file, if it is locked. */
1843 unlock_buffer (b);
1844 #endif /* CLASH_DETECTION */
1846 GCPRO1 (buffer);
1847 kill_buffer_processes (buffer);
1848 UNGCPRO;
1850 /* Killing buffer processes may run sentinels which may have killed
1851 our buffer. */
1852 if (!BUFFER_LIVE_P (b))
1853 return Qt;
1855 /* These may run Lisp code and into infinite loops (if someone
1856 insisted on circular lists) so allow quitting here. */
1857 frames_discard_buffer (buffer);
1859 clear_charpos_cache (b);
1861 tem = Vinhibit_quit;
1862 Vinhibit_quit = Qt;
1863 /* Remove the buffer from the list of all buffers. */
1864 Vbuffer_alist = Fdelq (Frassq (buffer, Vbuffer_alist), Vbuffer_alist);
1865 /* If replace_buffer_in_windows didn't do its job fix that now. */
1866 replace_buffer_in_windows_safely (buffer);
1867 Vinhibit_quit = tem;
1869 /* Delete any auto-save file, if we saved it in this session.
1870 But not if the buffer is modified. */
1871 if (STRINGP (BVAR (b, auto_save_file_name))
1872 && BUF_AUTOSAVE_MODIFF (b) != 0
1873 && BUF_SAVE_MODIFF (b) < BUF_AUTOSAVE_MODIFF (b)
1874 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
1875 && NILP (Fsymbol_value (intern ("auto-save-visited-file-name"))))
1877 Lisp_Object delete;
1878 delete = Fsymbol_value (intern ("delete-auto-save-files"));
1879 if (! NILP (delete))
1880 internal_delete_file (BVAR (b, auto_save_file_name));
1883 /* Deleting an auto-save file could have killed our buffer. */
1884 if (!BUFFER_LIVE_P (b))
1885 return Qt;
1887 if (b->base_buffer)
1889 /* Unchain all markers that belong to this indirect buffer.
1890 Don't unchain the markers that belong to the base buffer
1891 or its other indirect buffers. */
1892 for (m = BUF_MARKERS (b); m; )
1894 struct Lisp_Marker *next = m->next;
1895 if (m->buffer == b)
1896 unchain_marker (m);
1897 m = next;
1900 else
1902 /* Unchain all markers of this buffer and its indirect buffers.
1903 and leave them pointing nowhere. */
1904 for (m = BUF_MARKERS (b); m; )
1906 struct Lisp_Marker *next = m->next;
1907 m->buffer = 0;
1908 m->next = NULL;
1909 m = next;
1911 BUF_MARKERS (b) = NULL;
1912 set_buffer_intervals (b, NULL);
1914 /* Perhaps we should explicitly free the interval tree here... */
1917 /* Reset the local variables, so that this buffer's local values
1918 won't be protected from GC. They would be protected
1919 if they happened to remain cached in their symbols.
1920 This gets rid of them for certain. */
1921 swap_out_buffer_local_variables (b);
1922 reset_buffer_local_variables (b, 1);
1924 bset_name (b, Qnil);
1926 block_input ();
1927 if (b->base_buffer)
1929 /* Notify our base buffer that we don't share the text anymore. */
1930 eassert (b->indirections == -1);
1931 b->base_buffer->indirections--;
1932 eassert (b->base_buffer->indirections >= 0);
1934 else
1935 /* No one shares our buffer text, can free it. */
1936 free_buffer_text (b);
1938 if (b->newline_cache)
1940 free_region_cache (b->newline_cache);
1941 b->newline_cache = 0;
1943 if (b->width_run_cache)
1945 free_region_cache (b->width_run_cache);
1946 b->width_run_cache = 0;
1948 bset_width_table (b, Qnil);
1949 unblock_input ();
1950 bset_undo_list (b, Qnil);
1952 /* Run buffer-list-update-hook. */
1953 if (!NILP (Vrun_hooks))
1954 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1956 return Qt;
1959 /* Move association for BUFFER to the front of buffer (a)lists. Since
1960 we do this each time BUFFER is selected visibly, the more recently
1961 selected buffers are always closer to the front of those lists. This
1962 means that other_buffer is more likely to choose a relevant buffer.
1964 Note that this moves BUFFER to the front of the buffer lists of the
1965 selected frame even if BUFFER is not shown there. If BUFFER is not
1966 shown in the selected frame, consider the present behavior a feature.
1967 `select-window' gets this right since it shows BUFFER in the selected
1968 window when calling us. */
1970 void
1971 record_buffer (Lisp_Object buffer)
1973 Lisp_Object aelt, aelt_cons, tem;
1974 register struct frame *f = XFRAME (selected_frame);
1976 CHECK_BUFFER (buffer);
1978 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
1979 Don't allow quitting since this might leave the buffer list in an
1980 inconsistent state. */
1981 tem = Vinhibit_quit;
1982 Vinhibit_quit = Qt;
1983 aelt = Frassq (buffer, Vbuffer_alist);
1984 aelt_cons = Fmemq (aelt, Vbuffer_alist);
1985 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
1986 XSETCDR (aelt_cons, Vbuffer_alist);
1987 Vbuffer_alist = aelt_cons;
1988 Vinhibit_quit = tem;
1990 /* Update buffer list of selected frame. */
1991 fset_buffer_list (f, Fcons (buffer, Fdelq (buffer, f->buffer_list)));
1992 fset_buried_buffer_list (f, Fdelq (buffer, f->buried_buffer_list));
1994 /* Run buffer-list-update-hook. */
1995 if (!NILP (Vrun_hooks))
1996 call1 (Vrun_hooks, Qbuffer_list_update_hook);
2000 /* Move BUFFER to the end of the buffer (a)lists. Do nothing if the
2001 buffer is killed. For the selected frame's buffer list this moves
2002 BUFFER to its end even if it was never shown in that frame. If
2003 this happens we have a feature, hence `bury-buffer-internal' should be
2004 called only when BUFFER was shown in the selected frame. */
2006 DEFUN ("bury-buffer-internal", Fbury_buffer_internal, Sbury_buffer_internal,
2007 1, 1, 0,
2008 doc: /* Move BUFFER to the end of the buffer list. */)
2009 (Lisp_Object buffer)
2011 Lisp_Object aelt, aelt_cons, tem;
2012 register struct frame *f = XFRAME (selected_frame);
2014 CHECK_BUFFER (buffer);
2016 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
2017 Don't allow quitting since this might leave the buffer list in an
2018 inconsistent state. */
2019 tem = Vinhibit_quit;
2020 Vinhibit_quit = Qt;
2021 aelt = Frassq (buffer, Vbuffer_alist);
2022 aelt_cons = Fmemq (aelt, Vbuffer_alist);
2023 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
2024 XSETCDR (aelt_cons, Qnil);
2025 Vbuffer_alist = nconc2 (Vbuffer_alist, aelt_cons);
2026 Vinhibit_quit = tem;
2028 /* Update buffer lists of selected frame. */
2029 fset_buffer_list (f, Fdelq (buffer, f->buffer_list));
2030 fset_buried_buffer_list
2031 (f, Fcons (buffer, Fdelq (buffer, f->buried_buffer_list)));
2033 /* Run buffer-list-update-hook. */
2034 if (!NILP (Vrun_hooks))
2035 call1 (Vrun_hooks, Qbuffer_list_update_hook);
2037 return Qnil;
2040 DEFUN ("set-buffer-major-mode", Fset_buffer_major_mode, Sset_buffer_major_mode, 1, 1, 0,
2041 doc: /* Set an appropriate major mode for BUFFER.
2042 For the *scratch* buffer, use `initial-major-mode', otherwise choose a mode
2043 according to `default-major-mode'.
2044 Use this function before selecting the buffer, since it may need to inspect
2045 the current buffer's major mode. */)
2046 (Lisp_Object buffer)
2048 ptrdiff_t count;
2049 Lisp_Object function;
2051 CHECK_BUFFER (buffer);
2053 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
2054 error ("Attempt to set major mode for a dead buffer");
2056 if (strcmp (SSDATA (BVAR (XBUFFER (buffer), name)), "*scratch*") == 0)
2057 function = find_symbol_value (intern ("initial-major-mode"));
2058 else
2060 function = BVAR (&buffer_defaults, major_mode);
2061 if (NILP (function)
2062 && NILP (Fget (BVAR (current_buffer, major_mode), Qmode_class)))
2063 function = BVAR (current_buffer, major_mode);
2066 if (NILP (function) || EQ (function, Qfundamental_mode))
2067 return Qnil;
2069 count = SPECPDL_INDEX ();
2071 /* To select a nonfundamental mode,
2072 select the buffer temporarily and then call the mode function. */
2074 record_unwind_protect (save_excursion_restore, save_excursion_save ());
2076 Fset_buffer (buffer);
2077 call0 (function);
2079 return unbind_to (count, Qnil);
2082 DEFUN ("current-buffer", Fcurrent_buffer, Scurrent_buffer, 0, 0, 0,
2083 doc: /* Return the current buffer as a Lisp object. */)
2084 (void)
2086 register Lisp_Object buf;
2087 XSETBUFFER (buf, current_buffer);
2088 return buf;
2091 /* Set the current buffer to B, and do not set windows_or_buffers_changed.
2092 This is used by redisplay. */
2094 void
2095 set_buffer_internal_1 (register struct buffer *b)
2097 register struct buffer *old_buf;
2098 register Lisp_Object tail;
2100 #ifdef USE_MMAP_FOR_BUFFERS
2101 if (b->text->beg == NULL)
2102 enlarge_buffer_text (b, 0);
2103 #endif /* USE_MMAP_FOR_BUFFERS */
2105 if (current_buffer == b)
2106 return;
2108 old_buf = current_buffer;
2109 current_buffer = b;
2110 last_known_column_point = -1; /* invalidate indentation cache */
2112 if (old_buf)
2114 /* Put the undo list back in the base buffer, so that it appears
2115 that an indirect buffer shares the undo list of its base. */
2116 if (old_buf->base_buffer)
2117 bset_undo_list (old_buf->base_buffer, BVAR (old_buf, undo_list));
2119 /* If the old current buffer has markers to record PT, BEGV and ZV
2120 when it is not current, update them now. */
2121 record_buffer_markers (old_buf);
2124 /* Get the undo list from the base buffer, so that it appears
2125 that an indirect buffer shares the undo list of its base. */
2126 if (b->base_buffer)
2127 bset_undo_list (b, BVAR (b->base_buffer, undo_list));
2129 /* If the new current buffer has markers to record PT, BEGV and ZV
2130 when it is not current, fetch them now. */
2131 fetch_buffer_markers (b);
2133 /* Look down buffer's list of local Lisp variables
2134 to find and update any that forward into C variables. */
2138 for (tail = BVAR (b, local_var_alist); CONSP (tail); tail = XCDR (tail))
2140 Lisp_Object var = XCAR (XCAR (tail));
2141 struct Lisp_Symbol *sym = XSYMBOL (var);
2142 if (sym->redirect == SYMBOL_LOCALIZED /* Just to be sure. */
2143 && SYMBOL_BLV (sym)->fwd)
2144 /* Just reference the variable
2145 to cause it to become set for this buffer. */
2146 Fsymbol_value (var);
2149 /* Do the same with any others that were local to the previous buffer */
2150 while (b != old_buf && (b = old_buf, b));
2153 /* Switch to buffer B temporarily for redisplay purposes.
2154 This avoids certain things that don't need to be done within redisplay. */
2156 void
2157 set_buffer_temp (struct buffer *b)
2159 register struct buffer *old_buf;
2161 if (current_buffer == b)
2162 return;
2164 old_buf = current_buffer;
2165 current_buffer = b;
2167 /* If the old current buffer has markers to record PT, BEGV and ZV
2168 when it is not current, update them now. */
2169 record_buffer_markers (old_buf);
2171 /* If the new current buffer has markers to record PT, BEGV and ZV
2172 when it is not current, fetch them now. */
2173 fetch_buffer_markers (b);
2176 DEFUN ("set-buffer", Fset_buffer, Sset_buffer, 1, 1, 0,
2177 doc: /* Make buffer BUFFER-OR-NAME current for editing operations.
2178 BUFFER-OR-NAME may be a buffer or the name of an existing buffer. See
2179 also `save-excursion' when you want to make a buffer current
2180 temporarily. This function does not display the buffer, so its effect
2181 ends when the current command terminates. Use `switch-to-buffer' or
2182 `pop-to-buffer' to switch buffers permanently. */)
2183 (register Lisp_Object buffer_or_name)
2185 register Lisp_Object buffer;
2186 buffer = Fget_buffer (buffer_or_name);
2187 if (NILP (buffer))
2188 nsberror (buffer_or_name);
2189 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
2190 error ("Selecting deleted buffer");
2191 set_buffer_internal (XBUFFER (buffer));
2192 return buffer;
2195 /* Set the current buffer to BUFFER provided if it is alive. */
2197 Lisp_Object
2198 set_buffer_if_live (Lisp_Object buffer)
2200 if (BUFFER_LIVE_P (XBUFFER (buffer)))
2201 set_buffer_internal (XBUFFER (buffer));
2202 return Qnil;
2205 DEFUN ("barf-if-buffer-read-only", Fbarf_if_buffer_read_only,
2206 Sbarf_if_buffer_read_only, 0, 0, 0,
2207 doc: /* Signal a `buffer-read-only' error if the current buffer is read-only. */)
2208 (void)
2210 if (!NILP (BVAR (current_buffer, read_only))
2211 && NILP (Vinhibit_read_only))
2212 xsignal1 (Qbuffer_read_only, Fcurrent_buffer ());
2213 return Qnil;
2216 DEFUN ("erase-buffer", Ferase_buffer, Serase_buffer, 0, 0, "*",
2217 doc: /* Delete the entire contents of the current buffer.
2218 Any narrowing restriction in effect (see `narrow-to-region') is removed,
2219 so the buffer is truly empty after this. */)
2220 (void)
2222 Fwiden ();
2224 del_range (BEG, Z);
2226 current_buffer->last_window_start = 1;
2227 /* Prevent warnings, or suspension of auto saving, that would happen
2228 if future size is less than past size. Use of erase-buffer
2229 implies that the future text is not really related to the past text. */
2230 XSETFASTINT (BVAR (current_buffer, save_length), 0);
2231 return Qnil;
2234 void
2235 validate_region (register Lisp_Object *b, register Lisp_Object *e)
2237 CHECK_NUMBER_COERCE_MARKER (*b);
2238 CHECK_NUMBER_COERCE_MARKER (*e);
2240 if (XINT (*b) > XINT (*e))
2242 Lisp_Object tem;
2243 tem = *b; *b = *e; *e = tem;
2246 if (! (BEGV <= XINT (*b) && XINT (*e) <= ZV))
2247 args_out_of_range (*b, *e);
2250 /* Advance BYTE_POS up to a character boundary
2251 and return the adjusted position. */
2253 static ptrdiff_t
2254 advance_to_char_boundary (ptrdiff_t byte_pos)
2256 int c;
2258 if (byte_pos == BEG)
2259 /* Beginning of buffer is always a character boundary. */
2260 return BEG;
2262 c = FETCH_BYTE (byte_pos);
2263 if (! CHAR_HEAD_P (c))
2265 /* We should advance BYTE_POS only when C is a constituent of a
2266 multibyte sequence. */
2267 ptrdiff_t orig_byte_pos = byte_pos;
2271 byte_pos--;
2272 c = FETCH_BYTE (byte_pos);
2274 while (! CHAR_HEAD_P (c) && byte_pos > BEG);
2275 INC_POS (byte_pos);
2276 if (byte_pos < orig_byte_pos)
2277 byte_pos = orig_byte_pos;
2278 /* If C is a constituent of a multibyte sequence, BYTE_POS was
2279 surely advance to the correct character boundary. If C is
2280 not, BYTE_POS was unchanged. */
2283 return byte_pos;
2286 DEFUN ("buffer-swap-text", Fbuffer_swap_text, Sbuffer_swap_text,
2287 1, 1, 0,
2288 doc: /* Swap the text between current buffer and BUFFER. */)
2289 (Lisp_Object buffer)
2291 struct buffer *other_buffer;
2292 CHECK_BUFFER (buffer);
2293 other_buffer = XBUFFER (buffer);
2295 if (!BUFFER_LIVE_P (other_buffer))
2296 error ("Cannot swap a dead buffer's text");
2298 /* Actually, it probably works just fine.
2299 * if (other_buffer == current_buffer)
2300 * error ("Cannot swap a buffer's text with itself"); */
2302 /* Actually, this may be workable as well, tho probably only if they're
2303 *both* indirect. */
2304 if (other_buffer->base_buffer
2305 || current_buffer->base_buffer)
2306 error ("Cannot swap indirect buffers's text");
2308 { /* This is probably harder to make work. */
2309 struct buffer *other;
2310 FOR_EACH_BUFFER (other)
2311 if (other->base_buffer == other_buffer
2312 || other->base_buffer == current_buffer)
2313 error ("One of the buffers to swap has indirect buffers");
2316 #define swapfield(field, type) \
2317 do { \
2318 type tmp##field = other_buffer->field; \
2319 other_buffer->field = current_buffer->field; \
2320 current_buffer->field = tmp##field; \
2321 } while (0)
2322 #define swapfield_(field, type) \
2323 do { \
2324 type tmp##field = BVAR (other_buffer, field); \
2325 bset_##field (other_buffer, BVAR (current_buffer, field)); \
2326 bset_##field (current_buffer, tmp##field); \
2327 } while (0)
2329 swapfield (own_text, struct buffer_text);
2330 eassert (current_buffer->text == &current_buffer->own_text);
2331 eassert (other_buffer->text == &other_buffer->own_text);
2332 #ifdef REL_ALLOC
2333 r_alloc_reset_variable ((void **) &current_buffer->own_text.beg,
2334 (void **) &other_buffer->own_text.beg);
2335 r_alloc_reset_variable ((void **) &other_buffer->own_text.beg,
2336 (void **) &current_buffer->own_text.beg);
2337 #endif /* REL_ALLOC */
2339 swapfield (pt, ptrdiff_t);
2340 swapfield (pt_byte, ptrdiff_t);
2341 swapfield (begv, ptrdiff_t);
2342 swapfield (begv_byte, ptrdiff_t);
2343 swapfield (zv, ptrdiff_t);
2344 swapfield (zv_byte, ptrdiff_t);
2345 eassert (!current_buffer->base_buffer);
2346 eassert (!other_buffer->base_buffer);
2347 swapfield (indirections, ptrdiff_t);
2348 current_buffer->clip_changed = 1; other_buffer->clip_changed = 1;
2349 swapfield (newline_cache, struct region_cache *);
2350 swapfield (width_run_cache, struct region_cache *);
2351 current_buffer->prevent_redisplay_optimizations_p = 1;
2352 other_buffer->prevent_redisplay_optimizations_p = 1;
2353 swapfield (overlays_before, struct Lisp_Overlay *);
2354 swapfield (overlays_after, struct Lisp_Overlay *);
2355 swapfield (overlay_center, ptrdiff_t);
2356 swapfield_ (undo_list, Lisp_Object);
2357 swapfield_ (mark, Lisp_Object);
2358 swapfield_ (enable_multibyte_characters, Lisp_Object);
2359 swapfield_ (bidi_display_reordering, Lisp_Object);
2360 swapfield_ (bidi_paragraph_direction, Lisp_Object);
2361 /* FIXME: Not sure what we should do with these *_marker fields.
2362 Hopefully they're just nil anyway. */
2363 swapfield_ (pt_marker, Lisp_Object);
2364 swapfield_ (begv_marker, Lisp_Object);
2365 swapfield_ (zv_marker, Lisp_Object);
2366 bset_point_before_scroll (current_buffer, Qnil);
2367 bset_point_before_scroll (other_buffer, Qnil);
2369 current_buffer->text->modiff++; other_buffer->text->modiff++;
2370 current_buffer->text->chars_modiff++; other_buffer->text->chars_modiff++;
2371 current_buffer->text->overlay_modiff++; other_buffer->text->overlay_modiff++;
2372 current_buffer->text->beg_unchanged = current_buffer->text->gpt;
2373 current_buffer->text->end_unchanged = current_buffer->text->gpt;
2374 other_buffer->text->beg_unchanged = other_buffer->text->gpt;
2375 other_buffer->text->end_unchanged = other_buffer->text->gpt;
2377 struct Lisp_Marker *m;
2378 for (m = BUF_MARKERS (current_buffer); m; m = m->next)
2379 if (m->buffer == other_buffer)
2380 m->buffer = current_buffer;
2381 else
2382 /* Since there's no indirect buffer in sight, markers on
2383 BUF_MARKERS(buf) should either be for `buf' or dead. */
2384 eassert (!m->buffer);
2385 for (m = BUF_MARKERS (other_buffer); m; m = m->next)
2386 if (m->buffer == current_buffer)
2387 m->buffer = other_buffer;
2388 else
2389 /* Since there's no indirect buffer in sight, markers on
2390 BUF_MARKERS(buf) should either be for `buf' or dead. */
2391 eassert (!m->buffer);
2393 { /* Some of the C code expects that w->buffer == w->pointm->buffer.
2394 So since we just swapped the markers between the two buffers, we need
2395 to undo the effect of this swap for window markers. */
2396 Lisp_Object w = Fselected_window (), ws = Qnil;
2397 Lisp_Object buf1, buf2;
2398 XSETBUFFER (buf1, current_buffer); XSETBUFFER (buf2, other_buffer);
2400 while (NILP (Fmemq (w, ws)))
2402 ws = Fcons (w, ws);
2403 if (MARKERP (XWINDOW (w)->pointm)
2404 && (EQ (XWINDOW (w)->buffer, buf1)
2405 || EQ (XWINDOW (w)->buffer, buf2)))
2406 Fset_marker (XWINDOW (w)->pointm,
2407 make_number
2408 (BUF_BEGV (XBUFFER (XWINDOW (w)->buffer))),
2409 XWINDOW (w)->buffer);
2410 w = Fnext_window (w, Qt, Qt);
2414 if (current_buffer->text->intervals)
2415 (eassert (EQ (current_buffer->text->intervals->up.obj, buffer)),
2416 XSETBUFFER (current_buffer->text->intervals->up.obj, current_buffer));
2417 if (other_buffer->text->intervals)
2418 (eassert (EQ (other_buffer->text->intervals->up.obj, Fcurrent_buffer ())),
2419 XSETBUFFER (other_buffer->text->intervals->up.obj, other_buffer));
2421 return Qnil;
2424 DEFUN ("set-buffer-multibyte", Fset_buffer_multibyte, Sset_buffer_multibyte,
2425 1, 1, 0,
2426 doc: /* Set the multibyte flag of the current buffer to FLAG.
2427 If FLAG is t, this makes the buffer a multibyte buffer.
2428 If FLAG is nil, this makes the buffer a single-byte buffer.
2429 In these cases, the buffer contents remain unchanged as a sequence of
2430 bytes but the contents viewed as characters do change.
2431 If FLAG is `to', this makes the buffer a multibyte buffer by changing
2432 all eight-bit bytes to eight-bit characters.
2433 If the multibyte flag was really changed, undo information of the
2434 current buffer is cleared. */)
2435 (Lisp_Object flag)
2437 struct Lisp_Marker *tail, *markers;
2438 struct buffer *other;
2439 ptrdiff_t begv, zv;
2440 bool narrowed = (BEG != BEGV || Z != ZV);
2441 bool modified_p = !NILP (Fbuffer_modified_p (Qnil));
2442 Lisp_Object old_undo = BVAR (current_buffer, undo_list);
2443 struct gcpro gcpro1;
2445 if (current_buffer->base_buffer)
2446 error ("Cannot do `set-buffer-multibyte' on an indirect buffer");
2448 /* Do nothing if nothing actually changes. */
2449 if (NILP (flag) == NILP (BVAR (current_buffer, enable_multibyte_characters)))
2450 return flag;
2452 GCPRO1 (old_undo);
2454 /* Don't record these buffer changes. We will put a special undo entry
2455 instead. */
2456 bset_undo_list (current_buffer, Qt);
2458 /* If the cached position is for this buffer, clear it out. */
2459 clear_charpos_cache (current_buffer);
2461 if (NILP (flag))
2462 begv = BEGV_BYTE, zv = ZV_BYTE;
2463 else
2464 begv = BEGV, zv = ZV;
2466 if (narrowed)
2467 error ("Changing multibyteness in a narrowed buffer");
2469 if (NILP (flag))
2471 ptrdiff_t pos, stop;
2472 unsigned char *p;
2474 /* Do this first, so it can use CHAR_TO_BYTE
2475 to calculate the old correspondences. */
2476 set_intervals_multibyte (0);
2478 bset_enable_multibyte_characters (current_buffer, Qnil);
2480 Z = Z_BYTE;
2481 BEGV = BEGV_BYTE;
2482 ZV = ZV_BYTE;
2483 GPT = GPT_BYTE;
2484 TEMP_SET_PT_BOTH (PT_BYTE, PT_BYTE);
2487 for (tail = BUF_MARKERS (current_buffer); tail; tail = tail->next)
2488 tail->charpos = tail->bytepos;
2490 /* Convert multibyte form of 8-bit characters to unibyte. */
2491 pos = BEG;
2492 stop = GPT;
2493 p = BEG_ADDR;
2494 while (1)
2496 int c, bytes;
2498 if (pos == stop)
2500 if (pos == Z)
2501 break;
2502 p = GAP_END_ADDR;
2503 stop = Z;
2505 if (ASCII_BYTE_P (*p))
2506 p++, pos++;
2507 else if (CHAR_BYTE8_HEAD_P (*p))
2509 c = STRING_CHAR_AND_LENGTH (p, bytes);
2510 /* Delete all bytes for this 8-bit character but the
2511 last one, and change the last one to the character
2512 code. */
2513 bytes--;
2514 del_range_2 (pos, pos, pos + bytes, pos + bytes, 0);
2515 p = GAP_END_ADDR;
2516 *p++ = c;
2517 pos++;
2518 if (begv > pos)
2519 begv -= bytes;
2520 if (zv > pos)
2521 zv -= bytes;
2522 stop = Z;
2524 else
2526 bytes = BYTES_BY_CHAR_HEAD (*p);
2527 p += bytes, pos += bytes;
2530 if (narrowed)
2531 Fnarrow_to_region (make_number (begv), make_number (zv));
2533 else
2535 ptrdiff_t pt = PT;
2536 ptrdiff_t pos, stop;
2537 unsigned char *p, *pend;
2539 /* Be sure not to have a multibyte sequence striding over the GAP.
2540 Ex: We change this: "...abc\302 _GAP_ \241def..."
2541 to: "...abc _GAP_ \302\241def..." */
2543 if (EQ (flag, Qt)
2544 && GPT_BYTE > 1 && GPT_BYTE < Z_BYTE
2545 && ! CHAR_HEAD_P (*(GAP_END_ADDR)))
2547 unsigned char *q = GPT_ADDR - 1;
2549 while (! CHAR_HEAD_P (*q) && q > BEG_ADDR) q--;
2550 if (LEADING_CODE_P (*q))
2552 ptrdiff_t new_gpt = GPT_BYTE - (GPT_ADDR - q);
2554 move_gap_both (new_gpt, new_gpt);
2558 /* Make the buffer contents valid as multibyte by converting
2559 8-bit characters to multibyte form. */
2560 pos = BEG;
2561 stop = GPT;
2562 p = BEG_ADDR;
2563 pend = GPT_ADDR;
2564 while (1)
2566 int bytes;
2568 if (pos == stop)
2570 if (pos == Z)
2571 break;
2572 p = GAP_END_ADDR;
2573 pend = Z_ADDR;
2574 stop = Z;
2577 if (ASCII_BYTE_P (*p))
2578 p++, pos++;
2579 else if (EQ (flag, Qt)
2580 && ! CHAR_BYTE8_HEAD_P (*p)
2581 && (bytes = MULTIBYTE_LENGTH (p, pend)) > 0)
2582 p += bytes, pos += bytes;
2583 else
2585 unsigned char tmp[MAX_MULTIBYTE_LENGTH];
2586 int c;
2588 c = BYTE8_TO_CHAR (*p);
2589 bytes = CHAR_STRING (c, tmp);
2590 *p = tmp[0];
2591 TEMP_SET_PT_BOTH (pos + 1, pos + 1);
2592 bytes--;
2593 insert_1_both ((char *) tmp + 1, bytes, bytes, 1, 0, 0);
2594 /* Now the gap is after the just inserted data. */
2595 pos = GPT;
2596 p = GAP_END_ADDR;
2597 if (pos <= begv)
2598 begv += bytes;
2599 if (pos <= zv)
2600 zv += bytes;
2601 if (pos <= pt)
2602 pt += bytes;
2603 pend = Z_ADDR;
2604 stop = Z;
2608 if (pt != PT)
2609 TEMP_SET_PT (pt);
2611 if (narrowed)
2612 Fnarrow_to_region (make_number (begv), make_number (zv));
2614 /* Do this first, so that chars_in_text asks the right question.
2615 set_intervals_multibyte needs it too. */
2616 bset_enable_multibyte_characters (current_buffer, Qt);
2618 GPT_BYTE = advance_to_char_boundary (GPT_BYTE);
2619 GPT = chars_in_text (BEG_ADDR, GPT_BYTE - BEG_BYTE) + BEG;
2621 Z = chars_in_text (GAP_END_ADDR, Z_BYTE - GPT_BYTE) + GPT;
2623 BEGV_BYTE = advance_to_char_boundary (BEGV_BYTE);
2624 if (BEGV_BYTE > GPT_BYTE)
2625 BEGV = chars_in_text (GAP_END_ADDR, BEGV_BYTE - GPT_BYTE) + GPT;
2626 else
2627 BEGV = chars_in_text (BEG_ADDR, BEGV_BYTE - BEG_BYTE) + BEG;
2629 ZV_BYTE = advance_to_char_boundary (ZV_BYTE);
2630 if (ZV_BYTE > GPT_BYTE)
2631 ZV = chars_in_text (GAP_END_ADDR, ZV_BYTE - GPT_BYTE) + GPT;
2632 else
2633 ZV = chars_in_text (BEG_ADDR, ZV_BYTE - BEG_BYTE) + BEG;
2636 ptrdiff_t byte = advance_to_char_boundary (PT_BYTE);
2637 ptrdiff_t position;
2639 if (byte > GPT_BYTE)
2640 position = chars_in_text (GAP_END_ADDR, byte - GPT_BYTE) + GPT;
2641 else
2642 position = chars_in_text (BEG_ADDR, byte - BEG_BYTE) + BEG;
2643 TEMP_SET_PT_BOTH (position, byte);
2646 tail = markers = BUF_MARKERS (current_buffer);
2648 /* This prevents BYTE_TO_CHAR (that is, buf_bytepos_to_charpos) from
2649 getting confused by the markers that have not yet been updated.
2650 It is also a signal that it should never create a marker. */
2651 BUF_MARKERS (current_buffer) = NULL;
2653 for (; tail; tail = tail->next)
2655 tail->bytepos = advance_to_char_boundary (tail->bytepos);
2656 tail->charpos = BYTE_TO_CHAR (tail->bytepos);
2659 /* Make sure no markers were put on the chain
2660 while the chain value was incorrect. */
2661 if (BUF_MARKERS (current_buffer))
2662 emacs_abort ();
2664 BUF_MARKERS (current_buffer) = markers;
2666 /* Do this last, so it can calculate the new correspondences
2667 between chars and bytes. */
2668 set_intervals_multibyte (1);
2671 if (!EQ (old_undo, Qt))
2673 /* Represent all the above changes by a special undo entry. */
2674 bset_undo_list (current_buffer,
2675 Fcons (list3 (Qapply,
2676 intern ("set-buffer-multibyte"),
2677 NILP (flag) ? Qt : Qnil),
2678 old_undo));
2681 UNGCPRO;
2683 /* Changing the multibyteness of a buffer means that all windows
2684 showing that buffer must be updated thoroughly. */
2685 current_buffer->prevent_redisplay_optimizations_p = 1;
2686 ++windows_or_buffers_changed;
2688 /* Copy this buffer's new multibyte status
2689 into all of its indirect buffers. */
2690 FOR_EACH_BUFFER (other)
2691 if (other->base_buffer == current_buffer && BUFFER_LIVE_P (other))
2693 BVAR (other, enable_multibyte_characters)
2694 = BVAR (current_buffer, enable_multibyte_characters);
2695 other->prevent_redisplay_optimizations_p = 1;
2698 /* Restore the modifiedness of the buffer. */
2699 if (!modified_p && !NILP (Fbuffer_modified_p (Qnil)))
2700 Fset_buffer_modified_p (Qnil);
2702 /* Update coding systems of this buffer's process (if any). */
2704 Lisp_Object process;
2706 process = Fget_buffer_process (Fcurrent_buffer ());
2707 if (PROCESSP (process))
2708 setup_process_coding_systems (process);
2711 return flag;
2714 DEFUN ("kill-all-local-variables", Fkill_all_local_variables,
2715 Skill_all_local_variables, 0, 0, 0,
2716 doc: /* Switch to Fundamental mode by killing current buffer's local variables.
2717 Most local variable bindings are eliminated so that the default values
2718 become effective once more. Also, the syntax table is set from
2719 `standard-syntax-table', the local keymap is set to nil,
2720 and the abbrev table from `fundamental-mode-abbrev-table'.
2721 This function also forces redisplay of the mode line.
2723 Every function to select a new major mode starts by
2724 calling this function.
2726 As a special exception, local variables whose names have
2727 a non-nil `permanent-local' property are not eliminated by this function.
2729 The first thing this function does is run
2730 the normal hook `change-major-mode-hook'. */)
2731 (void)
2733 Frun_hooks (1, &Qchange_major_mode_hook);
2735 /* Make sure none of the bindings in local_var_alist
2736 remain swapped in, in their symbols. */
2738 swap_out_buffer_local_variables (current_buffer);
2740 /* Actually eliminate all local bindings of this buffer. */
2742 reset_buffer_local_variables (current_buffer, 0);
2744 /* Force mode-line redisplay. Useful here because all major mode
2745 commands call this function. */
2746 update_mode_lines++;
2748 return Qnil;
2751 /* Make sure no local variables remain set up with buffer B
2752 for their current values. */
2754 static void
2755 swap_out_buffer_local_variables (struct buffer *b)
2757 Lisp_Object oalist, alist, buffer;
2759 XSETBUFFER (buffer, b);
2760 oalist = BVAR (b, local_var_alist);
2762 for (alist = oalist; CONSP (alist); alist = XCDR (alist))
2764 Lisp_Object sym = XCAR (XCAR (alist));
2765 eassert (XSYMBOL (sym)->redirect == SYMBOL_LOCALIZED);
2766 /* Need not do anything if some other buffer's binding is
2767 now cached. */
2768 if (EQ (SYMBOL_BLV (XSYMBOL (sym))->where, buffer))
2770 /* Symbol is set up for this buffer's old local value:
2771 swap it out! */
2772 swap_in_global_binding (XSYMBOL (sym));
2777 /* Find all the overlays in the current buffer that contain position POS.
2778 Return the number found, and store them in a vector in *VEC_PTR.
2779 Store in *LEN_PTR the size allocated for the vector.
2780 Store in *NEXT_PTR the next position after POS where an overlay starts,
2781 or ZV if there are no more overlays between POS and ZV.
2782 Store in *PREV_PTR the previous position before POS where an overlay ends,
2783 or where an overlay starts which ends at or after POS;
2784 or BEGV if there are no such overlays from BEGV to POS.
2785 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2787 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2788 when this function is called.
2790 If EXTEND, make the vector bigger if necessary.
2791 If not, never extend the vector,
2792 and store only as many overlays as will fit.
2793 But still return the total number of overlays.
2795 If CHANGE_REQ, any position written into *PREV_PTR or
2796 *NEXT_PTR is guaranteed to be not equal to POS, unless it is the
2797 default (BEGV or ZV). */
2799 ptrdiff_t
2800 overlays_at (EMACS_INT pos, bool extend, Lisp_Object **vec_ptr,
2801 ptrdiff_t *len_ptr,
2802 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr, bool change_req)
2804 Lisp_Object overlay, start, end;
2805 struct Lisp_Overlay *tail;
2806 ptrdiff_t idx = 0;
2807 ptrdiff_t len = *len_ptr;
2808 Lisp_Object *vec = *vec_ptr;
2809 ptrdiff_t next = ZV;
2810 ptrdiff_t prev = BEGV;
2811 bool inhibit_storing = 0;
2813 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2815 ptrdiff_t startpos, endpos;
2817 XSETMISC (overlay, tail);
2819 start = OVERLAY_START (overlay);
2820 end = OVERLAY_END (overlay);
2821 endpos = OVERLAY_POSITION (end);
2822 if (endpos < pos)
2824 if (prev < endpos)
2825 prev = endpos;
2826 break;
2828 startpos = OVERLAY_POSITION (start);
2829 /* This one ends at or after POS
2830 so its start counts for PREV_PTR if it's before POS. */
2831 if (prev < startpos && startpos < pos)
2832 prev = startpos;
2833 if (endpos == pos)
2834 continue;
2835 if (startpos <= pos)
2837 if (idx == len)
2839 /* The supplied vector is full.
2840 Either make it bigger, or don't store any more in it. */
2841 if (extend)
2843 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2844 sizeof *vec);
2845 *vec_ptr = vec;
2846 len = *len_ptr;
2848 else
2849 inhibit_storing = 1;
2852 if (!inhibit_storing)
2853 vec[idx] = overlay;
2854 /* Keep counting overlays even if we can't return them all. */
2855 idx++;
2857 else if (startpos < next)
2858 next = startpos;
2861 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2863 ptrdiff_t startpos, endpos;
2865 XSETMISC (overlay, tail);
2867 start = OVERLAY_START (overlay);
2868 end = OVERLAY_END (overlay);
2869 startpos = OVERLAY_POSITION (start);
2870 if (pos < startpos)
2872 if (startpos < next)
2873 next = startpos;
2874 break;
2876 endpos = OVERLAY_POSITION (end);
2877 if (pos < endpos)
2879 if (idx == len)
2881 if (extend)
2883 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2884 sizeof *vec);
2885 *vec_ptr = vec;
2886 len = *len_ptr;
2888 else
2889 inhibit_storing = 1;
2892 if (!inhibit_storing)
2893 vec[idx] = overlay;
2894 idx++;
2896 if (startpos < pos && startpos > prev)
2897 prev = startpos;
2899 else if (endpos < pos && endpos > prev)
2900 prev = endpos;
2901 else if (endpos == pos && startpos > prev
2902 && (!change_req || startpos < pos))
2903 prev = startpos;
2906 if (next_ptr)
2907 *next_ptr = next;
2908 if (prev_ptr)
2909 *prev_ptr = prev;
2910 return idx;
2913 /* Find all the overlays in the current buffer that overlap the range
2914 BEG-END, or are empty at BEG, or are empty at END provided END
2915 denotes the position at the end of the current buffer.
2917 Return the number found, and store them in a vector in *VEC_PTR.
2918 Store in *LEN_PTR the size allocated for the vector.
2919 Store in *NEXT_PTR the next position after POS where an overlay starts,
2920 or ZV if there are no more overlays.
2921 Store in *PREV_PTR the previous position before POS where an overlay ends,
2922 or BEGV if there are no previous overlays.
2923 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2925 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2926 when this function is called.
2928 If EXTEND, make the vector bigger if necessary.
2929 If not, never extend the vector,
2930 and store only as many overlays as will fit.
2931 But still return the total number of overlays. */
2933 static ptrdiff_t
2934 overlays_in (EMACS_INT beg, EMACS_INT end, bool extend,
2935 Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
2936 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr)
2938 Lisp_Object overlay, ostart, oend;
2939 struct Lisp_Overlay *tail;
2940 ptrdiff_t idx = 0;
2941 ptrdiff_t len = *len_ptr;
2942 Lisp_Object *vec = *vec_ptr;
2943 ptrdiff_t next = ZV;
2944 ptrdiff_t prev = BEGV;
2945 bool inhibit_storing = 0;
2946 bool end_is_Z = end == Z;
2948 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2950 ptrdiff_t startpos, endpos;
2952 XSETMISC (overlay, tail);
2954 ostart = OVERLAY_START (overlay);
2955 oend = OVERLAY_END (overlay);
2956 endpos = OVERLAY_POSITION (oend);
2957 if (endpos < beg)
2959 if (prev < endpos)
2960 prev = endpos;
2961 break;
2963 startpos = OVERLAY_POSITION (ostart);
2964 /* Count an interval if it overlaps the range, is empty at the
2965 start of the range, or is empty at END provided END denotes the
2966 end of the buffer. */
2967 if ((beg < endpos && startpos < end)
2968 || (startpos == endpos
2969 && (beg == endpos || (end_is_Z && endpos == end))))
2971 if (idx == len)
2973 /* The supplied vector is full.
2974 Either make it bigger, or don't store any more in it. */
2975 if (extend)
2977 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2978 sizeof *vec);
2979 *vec_ptr = vec;
2980 len = *len_ptr;
2982 else
2983 inhibit_storing = 1;
2986 if (!inhibit_storing)
2987 vec[idx] = overlay;
2988 /* Keep counting overlays even if we can't return them all. */
2989 idx++;
2991 else if (startpos < next)
2992 next = startpos;
2995 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2997 ptrdiff_t startpos, endpos;
2999 XSETMISC (overlay, tail);
3001 ostart = OVERLAY_START (overlay);
3002 oend = OVERLAY_END (overlay);
3003 startpos = OVERLAY_POSITION (ostart);
3004 if (end < startpos)
3006 if (startpos < next)
3007 next = startpos;
3008 break;
3010 endpos = OVERLAY_POSITION (oend);
3011 /* Count an interval if it overlaps the range, is empty at the
3012 start of the range, or is empty at END provided END denotes the
3013 end of the buffer. */
3014 if ((beg < endpos && startpos < end)
3015 || (startpos == endpos
3016 && (beg == endpos || (end_is_Z && endpos == end))))
3018 if (idx == len)
3020 if (extend)
3022 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
3023 sizeof *vec);
3024 *vec_ptr = vec;
3025 len = *len_ptr;
3027 else
3028 inhibit_storing = 1;
3031 if (!inhibit_storing)
3032 vec[idx] = overlay;
3033 idx++;
3035 else if (endpos < beg && endpos > prev)
3036 prev = endpos;
3039 if (next_ptr)
3040 *next_ptr = next;
3041 if (prev_ptr)
3042 *prev_ptr = prev;
3043 return idx;
3047 /* Return true if there exists an overlay with a non-nil
3048 `mouse-face' property overlapping OVERLAY. */
3050 bool
3051 mouse_face_overlay_overlaps (Lisp_Object overlay)
3053 ptrdiff_t start = OVERLAY_POSITION (OVERLAY_START (overlay));
3054 ptrdiff_t end = OVERLAY_POSITION (OVERLAY_END (overlay));
3055 ptrdiff_t n, i, size;
3056 Lisp_Object *v, tem;
3058 size = 10;
3059 v = alloca (size * sizeof *v);
3060 n = overlays_in (start, end, 0, &v, &size, NULL, NULL);
3061 if (n > size)
3063 v = alloca (n * sizeof *v);
3064 overlays_in (start, end, 0, &v, &n, NULL, NULL);
3067 for (i = 0; i < n; ++i)
3068 if (!EQ (v[i], overlay)
3069 && (tem = Foverlay_get (overlay, Qmouse_face),
3070 !NILP (tem)))
3071 break;
3073 return i < n;
3078 /* Fast function to just test if we're at an overlay boundary. */
3079 bool
3080 overlay_touches_p (ptrdiff_t pos)
3082 Lisp_Object overlay;
3083 struct Lisp_Overlay *tail;
3085 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
3087 ptrdiff_t endpos;
3089 XSETMISC (overlay ,tail);
3090 eassert (OVERLAYP (overlay));
3092 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3093 if (endpos < pos)
3094 break;
3095 if (endpos == pos || OVERLAY_POSITION (OVERLAY_START (overlay)) == pos)
3096 return 1;
3099 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
3101 ptrdiff_t startpos;
3103 XSETMISC (overlay, tail);
3104 eassert (OVERLAYP (overlay));
3106 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3107 if (pos < startpos)
3108 break;
3109 if (startpos == pos || OVERLAY_POSITION (OVERLAY_END (overlay)) == pos)
3110 return 1;
3112 return 0;
3115 struct sortvec
3117 Lisp_Object overlay;
3118 ptrdiff_t beg, end;
3119 EMACS_INT priority;
3122 static int
3123 compare_overlays (const void *v1, const void *v2)
3125 const struct sortvec *s1 = (const struct sortvec *) v1;
3126 const struct sortvec *s2 = (const struct sortvec *) v2;
3127 if (s1->priority != s2->priority)
3128 return s1->priority < s2->priority ? -1 : 1;
3129 if (s1->beg != s2->beg)
3130 return s1->beg < s2->beg ? -1 : 1;
3131 if (s1->end != s2->end)
3132 return s2->end < s1->end ? -1 : 1;
3133 /* Avoid the non-determinism of qsort by choosing an arbitrary ordering
3134 between "equal" overlays. The result can still change between
3135 invocations of Emacs, but it won't change in the middle of
3136 `find_field' (bug#6830). */
3137 if (XHASH (s1->overlay) != XHASH (s2->overlay))
3138 return XHASH (s1->overlay) < XHASH (s2->overlay) ? -1 : 1;
3139 return 0;
3142 /* Sort an array of overlays by priority. The array is modified in place.
3143 The return value is the new size; this may be smaller than the original
3144 size if some of the overlays were invalid or were window-specific. */
3145 ptrdiff_t
3146 sort_overlays (Lisp_Object *overlay_vec, ptrdiff_t noverlays, struct window *w)
3148 ptrdiff_t i, j;
3149 struct sortvec *sortvec = alloca (noverlays * sizeof *sortvec);
3151 /* Put the valid and relevant overlays into sortvec. */
3153 for (i = 0, j = 0; i < noverlays; i++)
3155 Lisp_Object tem;
3156 Lisp_Object overlay;
3158 overlay = overlay_vec[i];
3159 if (OVERLAYP (overlay)
3160 && OVERLAY_POSITION (OVERLAY_START (overlay)) > 0
3161 && OVERLAY_POSITION (OVERLAY_END (overlay)) > 0)
3163 /* If we're interested in a specific window, then ignore
3164 overlays that are limited to some other window. */
3165 if (w)
3167 Lisp_Object window;
3169 window = Foverlay_get (overlay, Qwindow);
3170 if (WINDOWP (window) && XWINDOW (window) != w)
3171 continue;
3174 /* This overlay is good and counts: put it into sortvec. */
3175 sortvec[j].overlay = overlay;
3176 sortvec[j].beg = OVERLAY_POSITION (OVERLAY_START (overlay));
3177 sortvec[j].end = OVERLAY_POSITION (OVERLAY_END (overlay));
3178 tem = Foverlay_get (overlay, Qpriority);
3179 if (INTEGERP (tem))
3180 sortvec[j].priority = XINT (tem);
3181 else
3182 sortvec[j].priority = 0;
3183 j++;
3186 noverlays = j;
3188 /* Sort the overlays into the proper order: increasing priority. */
3190 if (noverlays > 1)
3191 qsort (sortvec, noverlays, sizeof (struct sortvec), compare_overlays);
3193 for (i = 0; i < noverlays; i++)
3194 overlay_vec[i] = sortvec[i].overlay;
3195 return (noverlays);
3198 struct sortstr
3200 Lisp_Object string, string2;
3201 ptrdiff_t size;
3202 EMACS_INT priority;
3205 struct sortstrlist
3207 struct sortstr *buf; /* An array that expands as needed; never freed. */
3208 ptrdiff_t size; /* Allocated length of that array. */
3209 ptrdiff_t used; /* How much of the array is currently in use. */
3210 ptrdiff_t bytes; /* Total length of the strings in buf. */
3213 /* Buffers for storing information about the overlays touching a given
3214 position. These could be automatic variables in overlay_strings, but
3215 it's more efficient to hold onto the memory instead of repeatedly
3216 allocating and freeing it. */
3217 static struct sortstrlist overlay_heads, overlay_tails;
3218 static unsigned char *overlay_str_buf;
3220 /* Allocated length of overlay_str_buf. */
3221 static ptrdiff_t overlay_str_len;
3223 /* A comparison function suitable for passing to qsort. */
3224 static int
3225 cmp_for_strings (const void *as1, const void *as2)
3227 struct sortstr *s1 = (struct sortstr *)as1;
3228 struct sortstr *s2 = (struct sortstr *)as2;
3229 if (s1->size != s2->size)
3230 return s2->size < s1->size ? -1 : 1;
3231 if (s1->priority != s2->priority)
3232 return s1->priority < s2->priority ? -1 : 1;
3233 return 0;
3236 static void
3237 record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
3238 Lisp_Object str2, Lisp_Object pri, ptrdiff_t size)
3240 ptrdiff_t nbytes;
3242 if (ssl->used == ssl->size)
3243 ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
3244 ssl->buf[ssl->used].string = str;
3245 ssl->buf[ssl->used].string2 = str2;
3246 ssl->buf[ssl->used].size = size;
3247 ssl->buf[ssl->used].priority = (INTEGERP (pri) ? XINT (pri) : 0);
3248 ssl->used++;
3250 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3251 nbytes = SCHARS (str);
3252 else if (! STRING_MULTIBYTE (str))
3253 nbytes = count_size_as_multibyte (SDATA (str),
3254 SBYTES (str));
3255 else
3256 nbytes = SBYTES (str);
3258 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3259 memory_full (SIZE_MAX);
3260 ssl->bytes += nbytes;
3262 if (STRINGP (str2))
3264 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3265 nbytes = SCHARS (str2);
3266 else if (! STRING_MULTIBYTE (str2))
3267 nbytes = count_size_as_multibyte (SDATA (str2),
3268 SBYTES (str2));
3269 else
3270 nbytes = SBYTES (str2);
3272 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3273 memory_full (SIZE_MAX);
3274 ssl->bytes += nbytes;
3278 /* Return the concatenation of the strings associated with overlays that
3279 begin or end at POS, ignoring overlays that are specific to a window
3280 other than W. The strings are concatenated in the appropriate order:
3281 shorter overlays nest inside longer ones, and higher priority inside
3282 lower. Normally all of the after-strings come first, but zero-sized
3283 overlays have their after-strings ride along with the before-strings
3284 because it would look strange to print them inside-out.
3286 Returns the string length, and stores the contents indirectly through
3287 PSTR, if that variable is non-null. The string may be overwritten by
3288 subsequent calls. */
3290 ptrdiff_t
3291 overlay_strings (ptrdiff_t pos, struct window *w, unsigned char **pstr)
3293 Lisp_Object overlay, window, str;
3294 struct Lisp_Overlay *ov;
3295 ptrdiff_t startpos, endpos;
3296 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3298 overlay_heads.used = overlay_heads.bytes = 0;
3299 overlay_tails.used = overlay_tails.bytes = 0;
3300 for (ov = current_buffer->overlays_before; ov; ov = ov->next)
3302 XSETMISC (overlay, ov);
3303 eassert (OVERLAYP (overlay));
3305 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3306 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3307 if (endpos < pos)
3308 break;
3309 if (endpos != pos && startpos != pos)
3310 continue;
3311 window = Foverlay_get (overlay, Qwindow);
3312 if (WINDOWP (window) && XWINDOW (window) != w)
3313 continue;
3314 if (startpos == pos
3315 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3316 record_overlay_string (&overlay_heads, str,
3317 (startpos == endpos
3318 ? Foverlay_get (overlay, Qafter_string)
3319 : Qnil),
3320 Foverlay_get (overlay, Qpriority),
3321 endpos - startpos);
3322 else if (endpos == pos
3323 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3324 record_overlay_string (&overlay_tails, str, Qnil,
3325 Foverlay_get (overlay, Qpriority),
3326 endpos - startpos);
3328 for (ov = current_buffer->overlays_after; ov; ov = ov->next)
3330 XSETMISC (overlay, ov);
3331 eassert (OVERLAYP (overlay));
3333 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3334 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3335 if (startpos > pos)
3336 break;
3337 if (endpos != pos && startpos != pos)
3338 continue;
3339 window = Foverlay_get (overlay, Qwindow);
3340 if (WINDOWP (window) && XWINDOW (window) != w)
3341 continue;
3342 if (startpos == pos
3343 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3344 record_overlay_string (&overlay_heads, str,
3345 (startpos == endpos
3346 ? Foverlay_get (overlay, Qafter_string)
3347 : Qnil),
3348 Foverlay_get (overlay, Qpriority),
3349 endpos - startpos);
3350 else if (endpos == pos
3351 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3352 record_overlay_string (&overlay_tails, str, Qnil,
3353 Foverlay_get (overlay, Qpriority),
3354 endpos - startpos);
3356 if (overlay_tails.used > 1)
3357 qsort (overlay_tails.buf, overlay_tails.used, sizeof (struct sortstr),
3358 cmp_for_strings);
3359 if (overlay_heads.used > 1)
3360 qsort (overlay_heads.buf, overlay_heads.used, sizeof (struct sortstr),
3361 cmp_for_strings);
3362 if (overlay_heads.bytes || overlay_tails.bytes)
3364 Lisp_Object tem;
3365 ptrdiff_t i;
3366 unsigned char *p;
3367 ptrdiff_t total;
3369 if (INT_ADD_OVERFLOW (overlay_heads.bytes, overlay_tails.bytes))
3370 memory_full (SIZE_MAX);
3371 total = overlay_heads.bytes + overlay_tails.bytes;
3372 if (total > overlay_str_len)
3373 overlay_str_buf = xpalloc (overlay_str_buf, &overlay_str_len,
3374 total - overlay_str_len, -1, 1);
3376 p = overlay_str_buf;
3377 for (i = overlay_tails.used; --i >= 0;)
3379 ptrdiff_t nbytes;
3380 tem = overlay_tails.buf[i].string;
3381 nbytes = copy_text (SDATA (tem), p,
3382 SBYTES (tem),
3383 STRING_MULTIBYTE (tem), multibyte);
3384 p += nbytes;
3386 for (i = 0; i < overlay_heads.used; ++i)
3388 ptrdiff_t nbytes;
3389 tem = overlay_heads.buf[i].string;
3390 nbytes = copy_text (SDATA (tem), p,
3391 SBYTES (tem),
3392 STRING_MULTIBYTE (tem), multibyte);
3393 p += nbytes;
3394 tem = overlay_heads.buf[i].string2;
3395 if (STRINGP (tem))
3397 nbytes = copy_text (SDATA (tem), p,
3398 SBYTES (tem),
3399 STRING_MULTIBYTE (tem), multibyte);
3400 p += nbytes;
3403 if (p != overlay_str_buf + total)
3404 emacs_abort ();
3405 if (pstr)
3406 *pstr = overlay_str_buf;
3407 return total;
3409 return 0;
3412 /* Shift overlays in BUF's overlay lists, to center the lists at POS. */
3414 void
3415 recenter_overlay_lists (struct buffer *buf, ptrdiff_t pos)
3417 Lisp_Object overlay, beg, end;
3418 struct Lisp_Overlay *prev, *tail, *next;
3420 /* See if anything in overlays_before should move to overlays_after. */
3422 /* We don't strictly need prev in this loop; it should always be nil.
3423 But we use it for symmetry and in case that should cease to be true
3424 with some future change. */
3425 prev = NULL;
3426 for (tail = buf->overlays_before; tail; prev = tail, tail = next)
3428 next = tail->next;
3429 XSETMISC (overlay, tail);
3430 eassert (OVERLAYP (overlay));
3432 beg = OVERLAY_START (overlay);
3433 end = OVERLAY_END (overlay);
3435 if (OVERLAY_POSITION (end) > pos)
3437 /* OVERLAY needs to be moved. */
3438 ptrdiff_t where = OVERLAY_POSITION (beg);
3439 struct Lisp_Overlay *other, *other_prev;
3441 /* Splice the cons cell TAIL out of overlays_before. */
3442 if (prev)
3443 prev->next = next;
3444 else
3445 set_buffer_overlays_before (buf, next);
3447 /* Search thru overlays_after for where to put it. */
3448 other_prev = NULL;
3449 for (other = buf->overlays_after; other;
3450 other_prev = other, other = other->next)
3452 Lisp_Object otherbeg, otheroverlay;
3454 XSETMISC (otheroverlay, other);
3455 eassert (OVERLAYP (otheroverlay));
3457 otherbeg = OVERLAY_START (otheroverlay);
3458 if (OVERLAY_POSITION (otherbeg) >= where)
3459 break;
3462 /* Add TAIL to overlays_after before OTHER. */
3463 tail->next = other;
3464 if (other_prev)
3465 other_prev->next = tail;
3466 else
3467 set_buffer_overlays_after (buf, tail);
3468 tail = prev;
3470 else
3471 /* We've reached the things that should stay in overlays_before.
3472 All the rest of overlays_before must end even earlier,
3473 so stop now. */
3474 break;
3477 /* See if anything in overlays_after should be in overlays_before. */
3478 prev = NULL;
3479 for (tail = buf->overlays_after; tail; prev = tail, tail = next)
3481 next = tail->next;
3482 XSETMISC (overlay, tail);
3483 eassert (OVERLAYP (overlay));
3485 beg = OVERLAY_START (overlay);
3486 end = OVERLAY_END (overlay);
3488 /* Stop looking, when we know that nothing further
3489 can possibly end before POS. */
3490 if (OVERLAY_POSITION (beg) > pos)
3491 break;
3493 if (OVERLAY_POSITION (end) <= pos)
3495 /* OVERLAY needs to be moved. */
3496 ptrdiff_t where = OVERLAY_POSITION (end);
3497 struct Lisp_Overlay *other, *other_prev;
3499 /* Splice the cons cell TAIL out of overlays_after. */
3500 if (prev)
3501 prev->next = next;
3502 else
3503 set_buffer_overlays_after (buf, next);
3505 /* Search thru overlays_before for where to put it. */
3506 other_prev = NULL;
3507 for (other = buf->overlays_before; other;
3508 other_prev = other, other = other->next)
3510 Lisp_Object otherend, otheroverlay;
3512 XSETMISC (otheroverlay, other);
3513 eassert (OVERLAYP (otheroverlay));
3515 otherend = OVERLAY_END (otheroverlay);
3516 if (OVERLAY_POSITION (otherend) <= where)
3517 break;
3520 /* Add TAIL to overlays_before before OTHER. */
3521 tail->next = other;
3522 if (other_prev)
3523 other_prev->next = tail;
3524 else
3525 set_buffer_overlays_before (buf, tail);
3526 tail = prev;
3530 buf->overlay_center = pos;
3533 void
3534 adjust_overlays_for_insert (ptrdiff_t pos, ptrdiff_t length)
3536 /* After an insertion, the lists are still sorted properly,
3537 but we may need to update the value of the overlay center. */
3538 if (current_buffer->overlay_center >= pos)
3539 current_buffer->overlay_center += length;
3542 void
3543 adjust_overlays_for_delete (ptrdiff_t pos, ptrdiff_t length)
3545 if (current_buffer->overlay_center < pos)
3546 /* The deletion was to our right. No change needed; the before- and
3547 after-lists are still consistent. */
3549 else if (current_buffer->overlay_center - pos > length)
3550 /* The deletion was to our left. We need to adjust the center value
3551 to account for the change in position, but the lists are consistent
3552 given the new value. */
3553 current_buffer->overlay_center -= length;
3554 else
3555 /* We're right in the middle. There might be things on the after-list
3556 that now belong on the before-list. Recentering will move them,
3557 and also update the center point. */
3558 recenter_overlay_lists (current_buffer, pos);
3561 /* Fix up overlays that were garbled as a result of permuting markers
3562 in the range START through END. Any overlay with at least one
3563 endpoint in this range will need to be unlinked from the overlay
3564 list and reinserted in its proper place.
3565 Such an overlay might even have negative size at this point.
3566 If so, we'll make the overlay empty. */
3567 void
3568 fix_start_end_in_overlays (register ptrdiff_t start, register ptrdiff_t end)
3570 Lisp_Object overlay;
3571 struct Lisp_Overlay *before_list IF_LINT (= NULL);
3572 struct Lisp_Overlay *after_list IF_LINT (= NULL);
3573 /* These are either nil, indicating that before_list or after_list
3574 should be assigned, or the cons cell the cdr of which should be
3575 assigned. */
3576 struct Lisp_Overlay *beforep = NULL, *afterp = NULL;
3577 /* 'Parent', likewise, indicates a cons cell or
3578 current_buffer->overlays_before or overlays_after, depending
3579 which loop we're in. */
3580 struct Lisp_Overlay *tail, *parent;
3581 ptrdiff_t startpos, endpos;
3583 /* This algorithm shifts links around instead of consing and GCing.
3584 The loop invariant is that before_list (resp. after_list) is a
3585 well-formed list except that its last element, the CDR of beforep
3586 (resp. afterp) if beforep (afterp) isn't nil or before_list
3587 (after_list) if it is, is still uninitialized. So it's not a bug
3588 that before_list isn't initialized, although it may look
3589 strange. */
3590 for (parent = NULL, tail = current_buffer->overlays_before; tail;)
3592 XSETMISC (overlay, tail);
3594 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3595 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3597 /* If the overlay is backwards, make it empty. */
3598 if (endpos < startpos)
3600 startpos = endpos;
3601 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3602 Qnil);
3605 if (endpos < start)
3606 break;
3608 if (endpos < end
3609 || (startpos >= start && startpos < end))
3611 /* Add it to the end of the wrong list. Later on,
3612 recenter_overlay_lists will move it to the right place. */
3613 if (endpos < current_buffer->overlay_center)
3615 if (!afterp)
3616 after_list = tail;
3617 else
3618 afterp->next = tail;
3619 afterp = tail;
3621 else
3623 if (!beforep)
3624 before_list = tail;
3625 else
3626 beforep->next = tail;
3627 beforep = tail;
3629 if (!parent)
3630 set_buffer_overlays_before (current_buffer, tail->next);
3631 else
3632 parent->next = tail->next;
3633 tail = tail->next;
3635 else
3636 parent = tail, tail = parent->next;
3638 for (parent = NULL, tail = current_buffer->overlays_after; tail;)
3640 XSETMISC (overlay, tail);
3642 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3643 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3645 /* If the overlay is backwards, make it empty. */
3646 if (endpos < startpos)
3648 startpos = endpos;
3649 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3650 Qnil);
3653 if (startpos >= end)
3654 break;
3656 if (startpos >= start
3657 || (endpos >= start && endpos < end))
3659 if (endpos < current_buffer->overlay_center)
3661 if (!afterp)
3662 after_list = tail;
3663 else
3664 afterp->next = tail;
3665 afterp = tail;
3667 else
3669 if (!beforep)
3670 before_list = tail;
3671 else
3672 beforep->next = tail;
3673 beforep = tail;
3675 if (!parent)
3676 set_buffer_overlays_after (current_buffer, tail->next);
3677 else
3678 parent->next = tail->next;
3679 tail = tail->next;
3681 else
3682 parent = tail, tail = parent->next;
3685 /* Splice the constructed (wrong) lists into the buffer's lists,
3686 and let the recenter function make it sane again. */
3687 if (beforep)
3689 beforep->next = current_buffer->overlays_before;
3690 set_buffer_overlays_before (current_buffer, before_list);
3693 if (afterp)
3695 afterp->next = current_buffer->overlays_after;
3696 set_buffer_overlays_after (current_buffer, after_list);
3698 recenter_overlay_lists (current_buffer, current_buffer->overlay_center);
3701 /* We have two types of overlay: the one whose ending marker is
3702 after-insertion-marker (this is the usual case) and the one whose
3703 ending marker is before-insertion-marker. When `overlays_before'
3704 contains overlays of the latter type and the former type in this
3705 order and both overlays end at inserting position, inserting a text
3706 increases only the ending marker of the latter type, which results
3707 in incorrect ordering of `overlays_before'.
3709 This function fixes ordering of overlays in the slot
3710 `overlays_before' of the buffer *BP. Before the insertion, `point'
3711 was at PREV, and now is at POS. */
3713 void
3714 fix_overlays_before (struct buffer *bp, ptrdiff_t prev, ptrdiff_t pos)
3716 /* If parent is nil, replace overlays_before; otherwise, parent->next. */
3717 struct Lisp_Overlay *tail = bp->overlays_before, *parent = NULL, *right_pair;
3718 Lisp_Object tem;
3719 ptrdiff_t end IF_LINT (= 0);
3721 /* After the insertion, the several overlays may be in incorrect
3722 order. The possibility is that, in the list `overlays_before',
3723 an overlay which ends at POS appears after an overlay which ends
3724 at PREV. Since POS is greater than PREV, we must fix the
3725 ordering of these overlays, by moving overlays ends at POS before
3726 the overlays ends at PREV. */
3728 /* At first, find a place where disordered overlays should be linked
3729 in. It is where an overlay which end before POS exists. (i.e. an
3730 overlay whose ending marker is after-insertion-marker if disorder
3731 exists). */
3732 while (tail
3733 && (XSETMISC (tem, tail),
3734 (end = OVERLAY_POSITION (OVERLAY_END (tem))) >= pos))
3736 parent = tail;
3737 tail = tail->next;
3740 /* If we don't find such an overlay,
3741 or the found one ends before PREV,
3742 or the found one is the last one in the list,
3743 we don't have to fix anything. */
3744 if (!tail || end < prev || !tail->next)
3745 return;
3747 right_pair = parent;
3748 parent = tail;
3749 tail = tail->next;
3751 /* Now, end position of overlays in the list TAIL should be before
3752 or equal to PREV. In the loop, an overlay which ends at POS is
3753 moved ahead to the place indicated by the CDR of RIGHT_PAIR. If
3754 we found an overlay which ends before PREV, the remaining
3755 overlays are in correct order. */
3756 while (tail)
3758 XSETMISC (tem, tail);
3759 end = OVERLAY_POSITION (OVERLAY_END (tem));
3761 if (end == pos)
3762 { /* This overlay is disordered. */
3763 struct Lisp_Overlay *found = tail;
3765 /* Unlink the found overlay. */
3766 tail = found->next;
3767 parent->next = tail;
3768 /* Move an overlay at RIGHT_PLACE to the next of the found one,
3769 and link it into the right place. */
3770 if (!right_pair)
3772 found->next = bp->overlays_before;
3773 set_buffer_overlays_before (bp, found);
3775 else
3777 found->next = right_pair->next;
3778 right_pair->next = found;
3781 else if (end == prev)
3783 parent = tail;
3784 tail = tail->next;
3786 else /* No more disordered overlay. */
3787 break;
3791 DEFUN ("overlayp", Foverlayp, Soverlayp, 1, 1, 0,
3792 doc: /* Return t if OBJECT is an overlay. */)
3793 (Lisp_Object object)
3795 return (OVERLAYP (object) ? Qt : Qnil);
3798 DEFUN ("make-overlay", Fmake_overlay, Smake_overlay, 2, 5, 0,
3799 doc: /* Create a new overlay with range BEG to END in BUFFER.
3800 If omitted, BUFFER defaults to the current buffer.
3801 BEG and END may be integers or markers.
3802 The fourth arg FRONT-ADVANCE, if non-nil, makes the marker
3803 for the front of the overlay advance when text is inserted there
3804 \(which means the text *is not* included in the overlay).
3805 The fifth arg REAR-ADVANCE, if non-nil, makes the marker
3806 for the rear of the overlay advance when text is inserted there
3807 \(which means the text *is* included in the overlay). */)
3808 (Lisp_Object beg, Lisp_Object end, Lisp_Object buffer, Lisp_Object front_advance, Lisp_Object rear_advance)
3810 Lisp_Object overlay;
3811 struct buffer *b;
3813 if (NILP (buffer))
3814 XSETBUFFER (buffer, current_buffer);
3815 else
3816 CHECK_BUFFER (buffer);
3817 if (MARKERP (beg)
3818 && ! EQ (Fmarker_buffer (beg), buffer))
3819 error ("Marker points into wrong buffer");
3820 if (MARKERP (end)
3821 && ! EQ (Fmarker_buffer (end), buffer))
3822 error ("Marker points into wrong buffer");
3824 CHECK_NUMBER_COERCE_MARKER (beg);
3825 CHECK_NUMBER_COERCE_MARKER (end);
3827 if (XINT (beg) > XINT (end))
3829 Lisp_Object temp;
3830 temp = beg; beg = end; end = temp;
3833 b = XBUFFER (buffer);
3835 beg = Fset_marker (Fmake_marker (), beg, buffer);
3836 end = Fset_marker (Fmake_marker (), end, buffer);
3838 if (!NILP (front_advance))
3839 XMARKER (beg)->insertion_type = 1;
3840 if (!NILP (rear_advance))
3841 XMARKER (end)->insertion_type = 1;
3843 overlay = build_overlay (beg, end, Qnil);
3845 /* Put the new overlay on the wrong list. */
3846 end = OVERLAY_END (overlay);
3847 if (OVERLAY_POSITION (end) < b->overlay_center)
3849 eassert (b->overlays_after || (XOVERLAY (overlay)->next == NULL));
3850 XOVERLAY (overlay)->next = b->overlays_after;
3851 set_buffer_overlays_after (b, XOVERLAY (overlay));
3853 else
3855 eassert (b->overlays_before || (XOVERLAY (overlay)->next == NULL));
3856 XOVERLAY (overlay)->next = b->overlays_before;
3857 set_buffer_overlays_before (b, XOVERLAY (overlay));
3859 /* This puts it in the right list, and in the right order. */
3860 recenter_overlay_lists (b, b->overlay_center);
3862 /* We don't need to redisplay the region covered by the overlay, because
3863 the overlay has no properties at the moment. */
3865 return overlay;
3868 /* Mark a section of BUF as needing redisplay because of overlays changes. */
3870 static void
3871 modify_overlay (struct buffer *buf, ptrdiff_t start, ptrdiff_t end)
3873 if (start > end)
3875 ptrdiff_t temp = start;
3876 start = end;
3877 end = temp;
3880 BUF_COMPUTE_UNCHANGED (buf, start, end);
3882 /* If this is a buffer not in the selected window,
3883 we must do other windows. */
3884 if (buf != XBUFFER (XWINDOW (selected_window)->buffer))
3885 windows_or_buffers_changed = 1;
3886 /* If multiple windows show this buffer, we must do other windows. */
3887 else if (buffer_shared > 1)
3888 windows_or_buffers_changed = 1;
3889 /* If we modify an overlay at the end of the buffer, we cannot
3890 be sure that window end is still valid. */
3891 else if (end >= ZV && start <= ZV)
3892 windows_or_buffers_changed = 1;
3894 ++BUF_OVERLAY_MODIFF (buf);
3897 /* Remove OVERLAY from LIST. */
3899 static struct Lisp_Overlay *
3900 unchain_overlay (struct Lisp_Overlay *list, struct Lisp_Overlay *overlay)
3902 register struct Lisp_Overlay *tail, **prev = &list;
3904 for (tail = list; tail; prev = &tail->next, tail = *prev)
3905 if (tail == overlay)
3907 *prev = overlay->next;
3908 overlay->next = NULL;
3909 break;
3911 return list;
3914 /* Remove OVERLAY from both overlay lists of B. */
3916 static void
3917 unchain_both (struct buffer *b, Lisp_Object overlay)
3919 struct Lisp_Overlay *ov = XOVERLAY (overlay);
3921 set_buffer_overlays_before (b, unchain_overlay (b->overlays_before, ov));
3922 set_buffer_overlays_after (b, unchain_overlay (b->overlays_after, ov));
3923 eassert (XOVERLAY (overlay)->next == NULL);
3926 DEFUN ("move-overlay", Fmove_overlay, Smove_overlay, 3, 4, 0,
3927 doc: /* Set the endpoints of OVERLAY to BEG and END in BUFFER.
3928 If BUFFER is omitted, leave OVERLAY in the same buffer it inhabits now.
3929 If BUFFER is omitted, and OVERLAY is in no buffer, put it in the current
3930 buffer. */)
3931 (Lisp_Object overlay, Lisp_Object beg, Lisp_Object end, Lisp_Object buffer)
3933 struct buffer *b, *ob = 0;
3934 Lisp_Object obuffer;
3935 ptrdiff_t count = SPECPDL_INDEX ();
3936 ptrdiff_t n_beg, n_end, o_beg IF_LINT (= 0), o_end IF_LINT (= 0);
3938 CHECK_OVERLAY (overlay);
3939 if (NILP (buffer))
3940 buffer = Fmarker_buffer (OVERLAY_START (overlay));
3941 if (NILP (buffer))
3942 XSETBUFFER (buffer, current_buffer);
3943 CHECK_BUFFER (buffer);
3945 if (NILP (Fbuffer_live_p (buffer)))
3946 error ("Attempt to move overlay to a dead buffer");
3948 if (MARKERP (beg)
3949 && ! EQ (Fmarker_buffer (beg), buffer))
3950 error ("Marker points into wrong buffer");
3951 if (MARKERP (end)
3952 && ! EQ (Fmarker_buffer (end), buffer))
3953 error ("Marker points into wrong buffer");
3955 CHECK_NUMBER_COERCE_MARKER (beg);
3956 CHECK_NUMBER_COERCE_MARKER (end);
3958 if (XINT (beg) > XINT (end))
3960 Lisp_Object temp;
3961 temp = beg; beg = end; end = temp;
3964 specbind (Qinhibit_quit, Qt);
3966 obuffer = Fmarker_buffer (OVERLAY_START (overlay));
3967 b = XBUFFER (buffer);
3969 if (!NILP (obuffer))
3971 ob = XBUFFER (obuffer);
3973 o_beg = OVERLAY_POSITION (OVERLAY_START (overlay));
3974 o_end = OVERLAY_POSITION (OVERLAY_END (overlay));
3976 unchain_both (ob, overlay);
3979 /* Set the overlay boundaries, which may clip them. */
3980 Fset_marker (OVERLAY_START (overlay), beg, buffer);
3981 Fset_marker (OVERLAY_END (overlay), end, buffer);
3983 n_beg = marker_position (OVERLAY_START (overlay));
3984 n_end = marker_position (OVERLAY_END (overlay));
3986 /* If the overlay has changed buffers, do a thorough redisplay. */
3987 if (!EQ (buffer, obuffer))
3989 /* Redisplay where the overlay was. */
3990 if (ob)
3991 modify_overlay (ob, o_beg, o_end);
3993 /* Redisplay where the overlay is going to be. */
3994 modify_overlay (b, n_beg, n_end);
3996 else
3997 /* Redisplay the area the overlay has just left, or just enclosed. */
3999 if (o_beg == n_beg)
4000 modify_overlay (b, o_end, n_end);
4001 else if (o_end == n_end)
4002 modify_overlay (b, o_beg, n_beg);
4003 else
4004 modify_overlay (b, min (o_beg, n_beg), max (o_end, n_end));
4007 /* Delete the overlay if it is empty after clipping and has the
4008 evaporate property. */
4009 if (n_beg == n_end && !NILP (Foverlay_get (overlay, Qevaporate)))
4010 return unbind_to (count, Fdelete_overlay (overlay));
4012 /* Put the overlay into the new buffer's overlay lists, first on the
4013 wrong list. */
4014 if (n_end < b->overlay_center)
4016 XOVERLAY (overlay)->next = b->overlays_after;
4017 set_buffer_overlays_after (b, XOVERLAY (overlay));
4019 else
4021 XOVERLAY (overlay)->next = b->overlays_before;
4022 set_buffer_overlays_before (b, XOVERLAY (overlay));
4025 /* This puts it in the right list, and in the right order. */
4026 recenter_overlay_lists (b, b->overlay_center);
4028 return unbind_to (count, overlay);
4031 DEFUN ("delete-overlay", Fdelete_overlay, Sdelete_overlay, 1, 1, 0,
4032 doc: /* Delete the overlay OVERLAY from its buffer. */)
4033 (Lisp_Object overlay)
4035 Lisp_Object buffer;
4036 struct buffer *b;
4037 ptrdiff_t count = SPECPDL_INDEX ();
4039 CHECK_OVERLAY (overlay);
4041 buffer = Fmarker_buffer (OVERLAY_START (overlay));
4042 if (NILP (buffer))
4043 return Qnil;
4045 b = XBUFFER (buffer);
4046 specbind (Qinhibit_quit, Qt);
4048 unchain_both (b, overlay);
4049 drop_overlay (b, XOVERLAY (overlay));
4051 /* When deleting an overlay with before or after strings, turn off
4052 display optimizations for the affected buffer, on the basis that
4053 these strings may contain newlines. This is easier to do than to
4054 check for that situation during redisplay. */
4055 if (!windows_or_buffers_changed
4056 && (!NILP (Foverlay_get (overlay, Qbefore_string))
4057 || !NILP (Foverlay_get (overlay, Qafter_string))))
4058 b->prevent_redisplay_optimizations_p = 1;
4060 return unbind_to (count, Qnil);
4063 DEFUN ("delete-all-overlays", Fdelete_all_overlays, Sdelete_all_overlays, 0, 1, 0,
4064 doc: /* Delete all overlays of BUFFER.
4065 BUFFER omitted or nil means delete all overlays of the current
4066 buffer. */)
4067 (Lisp_Object buffer)
4069 register struct buffer *buf;
4071 if (NILP (buffer))
4072 buf = current_buffer;
4073 else
4075 CHECK_BUFFER (buffer);
4076 buf = XBUFFER (buffer);
4079 delete_all_overlays (buf);
4080 return Qnil;
4083 /* Overlay dissection functions. */
4085 DEFUN ("overlay-start", Foverlay_start, Soverlay_start, 1, 1, 0,
4086 doc: /* Return the position at which OVERLAY starts. */)
4087 (Lisp_Object overlay)
4089 CHECK_OVERLAY (overlay);
4091 return (Fmarker_position (OVERLAY_START (overlay)));
4094 DEFUN ("overlay-end", Foverlay_end, Soverlay_end, 1, 1, 0,
4095 doc: /* Return the position at which OVERLAY ends. */)
4096 (Lisp_Object overlay)
4098 CHECK_OVERLAY (overlay);
4100 return (Fmarker_position (OVERLAY_END (overlay)));
4103 DEFUN ("overlay-buffer", Foverlay_buffer, Soverlay_buffer, 1, 1, 0,
4104 doc: /* Return the buffer OVERLAY belongs to.
4105 Return nil if OVERLAY has been deleted. */)
4106 (Lisp_Object overlay)
4108 CHECK_OVERLAY (overlay);
4110 return Fmarker_buffer (OVERLAY_START (overlay));
4113 DEFUN ("overlay-properties", Foverlay_properties, Soverlay_properties, 1, 1, 0,
4114 doc: /* Return a list of the properties on OVERLAY.
4115 This is a copy of OVERLAY's plist; modifying its conses has no effect on
4116 OVERLAY. */)
4117 (Lisp_Object overlay)
4119 CHECK_OVERLAY (overlay);
4121 return Fcopy_sequence (XOVERLAY (overlay)->plist);
4125 DEFUN ("overlays-at", Foverlays_at, Soverlays_at, 1, 1, 0,
4126 doc: /* Return a list of the overlays that contain the character at POS. */)
4127 (Lisp_Object pos)
4129 ptrdiff_t len, noverlays;
4130 Lisp_Object *overlay_vec;
4131 Lisp_Object result;
4133 CHECK_NUMBER_COERCE_MARKER (pos);
4135 len = 10;
4136 /* We can't use alloca here because overlays_at can call xrealloc. */
4137 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4139 /* Put all the overlays we want in a vector in overlay_vec.
4140 Store the length in len. */
4141 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
4142 NULL, NULL, 0);
4144 /* Make a list of them all. */
4145 result = Flist (noverlays, overlay_vec);
4147 xfree (overlay_vec);
4148 return result;
4151 DEFUN ("overlays-in", Foverlays_in, Soverlays_in, 2, 2, 0,
4152 doc: /* Return a list of the overlays that overlap the region BEG ... END.
4153 Overlap means that at least one character is contained within the overlay
4154 and also contained within the specified region.
4155 Empty overlays are included in the result if they are located at BEG,
4156 between BEG and END, or at END provided END denotes the position at the
4157 end of the buffer. */)
4158 (Lisp_Object beg, Lisp_Object end)
4160 ptrdiff_t len, noverlays;
4161 Lisp_Object *overlay_vec;
4162 Lisp_Object result;
4164 CHECK_NUMBER_COERCE_MARKER (beg);
4165 CHECK_NUMBER_COERCE_MARKER (end);
4167 len = 10;
4168 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4170 /* Put all the overlays we want in a vector in overlay_vec.
4171 Store the length in len. */
4172 noverlays = overlays_in (XINT (beg), XINT (end), 1, &overlay_vec, &len,
4173 NULL, NULL);
4175 /* Make a list of them all. */
4176 result = Flist (noverlays, overlay_vec);
4178 xfree (overlay_vec);
4179 return result;
4182 DEFUN ("next-overlay-change", Fnext_overlay_change, Snext_overlay_change,
4183 1, 1, 0,
4184 doc: /* Return the next position after POS where an overlay starts or ends.
4185 If there are no overlay boundaries from POS to (point-max),
4186 the value is (point-max). */)
4187 (Lisp_Object pos)
4189 ptrdiff_t i, len, noverlays;
4190 ptrdiff_t endpos;
4191 Lisp_Object *overlay_vec;
4193 CHECK_NUMBER_COERCE_MARKER (pos);
4195 len = 10;
4196 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4198 /* Put all the overlays we want in a vector in overlay_vec.
4199 Store the length in len.
4200 endpos gets the position where the next overlay starts. */
4201 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
4202 &endpos, 0, 1);
4204 /* If any of these overlays ends before endpos,
4205 use its ending point instead. */
4206 for (i = 0; i < noverlays; i++)
4208 Lisp_Object oend;
4209 ptrdiff_t oendpos;
4211 oend = OVERLAY_END (overlay_vec[i]);
4212 oendpos = OVERLAY_POSITION (oend);
4213 if (oendpos < endpos)
4214 endpos = oendpos;
4217 xfree (overlay_vec);
4218 return make_number (endpos);
4221 DEFUN ("previous-overlay-change", Fprevious_overlay_change,
4222 Sprevious_overlay_change, 1, 1, 0,
4223 doc: /* Return the previous position before POS where an overlay starts or ends.
4224 If there are no overlay boundaries from (point-min) to POS,
4225 the value is (point-min). */)
4226 (Lisp_Object pos)
4228 ptrdiff_t prevpos;
4229 Lisp_Object *overlay_vec;
4230 ptrdiff_t len;
4232 CHECK_NUMBER_COERCE_MARKER (pos);
4234 /* At beginning of buffer, we know the answer;
4235 avoid bug subtracting 1 below. */
4236 if (XINT (pos) == BEGV)
4237 return pos;
4239 len = 10;
4240 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4242 /* Put all the overlays we want in a vector in overlay_vec.
4243 Store the length in len.
4244 prevpos gets the position of the previous change. */
4245 overlays_at (XINT (pos), 1, &overlay_vec, &len,
4246 0, &prevpos, 1);
4248 xfree (overlay_vec);
4249 return make_number (prevpos);
4252 /* These functions are for debugging overlays. */
4254 DEFUN ("overlay-lists", Foverlay_lists, Soverlay_lists, 0, 0, 0,
4255 doc: /* Return a pair of lists giving all the overlays of the current buffer.
4256 The car has all the overlays before the overlay center;
4257 the cdr has all the overlays after the overlay center.
4258 Recentering overlays moves overlays between these lists.
4259 The lists you get are copies, so that changing them has no effect.
4260 However, the overlays you get are the real objects that the buffer uses. */)
4261 (void)
4263 struct Lisp_Overlay *ol;
4264 Lisp_Object before = Qnil, after = Qnil, tmp;
4266 for (ol = current_buffer->overlays_before; ol; ol = ol->next)
4268 XSETMISC (tmp, ol);
4269 before = Fcons (tmp, before);
4271 for (ol = current_buffer->overlays_after; ol; ol = ol->next)
4273 XSETMISC (tmp, ol);
4274 after = Fcons (tmp, after);
4277 return Fcons (Fnreverse (before), Fnreverse (after));
4280 DEFUN ("overlay-recenter", Foverlay_recenter, Soverlay_recenter, 1, 1, 0,
4281 doc: /* Recenter the overlays of the current buffer around position POS.
4282 That makes overlay lookup faster for positions near POS (but perhaps slower
4283 for positions far away from POS). */)
4284 (Lisp_Object pos)
4286 ptrdiff_t p;
4287 CHECK_NUMBER_COERCE_MARKER (pos);
4289 p = clip_to_bounds (PTRDIFF_MIN, XINT (pos), PTRDIFF_MAX);
4290 recenter_overlay_lists (current_buffer, p);
4291 return Qnil;
4294 DEFUN ("overlay-get", Foverlay_get, Soverlay_get, 2, 2, 0,
4295 doc: /* Get the property of overlay OVERLAY with property name PROP. */)
4296 (Lisp_Object overlay, Lisp_Object prop)
4298 CHECK_OVERLAY (overlay);
4299 return lookup_char_property (XOVERLAY (overlay)->plist, prop, 0);
4302 DEFUN ("overlay-put", Foverlay_put, Soverlay_put, 3, 3, 0,
4303 doc: /* Set one property of overlay OVERLAY: give property PROP value VALUE.
4304 VALUE will be returned.*/)
4305 (Lisp_Object overlay, Lisp_Object prop, Lisp_Object value)
4307 Lisp_Object tail, buffer;
4308 bool changed;
4310 CHECK_OVERLAY (overlay);
4312 buffer = Fmarker_buffer (OVERLAY_START (overlay));
4314 for (tail = XOVERLAY (overlay)->plist;
4315 CONSP (tail) && CONSP (XCDR (tail));
4316 tail = XCDR (XCDR (tail)))
4317 if (EQ (XCAR (tail), prop))
4319 changed = !EQ (XCAR (XCDR (tail)), value);
4320 XSETCAR (XCDR (tail), value);
4321 goto found;
4323 /* It wasn't in the list, so add it to the front. */
4324 changed = !NILP (value);
4325 set_overlay_plist
4326 (overlay, Fcons (prop, Fcons (value, XOVERLAY (overlay)->plist)));
4327 found:
4328 if (! NILP (buffer))
4330 if (changed)
4331 modify_overlay (XBUFFER (buffer),
4332 marker_position (OVERLAY_START (overlay)),
4333 marker_position (OVERLAY_END (overlay)));
4334 if (EQ (prop, Qevaporate) && ! NILP (value)
4335 && (OVERLAY_POSITION (OVERLAY_START (overlay))
4336 == OVERLAY_POSITION (OVERLAY_END (overlay))))
4337 Fdelete_overlay (overlay);
4340 return value;
4343 /* Subroutine of report_overlay_modification. */
4345 /* Lisp vector holding overlay hook functions to call.
4346 Vector elements come in pairs.
4347 Each even-index element is a list of hook functions.
4348 The following odd-index element is the overlay they came from.
4350 Before the buffer change, we fill in this vector
4351 as we call overlay hook functions.
4352 After the buffer change, we get the functions to call from this vector.
4353 This way we always call the same functions before and after the change. */
4354 static Lisp_Object last_overlay_modification_hooks;
4356 /* Number of elements actually used in last_overlay_modification_hooks. */
4357 static ptrdiff_t last_overlay_modification_hooks_used;
4359 /* Add one functionlist/overlay pair
4360 to the end of last_overlay_modification_hooks. */
4362 static void
4363 add_overlay_mod_hooklist (Lisp_Object functionlist, Lisp_Object overlay)
4365 ptrdiff_t oldsize = ASIZE (last_overlay_modification_hooks);
4367 if (oldsize - 1 <= last_overlay_modification_hooks_used)
4368 last_overlay_modification_hooks =
4369 larger_vector (last_overlay_modification_hooks, 2, -1);
4370 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4371 functionlist); last_overlay_modification_hooks_used++;
4372 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4373 overlay); last_overlay_modification_hooks_used++;
4376 /* Run the modification-hooks of overlays that include
4377 any part of the text in START to END.
4378 If this change is an insertion, also
4379 run the insert-before-hooks of overlay starting at END,
4380 and the insert-after-hooks of overlay ending at START.
4382 This is called both before and after the modification.
4383 AFTER is true when we call after the modification.
4385 ARG1, ARG2, ARG3 are arguments to pass to the hook functions.
4386 When AFTER is nonzero, they are the start position,
4387 the position after the inserted new text,
4388 and the length of deleted or replaced old text. */
4390 void
4391 report_overlay_modification (Lisp_Object start, Lisp_Object end, bool after,
4392 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4394 Lisp_Object prop, overlay;
4395 struct Lisp_Overlay *tail;
4396 /* True if this change is an insertion. */
4397 bool insertion = (after ? XFASTINT (arg3) == 0 : EQ (start, end));
4398 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4400 overlay = Qnil;
4401 tail = NULL;
4403 /* We used to run the functions as soon as we found them and only register
4404 them in last_overlay_modification_hooks for the purpose of the `after'
4405 case. But running elisp code as we traverse the list of overlays is
4406 painful because the list can be modified by the elisp code so we had to
4407 copy at several places. We now simply do a read-only traversal that
4408 only collects the functions to run and we run them afterwards. It's
4409 simpler, especially since all the code was already there. -stef */
4411 if (!after)
4413 /* We are being called before a change.
4414 Scan the overlays to find the functions to call. */
4415 last_overlay_modification_hooks_used = 0;
4416 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4418 ptrdiff_t startpos, endpos;
4419 Lisp_Object ostart, oend;
4421 XSETMISC (overlay, tail);
4423 ostart = OVERLAY_START (overlay);
4424 oend = OVERLAY_END (overlay);
4425 endpos = OVERLAY_POSITION (oend);
4426 if (XFASTINT (start) > endpos)
4427 break;
4428 startpos = OVERLAY_POSITION (ostart);
4429 if (insertion && (XFASTINT (start) == startpos
4430 || XFASTINT (end) == startpos))
4432 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4433 if (!NILP (prop))
4434 add_overlay_mod_hooklist (prop, overlay);
4436 if (insertion && (XFASTINT (start) == endpos
4437 || XFASTINT (end) == endpos))
4439 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4440 if (!NILP (prop))
4441 add_overlay_mod_hooklist (prop, overlay);
4443 /* Test for intersecting intervals. This does the right thing
4444 for both insertion and deletion. */
4445 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4447 prop = Foverlay_get (overlay, Qmodification_hooks);
4448 if (!NILP (prop))
4449 add_overlay_mod_hooklist (prop, overlay);
4453 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4455 ptrdiff_t startpos, endpos;
4456 Lisp_Object ostart, oend;
4458 XSETMISC (overlay, tail);
4460 ostart = OVERLAY_START (overlay);
4461 oend = OVERLAY_END (overlay);
4462 startpos = OVERLAY_POSITION (ostart);
4463 endpos = OVERLAY_POSITION (oend);
4464 if (XFASTINT (end) < startpos)
4465 break;
4466 if (insertion && (XFASTINT (start) == startpos
4467 || XFASTINT (end) == startpos))
4469 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4470 if (!NILP (prop))
4471 add_overlay_mod_hooklist (prop, overlay);
4473 if (insertion && (XFASTINT (start) == endpos
4474 || XFASTINT (end) == endpos))
4476 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4477 if (!NILP (prop))
4478 add_overlay_mod_hooklist (prop, overlay);
4480 /* Test for intersecting intervals. This does the right thing
4481 for both insertion and deletion. */
4482 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4484 prop = Foverlay_get (overlay, Qmodification_hooks);
4485 if (!NILP (prop))
4486 add_overlay_mod_hooklist (prop, overlay);
4491 GCPRO4 (overlay, arg1, arg2, arg3);
4493 /* Call the functions recorded in last_overlay_modification_hooks.
4494 First copy the vector contents, in case some of these hooks
4495 do subsequent modification of the buffer. */
4496 ptrdiff_t size = last_overlay_modification_hooks_used;
4497 Lisp_Object *copy = alloca (size * sizeof *copy);
4498 ptrdiff_t i;
4500 memcpy (copy, XVECTOR (last_overlay_modification_hooks)->contents,
4501 size * word_size);
4502 gcpro1.var = copy;
4503 gcpro1.nvars = size;
4505 for (i = 0; i < size;)
4507 Lisp_Object prop_i, overlay_i;
4508 prop_i = copy[i++];
4509 overlay_i = copy[i++];
4510 call_overlay_mod_hooks (prop_i, overlay_i, after, arg1, arg2, arg3);
4513 UNGCPRO;
4516 static void
4517 call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay, bool after,
4518 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4520 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4522 GCPRO4 (list, arg1, arg2, arg3);
4524 while (CONSP (list))
4526 if (NILP (arg3))
4527 call4 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2);
4528 else
4529 call5 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2, arg3);
4530 list = XCDR (list);
4532 UNGCPRO;
4535 /* Delete any zero-sized overlays at position POS, if the `evaporate'
4536 property is set. */
4537 void
4538 evaporate_overlays (ptrdiff_t pos)
4540 Lisp_Object overlay, hit_list;
4541 struct Lisp_Overlay *tail;
4543 hit_list = Qnil;
4544 if (pos <= current_buffer->overlay_center)
4545 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4547 ptrdiff_t endpos;
4548 XSETMISC (overlay, tail);
4549 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
4550 if (endpos < pos)
4551 break;
4552 if (endpos == pos && OVERLAY_POSITION (OVERLAY_START (overlay)) == pos
4553 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4554 hit_list = Fcons (overlay, hit_list);
4556 else
4557 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4559 ptrdiff_t startpos;
4560 XSETMISC (overlay, tail);
4561 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
4562 if (startpos > pos)
4563 break;
4564 if (startpos == pos && OVERLAY_POSITION (OVERLAY_END (overlay)) == pos
4565 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4566 hit_list = Fcons (overlay, hit_list);
4568 for (; CONSP (hit_list); hit_list = XCDR (hit_list))
4569 Fdelete_overlay (XCAR (hit_list));
4572 /* Somebody has tried to store a value with an unacceptable type
4573 in the slot with offset OFFSET. */
4575 void
4576 buffer_slot_type_mismatch (Lisp_Object newval, int type)
4578 Lisp_Object predicate;
4580 switch (type)
4582 case_Lisp_Int: predicate = Qintegerp; break;
4583 case Lisp_String: predicate = Qstringp; break;
4584 case Lisp_Symbol: predicate = Qsymbolp; break;
4585 default: emacs_abort ();
4588 wrong_type_argument (predicate, newval);
4592 /***********************************************************************
4593 Allocation with mmap
4594 ***********************************************************************/
4596 #ifdef USE_MMAP_FOR_BUFFERS
4598 #include <sys/types.h>
4599 #include <sys/mman.h>
4601 #ifndef MAP_ANON
4602 #ifdef MAP_ANONYMOUS
4603 #define MAP_ANON MAP_ANONYMOUS
4604 #else
4605 #define MAP_ANON 0
4606 #endif
4607 #endif
4609 #ifndef MAP_FAILED
4610 #define MAP_FAILED ((void *) -1)
4611 #endif
4613 #include <stdio.h>
4615 #if MAP_ANON == 0
4616 #include <fcntl.h>
4617 #endif
4619 #include "coding.h"
4622 /* Memory is allocated in regions which are mapped using mmap(2).
4623 The current implementation lets the system select mapped
4624 addresses; we're not using MAP_FIXED in general, except when
4625 trying to enlarge regions.
4627 Each mapped region starts with a mmap_region structure, the user
4628 area starts after that structure, aligned to MEM_ALIGN.
4630 +-----------------------+
4631 | struct mmap_info + |
4632 | padding |
4633 +-----------------------+
4634 | user data |
4637 +-----------------------+ */
4639 struct mmap_region
4641 /* User-specified size. */
4642 size_t nbytes_specified;
4644 /* Number of bytes mapped */
4645 size_t nbytes_mapped;
4647 /* Pointer to the location holding the address of the memory
4648 allocated with the mmap'd block. The variable actually points
4649 after this structure. */
4650 void **var;
4652 /* Next and previous in list of all mmap'd regions. */
4653 struct mmap_region *next, *prev;
4656 /* Doubly-linked list of mmap'd regions. */
4658 static struct mmap_region *mmap_regions;
4660 /* File descriptor for mmap. If we don't have anonymous mapping,
4661 /dev/zero will be opened on it. */
4663 static int mmap_fd;
4665 /* Temporary storage for mmap_set_vars, see there. */
4667 static struct mmap_region *mmap_regions_1;
4668 static int mmap_fd_1;
4670 /* Page size on this system. */
4672 static int mmap_page_size;
4674 /* 1 means mmap has been initialized. */
4676 static bool mmap_initialized_p;
4678 /* Value is X rounded up to the next multiple of N. */
4680 #define ROUND(X, N) (((X) + (N) - 1) / (N) * (N))
4682 /* Size of mmap_region structure plus padding. */
4684 #define MMAP_REGION_STRUCT_SIZE \
4685 ROUND (sizeof (struct mmap_region), MEM_ALIGN)
4687 /* Given a pointer P to the start of the user-visible part of a mapped
4688 region, return a pointer to the start of the region. */
4690 #define MMAP_REGION(P) \
4691 ((struct mmap_region *) ((char *) (P) - MMAP_REGION_STRUCT_SIZE))
4693 /* Given a pointer P to the start of a mapped region, return a pointer
4694 to the start of the user-visible part of the region. */
4696 #define MMAP_USER_AREA(P) \
4697 ((void *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
4699 #define MEM_ALIGN sizeof (double)
4701 /* Predicate returning true if part of the address range [START .. END]
4702 is currently mapped. Used to prevent overwriting an existing
4703 memory mapping.
4705 Default is to conservatively assume the address range is occupied by
4706 something else. This can be overridden by system configuration
4707 files if system-specific means to determine this exists. */
4709 #ifndef MMAP_ALLOCATED_P
4710 #define MMAP_ALLOCATED_P(start, end) 1
4711 #endif
4713 /* Perform necessary initializations for the use of mmap. */
4715 static void
4716 mmap_init (void)
4718 #if MAP_ANON == 0
4719 /* The value of mmap_fd is initially 0 in temacs, and -1
4720 in a dumped Emacs. */
4721 if (mmap_fd <= 0)
4723 /* No anonymous mmap -- we need the file descriptor. */
4724 mmap_fd = open ("/dev/zero", O_RDONLY);
4725 if (mmap_fd == -1)
4726 fatal ("Cannot open /dev/zero: %s", emacs_strerror (errno));
4728 #endif /* MAP_ANON == 0 */
4730 if (mmap_initialized_p)
4731 return;
4732 mmap_initialized_p = 1;
4734 #if MAP_ANON != 0
4735 mmap_fd = -1;
4736 #endif
4738 mmap_page_size = getpagesize ();
4741 /* Return a region overlapping address range START...END, or null if
4742 none. END is not including, i.e. the last byte in the range
4743 is at END - 1. */
4745 static struct mmap_region *
4746 mmap_find (void *start, void *end)
4748 struct mmap_region *r;
4749 char *s = (char *) start, *e = (char *) end;
4751 for (r = mmap_regions; r; r = r->next)
4753 char *rstart = (char *) r;
4754 char *rend = rstart + r->nbytes_mapped;
4756 if (/* First byte of range, i.e. START, in this region? */
4757 (s >= rstart && s < rend)
4758 /* Last byte of range, i.e. END - 1, in this region? */
4759 || (e > rstart && e <= rend)
4760 /* First byte of this region in the range? */
4761 || (rstart >= s && rstart < e)
4762 /* Last byte of this region in the range? */
4763 || (rend > s && rend <= e))
4764 break;
4767 return r;
4771 /* Unmap a region. P is a pointer to the start of the user-araa of
4772 the region. */
4774 static void
4775 mmap_free_1 (struct mmap_region *r)
4777 if (r->next)
4778 r->next->prev = r->prev;
4779 if (r->prev)
4780 r->prev->next = r->next;
4781 else
4782 mmap_regions = r->next;
4784 if (munmap (r, r->nbytes_mapped) == -1)
4785 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4789 /* Enlarge region R by NPAGES pages. NPAGES < 0 means shrink R.
4790 Value is true if successful. */
4792 static bool
4793 mmap_enlarge (struct mmap_region *r, int npages)
4795 char *region_end = (char *) r + r->nbytes_mapped;
4796 size_t nbytes;
4797 bool success = 0;
4799 if (npages < 0)
4801 /* Unmap pages at the end of the region. */
4802 nbytes = - npages * mmap_page_size;
4803 if (munmap (region_end - nbytes, nbytes) == -1)
4804 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4805 else
4807 r->nbytes_mapped -= nbytes;
4808 success = 1;
4811 else if (npages > 0)
4813 nbytes = npages * mmap_page_size;
4815 /* Try to map additional pages at the end of the region. We
4816 cannot do this if the address range is already occupied by
4817 something else because mmap deletes any previous mapping.
4818 I'm not sure this is worth doing, let's see. */
4819 if (!MMAP_ALLOCATED_P (region_end, region_end + nbytes))
4821 void *p;
4823 p = mmap (region_end, nbytes, PROT_READ | PROT_WRITE,
4824 MAP_ANON | MAP_PRIVATE | MAP_FIXED, mmap_fd, 0);
4825 if (p == MAP_FAILED)
4826 ; /* fprintf (stderr, "mmap: %s\n", emacs_strerror (errno)); */
4827 else if (p != region_end)
4829 /* Kernels are free to choose a different address. In
4830 that case, unmap what we've mapped above; we have
4831 no use for it. */
4832 if (munmap (p, nbytes) == -1)
4833 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4835 else
4837 r->nbytes_mapped += nbytes;
4838 success = 1;
4843 return success;
4847 /* Set or reset variables holding references to mapped regions.
4848 If not RESTORE_P, set all variables to null. If RESTORE_P, set all
4849 variables to the start of the user-areas of mapped regions.
4851 This function is called from Fdump_emacs to ensure that the dumped
4852 Emacs doesn't contain references to memory that won't be mapped
4853 when Emacs starts. */
4855 void
4856 mmap_set_vars (bool restore_p)
4858 struct mmap_region *r;
4860 if (restore_p)
4862 mmap_regions = mmap_regions_1;
4863 mmap_fd = mmap_fd_1;
4864 for (r = mmap_regions; r; r = r->next)
4865 *r->var = MMAP_USER_AREA (r);
4867 else
4869 for (r = mmap_regions; r; r = r->next)
4870 *r->var = NULL;
4871 mmap_regions_1 = mmap_regions;
4872 mmap_regions = NULL;
4873 mmap_fd_1 = mmap_fd;
4874 mmap_fd = -1;
4879 /* Allocate a block of storage large enough to hold NBYTES bytes of
4880 data. A pointer to the data is returned in *VAR. VAR is thus the
4881 address of some variable which will use the data area.
4883 The allocation of 0 bytes is valid.
4885 If we can't allocate the necessary memory, set *VAR to null, and
4886 return null. */
4888 static void *
4889 mmap_alloc (void **var, size_t nbytes)
4891 void *p;
4892 size_t map;
4894 mmap_init ();
4896 map = ROUND (nbytes + MMAP_REGION_STRUCT_SIZE, mmap_page_size);
4897 p = mmap (NULL, map, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
4898 mmap_fd, 0);
4900 if (p == MAP_FAILED)
4902 if (errno != ENOMEM)
4903 fprintf (stderr, "mmap: %s\n", emacs_strerror (errno));
4904 p = NULL;
4906 else
4908 struct mmap_region *r = (struct mmap_region *) p;
4910 r->nbytes_specified = nbytes;
4911 r->nbytes_mapped = map;
4912 r->var = var;
4913 r->prev = NULL;
4914 r->next = mmap_regions;
4915 if (r->next)
4916 r->next->prev = r;
4917 mmap_regions = r;
4919 p = MMAP_USER_AREA (p);
4922 return *var = p;
4926 /* Free a block of relocatable storage whose data is pointed to by
4927 PTR. Store 0 in *PTR to show there's no block allocated. */
4929 static void
4930 mmap_free (void **var)
4932 mmap_init ();
4934 if (*var)
4936 mmap_free_1 (MMAP_REGION (*var));
4937 *var = NULL;
4942 /* Given a pointer at address VAR to data allocated with mmap_alloc,
4943 resize it to size NBYTES. Change *VAR to reflect the new block,
4944 and return this value. If more memory cannot be allocated, then
4945 leave *VAR unchanged, and return null. */
4947 static void *
4948 mmap_realloc (void **var, size_t nbytes)
4950 void *result;
4952 mmap_init ();
4954 if (*var == NULL)
4955 result = mmap_alloc (var, nbytes);
4956 else if (nbytes == 0)
4958 mmap_free (var);
4959 result = mmap_alloc (var, nbytes);
4961 else
4963 struct mmap_region *r = MMAP_REGION (*var);
4964 size_t room = r->nbytes_mapped - MMAP_REGION_STRUCT_SIZE;
4966 if (room < nbytes)
4968 /* Must enlarge. */
4969 void *old_ptr = *var;
4971 /* Try to map additional pages at the end of the region.
4972 If that fails, allocate a new region, copy data
4973 from the old region, then free it. */
4974 if (mmap_enlarge (r, (ROUND (nbytes - room, mmap_page_size)
4975 / mmap_page_size)))
4977 r->nbytes_specified = nbytes;
4978 *var = result = old_ptr;
4980 else if (mmap_alloc (var, nbytes))
4982 memcpy (*var, old_ptr, r->nbytes_specified);
4983 mmap_free_1 (MMAP_REGION (old_ptr));
4984 result = *var;
4985 r = MMAP_REGION (result);
4986 r->nbytes_specified = nbytes;
4988 else
4990 *var = old_ptr;
4991 result = NULL;
4994 else if (room - nbytes >= mmap_page_size)
4996 /* Shrinking by at least a page. Let's give some
4997 memory back to the system.
4999 The extra parens are to make the division happens first,
5000 on positive values, so we know it will round towards
5001 zero. */
5002 mmap_enlarge (r, - ((room - nbytes) / mmap_page_size));
5003 result = *var;
5004 r->nbytes_specified = nbytes;
5006 else
5008 /* Leave it alone. */
5009 result = *var;
5010 r->nbytes_specified = nbytes;
5014 return result;
5018 #endif /* USE_MMAP_FOR_BUFFERS */
5022 /***********************************************************************
5023 Buffer-text Allocation
5024 ***********************************************************************/
5026 /* Allocate NBYTES bytes for buffer B's text buffer. */
5028 static void
5029 alloc_buffer_text (struct buffer *b, ptrdiff_t nbytes)
5031 void *p;
5033 block_input ();
5034 #if defined USE_MMAP_FOR_BUFFERS
5035 p = mmap_alloc ((void **) &b->text->beg, nbytes);
5036 #elif defined REL_ALLOC
5037 p = r_alloc ((void **) &b->text->beg, nbytes);
5038 #else
5039 p = xmalloc (nbytes);
5040 #endif
5042 if (p == NULL)
5044 unblock_input ();
5045 memory_full (nbytes);
5048 b->text->beg = (unsigned char *) p;
5049 unblock_input ();
5052 /* Enlarge buffer B's text buffer by DELTA bytes. DELTA < 0 means
5053 shrink it. */
5055 void
5056 enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
5058 void *p;
5059 ptrdiff_t nbytes = (BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1
5060 + delta);
5061 block_input ();
5062 #if defined USE_MMAP_FOR_BUFFERS
5063 p = mmap_realloc ((void **) &b->text->beg, nbytes);
5064 #elif defined REL_ALLOC
5065 p = r_re_alloc ((void **) &b->text->beg, nbytes);
5066 #else
5067 p = xrealloc (b->text->beg, nbytes);
5068 #endif
5070 if (p == NULL)
5072 unblock_input ();
5073 memory_full (nbytes);
5076 BUF_BEG_ADDR (b) = (unsigned char *) p;
5077 unblock_input ();
5081 /* Free buffer B's text buffer. */
5083 static void
5084 free_buffer_text (struct buffer *b)
5086 block_input ();
5088 #if defined USE_MMAP_FOR_BUFFERS
5089 mmap_free ((void **) &b->text->beg);
5090 #elif defined REL_ALLOC
5091 r_alloc_free ((void **) &b->text->beg);
5092 #else
5093 xfree (b->text->beg);
5094 #endif
5096 BUF_BEG_ADDR (b) = NULL;
5097 unblock_input ();
5102 /***********************************************************************
5103 Initialization
5104 ***********************************************************************/
5106 void
5107 init_buffer_once (void)
5109 int idx;
5110 /* If you add, remove, or reorder Lisp_Objects in a struct buffer, make
5111 sure that this is still correct. Otherwise, mark_vectorlike may not
5112 trace all Lisp_Objects in buffer_defaults and buffer_local_symbols. */
5113 const int pvecsize
5114 = (offsetof (struct buffer, own_text) - header_size) / word_size;
5116 memset (buffer_permanent_local_flags, 0, sizeof buffer_permanent_local_flags);
5118 /* Make sure all markable slots in buffer_defaults
5119 are initialized reasonably, so mark_buffer won't choke. */
5120 reset_buffer (&buffer_defaults);
5121 eassert (EQ (BVAR (&buffer_defaults, name), make_number (0)));
5122 reset_buffer_local_variables (&buffer_defaults, 1);
5123 eassert (EQ (BVAR (&buffer_local_symbols, name), make_number (0)));
5124 reset_buffer (&buffer_local_symbols);
5125 reset_buffer_local_variables (&buffer_local_symbols, 1);
5126 /* Prevent GC from getting confused. */
5127 buffer_defaults.text = &buffer_defaults.own_text;
5128 buffer_local_symbols.text = &buffer_local_symbols.own_text;
5129 /* No one will share the text with these buffers, but let's play it safe. */
5130 buffer_defaults.indirections = 0;
5131 buffer_local_symbols.indirections = 0;
5132 set_buffer_intervals (&buffer_defaults, NULL);
5133 set_buffer_intervals (&buffer_local_symbols, NULL);
5134 /* This is not strictly necessary, but let's make them initialized. */
5135 bset_name (&buffer_defaults, build_pure_c_string (" *buffer-defaults*"));
5136 bset_name (&buffer_local_symbols, build_pure_c_string (" *buffer-local-symbols*"));
5137 XSETPVECTYPESIZE (&buffer_defaults, PVEC_BUFFER, pvecsize);
5138 XSETPVECTYPESIZE (&buffer_local_symbols, PVEC_BUFFER, pvecsize);
5140 /* Set up the default values of various buffer slots. */
5141 /* Must do these before making the first buffer! */
5143 /* real setup is done in bindings.el */
5144 bset_mode_line_format (&buffer_defaults, build_pure_c_string ("%-"));
5145 bset_header_line_format (&buffer_defaults, Qnil);
5146 bset_abbrev_mode (&buffer_defaults, Qnil);
5147 bset_overwrite_mode (&buffer_defaults, Qnil);
5148 bset_case_fold_search (&buffer_defaults, Qt);
5149 bset_auto_fill_function (&buffer_defaults, Qnil);
5150 bset_selective_display (&buffer_defaults, Qnil);
5151 bset_selective_display_ellipses (&buffer_defaults, Qt);
5152 bset_abbrev_table (&buffer_defaults, Qnil);
5153 bset_display_table (&buffer_defaults, Qnil);
5154 bset_undo_list (&buffer_defaults, Qnil);
5155 bset_mark_active (&buffer_defaults, Qnil);
5156 bset_file_format (&buffer_defaults, Qnil);
5157 bset_auto_save_file_format (&buffer_defaults, Qt);
5158 set_buffer_overlays_before (&buffer_defaults, NULL);
5159 set_buffer_overlays_after (&buffer_defaults, NULL);
5160 buffer_defaults.overlay_center = BEG;
5162 XSETFASTINT (BVAR (&buffer_defaults, tab_width), 8);
5163 bset_truncate_lines (&buffer_defaults, Qnil);
5164 bset_word_wrap (&buffer_defaults, Qnil);
5165 bset_ctl_arrow (&buffer_defaults, Qt);
5166 bset_bidi_display_reordering (&buffer_defaults, Qt);
5167 bset_bidi_paragraph_direction (&buffer_defaults, Qnil);
5168 bset_cursor_type (&buffer_defaults, Qt);
5169 bset_extra_line_spacing (&buffer_defaults, Qnil);
5170 bset_cursor_in_non_selected_windows (&buffer_defaults, Qt);
5172 bset_enable_multibyte_characters (&buffer_defaults, Qt);
5173 bset_buffer_file_coding_system (&buffer_defaults, Qnil);
5174 XSETFASTINT (BVAR (&buffer_defaults, fill_column), 70);
5175 XSETFASTINT (BVAR (&buffer_defaults, left_margin), 0);
5176 bset_cache_long_line_scans (&buffer_defaults, Qnil);
5177 bset_file_truename (&buffer_defaults, Qnil);
5178 XSETFASTINT (BVAR (&buffer_defaults, display_count), 0);
5179 XSETFASTINT (BVAR (&buffer_defaults, left_margin_cols), 0);
5180 XSETFASTINT (BVAR (&buffer_defaults, right_margin_cols), 0);
5181 bset_left_fringe_width (&buffer_defaults, Qnil);
5182 bset_right_fringe_width (&buffer_defaults, Qnil);
5183 bset_fringes_outside_margins (&buffer_defaults, Qnil);
5184 bset_scroll_bar_width (&buffer_defaults, Qnil);
5185 bset_vertical_scroll_bar_type (&buffer_defaults, Qt);
5186 bset_indicate_empty_lines (&buffer_defaults, Qnil);
5187 bset_indicate_buffer_boundaries (&buffer_defaults, Qnil);
5188 bset_fringe_indicator_alist (&buffer_defaults, Qnil);
5189 bset_fringe_cursor_alist (&buffer_defaults, Qnil);
5190 bset_scroll_up_aggressively (&buffer_defaults, Qnil);
5191 bset_scroll_down_aggressively (&buffer_defaults, Qnil);
5192 bset_display_time (&buffer_defaults, Qnil);
5194 /* Assign the local-flags to the slots that have default values.
5195 The local flag is a bit that is used in the buffer
5196 to say that it has its own local value for the slot.
5197 The local flag bits are in the local_var_flags slot of the buffer. */
5199 /* Nothing can work if this isn't true */
5200 { verify (sizeof (EMACS_INT) == word_size); }
5202 /* 0 means not a lisp var, -1 means always local, else mask */
5203 memset (&buffer_local_flags, 0, sizeof buffer_local_flags);
5204 bset_filename (&buffer_local_flags, make_number (-1));
5205 bset_directory (&buffer_local_flags, make_number (-1));
5206 bset_backed_up (&buffer_local_flags, make_number (-1));
5207 bset_save_length (&buffer_local_flags, make_number (-1));
5208 bset_auto_save_file_name (&buffer_local_flags, make_number (-1));
5209 bset_read_only (&buffer_local_flags, make_number (-1));
5210 bset_major_mode (&buffer_local_flags, make_number (-1));
5211 bset_mode_name (&buffer_local_flags, make_number (-1));
5212 bset_undo_list (&buffer_local_flags, make_number (-1));
5213 bset_mark_active (&buffer_local_flags, make_number (-1));
5214 bset_point_before_scroll (&buffer_local_flags, make_number (-1));
5215 bset_file_truename (&buffer_local_flags, make_number (-1));
5216 bset_invisibility_spec (&buffer_local_flags, make_number (-1));
5217 bset_file_format (&buffer_local_flags, make_number (-1));
5218 bset_auto_save_file_format (&buffer_local_flags, make_number (-1));
5219 bset_display_count (&buffer_local_flags, make_number (-1));
5220 bset_display_time (&buffer_local_flags, make_number (-1));
5221 bset_enable_multibyte_characters (&buffer_local_flags, make_number (-1));
5223 idx = 1;
5224 XSETFASTINT (BVAR (&buffer_local_flags, mode_line_format), idx); ++idx;
5225 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_mode), idx); ++idx;
5226 XSETFASTINT (BVAR (&buffer_local_flags, overwrite_mode), idx); ++idx;
5227 XSETFASTINT (BVAR (&buffer_local_flags, case_fold_search), idx); ++idx;
5228 XSETFASTINT (BVAR (&buffer_local_flags, auto_fill_function), idx); ++idx;
5229 XSETFASTINT (BVAR (&buffer_local_flags, selective_display), idx); ++idx;
5230 XSETFASTINT (BVAR (&buffer_local_flags, selective_display_ellipses), idx); ++idx;
5231 XSETFASTINT (BVAR (&buffer_local_flags, tab_width), idx); ++idx;
5232 XSETFASTINT (BVAR (&buffer_local_flags, truncate_lines), idx); ++idx;
5233 XSETFASTINT (BVAR (&buffer_local_flags, word_wrap), idx); ++idx;
5234 XSETFASTINT (BVAR (&buffer_local_flags, ctl_arrow), idx); ++idx;
5235 XSETFASTINT (BVAR (&buffer_local_flags, fill_column), idx); ++idx;
5236 XSETFASTINT (BVAR (&buffer_local_flags, left_margin), idx); ++idx;
5237 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_table), idx); ++idx;
5238 XSETFASTINT (BVAR (&buffer_local_flags, display_table), idx); ++idx;
5239 XSETFASTINT (BVAR (&buffer_local_flags, syntax_table), idx); ++idx;
5240 XSETFASTINT (BVAR (&buffer_local_flags, cache_long_line_scans), idx); ++idx;
5241 XSETFASTINT (BVAR (&buffer_local_flags, category_table), idx); ++idx;
5242 XSETFASTINT (BVAR (&buffer_local_flags, bidi_display_reordering), idx); ++idx;
5243 XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_direction), idx); ++idx;
5244 XSETFASTINT (BVAR (&buffer_local_flags, buffer_file_coding_system), idx);
5245 /* Make this one a permanent local. */
5246 buffer_permanent_local_flags[idx++] = 1;
5247 XSETFASTINT (BVAR (&buffer_local_flags, left_margin_cols), idx); ++idx;
5248 XSETFASTINT (BVAR (&buffer_local_flags, right_margin_cols), idx); ++idx;
5249 XSETFASTINT (BVAR (&buffer_local_flags, left_fringe_width), idx); ++idx;
5250 XSETFASTINT (BVAR (&buffer_local_flags, right_fringe_width), idx); ++idx;
5251 XSETFASTINT (BVAR (&buffer_local_flags, fringes_outside_margins), idx); ++idx;
5252 XSETFASTINT (BVAR (&buffer_local_flags, scroll_bar_width), idx); ++idx;
5253 XSETFASTINT (BVAR (&buffer_local_flags, vertical_scroll_bar_type), idx); ++idx;
5254 XSETFASTINT (BVAR (&buffer_local_flags, indicate_empty_lines), idx); ++idx;
5255 XSETFASTINT (BVAR (&buffer_local_flags, indicate_buffer_boundaries), idx); ++idx;
5256 XSETFASTINT (BVAR (&buffer_local_flags, fringe_indicator_alist), idx); ++idx;
5257 XSETFASTINT (BVAR (&buffer_local_flags, fringe_cursor_alist), idx); ++idx;
5258 XSETFASTINT (BVAR (&buffer_local_flags, scroll_up_aggressively), idx); ++idx;
5259 XSETFASTINT (BVAR (&buffer_local_flags, scroll_down_aggressively), idx); ++idx;
5260 XSETFASTINT (BVAR (&buffer_local_flags, header_line_format), idx); ++idx;
5261 XSETFASTINT (BVAR (&buffer_local_flags, cursor_type), idx); ++idx;
5262 XSETFASTINT (BVAR (&buffer_local_flags, extra_line_spacing), idx); ++idx;
5263 XSETFASTINT (BVAR (&buffer_local_flags, cursor_in_non_selected_windows), idx); ++idx;
5265 /* Need more room? */
5266 if (idx >= MAX_PER_BUFFER_VARS)
5267 emacs_abort ();
5268 last_per_buffer_idx = idx;
5270 Vbuffer_alist = Qnil;
5271 current_buffer = 0;
5272 all_buffers = 0;
5274 QSFundamental = build_pure_c_string ("Fundamental");
5276 Qfundamental_mode = intern_c_string ("fundamental-mode");
5277 bset_major_mode (&buffer_defaults, Qfundamental_mode);
5279 Qmode_class = intern_c_string ("mode-class");
5281 Qprotected_field = intern_c_string ("protected-field");
5283 Qpermanent_local = intern_c_string ("permanent-local");
5285 Qkill_buffer_hook = intern_c_string ("kill-buffer-hook");
5286 Fput (Qkill_buffer_hook, Qpermanent_local, Qt);
5288 /* super-magic invisible buffer */
5289 Vprin1_to_string_buffer = Fget_buffer_create (build_pure_c_string (" prin1"));
5290 Vbuffer_alist = Qnil;
5292 Fset_buffer (Fget_buffer_create (build_pure_c_string ("*scratch*")));
5294 inhibit_modification_hooks = 0;
5297 void
5298 init_buffer (void)
5300 char *pwd;
5301 Lisp_Object temp;
5302 ptrdiff_t len;
5304 #ifdef USE_MMAP_FOR_BUFFERS
5306 /* When using the ralloc implementation based on mmap(2), buffer
5307 text pointers will have been set to null in the dumped Emacs.
5308 Map new memory. */
5309 struct buffer *b;
5311 FOR_EACH_BUFFER (b)
5312 if (b->text->beg == NULL)
5313 enlarge_buffer_text (b, 0);
5315 #endif /* USE_MMAP_FOR_BUFFERS */
5317 Fset_buffer (Fget_buffer_create (build_string ("*scratch*")));
5318 if (NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
5319 Fset_buffer_multibyte (Qnil);
5321 pwd = get_current_dir_name ();
5323 if (!pwd)
5324 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5326 /* Maybe this should really use some standard subroutine
5327 whose definition is filename syntax dependent. */
5328 len = strlen (pwd);
5329 if (!(IS_DIRECTORY_SEP (pwd[len - 1])))
5331 /* Grow buffer to add directory separator and '\0'. */
5332 pwd = realloc (pwd, len + 2);
5333 if (!pwd)
5334 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5335 pwd[len] = DIRECTORY_SEP;
5336 pwd[len + 1] = '\0';
5337 len++;
5340 bset_directory (current_buffer, make_unibyte_string (pwd, len));
5341 if (! NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
5342 /* At this moment, we still don't know how to decode the
5343 directory name. So, we keep the bytes in multibyte form so
5344 that ENCODE_FILE correctly gets the original bytes. */
5345 bset_directory
5346 (current_buffer, string_to_multibyte (BVAR (current_buffer, directory)));
5348 /* Add /: to the front of the name
5349 if it would otherwise be treated as magic. */
5350 temp = Ffind_file_name_handler (BVAR (current_buffer, directory), Qt);
5351 if (! NILP (temp)
5352 /* If the default dir is just /, TEMP is non-nil
5353 because of the ange-ftp completion handler.
5354 However, it is not necessary to turn / into /:/.
5355 So avoid doing that. */
5356 && strcmp ("/", SSDATA (BVAR (current_buffer, directory))))
5357 bset_directory
5358 (current_buffer,
5359 concat2 (build_string ("/:"), BVAR (current_buffer, directory)));
5361 temp = get_minibuffer (0);
5362 bset_directory (XBUFFER (temp), BVAR (current_buffer, directory));
5364 free (pwd);
5367 /* Similar to defvar_lisp but define a variable whose value is the Lisp
5368 Object stored in the current buffer. address is the address of the slot
5369 in the buffer that is current now. */
5371 /* TYPE is nil for a general Lisp variable.
5372 An integer specifies a type; then only Lisp values
5373 with that type code are allowed (except that nil is allowed too).
5374 LNAME is the Lisp-level variable name.
5375 VNAME is the name of the buffer slot.
5376 DOC is a dummy where you write the doc string as a comment. */
5377 #define DEFVAR_PER_BUFFER(lname, vname, type, doc) \
5378 do { \
5379 static struct Lisp_Buffer_Objfwd bo_fwd; \
5380 defvar_per_buffer (&bo_fwd, lname, vname, type); \
5381 } while (0)
5383 static void
5384 defvar_per_buffer (struct Lisp_Buffer_Objfwd *bo_fwd, const char *namestring,
5385 Lisp_Object *address, Lisp_Object type)
5387 struct Lisp_Symbol *sym;
5388 int offset;
5390 sym = XSYMBOL (intern (namestring));
5391 offset = (char *)address - (char *)current_buffer;
5393 bo_fwd->type = Lisp_Fwd_Buffer_Obj;
5394 bo_fwd->offset = offset;
5395 bo_fwd->slottype = type;
5396 sym->declared_special = 1;
5397 sym->redirect = SYMBOL_FORWARDED;
5399 /* I tried to do the job without a cast, but it seems impossible.
5400 union Lisp_Fwd *fwd; &(fwd->u_buffer_objfwd) = bo_fwd; */
5401 SET_SYMBOL_FWD (sym, (union Lisp_Fwd *)bo_fwd);
5403 XSETSYMBOL (PER_BUFFER_SYMBOL (offset), sym);
5405 if (PER_BUFFER_IDX (offset) == 0)
5406 /* Did a DEFVAR_PER_BUFFER without initializing the corresponding
5407 slot of buffer_local_flags */
5408 emacs_abort ();
5412 /* initialize the buffer routines */
5413 void
5414 syms_of_buffer (void)
5416 staticpro (&last_overlay_modification_hooks);
5417 last_overlay_modification_hooks
5418 = Fmake_vector (make_number (10), Qnil);
5420 staticpro (&Qfundamental_mode);
5421 staticpro (&Qmode_class);
5422 staticpro (&QSFundamental);
5423 staticpro (&Vbuffer_alist);
5424 staticpro (&Qprotected_field);
5425 staticpro (&Qpermanent_local);
5426 staticpro (&Qkill_buffer_hook);
5428 DEFSYM (Qpermanent_local_hook, "permanent-local-hook");
5429 DEFSYM (Qoverlayp, "overlayp");
5430 DEFSYM (Qevaporate, "evaporate");
5431 DEFSYM (Qmodification_hooks, "modification-hooks");
5432 DEFSYM (Qinsert_in_front_hooks, "insert-in-front-hooks");
5433 DEFSYM (Qinsert_behind_hooks, "insert-behind-hooks");
5434 DEFSYM (Qget_file_buffer, "get-file-buffer");
5435 DEFSYM (Qpriority, "priority");
5436 DEFSYM (Qbefore_string, "before-string");
5437 DEFSYM (Qafter_string, "after-string");
5438 DEFSYM (Qfirst_change_hook, "first-change-hook");
5439 DEFSYM (Qbefore_change_functions, "before-change-functions");
5440 DEFSYM (Qafter_change_functions, "after-change-functions");
5441 DEFSYM (Qkill_buffer_query_functions, "kill-buffer-query-functions");
5443 Fput (Qprotected_field, Qerror_conditions,
5444 listn (CONSTYPE_PURE, 2, Qprotected_field, Qerror));
5445 Fput (Qprotected_field, Qerror_message,
5446 build_pure_c_string ("Attempt to modify a protected field"));
5448 DEFVAR_BUFFER_DEFAULTS ("default-mode-line-format",
5449 mode_line_format,
5450 doc: /* Default value of `mode-line-format' for buffers that don't override it.
5451 This is the same as (default-value 'mode-line-format). */);
5453 DEFVAR_BUFFER_DEFAULTS ("default-header-line-format",
5454 header_line_format,
5455 doc: /* Default value of `header-line-format' for buffers that don't override it.
5456 This is the same as (default-value 'header-line-format). */);
5458 DEFVAR_BUFFER_DEFAULTS ("default-cursor-type", cursor_type,
5459 doc: /* Default value of `cursor-type' for buffers that don't override it.
5460 This is the same as (default-value 'cursor-type). */);
5462 DEFVAR_BUFFER_DEFAULTS ("default-line-spacing",
5463 extra_line_spacing,
5464 doc: /* Default value of `line-spacing' for buffers that don't override it.
5465 This is the same as (default-value 'line-spacing). */);
5467 DEFVAR_BUFFER_DEFAULTS ("default-cursor-in-non-selected-windows",
5468 cursor_in_non_selected_windows,
5469 doc: /* Default value of `cursor-in-non-selected-windows'.
5470 This is the same as (default-value 'cursor-in-non-selected-windows). */);
5472 DEFVAR_BUFFER_DEFAULTS ("default-abbrev-mode",
5473 abbrev_mode,
5474 doc: /* Default value of `abbrev-mode' for buffers that do not override it.
5475 This is the same as (default-value 'abbrev-mode). */);
5477 DEFVAR_BUFFER_DEFAULTS ("default-ctl-arrow",
5478 ctl_arrow,
5479 doc: /* Default value of `ctl-arrow' for buffers that do not override it.
5480 This is the same as (default-value 'ctl-arrow). */);
5482 DEFVAR_BUFFER_DEFAULTS ("default-enable-multibyte-characters",
5483 enable_multibyte_characters,
5484 doc: /* Default value of `enable-multibyte-characters' for buffers not overriding it.
5485 This is the same as (default-value 'enable-multibyte-characters). */);
5487 DEFVAR_BUFFER_DEFAULTS ("default-buffer-file-coding-system",
5488 buffer_file_coding_system,
5489 doc: /* Default value of `buffer-file-coding-system' for buffers not overriding it.
5490 This is the same as (default-value 'buffer-file-coding-system). */);
5492 DEFVAR_BUFFER_DEFAULTS ("default-truncate-lines",
5493 truncate_lines,
5494 doc: /* Default value of `truncate-lines' for buffers that do not override it.
5495 This is the same as (default-value 'truncate-lines). */);
5497 DEFVAR_BUFFER_DEFAULTS ("default-fill-column",
5498 fill_column,
5499 doc: /* Default value of `fill-column' for buffers that do not override it.
5500 This is the same as (default-value 'fill-column). */);
5502 DEFVAR_BUFFER_DEFAULTS ("default-left-margin",
5503 left_margin,
5504 doc: /* Default value of `left-margin' for buffers that do not override it.
5505 This is the same as (default-value 'left-margin). */);
5507 DEFVAR_BUFFER_DEFAULTS ("default-tab-width",
5508 tab_width,
5509 doc: /* Default value of `tab-width' for buffers that do not override it.
5510 This is the same as (default-value 'tab-width). */);
5512 DEFVAR_BUFFER_DEFAULTS ("default-case-fold-search",
5513 case_fold_search,
5514 doc: /* Default value of `case-fold-search' for buffers that don't override it.
5515 This is the same as (default-value 'case-fold-search). */);
5517 DEFVAR_BUFFER_DEFAULTS ("default-left-margin-width",
5518 left_margin_cols,
5519 doc: /* Default value of `left-margin-width' for buffers that don't override it.
5520 This is the same as (default-value 'left-margin-width). */);
5522 DEFVAR_BUFFER_DEFAULTS ("default-right-margin-width",
5523 right_margin_cols,
5524 doc: /* Default value of `right-margin-width' for buffers that don't override it.
5525 This is the same as (default-value 'right-margin-width). */);
5527 DEFVAR_BUFFER_DEFAULTS ("default-left-fringe-width",
5528 left_fringe_width,
5529 doc: /* Default value of `left-fringe-width' for buffers that don't override it.
5530 This is the same as (default-value 'left-fringe-width). */);
5532 DEFVAR_BUFFER_DEFAULTS ("default-right-fringe-width",
5533 right_fringe_width,
5534 doc: /* Default value of `right-fringe-width' for buffers that don't override it.
5535 This is the same as (default-value 'right-fringe-width). */);
5537 DEFVAR_BUFFER_DEFAULTS ("default-fringes-outside-margins",
5538 fringes_outside_margins,
5539 doc: /* Default value of `fringes-outside-margins' for buffers that don't override it.
5540 This is the same as (default-value 'fringes-outside-margins). */);
5542 DEFVAR_BUFFER_DEFAULTS ("default-scroll-bar-width",
5543 scroll_bar_width,
5544 doc: /* Default value of `scroll-bar-width' for buffers that don't override it.
5545 This is the same as (default-value 'scroll-bar-width). */);
5547 DEFVAR_BUFFER_DEFAULTS ("default-vertical-scroll-bar",
5548 vertical_scroll_bar_type,
5549 doc: /* Default value of `vertical-scroll-bar' for buffers that don't override it.
5550 This is the same as (default-value 'vertical-scroll-bar). */);
5552 DEFVAR_BUFFER_DEFAULTS ("default-indicate-empty-lines",
5553 indicate_empty_lines,
5554 doc: /* Default value of `indicate-empty-lines' for buffers that don't override it.
5555 This is the same as (default-value 'indicate-empty-lines). */);
5557 DEFVAR_BUFFER_DEFAULTS ("default-indicate-buffer-boundaries",
5558 indicate_buffer_boundaries,
5559 doc: /* Default value of `indicate-buffer-boundaries' for buffers that don't override it.
5560 This is the same as (default-value 'indicate-buffer-boundaries). */);
5562 DEFVAR_BUFFER_DEFAULTS ("default-fringe-indicator-alist",
5563 fringe_indicator_alist,
5564 doc: /* Default value of `fringe-indicator-alist' for buffers that don't override it.
5565 This is the same as (default-value 'fringe-indicator-alist'). */);
5567 DEFVAR_BUFFER_DEFAULTS ("default-fringe-cursor-alist",
5568 fringe_cursor_alist,
5569 doc: /* Default value of `fringe-cursor-alist' for buffers that don't override it.
5570 This is the same as (default-value 'fringe-cursor-alist'). */);
5572 DEFVAR_BUFFER_DEFAULTS ("default-scroll-up-aggressively",
5573 scroll_up_aggressively,
5574 doc: /* Default value of `scroll-up-aggressively'.
5575 This value applies in buffers that don't have their own local values.
5576 This is the same as (default-value 'scroll-up-aggressively). */);
5578 DEFVAR_BUFFER_DEFAULTS ("default-scroll-down-aggressively",
5579 scroll_down_aggressively,
5580 doc: /* Default value of `scroll-down-aggressively'.
5581 This value applies in buffers that don't have their own local values.
5582 This is the same as (default-value 'scroll-down-aggressively). */);
5584 DEFVAR_PER_BUFFER ("header-line-format",
5585 &BVAR (current_buffer, header_line_format),
5586 Qnil,
5587 doc: /* Analogous to `mode-line-format', but controls the header line.
5588 The header line appears, optionally, at the top of a window;
5589 the mode line appears at the bottom. */);
5591 DEFVAR_PER_BUFFER ("mode-line-format", &BVAR (current_buffer, mode_line_format),
5592 Qnil,
5593 doc: /* Template for displaying mode line for current buffer.
5595 The value may be nil, a string, a symbol or a list.
5597 A value of nil means don't display a mode line.
5599 For any symbol other than t or nil, the symbol's value is processed as
5600 a mode line construct. As a special exception, if that value is a
5601 string, the string is processed verbatim, without handling any
5602 %-constructs (see below). Also, unless the symbol has a non-nil
5603 `risky-local-variable' property, all properties in any strings, as
5604 well as all :eval and :propertize forms in the value, are ignored.
5606 A list whose car is a string or list is processed by processing each
5607 of the list elements recursively, as separate mode line constructs,
5608 and concatenating the results.
5610 A list of the form `(:eval FORM)' is processed by evaluating FORM and
5611 using the result as a mode line construct. Be careful--FORM should
5612 not load any files, because that can cause an infinite recursion.
5614 A list of the form `(:propertize ELT PROPS...)' is processed by
5615 processing ELT as the mode line construct, and adding the text
5616 properties PROPS to the result.
5618 A list whose car is a symbol is processed by examining the symbol's
5619 value, and, if that value is non-nil, processing the cadr of the list
5620 recursively; and if that value is nil, processing the caddr of the
5621 list recursively.
5623 A list whose car is an integer is processed by processing the cadr of
5624 the list, and padding (if the number is positive) or truncating (if
5625 negative) to the width specified by that number.
5627 A string is printed verbatim in the mode line except for %-constructs:
5628 %b -- print buffer name. %f -- print visited file name.
5629 %F -- print frame name.
5630 %* -- print %, * or hyphen. %+ -- print *, % or hyphen.
5631 %& is like %*, but ignore read-only-ness.
5632 % means buffer is read-only and * means it is modified.
5633 For a modified read-only buffer, %* gives % and %+ gives *.
5634 %s -- print process status. %l -- print the current line number.
5635 %c -- print the current column number (this makes editing slower).
5636 To make the column number update correctly in all cases,
5637 `column-number-mode' must be non-nil.
5638 %i -- print the size of the buffer.
5639 %I -- like %i, but use k, M, G, etc., to abbreviate.
5640 %p -- print percent of buffer above top of window, or Top, Bot or All.
5641 %P -- print percent of buffer above bottom of window, perhaps plus Top,
5642 or print Bottom or All.
5643 %n -- print Narrow if appropriate.
5644 %t -- visited file is text or binary (if OS supports this distinction).
5645 %z -- print mnemonics of keyboard, terminal, and buffer coding systems.
5646 %Z -- like %z, but including the end-of-line format.
5647 %e -- print error message about full memory.
5648 %@ -- print @ or hyphen. @ means that default-directory is on a
5649 remote machine.
5650 %[ -- print one [ for each recursive editing level. %] similar.
5651 %% -- print %. %- -- print infinitely many dashes.
5652 Decimal digits after the % specify field width to which to pad. */);
5654 DEFVAR_BUFFER_DEFAULTS ("default-major-mode", major_mode,
5655 doc: /* Value of `major-mode' for new buffers. */);
5657 DEFVAR_PER_BUFFER ("major-mode", &BVAR (current_buffer, major_mode),
5658 make_number (Lisp_Symbol),
5659 doc: /* Symbol for current buffer's major mode.
5660 The default value (normally `fundamental-mode') affects new buffers.
5661 A value of nil means to use the current buffer's major mode, provided
5662 it is not marked as "special".
5664 When a mode is used by default, `find-file' switches to it before it
5665 reads the contents into the buffer and before it finishes setting up
5666 the buffer. Thus, the mode and its hooks should not expect certain
5667 variables such as `buffer-read-only' and `buffer-file-coding-system'
5668 to be set up. */);
5670 DEFVAR_PER_BUFFER ("mode-name", &BVAR (current_buffer, mode_name),
5671 Qnil,
5672 doc: /* Pretty name of current buffer's major mode.
5673 Usually a string, but can use any of the constructs for `mode-line-format',
5674 which see.
5675 Format with `format-mode-line' to produce a string value. */);
5677 DEFVAR_PER_BUFFER ("local-abbrev-table", &BVAR (current_buffer, abbrev_table), Qnil,
5678 doc: /* Local (mode-specific) abbrev table of current buffer. */);
5680 DEFVAR_PER_BUFFER ("abbrev-mode", &BVAR (current_buffer, abbrev_mode), Qnil,
5681 doc: /* Non-nil if Abbrev mode is enabled.
5682 Use the command `abbrev-mode' to change this variable. */);
5684 DEFVAR_PER_BUFFER ("case-fold-search", &BVAR (current_buffer, case_fold_search),
5685 Qnil,
5686 doc: /* Non-nil if searches and matches should ignore case. */);
5688 DEFVAR_PER_BUFFER ("fill-column", &BVAR (current_buffer, fill_column),
5689 make_number (Lisp_Int0),
5690 doc: /* Column beyond which automatic line-wrapping should happen.
5691 Interactively, you can set the buffer local value using \\[set-fill-column]. */);
5693 DEFVAR_PER_BUFFER ("left-margin", &BVAR (current_buffer, left_margin),
5694 make_number (Lisp_Int0),
5695 doc: /* Column for the default `indent-line-function' to indent to.
5696 Linefeed indents to this column in Fundamental mode. */);
5698 DEFVAR_PER_BUFFER ("tab-width", &BVAR (current_buffer, tab_width),
5699 make_number (Lisp_Int0),
5700 doc: /* Distance between tab stops (for display of tab characters), in columns.
5701 This should be an integer greater than zero. */);
5703 DEFVAR_PER_BUFFER ("ctl-arrow", &BVAR (current_buffer, ctl_arrow), Qnil,
5704 doc: /* Non-nil means display control chars with uparrow.
5705 A value of nil means use backslash and octal digits.
5706 This variable does not apply to characters whose display is specified
5707 in the current display table (if there is one). */);
5709 DEFVAR_PER_BUFFER ("enable-multibyte-characters",
5710 &BVAR (current_buffer, enable_multibyte_characters),
5711 Qnil,
5712 doc: /* Non-nil means the buffer contents are regarded as multi-byte characters.
5713 Otherwise they are regarded as unibyte. This affects the display,
5714 file I/O and the behavior of various editing commands.
5716 This variable is buffer-local but you cannot set it directly;
5717 use the function `set-buffer-multibyte' to change a buffer's representation.
5718 See also Info node `(elisp)Text Representations'. */);
5719 XSYMBOL (intern_c_string ("enable-multibyte-characters"))->constant = 1;
5721 DEFVAR_PER_BUFFER ("buffer-file-coding-system",
5722 &BVAR (current_buffer, buffer_file_coding_system), Qnil,
5723 doc: /* Coding system to be used for encoding the buffer contents on saving.
5724 This variable applies to saving the buffer, and also to `write-region'
5725 and other functions that use `write-region'.
5726 It does not apply to sending output to subprocesses, however.
5728 If this is nil, the buffer is saved without any code conversion
5729 unless some coding system is specified in `file-coding-system-alist'
5730 for the buffer file.
5732 If the text to be saved cannot be encoded as specified by this variable,
5733 an alternative encoding is selected by `select-safe-coding-system', which see.
5735 The variable `coding-system-for-write', if non-nil, overrides this variable.
5737 This variable is never applied to a way of decoding a file while reading it. */);
5739 DEFVAR_PER_BUFFER ("bidi-display-reordering",
5740 &BVAR (current_buffer, bidi_display_reordering), Qnil,
5741 doc: /* Non-nil means reorder bidirectional text for display in the visual order. */);
5743 DEFVAR_PER_BUFFER ("bidi-paragraph-direction",
5744 &BVAR (current_buffer, bidi_paragraph_direction), Qnil,
5745 doc: /* If non-nil, forces directionality of text paragraphs in the buffer.
5747 If this is nil (the default), the direction of each paragraph is
5748 determined by the first strong directional character of its text.
5749 The values of `right-to-left' and `left-to-right' override that.
5750 Any other value is treated as nil.
5752 This variable has no effect unless the buffer's value of
5753 \`bidi-display-reordering' is non-nil. */);
5755 DEFVAR_PER_BUFFER ("truncate-lines", &BVAR (current_buffer, truncate_lines), Qnil,
5756 doc: /* Non-nil means do not display continuation lines.
5757 Instead, give each line of text just one screen line.
5759 Note that this is overridden by the variable
5760 `truncate-partial-width-windows' if that variable is non-nil
5761 and this buffer is not full-frame width.
5763 Minibuffers set this variable to nil. */);
5765 DEFVAR_PER_BUFFER ("word-wrap", &BVAR (current_buffer, word_wrap), Qnil,
5766 doc: /* Non-nil means to use word-wrapping for continuation lines.
5767 When word-wrapping is on, continuation lines are wrapped at the space
5768 or tab character nearest to the right window edge.
5769 If nil, continuation lines are wrapped at the right screen edge.
5771 This variable has no effect if long lines are truncated (see
5772 `truncate-lines' and `truncate-partial-width-windows'). If you use
5773 word-wrapping, you might want to reduce the value of
5774 `truncate-partial-width-windows', since wrapping can make text readable
5775 in narrower windows.
5777 Instead of setting this variable directly, most users should use
5778 Visual Line mode . Visual Line mode, when enabled, sets `word-wrap'
5779 to t, and additionally redefines simple editing commands to act on
5780 visual lines rather than logical lines. See the documentation of
5781 `visual-line-mode'. */);
5783 DEFVAR_PER_BUFFER ("default-directory", &BVAR (current_buffer, directory),
5784 make_number (Lisp_String),
5785 doc: /* Name of default directory of current buffer. Should end with slash.
5786 To interactively change the default directory, use command `cd'. */);
5788 DEFVAR_PER_BUFFER ("auto-fill-function", &BVAR (current_buffer, auto_fill_function),
5789 Qnil,
5790 doc: /* Function called (if non-nil) to perform auto-fill.
5791 It is called after self-inserting any character specified in
5792 the `auto-fill-chars' table.
5793 NOTE: This variable is not a hook;
5794 its value may not be a list of functions. */);
5796 DEFVAR_PER_BUFFER ("buffer-file-name", &BVAR (current_buffer, filename),
5797 make_number (Lisp_String),
5798 doc: /* Name of file visited in current buffer, or nil if not visiting a file. */);
5800 DEFVAR_PER_BUFFER ("buffer-file-truename", &BVAR (current_buffer, file_truename),
5801 make_number (Lisp_String),
5802 doc: /* Abbreviated truename of file visited in current buffer, or nil if none.
5803 The truename of a file is calculated by `file-truename'
5804 and then abbreviated with `abbreviate-file-name'. */);
5806 DEFVAR_PER_BUFFER ("buffer-auto-save-file-name",
5807 &BVAR (current_buffer, auto_save_file_name),
5808 make_number (Lisp_String),
5809 doc: /* Name of file for auto-saving current buffer.
5810 If it is nil, that means don't auto-save this buffer. */);
5812 DEFVAR_PER_BUFFER ("buffer-read-only", &BVAR (current_buffer, read_only), Qnil,
5813 doc: /* Non-nil if this buffer is read-only. */);
5815 DEFVAR_PER_BUFFER ("buffer-backed-up", &BVAR (current_buffer, backed_up), Qnil,
5816 doc: /* Non-nil if this buffer's file has been backed up.
5817 Backing up is done before the first time the file is saved. */);
5819 DEFVAR_PER_BUFFER ("buffer-saved-size", &BVAR (current_buffer, save_length),
5820 make_number (Lisp_Int0),
5821 doc: /* Length of current buffer when last read in, saved or auto-saved.
5822 0 initially.
5823 -1 means auto-saving turned off until next real save.
5825 If you set this to -2, that means don't turn off auto-saving in this buffer
5826 if its text size shrinks. If you use `buffer-swap-text' on a buffer,
5827 you probably should set this to -2 in that buffer. */);
5829 DEFVAR_PER_BUFFER ("selective-display", &BVAR (current_buffer, selective_display),
5830 Qnil,
5831 doc: /* Non-nil enables selective display.
5832 An integer N as value means display only lines
5833 that start with less than N columns of space.
5834 A value of t means that the character ^M makes itself and
5835 all the rest of the line invisible; also, when saving the buffer
5836 in a file, save the ^M as a newline. */);
5838 DEFVAR_PER_BUFFER ("selective-display-ellipses",
5839 &BVAR (current_buffer, selective_display_ellipses),
5840 Qnil,
5841 doc: /* Non-nil means display ... on previous line when a line is invisible. */);
5843 DEFVAR_PER_BUFFER ("overwrite-mode", &BVAR (current_buffer, overwrite_mode), Qnil,
5844 doc: /* Non-nil if self-insertion should replace existing text.
5845 The value should be one of `overwrite-mode-textual',
5846 `overwrite-mode-binary', or nil.
5847 If it is `overwrite-mode-textual', self-insertion still
5848 inserts at the end of a line, and inserts when point is before a tab,
5849 until the tab is filled in.
5850 If `overwrite-mode-binary', self-insertion replaces newlines and tabs too. */);
5852 DEFVAR_PER_BUFFER ("buffer-display-table", &BVAR (current_buffer, display_table),
5853 Qnil,
5854 doc: /* Display table that controls display of the contents of current buffer.
5856 If this variable is nil, the value of `standard-display-table' is used.
5857 Each window can have its own, overriding display table, see
5858 `set-window-display-table' and `window-display-table'.
5860 The display table is a char-table created with `make-display-table'.
5861 A char-table is an array indexed by character codes. Normal array
5862 primitives `aref' and `aset' can be used to access elements of a char-table.
5864 Each of the char-table elements control how to display the corresponding
5865 text character: the element at index C in the table says how to display
5866 the character whose code is C. Each element should be a vector of
5867 characters or nil. The value nil means display the character in the
5868 default fashion; otherwise, the characters from the vector are delivered
5869 to the screen instead of the original character.
5871 For example, (aset buffer-display-table ?X [?Y]) tells Emacs
5872 to display a capital Y instead of each X character.
5874 In addition, a char-table has six extra slots to control the display of:
5876 the end of a truncated screen line (extra-slot 0, a single character);
5877 the end of a continued line (extra-slot 1, a single character);
5878 the escape character used to display character codes in octal
5879 (extra-slot 2, a single character);
5880 the character used as an arrow for control characters (extra-slot 3,
5881 a single character);
5882 the decoration indicating the presence of invisible lines (extra-slot 4,
5883 a vector of characters);
5884 the character used to draw the border between side-by-side windows
5885 (extra-slot 5, a single character).
5887 See also the functions `display-table-slot' and `set-display-table-slot'. */);
5889 DEFVAR_PER_BUFFER ("left-margin-width", &BVAR (current_buffer, left_margin_cols),
5890 Qnil,
5891 doc: /* Width of left marginal area for display of a buffer.
5892 A value of nil means no marginal area. */);
5894 DEFVAR_PER_BUFFER ("right-margin-width", &BVAR (current_buffer, right_margin_cols),
5895 Qnil,
5896 doc: /* Width of right marginal area for display of a buffer.
5897 A value of nil means no marginal area. */);
5899 DEFVAR_PER_BUFFER ("left-fringe-width", &BVAR (current_buffer, left_fringe_width),
5900 Qnil,
5901 doc: /* Width of this buffer's left fringe (in pixels).
5902 A value of 0 means no left fringe is shown in this buffer's window.
5903 A value of nil means to use the left fringe width from the window's frame. */);
5905 DEFVAR_PER_BUFFER ("right-fringe-width", &BVAR (current_buffer, right_fringe_width),
5906 Qnil,
5907 doc: /* Width of this buffer's right fringe (in pixels).
5908 A value of 0 means no right fringe is shown in this buffer's window.
5909 A value of nil means to use the right fringe width from the window's frame. */);
5911 DEFVAR_PER_BUFFER ("fringes-outside-margins", &BVAR (current_buffer, fringes_outside_margins),
5912 Qnil,
5913 doc: /* Non-nil means to display fringes outside display margins.
5914 A value of nil means to display fringes between margins and buffer text. */);
5916 DEFVAR_PER_BUFFER ("scroll-bar-width", &BVAR (current_buffer, scroll_bar_width),
5917 Qnil,
5918 doc: /* Width of this buffer's scroll bars in pixels.
5919 A value of nil means to use the scroll bar width from the window's frame. */);
5921 DEFVAR_PER_BUFFER ("vertical-scroll-bar", &BVAR (current_buffer, vertical_scroll_bar_type),
5922 Qnil,
5923 doc: /* Position of this buffer's vertical scroll bar.
5924 The value takes effect whenever you tell a window to display this buffer;
5925 for instance, with `set-window-buffer' or when `display-buffer' displays it.
5927 A value of `left' or `right' means put the vertical scroll bar at that side
5928 of the window; a value of nil means don't show any vertical scroll bars.
5929 A value of t (the default) means do whatever the window's frame specifies. */);
5931 DEFVAR_PER_BUFFER ("indicate-empty-lines",
5932 &BVAR (current_buffer, indicate_empty_lines), Qnil,
5933 doc: /* Visually indicate empty lines after the buffer end.
5934 If non-nil, a bitmap is displayed in the left fringe of a window on
5935 window-systems. */);
5937 DEFVAR_PER_BUFFER ("indicate-buffer-boundaries",
5938 &BVAR (current_buffer, indicate_buffer_boundaries), Qnil,
5939 doc: /* Visually indicate buffer boundaries and scrolling.
5940 If non-nil, the first and last line of the buffer are marked in the fringe
5941 of a window on window-systems with angle bitmaps, or if the window can be
5942 scrolled, the top and bottom line of the window are marked with up and down
5943 arrow bitmaps.
5945 If value is a symbol `left' or `right', both angle and arrow bitmaps
5946 are displayed in the left or right fringe, resp. Any other value
5947 that doesn't look like an alist means display the angle bitmaps in
5948 the left fringe but no arrows.
5950 You can exercise more precise control by using an alist as the
5951 value. Each alist element (INDICATOR . POSITION) specifies
5952 where to show one of the indicators. INDICATOR is one of `top',
5953 `bottom', `up', `down', or t, which specifies the default position,
5954 and POSITION is one of `left', `right', or nil, meaning do not show
5955 this indicator.
5957 For example, ((top . left) (t . right)) places the top angle bitmap in
5958 left fringe, the bottom angle bitmap in right fringe, and both arrow
5959 bitmaps in right fringe. To show just the angle bitmaps in the left
5960 fringe, but no arrow bitmaps, use ((top . left) (bottom . left)). */);
5962 DEFVAR_PER_BUFFER ("fringe-indicator-alist",
5963 &BVAR (current_buffer, fringe_indicator_alist), Qnil,
5964 doc: /* Mapping from logical to physical fringe indicator bitmaps.
5965 The value is an alist where each element (INDICATOR . BITMAPS)
5966 specifies the fringe bitmaps used to display a specific logical
5967 fringe indicator.
5969 INDICATOR specifies the logical indicator type which is one of the
5970 following symbols: `truncation' , `continuation', `overlay-arrow',
5971 `top', `bottom', `top-bottom', `up', `down', empty-line', or `unknown'.
5973 BITMAPS is a list of symbols (LEFT RIGHT [LEFT1 RIGHT1]) which specifies
5974 the actual bitmap shown in the left or right fringe for the logical
5975 indicator. LEFT and RIGHT are the bitmaps shown in the left and/or
5976 right fringe for the specific indicator. The LEFT1 or RIGHT1 bitmaps
5977 are used only for the `bottom' and `top-bottom' indicators when the
5978 last (only) line has no final newline. BITMAPS may also be a single
5979 symbol which is used in both left and right fringes. */);
5981 DEFVAR_PER_BUFFER ("fringe-cursor-alist",
5982 &BVAR (current_buffer, fringe_cursor_alist), Qnil,
5983 doc: /* Mapping from logical to physical fringe cursor bitmaps.
5984 The value is an alist where each element (CURSOR . BITMAP)
5985 specifies the fringe bitmaps used to display a specific logical
5986 cursor type in the fringe.
5988 CURSOR specifies the logical cursor type which is one of the following
5989 symbols: `box' , `hollow', `bar', `hbar', or `hollow-small'. The last
5990 one is used to show a hollow cursor on narrow lines display lines
5991 where the normal hollow cursor will not fit.
5993 BITMAP is the corresponding fringe bitmap shown for the logical
5994 cursor type. */);
5996 DEFVAR_PER_BUFFER ("scroll-up-aggressively",
5997 &BVAR (current_buffer, scroll_up_aggressively), Qnil,
5998 doc: /* How far to scroll windows upward.
5999 If you move point off the bottom, the window scrolls automatically.
6000 This variable controls how far it scrolls. The value nil, the default,
6001 means scroll to center point. A fraction means scroll to put point
6002 that fraction of the window's height from the bottom of the window.
6003 When the value is 0.0, point goes at the bottom line, which in the
6004 simple case that you moved off with C-f means scrolling just one line.
6005 1.0 means point goes at the top, so that in that simple case, the
6006 window scrolls by a full window height. Meaningful values are
6007 between 0.0 and 1.0, inclusive. */);
6009 DEFVAR_PER_BUFFER ("scroll-down-aggressively",
6010 &BVAR (current_buffer, scroll_down_aggressively), Qnil,
6011 doc: /* How far to scroll windows downward.
6012 If you move point off the top, the window scrolls automatically.
6013 This variable controls how far it scrolls. The value nil, the default,
6014 means scroll to center point. A fraction means scroll to put point
6015 that fraction of the window's height from the top of the window.
6016 When the value is 0.0, point goes at the top line, which in the
6017 simple case that you moved off with C-b means scrolling just one line.
6018 1.0 means point goes at the bottom, so that in that simple case, the
6019 window scrolls by a full window height. Meaningful values are
6020 between 0.0 and 1.0, inclusive. */);
6022 /*DEFVAR_LISP ("debug-check-symbol", &Vcheck_symbol,
6023 "Don't ask.");
6026 DEFVAR_LISP ("before-change-functions", Vbefore_change_functions,
6027 doc: /* List of functions to call before each text change.
6028 Two arguments are passed to each function: the positions of
6029 the beginning and end of the range of old text to be changed.
6030 \(For an insertion, the beginning and end are at the same place.)
6031 No information is given about the length of the text after the change.
6033 Buffer changes made while executing the `before-change-functions'
6034 don't call any before-change or after-change functions.
6035 That's because `inhibit-modification-hooks' is temporarily set non-nil.
6037 If an unhandled error happens in running these functions,
6038 the variable's value remains nil. That prevents the error
6039 from happening repeatedly and making Emacs nonfunctional. */);
6040 Vbefore_change_functions = Qnil;
6042 DEFVAR_LISP ("after-change-functions", Vafter_change_functions,
6043 doc: /* List of functions to call after each text change.
6044 Three arguments are passed to each function: the positions of
6045 the beginning and end of the range of changed text,
6046 and the length in bytes of the pre-change text replaced by that range.
6047 \(For an insertion, the pre-change length is zero;
6048 for a deletion, that length is the number of bytes deleted,
6049 and the post-change beginning and end are at the same place.)
6051 Buffer changes made while executing the `after-change-functions'
6052 don't call any before-change or after-change functions.
6053 That's because `inhibit-modification-hooks' is temporarily set non-nil.
6055 If an unhandled error happens in running these functions,
6056 the variable's value remains nil. That prevents the error
6057 from happening repeatedly and making Emacs nonfunctional. */);
6058 Vafter_change_functions = Qnil;
6060 DEFVAR_LISP ("first-change-hook", Vfirst_change_hook,
6061 doc: /* A list of functions to call before changing a buffer which is unmodified.
6062 The functions are run using the `run-hooks' function. */);
6063 Vfirst_change_hook = Qnil;
6065 DEFVAR_PER_BUFFER ("buffer-undo-list", &BVAR (current_buffer, undo_list), Qnil,
6066 doc: /* List of undo entries in current buffer.
6067 Recent changes come first; older changes follow newer.
6069 An entry (BEG . END) represents an insertion which begins at
6070 position BEG and ends at position END.
6072 An entry (TEXT . POSITION) represents the deletion of the string TEXT
6073 from (abs POSITION). If POSITION is positive, point was at the front
6074 of the text being deleted; if negative, point was at the end.
6076 An entry (t HIGH LOW USEC PSEC) indicates that the buffer was previously
6077 unmodified; (HIGH LOW USEC PSEC) is in the same style as (current-time)
6078 and is the visited file's modification time, as of that time. If the
6079 modification time of the most recent save is different, this entry is
6080 obsolete.
6082 An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
6083 was modified between BEG and END. PROPERTY is the property name,
6084 and VALUE is the old value.
6086 An entry (apply FUN-NAME . ARGS) means undo the change with
6087 \(apply FUN-NAME ARGS).
6089 An entry (apply DELTA BEG END FUN-NAME . ARGS) supports selective undo
6090 in the active region. BEG and END is the range affected by this entry
6091 and DELTA is the number of bytes added or deleted in that range by
6092 this change.
6094 An entry (MARKER . DISTANCE) indicates that the marker MARKER
6095 was adjusted in position by the offset DISTANCE (an integer).
6097 An entry of the form POSITION indicates that point was at the buffer
6098 location given by the integer. Undoing an entry of this form places
6099 point at POSITION.
6101 Entries with value `nil' mark undo boundaries. The undo command treats
6102 the changes between two undo boundaries as a single step to be undone.
6104 If the value of the variable is t, undo information is not recorded. */);
6106 DEFVAR_PER_BUFFER ("mark-active", &BVAR (current_buffer, mark_active), Qnil,
6107 doc: /* Non-nil means the mark and region are currently active in this buffer. */);
6109 DEFVAR_PER_BUFFER ("cache-long-line-scans", &BVAR (current_buffer, cache_long_line_scans), Qnil,
6110 doc: /* Non-nil means that Emacs should use caches to handle long lines more quickly.
6112 Normally, the line-motion functions work by scanning the buffer for
6113 newlines. Columnar operations (like `move-to-column' and
6114 `compute-motion') also work by scanning the buffer, summing character
6115 widths as they go. This works well for ordinary text, but if the
6116 buffer's lines are very long (say, more than 500 characters), these
6117 motion functions will take longer to execute. Emacs may also take
6118 longer to update the display.
6120 If `cache-long-line-scans' is non-nil, these motion functions cache the
6121 results of their scans, and consult the cache to avoid rescanning
6122 regions of the buffer until the text is modified. The caches are most
6123 beneficial when they prevent the most searching---that is, when the
6124 buffer contains long lines and large regions of characters with the
6125 same, fixed screen width.
6127 When `cache-long-line-scans' is non-nil, processing short lines will
6128 become slightly slower (because of the overhead of consulting the
6129 cache), and the caches will use memory roughly proportional to the
6130 number of newlines and characters whose screen width varies.
6132 The caches require no explicit maintenance; their accuracy is
6133 maintained internally by the Emacs primitives. Enabling or disabling
6134 the cache should not affect the behavior of any of the motion
6135 functions; it should only affect their performance. */);
6137 DEFVAR_PER_BUFFER ("point-before-scroll", &BVAR (current_buffer, point_before_scroll), Qnil,
6138 doc: /* Value of point before the last series of scroll operations, or nil. */);
6140 DEFVAR_PER_BUFFER ("buffer-file-format", &BVAR (current_buffer, file_format), Qnil,
6141 doc: /* List of formats to use when saving this buffer.
6142 Formats are defined by `format-alist'. This variable is
6143 set when a file is visited. */);
6145 DEFVAR_PER_BUFFER ("buffer-auto-save-file-format",
6146 &BVAR (current_buffer, auto_save_file_format), Qnil,
6147 doc: /* Format in which to write auto-save files.
6148 Should be a list of symbols naming formats that are defined in `format-alist'.
6149 If it is t, which is the default, auto-save files are written in the
6150 same format as a regular save would use. */);
6152 DEFVAR_PER_BUFFER ("buffer-invisibility-spec",
6153 &BVAR (current_buffer, invisibility_spec), Qnil,
6154 doc: /* Invisibility spec of this buffer.
6155 The default is t, which means that text is invisible
6156 if it has a non-nil `invisible' property.
6157 If the value is a list, a text character is invisible if its `invisible'
6158 property is an element in that list (or is a list with members in common).
6159 If an element is a cons cell of the form (PROP . ELLIPSIS),
6160 then characters with property value PROP are invisible,
6161 and they have an ellipsis as well if ELLIPSIS is non-nil. */);
6163 DEFVAR_PER_BUFFER ("buffer-display-count",
6164 &BVAR (current_buffer, display_count), Qnil,
6165 doc: /* A number incremented each time this buffer is displayed in a window.
6166 The function `set-window-buffer' increments it. */);
6168 DEFVAR_PER_BUFFER ("buffer-display-time",
6169 &BVAR (current_buffer, display_time), Qnil,
6170 doc: /* Time stamp updated each time this buffer is displayed in a window.
6171 The function `set-window-buffer' updates this variable
6172 to the value obtained by calling `current-time'.
6173 If the buffer has never been shown in a window, the value is nil. */);
6175 DEFVAR_LISP ("transient-mark-mode", Vtransient_mark_mode,
6176 doc: /* Non-nil if Transient Mark mode is enabled.
6177 See the command `transient-mark-mode' for a description of this minor mode.
6179 Non-nil also enables highlighting of the region whenever the mark is active.
6180 The variable `highlight-nonselected-windows' controls whether to highlight
6181 all windows or just the selected window.
6183 Lisp programs may give this variable certain special values:
6185 - A value of `lambda' enables Transient Mark mode temporarily.
6186 It is disabled again after any subsequent action that would
6187 normally deactivate the mark (e.g. buffer modification).
6189 - A value of (only . OLDVAL) enables Transient Mark mode
6190 temporarily. After any subsequent point motion command that is
6191 not shift-translated, or any other action that would normally
6192 deactivate the mark (e.g. buffer modification), the value of
6193 `transient-mark-mode' is set to OLDVAL. */);
6194 Vtransient_mark_mode = Qnil;
6196 DEFVAR_LISP ("inhibit-read-only", Vinhibit_read_only,
6197 doc: /* Non-nil means disregard read-only status of buffers or characters.
6198 If the value is t, disregard `buffer-read-only' and all `read-only'
6199 text properties. If the value is a list, disregard `buffer-read-only'
6200 and disregard a `read-only' text property if the property value
6201 is a member of the list. */);
6202 Vinhibit_read_only = Qnil;
6204 DEFVAR_PER_BUFFER ("cursor-type", &BVAR (current_buffer, cursor_type), Qnil,
6205 doc: /* Cursor to use when this buffer is in the selected window.
6206 Values are interpreted as follows:
6208 t use the cursor specified for the frame
6209 nil don't display a cursor
6210 box display a filled box cursor
6211 hollow display a hollow box cursor
6212 bar display a vertical bar cursor with default width
6213 (bar . WIDTH) display a vertical bar cursor with width WIDTH
6214 hbar display a horizontal bar cursor with default height
6215 (hbar . HEIGHT) display a horizontal bar cursor with height HEIGHT
6216 ANYTHING ELSE display a hollow box cursor
6218 When the buffer is displayed in a non-selected window, the
6219 cursor's appearance is instead controlled by the variable
6220 `cursor-in-non-selected-windows'. */);
6222 DEFVAR_PER_BUFFER ("line-spacing",
6223 &BVAR (current_buffer, extra_line_spacing), Qnil,
6224 doc: /* Additional space to put between lines when displaying a buffer.
6225 The space is measured in pixels, and put below lines on graphic displays,
6226 see `display-graphic-p'.
6227 If value is a floating point number, it specifies the spacing relative
6228 to the default frame line height. A value of nil means add no extra space. */);
6230 DEFVAR_PER_BUFFER ("cursor-in-non-selected-windows",
6231 &BVAR (current_buffer, cursor_in_non_selected_windows), Qnil,
6232 doc: /* Non-nil means show a cursor in non-selected windows.
6233 If nil, only shows a cursor in the selected window.
6234 If t, displays a cursor related to the usual cursor type
6235 \(a solid box becomes hollow, a bar becomes a narrower bar).
6236 You can also specify the cursor type as in the `cursor-type' variable.
6237 Use Custom to set this variable and update the display." */);
6239 DEFVAR_LISP ("kill-buffer-query-functions", Vkill_buffer_query_functions,
6240 doc: /* List of functions called with no args to query before killing a buffer.
6241 The buffer being killed will be current while the functions are running.
6243 If any of them returns nil, the buffer is not killed. Functions run by
6244 this hook are supposed to not change the current buffer. */);
6245 Vkill_buffer_query_functions = Qnil;
6247 DEFVAR_LISP ("change-major-mode-hook", Vchange_major_mode_hook,
6248 doc: /* Normal hook run before changing the major mode of a buffer.
6249 The function `kill-all-local-variables' runs this before doing anything else. */);
6250 Vchange_major_mode_hook = Qnil;
6251 DEFSYM (Qchange_major_mode_hook, "change-major-mode-hook");
6253 DEFVAR_LISP ("buffer-list-update-hook", Vbuffer_list_update_hook,
6254 doc: /* Hook run when the buffer list changes.
6255 Functions running this hook are `get-buffer-create',
6256 `make-indirect-buffer', `rename-buffer', `kill-buffer',
6257 and `bury-buffer-internal'. */);
6258 Vbuffer_list_update_hook = Qnil;
6259 DEFSYM (Qbuffer_list_update_hook, "buffer-list-update-hook");
6261 defsubr (&Sbuffer_live_p);
6262 defsubr (&Sbuffer_list);
6263 defsubr (&Sget_buffer);
6264 defsubr (&Sget_file_buffer);
6265 defsubr (&Sget_buffer_create);
6266 defsubr (&Smake_indirect_buffer);
6267 defsubr (&Sgenerate_new_buffer_name);
6268 defsubr (&Sbuffer_name);
6269 defsubr (&Sbuffer_file_name);
6270 defsubr (&Sbuffer_base_buffer);
6271 defsubr (&Sbuffer_local_value);
6272 defsubr (&Sbuffer_local_variables);
6273 defsubr (&Sbuffer_modified_p);
6274 defsubr (&Sset_buffer_modified_p);
6275 defsubr (&Sbuffer_modified_tick);
6276 defsubr (&Sbuffer_chars_modified_tick);
6277 defsubr (&Srename_buffer);
6278 defsubr (&Sother_buffer);
6279 defsubr (&Sbuffer_enable_undo);
6280 defsubr (&Skill_buffer);
6281 defsubr (&Sbury_buffer_internal);
6282 defsubr (&Sset_buffer_major_mode);
6283 defsubr (&Scurrent_buffer);
6284 defsubr (&Sset_buffer);
6285 defsubr (&Sbarf_if_buffer_read_only);
6286 defsubr (&Serase_buffer);
6287 defsubr (&Sbuffer_swap_text);
6288 defsubr (&Sset_buffer_multibyte);
6289 defsubr (&Skill_all_local_variables);
6291 defsubr (&Soverlayp);
6292 defsubr (&Smake_overlay);
6293 defsubr (&Sdelete_overlay);
6294 defsubr (&Sdelete_all_overlays);
6295 defsubr (&Smove_overlay);
6296 defsubr (&Soverlay_start);
6297 defsubr (&Soverlay_end);
6298 defsubr (&Soverlay_buffer);
6299 defsubr (&Soverlay_properties);
6300 defsubr (&Soverlays_at);
6301 defsubr (&Soverlays_in);
6302 defsubr (&Snext_overlay_change);
6303 defsubr (&Sprevious_overlay_change);
6304 defsubr (&Soverlay_recenter);
6305 defsubr (&Soverlay_lists);
6306 defsubr (&Soverlay_get);
6307 defsubr (&Soverlay_put);
6308 defsubr (&Srestore_buffer_modified_p);
6311 void
6312 keys_of_buffer (void)
6314 initial_define_key (control_x_map, 'b', "switch-to-buffer");
6315 initial_define_key (control_x_map, 'k', "kill-buffer");
6317 /* This must not be in syms_of_buffer, because Qdisabled is not
6318 initialized when that function gets called. */
6319 Fput (intern_c_string ("erase-buffer"), Qdisabled, Qt);