* process.h (PSET): Remove.
[emacs.git] / src / buffer.c
blob476f2e363b94f63a2edbca1365fe1460fc6be750
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 <setjmp.h>
30 #include <unistd.h>
32 #include <verify.h>
34 #include "lisp.h"
35 #include "intervals.h"
36 #include "window.h"
37 #include "commands.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "region-cache.h"
41 #include "indent.h"
42 #include "blockinput.h"
43 #include "keyboard.h"
44 #include "keymap.h"
45 #include "frame.h"
47 struct buffer *current_buffer; /* the current buffer */
49 /* First buffer in chain of all buffers (in reverse order of creation).
50 Threaded through ->header.next.buffer. */
52 struct buffer *all_buffers;
54 /* This structure holds the default values of the buffer-local variables
55 defined with DEFVAR_PER_BUFFER, that have special slots in each buffer.
56 The default value occupies the same slot in this structure
57 as an individual buffer's value occupies in that buffer.
58 Setting the default value also goes through the alist of buffers
59 and stores into each buffer that does not say it has a local value. */
61 struct buffer alignas (GCALIGNMENT) buffer_defaults;
63 /* A Lisp_Object pointer to the above, used for staticpro */
65 static Lisp_Object Vbuffer_defaults;
67 /* This structure marks which slots in a buffer have corresponding
68 default values in buffer_defaults.
69 Each such slot has a nonzero value in this structure.
70 The value has only one nonzero bit.
72 When a buffer has its own local value for a slot,
73 the entry for that slot (found in the same slot in this structure)
74 is turned on in the buffer's local_flags array.
76 If a slot in this structure is -1, then even though there may
77 be a DEFVAR_PER_BUFFER for the slot, there is no default value for it;
78 and the corresponding slot in buffer_defaults is not used.
80 If a slot in this structure corresponding to a DEFVAR_PER_BUFFER is
81 zero, that is a bug */
83 struct buffer buffer_local_flags;
85 /* This structure holds the names of symbols whose values may be
86 buffer-local. It is indexed and accessed in the same way as the above. */
88 struct buffer alignas (GCALIGNMENT) buffer_local_symbols;
90 /* A Lisp_Object pointer to the above, used for staticpro */
91 static Lisp_Object Vbuffer_local_symbols;
93 /* Return the symbol of the per-buffer variable at offset OFFSET in
94 the buffer structure. */
96 #define PER_BUFFER_SYMBOL(OFFSET) \
97 (*(Lisp_Object *)((OFFSET) + (char *) &buffer_local_symbols))
99 /* Maximum length of an overlay vector. */
100 #define OVERLAY_COUNT_MAX \
101 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, \
102 min (PTRDIFF_MAX, SIZE_MAX) / word_size))
104 /* Flags indicating which built-in buffer-local variables
105 are permanent locals. */
106 static char buffer_permanent_local_flags[MAX_PER_BUFFER_VARS];
108 /* Number of per-buffer variables used. */
110 int last_per_buffer_idx;
112 static void call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay,
113 int after, Lisp_Object arg1,
114 Lisp_Object arg2, Lisp_Object arg3);
115 static void swap_out_buffer_local_variables (struct buffer *b);
116 static void reset_buffer_local_variables (struct buffer *b, int permanent_too);
118 /* Alist of all buffer names vs the buffers. */
119 /* This used to be a variable, but is no longer,
120 to prevent lossage due to user rplac'ing this alist or its elements. */
121 Lisp_Object Vbuffer_alist;
123 static Lisp_Object Qkill_buffer_query_functions;
125 /* Hook run before changing a major mode. */
126 static Lisp_Object Qchange_major_mode_hook;
128 Lisp_Object Qfirst_change_hook;
129 Lisp_Object Qbefore_change_functions;
130 Lisp_Object Qafter_change_functions;
132 static Lisp_Object Qfundamental_mode, Qmode_class, Qpermanent_local;
133 static Lisp_Object Qpermanent_local_hook;
135 static Lisp_Object Qprotected_field;
137 static Lisp_Object QSFundamental; /* A string "Fundamental" */
139 static Lisp_Object Qkill_buffer_hook;
140 static Lisp_Object Qbuffer_list_update_hook;
142 static Lisp_Object Qget_file_buffer;
144 static Lisp_Object Qoverlayp;
146 Lisp_Object Qpriority, Qbefore_string, Qafter_string;
148 static Lisp_Object Qevaporate;
150 Lisp_Object Qmodification_hooks;
151 Lisp_Object Qinsert_in_front_hooks;
152 Lisp_Object Qinsert_behind_hooks;
154 static void alloc_buffer_text (struct buffer *, ptrdiff_t);
155 static void free_buffer_text (struct buffer *b);
156 static struct Lisp_Overlay * copy_overlays (struct buffer *, struct Lisp_Overlay *);
157 static void modify_overlay (struct buffer *, ptrdiff_t, ptrdiff_t);
158 static Lisp_Object buffer_lisp_local_variables (struct buffer *, int);
160 /* For debugging; temporary. See set_buffer_internal. */
161 /* Lisp_Object Qlisp_mode, Vcheck_symbol; */
163 void
164 nsberror (Lisp_Object spec)
166 if (STRINGP (spec))
167 error ("No buffer named %s", SDATA (spec));
168 error ("Invalid buffer argument");
171 DEFUN ("buffer-live-p", Fbuffer_live_p, Sbuffer_live_p, 1, 1, 0,
172 doc: /* Return non-nil if OBJECT is a buffer which has not been killed.
173 Value is nil if OBJECT is not a buffer or if it has been killed. */)
174 (Lisp_Object object)
176 return ((BUFFERP (object) && ! NILP (BVAR (XBUFFER (object), name)))
177 ? Qt : Qnil);
180 DEFUN ("buffer-list", Fbuffer_list, Sbuffer_list, 0, 1, 0,
181 doc: /* Return a list of all existing live buffers.
182 If the optional arg FRAME is a frame, we return the buffer list in the
183 proper order for that frame: the buffers show in FRAME come first,
184 followed by the rest of the buffers. */)
185 (Lisp_Object frame)
187 Lisp_Object general;
188 general = Fmapcar (Qcdr, Vbuffer_alist);
190 if (FRAMEP (frame))
192 Lisp_Object framelist, prevlist, tail;
193 Lisp_Object args[3];
195 CHECK_FRAME (frame);
196 framelist = Fcopy_sequence (XFRAME (frame)->buffer_list);
197 prevlist = Fnreverse (Fcopy_sequence
198 (XFRAME (frame)->buried_buffer_list));
200 /* Remove from GENERAL any buffer that duplicates one in
201 FRAMELIST or PREVLIST. */
202 tail = framelist;
203 while (CONSP (tail))
205 general = Fdelq (XCAR (tail), general);
206 tail = XCDR (tail);
208 tail = prevlist;
209 while (CONSP (tail))
211 general = Fdelq (XCAR (tail), general);
212 tail = XCDR (tail);
215 args[0] = framelist;
216 args[1] = general;
217 args[2] = prevlist;
218 return Fnconc (3, args);
220 else
221 return general;
224 /* Like Fassoc, but use Fstring_equal to compare
225 (which ignores text properties),
226 and don't ever QUIT. */
228 static Lisp_Object
229 assoc_ignore_text_properties (register Lisp_Object key, Lisp_Object list)
231 register Lisp_Object tail;
232 for (tail = list; CONSP (tail); tail = XCDR (tail))
234 register Lisp_Object elt, tem;
235 elt = XCAR (tail);
236 tem = Fstring_equal (Fcar (elt), key);
237 if (!NILP (tem))
238 return elt;
240 return Qnil;
243 DEFUN ("get-buffer", Fget_buffer, Sget_buffer, 1, 1, 0,
244 doc: /* Return the buffer named BUFFER-OR-NAME.
245 BUFFER-OR-NAME must be either a string or a buffer. If BUFFER-OR-NAME
246 is a string and there is no buffer with that name, return nil. If
247 BUFFER-OR-NAME is a buffer, return it as given. */)
248 (register Lisp_Object buffer_or_name)
250 if (BUFFERP (buffer_or_name))
251 return buffer_or_name;
252 CHECK_STRING (buffer_or_name);
254 return Fcdr (assoc_ignore_text_properties (buffer_or_name, Vbuffer_alist));
257 DEFUN ("get-file-buffer", Fget_file_buffer, Sget_file_buffer, 1, 1, 0,
258 doc: /* Return the buffer visiting file FILENAME (a string).
259 The buffer's `buffer-file-name' must match exactly the expansion of FILENAME.
260 If there is no such live buffer, return nil.
261 See also `find-buffer-visiting'. */)
262 (register Lisp_Object filename)
264 register Lisp_Object tail, buf, tem;
265 Lisp_Object handler;
267 CHECK_STRING (filename);
268 filename = Fexpand_file_name (filename, Qnil);
270 /* If the file name has special constructs in it,
271 call the corresponding file handler. */
272 handler = Ffind_file_name_handler (filename, Qget_file_buffer);
273 if (!NILP (handler))
275 Lisp_Object handled_buf = call2 (handler, Qget_file_buffer,
276 filename);
277 return BUFFERP (handled_buf) ? handled_buf : Qnil;
280 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
282 buf = Fcdr (XCAR (tail));
283 if (!BUFFERP (buf)) continue;
284 if (!STRINGP (BVAR (XBUFFER (buf), filename))) continue;
285 tem = Fstring_equal (BVAR (XBUFFER (buf), filename), filename);
286 if (!NILP (tem))
287 return buf;
289 return Qnil;
292 Lisp_Object
293 get_truename_buffer (register Lisp_Object filename)
295 register Lisp_Object tail, buf, tem;
297 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
299 buf = Fcdr (XCAR (tail));
300 if (!BUFFERP (buf)) continue;
301 if (!STRINGP (BVAR (XBUFFER (buf), file_truename))) continue;
302 tem = Fstring_equal (BVAR (XBUFFER (buf), file_truename), filename);
303 if (!NILP (tem))
304 return buf;
306 return Qnil;
309 DEFUN ("get-buffer-create", Fget_buffer_create, Sget_buffer_create, 1, 1, 0,
310 doc: /* Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.
311 If BUFFER-OR-NAME is a string and a live buffer with that name exists,
312 return that buffer. If no such buffer exists, create a new buffer with
313 that name and return it. If BUFFER-OR-NAME starts with a space, the new
314 buffer does not keep undo information.
316 If BUFFER-OR-NAME is a buffer instead of a string, return it as given,
317 even if it is dead. The return value is never nil. */)
318 (register Lisp_Object buffer_or_name)
320 register Lisp_Object buffer, name;
321 register struct buffer *b;
323 buffer = Fget_buffer (buffer_or_name);
324 if (!NILP (buffer))
325 return buffer;
327 if (SCHARS (buffer_or_name) == 0)
328 error ("Empty string for buffer name is not allowed");
330 b = allocate_buffer ();
332 /* An ordinary buffer uses its own struct buffer_text. */
333 b->text = &b->own_text;
334 b->base_buffer = NULL;
335 /* No one shares the text with us now. */
336 b->indirections = 0;
338 BUF_GAP_SIZE (b) = 20;
339 BLOCK_INPUT;
340 /* We allocate extra 1-byte at the tail and keep it always '\0' for
341 anchoring a search. */
342 alloc_buffer_text (b, BUF_GAP_SIZE (b) + 1);
343 UNBLOCK_INPUT;
344 if (! BUF_BEG_ADDR (b))
345 buffer_memory_full (BUF_GAP_SIZE (b) + 1);
347 b->pt = BEG;
348 b->begv = BEG;
349 b->zv = BEG;
350 b->pt_byte = BEG_BYTE;
351 b->begv_byte = BEG_BYTE;
352 b->zv_byte = BEG_BYTE;
354 BUF_GPT (b) = BEG;
355 BUF_GPT_BYTE (b) = BEG_BYTE;
357 BUF_Z (b) = BEG;
358 BUF_Z_BYTE (b) = BEG_BYTE;
359 BUF_MODIFF (b) = 1;
360 BUF_CHARS_MODIFF (b) = 1;
361 BUF_OVERLAY_MODIFF (b) = 1;
362 BUF_SAVE_MODIFF (b) = 1;
363 set_buffer_intervals (b, NULL);
364 BUF_UNCHANGED_MODIFIED (b) = 1;
365 BUF_OVERLAY_UNCHANGED_MODIFIED (b) = 1;
366 BUF_END_UNCHANGED (b) = 0;
367 BUF_BEG_UNCHANGED (b) = 0;
368 *(BUF_GPT_ADDR (b)) = *(BUF_Z_ADDR (b)) = 0; /* Put an anchor '\0'. */
369 b->text->inhibit_shrinking = 0;
371 b->newline_cache = 0;
372 b->width_run_cache = 0;
373 BSET (b, width_table, Qnil);
374 b->prevent_redisplay_optimizations_p = 1;
376 /* Put this on the chain of all buffers including killed ones. */
377 b->header.next.buffer = all_buffers;
378 all_buffers = b;
380 /* An ordinary buffer normally doesn't need markers
381 to handle BEGV and ZV. */
382 BSET (b, pt_marker, Qnil);
383 BSET (b, begv_marker, Qnil);
384 BSET (b, zv_marker, Qnil);
386 name = Fcopy_sequence (buffer_or_name);
387 set_string_intervals (name, NULL);
388 BSET (b, name, name);
390 BSET (b, undo_list, (SREF (name, 0) != ' ') ? Qnil : Qt);
392 reset_buffer (b);
393 reset_buffer_local_variables (b, 1);
395 BSET (b, mark, Fmake_marker ());
396 BUF_MARKERS (b) = NULL;
398 /* Put this in the alist of all live buffers. */
399 XSETBUFFER (buffer, b);
400 Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (Fcons (name, buffer), Qnil));
401 /* And run buffer-list-update-hook. */
402 if (!NILP (Vrun_hooks))
403 call1 (Vrun_hooks, Qbuffer_list_update_hook);
405 return buffer;
409 /* Return a list of overlays which is a copy of the overlay list
410 LIST, but for buffer B. */
412 static struct Lisp_Overlay *
413 copy_overlays (struct buffer *b, struct Lisp_Overlay *list)
415 struct Lisp_Overlay *result = NULL, *tail = NULL;
417 for (; list; list = list->next)
419 Lisp_Object overlay, start, end;
420 struct Lisp_Marker *m;
422 eassert (MARKERP (list->start));
423 m = XMARKER (list->start);
424 start = build_marker (b, m->charpos, m->bytepos);
425 XMARKER (start)->insertion_type = m->insertion_type;
427 eassert (MARKERP (list->end));
428 m = XMARKER (list->end);
429 end = build_marker (b, m->charpos, m->bytepos);
430 XMARKER (end)->insertion_type = m->insertion_type;
432 overlay = build_overlay (start, end, Fcopy_sequence (list->plist));
433 if (tail)
434 tail = tail->next = XOVERLAY (overlay);
435 else
436 result = tail = XOVERLAY (overlay);
439 return result;
442 /* Set an appropriate overlay of B. */
444 static inline void
445 set_buffer_overlays_before (struct buffer *b, struct Lisp_Overlay *o)
447 b->overlays_before = o;
450 static inline void
451 set_buffer_overlays_after (struct buffer *b, struct Lisp_Overlay *o)
453 b->overlays_after = o;
456 /* Clone per-buffer values of buffer FROM.
458 Buffer TO gets the same per-buffer values as FROM, with the
459 following exceptions: (1) TO's name is left untouched, (2) markers
460 are copied and made to refer to TO, and (3) overlay lists are
461 copied. */
463 static void
464 clone_per_buffer_values (struct buffer *from, struct buffer *to)
466 int offset;
468 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
470 Lisp_Object obj;
472 /* Don't touch the `name' which should be unique for every buffer. */
473 if (offset == PER_BUFFER_VAR_OFFSET (name))
474 continue;
476 obj = PER_BUFFER_VALUE (from, offset);
477 if (MARKERP (obj) && XMARKER (obj)->buffer == from)
479 struct Lisp_Marker *m = XMARKER (obj);
481 obj = build_marker (to, m->charpos, m->bytepos);
482 XMARKER (obj)->insertion_type = m->insertion_type;
485 PER_BUFFER_VALUE (to, offset) = obj;
488 memcpy (to->local_flags, from->local_flags, sizeof to->local_flags);
490 set_buffer_overlays_before (to, copy_overlays (to, from->overlays_before));
491 set_buffer_overlays_after (to, copy_overlays (to, from->overlays_after));
493 /* Get (a copy of) the alist of Lisp-level local variables of FROM
494 and install that in TO. */
495 BSET (to, local_var_alist, buffer_lisp_local_variables (from, 1));
499 /* If buffer B has markers to record PT, BEGV and ZV when it is not
500 current, update these markers. */
502 static void
503 record_buffer_markers (struct buffer *b)
505 if (! NILP (BVAR (b, pt_marker)))
507 Lisp_Object buffer;
509 eassert (!NILP (BVAR (b, begv_marker)));
510 eassert (!NILP (BVAR (b, zv_marker)));
512 XSETBUFFER (buffer, b);
513 set_marker_both (BVAR (b, pt_marker), buffer, b->pt, b->pt_byte);
514 set_marker_both (BVAR (b, begv_marker), buffer, b->begv, b->begv_byte);
515 set_marker_both (BVAR (b, zv_marker), buffer, b->zv, b->zv_byte);
520 /* If buffer B has markers to record PT, BEGV and ZV when it is not
521 current, fetch these values into B->begv etc. */
523 static void
524 fetch_buffer_markers (struct buffer *b)
526 if (! NILP (BVAR (b, pt_marker)))
528 Lisp_Object m;
530 eassert (!NILP (BVAR (b, begv_marker)));
531 eassert (!NILP (BVAR (b, zv_marker)));
533 m = BVAR (b, pt_marker);
534 SET_BUF_PT_BOTH (b, marker_position (m), marker_byte_position (m));
536 m = BVAR (b, begv_marker);
537 SET_BUF_BEGV_BOTH (b, marker_position (m), marker_byte_position (m));
539 m = BVAR (b, zv_marker);
540 SET_BUF_ZV_BOTH (b, marker_position (m), marker_byte_position (m));
545 DEFUN ("make-indirect-buffer", Fmake_indirect_buffer, Smake_indirect_buffer,
546 2, 3,
547 "bMake indirect buffer (to buffer): \nBName of indirect buffer: ",
548 doc: /* Create and return an indirect buffer for buffer BASE-BUFFER, named NAME.
549 BASE-BUFFER should be a live buffer, or the name of an existing buffer.
550 NAME should be a string which is not the name of an existing buffer.
551 Optional argument CLONE non-nil means preserve BASE-BUFFER's state,
552 such as major and minor modes, in the indirect buffer.
553 CLONE nil means the indirect buffer's state is reset to default values. */)
554 (Lisp_Object base_buffer, Lisp_Object name, Lisp_Object clone)
556 Lisp_Object buf, tem;
557 struct buffer *b;
559 CHECK_STRING (name);
560 buf = Fget_buffer (name);
561 if (!NILP (buf))
562 error ("Buffer name `%s' is in use", SDATA (name));
564 tem = base_buffer;
565 base_buffer = Fget_buffer (base_buffer);
566 if (NILP (base_buffer))
567 error ("No such buffer: `%s'", SDATA (tem));
568 if (NILP (BVAR (XBUFFER (base_buffer), name)))
569 error ("Base buffer has been killed");
571 if (SCHARS (name) == 0)
572 error ("Empty string for buffer name is not allowed");
574 b = allocate_buffer ();
576 /* No double indirection - if base buffer is indirect,
577 new buffer becomes an indirect to base's base. */
578 b->base_buffer = (XBUFFER (base_buffer)->base_buffer
579 ? XBUFFER (base_buffer)->base_buffer
580 : XBUFFER (base_buffer));
582 /* Use the base buffer's text object. */
583 b->text = b->base_buffer->text;
584 /* We have no own text. */
585 b->indirections = -1;
586 /* Notify base buffer that we share the text now. */
587 b->base_buffer->indirections++;
589 b->pt = b->base_buffer->pt;
590 b->begv = b->base_buffer->begv;
591 b->zv = b->base_buffer->zv;
592 b->pt_byte = b->base_buffer->pt_byte;
593 b->begv_byte = b->base_buffer->begv_byte;
594 b->zv_byte = b->base_buffer->zv_byte;
596 b->newline_cache = 0;
597 b->width_run_cache = 0;
598 BSET (b, width_table, Qnil);
600 /* Put this on the chain of all buffers including killed ones. */
601 b->header.next.buffer = all_buffers;
602 all_buffers = b;
604 name = Fcopy_sequence (name);
605 set_string_intervals (name, NULL);
606 BSET (b, name, name);
608 reset_buffer (b);
609 reset_buffer_local_variables (b, 1);
611 /* Put this in the alist of all live buffers. */
612 XSETBUFFER (buf, b);
613 Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (Fcons (name, buf), Qnil));
615 BSET (b, mark, Fmake_marker ());
617 /* The multibyte status belongs to the base buffer. */
618 BSET (b, enable_multibyte_characters, BVAR (b->base_buffer, enable_multibyte_characters));
620 /* Make sure the base buffer has markers for its narrowing. */
621 if (NILP (BVAR (b->base_buffer, pt_marker)))
623 eassert (NILP (BVAR (b->base_buffer, begv_marker)));
624 eassert (NILP (BVAR (b->base_buffer, zv_marker)));
626 BSET (b->base_buffer, pt_marker,
627 build_marker (b->base_buffer, b->base_buffer->pt, b->base_buffer->pt_byte));
629 BSET (b->base_buffer, begv_marker,
630 build_marker (b->base_buffer, b->base_buffer->begv, b->base_buffer->begv_byte));
632 BSET (b->base_buffer, zv_marker,
633 build_marker (b->base_buffer, b->base_buffer->zv, b->base_buffer->zv_byte));
635 XMARKER (BVAR (b->base_buffer, zv_marker))->insertion_type = 1;
638 if (NILP (clone))
640 /* Give the indirect buffer markers for its narrowing. */
641 BSET (b, pt_marker, build_marker (b, b->pt, b->pt_byte));
642 BSET (b, begv_marker, build_marker (b, b->begv, b->begv_byte));
643 BSET (b, zv_marker, build_marker (b, b->zv, b->zv_byte));
644 XMARKER (BVAR (b, zv_marker))->insertion_type = 1;
646 else
648 struct buffer *old_b = current_buffer;
650 clone_per_buffer_values (b->base_buffer, b);
651 BSET (b, filename, Qnil);
652 BSET (b, file_truename, Qnil);
653 BSET (b, display_count, make_number (0));
654 BSET (b, backed_up, Qnil);
655 BSET (b, auto_save_file_name, Qnil);
656 set_buffer_internal_1 (b);
657 Fset (intern ("buffer-save-without-query"), Qnil);
658 Fset (intern ("buffer-file-number"), Qnil);
659 Fset (intern ("buffer-stale-function"), Qnil);
660 set_buffer_internal_1 (old_b);
663 /* Run buffer-list-update-hook. */
664 if (!NILP (Vrun_hooks))
665 call1 (Vrun_hooks, Qbuffer_list_update_hook);
667 return buf;
670 /* Mark OV as no longer associated with B. */
672 static void
673 drop_overlay (struct buffer *b, struct Lisp_Overlay *ov)
675 eassert (b == XBUFFER (Fmarker_buffer (ov->start)));
676 modify_overlay (b, marker_position (ov->start),
677 marker_position (ov->end));
678 Fset_marker (ov->start, Qnil, Qnil);
679 Fset_marker (ov->end, Qnil, Qnil);
683 /* Delete all overlays of B and reset it's overlay lists. */
685 void
686 delete_all_overlays (struct buffer *b)
688 struct Lisp_Overlay *ov, *next;
690 for (ov = b->overlays_before; ov; ov = next)
692 drop_overlay (b, ov);
693 next = ov->next;
694 ov->next = NULL;
697 for (ov = b->overlays_after; ov; ov = next)
699 drop_overlay (b, ov);
700 next = ov->next;
701 ov->next = NULL;
704 set_buffer_overlays_before (b, NULL);
705 set_buffer_overlays_after (b, NULL);
708 /* Reinitialize everything about a buffer except its name and contents
709 and local variables.
710 If called on an already-initialized buffer, the list of overlays
711 should be deleted before calling this function, otherwise we end up
712 with overlays that claim to belong to the buffer but the buffer
713 claims it doesn't belong to it. */
715 void
716 reset_buffer (register struct buffer *b)
718 BSET (b, filename, Qnil);
719 BSET (b, file_truename, Qnil);
720 BSET (b, directory,
721 (current_buffer) ? BVAR (current_buffer, directory) : Qnil);
722 b->modtime = make_emacs_time (0, UNKNOWN_MODTIME_NSECS);
723 b->modtime_size = -1;
724 XSETFASTINT (BVAR (b, save_length), 0);
725 b->last_window_start = 1;
726 /* It is more conservative to start out "changed" than "unchanged". */
727 b->clip_changed = 0;
728 b->prevent_redisplay_optimizations_p = 1;
729 BSET (b, backed_up, Qnil);
730 BUF_AUTOSAVE_MODIFF (b) = 0;
731 b->auto_save_failure_time = 0;
732 BSET (b, auto_save_file_name, Qnil);
733 BSET (b, read_only, Qnil);
734 set_buffer_overlays_before (b, NULL);
735 set_buffer_overlays_after (b, NULL);
736 b->overlay_center = BEG;
737 BSET (b, mark_active, Qnil);
738 BSET (b, point_before_scroll, Qnil);
739 BSET (b, file_format, Qnil);
740 BSET (b, auto_save_file_format, Qt);
741 BSET (b, last_selected_window, Qnil);
742 BSET (b, display_count, make_number (0));
743 BSET (b, display_time, Qnil);
744 BSET (b, enable_multibyte_characters,
745 BVAR (&buffer_defaults, enable_multibyte_characters));
746 BSET (b, cursor_type, BVAR (&buffer_defaults, cursor_type));
747 BSET (b, extra_line_spacing, BVAR (&buffer_defaults, extra_line_spacing));
749 b->display_error_modiff = 0;
752 /* Reset buffer B's local variables info.
753 Don't use this on a buffer that has already been in use;
754 it does not treat permanent locals consistently.
755 Instead, use Fkill_all_local_variables.
757 If PERMANENT_TOO is 1, then we reset permanent
758 buffer-local variables. If PERMANENT_TOO is 0,
759 we preserve those. */
761 static void
762 reset_buffer_local_variables (register struct buffer *b, int permanent_too)
764 register int offset;
765 int i;
767 /* Reset the major mode to Fundamental, together with all the
768 things that depend on the major mode.
769 default-major-mode is handled at a higher level.
770 We ignore it here. */
771 BSET (b, major_mode, Qfundamental_mode);
772 BSET (b, keymap, Qnil);
773 BSET (b, mode_name, QSFundamental);
774 BSET (b, minor_modes, Qnil);
776 /* If the standard case table has been altered and invalidated,
777 fix up its insides first. */
778 if (! (CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[0])
779 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[1])
780 && CHAR_TABLE_P (XCHAR_TABLE (Vascii_downcase_table)->extras[2])))
781 Fset_standard_case_table (Vascii_downcase_table);
783 BSET (b, downcase_table, Vascii_downcase_table);
784 BSET (b, upcase_table, XCHAR_TABLE (Vascii_downcase_table)->extras[0]);
785 BSET (b, case_canon_table, XCHAR_TABLE (Vascii_downcase_table)->extras[1]);
786 BSET (b, case_eqv_table, XCHAR_TABLE (Vascii_downcase_table)->extras[2]);
787 BSET (b, invisibility_spec, Qt);
789 /* Reset all (or most) per-buffer variables to their defaults. */
790 if (permanent_too)
791 BSET (b, local_var_alist, Qnil);
792 else
794 Lisp_Object tmp, prop, last = Qnil;
795 for (tmp = BVAR (b, local_var_alist); CONSP (tmp); tmp = XCDR (tmp))
796 if (!NILP (prop = Fget (XCAR (XCAR (tmp)), Qpermanent_local)))
798 /* If permanent-local, keep it. */
799 last = tmp;
800 if (EQ (prop, Qpermanent_local_hook))
802 /* This is a partially permanent hook variable.
803 Preserve only the elements that want to be preserved. */
804 Lisp_Object list, newlist;
805 list = XCDR (XCAR (tmp));
806 if (!CONSP (list))
807 newlist = list;
808 else
809 for (newlist = Qnil; CONSP (list); list = XCDR (list))
811 Lisp_Object elt = XCAR (list);
812 /* Preserve element ELT if it's t,
813 if it is a function with a `permanent-local-hook' property,
814 or if it's not a symbol. */
815 if (! SYMBOLP (elt)
816 || EQ (elt, Qt)
817 || !NILP (Fget (elt, Qpermanent_local_hook)))
818 newlist = Fcons (elt, newlist);
820 XSETCDR (XCAR (tmp), Fnreverse (newlist));
823 /* Delete this local variable. */
824 else if (NILP (last))
825 BSET (b, local_var_alist, XCDR (tmp));
826 else
827 XSETCDR (last, XCDR (tmp));
830 for (i = 0; i < last_per_buffer_idx; ++i)
831 if (permanent_too || buffer_permanent_local_flags[i] == 0)
832 SET_PER_BUFFER_VALUE_P (b, i, 0);
834 /* For each slot that has a default value, copy that into the slot. */
835 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
837 int idx = PER_BUFFER_IDX (offset);
838 if ((idx > 0
839 && (permanent_too
840 || buffer_permanent_local_flags[idx] == 0)))
841 PER_BUFFER_VALUE (b, offset) = PER_BUFFER_DEFAULT (offset);
845 /* We split this away from generate-new-buffer, because rename-buffer
846 and set-visited-file-name ought to be able to use this to really
847 rename the buffer properly. */
849 DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name,
850 Sgenerate_new_buffer_name, 1, 2, 0,
851 doc: /* Return a string that is the name of no existing buffer based on NAME.
852 If there is no live buffer named NAME, then return NAME.
853 Otherwise modify name by appending `<NUMBER>', incrementing NUMBER
854 \(starting at 2) until an unused name is found, and then return that name.
855 Optional second argument IGNORE specifies a name that is okay to use (if
856 it is in the sequence to be tried) even if a buffer with that name exists.
858 If NAME begins with a space (i.e., a buffer that is not normally
859 visible to users), then if buffer NAME already exists a random number
860 is first appended to NAME, to speed up finding a non-existent buffer. */)
861 (register Lisp_Object name, Lisp_Object ignore)
863 register Lisp_Object gentemp, tem, tem2;
864 ptrdiff_t count;
865 char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
867 CHECK_STRING (name);
869 tem = Fstring_equal (name, ignore);
870 if (!NILP (tem))
871 return name;
872 tem = Fget_buffer (name);
873 if (NILP (tem))
874 return name;
876 if (!strncmp (SSDATA (name), " ", 1)) /* see bug#1229 */
878 /* Note fileio.c:make_temp_name does random differently. */
879 tem2 = concat2 (name, make_formatted_string
880 (number, "-%"pI"d",
881 XFASTINT (Frandom (make_number (999999)))));
882 tem = Fget_buffer (tem2);
883 if (NILP (tem))
884 return tem2;
886 else
887 tem2 = name;
889 count = 1;
890 while (1)
892 gentemp = concat2 (tem2, make_formatted_string
893 (number, "<%"pD"d>", ++count));
894 tem = Fstring_equal (gentemp, ignore);
895 if (!NILP (tem))
896 return gentemp;
897 tem = Fget_buffer (gentemp);
898 if (NILP (tem))
899 return gentemp;
904 DEFUN ("buffer-name", Fbuffer_name, Sbuffer_name, 0, 1, 0,
905 doc: /* Return the name of BUFFER, as a string.
906 BUFFER defaults to the current buffer.
907 Return nil if BUFFER has been killed. */)
908 (register Lisp_Object buffer)
910 if (NILP (buffer))
911 return BVAR (current_buffer, name);
912 CHECK_BUFFER (buffer);
913 return BVAR (XBUFFER (buffer), name);
916 DEFUN ("buffer-file-name", Fbuffer_file_name, Sbuffer_file_name, 0, 1, 0,
917 doc: /* Return name of file BUFFER is visiting, or nil if none.
918 No argument or nil as argument means use the current buffer. */)
919 (register Lisp_Object buffer)
921 if (NILP (buffer))
922 return BVAR (current_buffer, filename);
923 CHECK_BUFFER (buffer);
924 return BVAR (XBUFFER (buffer), filename);
927 DEFUN ("buffer-base-buffer", Fbuffer_base_buffer, Sbuffer_base_buffer,
928 0, 1, 0,
929 doc: /* Return the base buffer of indirect buffer BUFFER.
930 If BUFFER is not indirect, return nil.
931 BUFFER defaults to the current buffer. */)
932 (register Lisp_Object buffer)
934 struct buffer *base;
935 Lisp_Object base_buffer;
937 if (NILP (buffer))
938 base = current_buffer->base_buffer;
939 else
941 CHECK_BUFFER (buffer);
942 base = XBUFFER (buffer)->base_buffer;
945 if (! base)
946 return Qnil;
947 XSETBUFFER (base_buffer, base);
948 return base_buffer;
951 DEFUN ("buffer-local-value", Fbuffer_local_value,
952 Sbuffer_local_value, 2, 2, 0,
953 doc: /* Return the value of VARIABLE in BUFFER.
954 If VARIABLE does not have a buffer-local binding in BUFFER, the value
955 is the default binding of the variable. */)
956 (register Lisp_Object variable, register Lisp_Object buffer)
958 register Lisp_Object result = buffer_local_value_1 (variable, buffer);
960 if (EQ (result, Qunbound))
961 xsignal1 (Qvoid_variable, variable);
963 return result;
967 /* Like Fbuffer_local_value, but return Qunbound if the variable is
968 locally unbound. */
970 Lisp_Object
971 buffer_local_value_1 (Lisp_Object variable, Lisp_Object buffer)
973 register struct buffer *buf;
974 register Lisp_Object result;
975 struct Lisp_Symbol *sym;
977 CHECK_SYMBOL (variable);
978 CHECK_BUFFER (buffer);
979 buf = XBUFFER (buffer);
980 sym = XSYMBOL (variable);
982 start:
983 switch (sym->redirect)
985 case SYMBOL_VARALIAS: sym = indirect_variable (sym); goto start;
986 case SYMBOL_PLAINVAL: result = SYMBOL_VAL (sym); break;
987 case SYMBOL_LOCALIZED:
988 { /* Look in local_var_alist. */
989 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
990 XSETSYMBOL (variable, sym); /* Update In case of aliasing. */
991 result = Fassoc (variable, BVAR (buf, local_var_alist));
992 if (!NILP (result))
994 if (blv->fwd)
995 { /* What binding is loaded right now? */
996 Lisp_Object current_alist_element = blv->valcell;
998 /* The value of the currently loaded binding is not
999 stored in it, but rather in the realvalue slot.
1000 Store that value into the binding it belongs to
1001 in case that is the one we are about to use. */
1003 XSETCDR (current_alist_element,
1004 do_symval_forwarding (blv->fwd));
1006 /* Now get the (perhaps updated) value out of the binding. */
1007 result = XCDR (result);
1009 else
1010 result = Fdefault_value (variable);
1011 break;
1013 case SYMBOL_FORWARDED:
1015 union Lisp_Fwd *fwd = SYMBOL_FWD (sym);
1016 if (BUFFER_OBJFWDP (fwd))
1017 result = PER_BUFFER_VALUE (buf, XBUFFER_OBJFWD (fwd)->offset);
1018 else
1019 result = Fdefault_value (variable);
1020 break;
1022 default: abort ();
1025 return result;
1028 /* Return an alist of the Lisp-level buffer-local bindings of
1029 buffer BUF. That is, don't include the variables maintained
1030 in special slots in the buffer object.
1031 If CLONE is zero elements of the form (VAR . unbound) are replaced
1032 by VAR. */
1034 static Lisp_Object
1035 buffer_lisp_local_variables (struct buffer *buf, int clone)
1037 Lisp_Object result = Qnil;
1038 register Lisp_Object tail;
1039 for (tail = BVAR (buf, local_var_alist); CONSP (tail); tail = XCDR (tail))
1041 Lisp_Object val, elt;
1043 elt = XCAR (tail);
1045 /* Reference each variable in the alist in buf.
1046 If inquiring about the current buffer, this gets the current values,
1047 so store them into the alist so the alist is up to date.
1048 If inquiring about some other buffer, this swaps out any values
1049 for that buffer, making the alist up to date automatically. */
1050 val = find_symbol_value (XCAR (elt));
1051 /* Use the current buffer value only if buf is the current buffer. */
1052 if (buf != current_buffer)
1053 val = XCDR (elt);
1055 result = Fcons (!clone && EQ (val, Qunbound)
1056 ? XCAR (elt)
1057 : Fcons (XCAR (elt), val),
1058 result);
1061 return result;
1064 DEFUN ("buffer-local-variables", Fbuffer_local_variables,
1065 Sbuffer_local_variables, 0, 1, 0,
1066 doc: /* Return an alist of variables that are buffer-local in BUFFER.
1067 Most elements look like (SYMBOL . VALUE), describing one variable.
1068 For a symbol that is locally unbound, just the symbol appears in the value.
1069 Note that storing new VALUEs in these elements doesn't change the variables.
1070 No argument or nil as argument means use current buffer as BUFFER. */)
1071 (register Lisp_Object buffer)
1073 register struct buffer *buf;
1074 register Lisp_Object result;
1076 if (NILP (buffer))
1077 buf = current_buffer;
1078 else
1080 CHECK_BUFFER (buffer);
1081 buf = XBUFFER (buffer);
1084 result = buffer_lisp_local_variables (buf, 0);
1086 /* Add on all the variables stored in special slots. */
1088 int offset, idx;
1090 FOR_EACH_PER_BUFFER_OBJECT_AT (offset)
1092 idx = PER_BUFFER_IDX (offset);
1093 if ((idx == -1 || PER_BUFFER_VALUE_P (buf, idx))
1094 && SYMBOLP (PER_BUFFER_SYMBOL (offset)))
1096 Lisp_Object sym = PER_BUFFER_SYMBOL (offset);
1097 Lisp_Object val = PER_BUFFER_VALUE (buf, offset);
1098 result = Fcons (EQ (val, Qunbound) ? sym : Fcons (sym, val),
1099 result);
1104 return result;
1107 DEFUN ("buffer-modified-p", Fbuffer_modified_p, Sbuffer_modified_p,
1108 0, 1, 0,
1109 doc: /* Return t if BUFFER was modified since its file was last read or saved.
1110 No argument or nil as argument means use current buffer as BUFFER. */)
1111 (register Lisp_Object buffer)
1113 register struct buffer *buf;
1114 if (NILP (buffer))
1115 buf = current_buffer;
1116 else
1118 CHECK_BUFFER (buffer);
1119 buf = XBUFFER (buffer);
1122 return BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf) ? Qt : Qnil;
1125 DEFUN ("set-buffer-modified-p", Fset_buffer_modified_p, Sset_buffer_modified_p,
1126 1, 1, 0,
1127 doc: /* Mark current buffer as modified or unmodified according to FLAG.
1128 A non-nil FLAG means mark the buffer modified. */)
1129 (register Lisp_Object flag)
1131 register int already;
1132 register Lisp_Object fn;
1133 Lisp_Object buffer, window;
1135 #ifdef CLASH_DETECTION
1136 /* If buffer becoming modified, lock the file.
1137 If buffer becoming unmodified, unlock the file. */
1139 fn = BVAR (current_buffer, file_truename);
1140 /* Test buffer-file-name so that binding it to nil is effective. */
1141 if (!NILP (fn) && ! NILP (BVAR (current_buffer, filename)))
1143 already = SAVE_MODIFF < MODIFF;
1144 if (!already && !NILP (flag))
1145 lock_file (fn);
1146 else if (already && NILP (flag))
1147 unlock_file (fn);
1149 #endif /* CLASH_DETECTION */
1151 /* Here we have a problem. SAVE_MODIFF is used here to encode
1152 buffer-modified-p (as SAVE_MODIFF<MODIFF) as well as
1153 recent-auto-save-p (as SAVE_MODIFF<auto_save_modified). So if we
1154 modify SAVE_MODIFF to affect one, we may affect the other
1155 as well.
1156 E.g. if FLAG is nil we need to set SAVE_MODIFF to MODIFF, but
1157 if SAVE_MODIFF<auto_save_modified that means we risk changing
1158 recent-auto-save-p from t to nil.
1159 Vice versa, if FLAG is non-nil and SAVE_MODIFF>=auto_save_modified
1160 we risk changing recent-auto-save-p from nil to t. */
1161 SAVE_MODIFF = (NILP (flag)
1162 /* FIXME: This unavoidably sets recent-auto-save-p to nil. */
1163 ? MODIFF
1164 /* Let's try to preserve recent-auto-save-p. */
1165 : SAVE_MODIFF < MODIFF ? SAVE_MODIFF
1166 /* If SAVE_MODIFF == auto_save_modified == MODIFF,
1167 we can either decrease SAVE_MODIFF and auto_save_modified
1168 or increase MODIFF. */
1169 : MODIFF++);
1171 /* Set update_mode_lines only if buffer is displayed in some window.
1172 Packages like jit-lock or lazy-lock preserve a buffer's modified
1173 state by recording/restoring the state around blocks of code.
1174 Setting update_mode_lines makes redisplay consider all windows
1175 (on all frames). Stealth fontification of buffers not displayed
1176 would incur additional redisplay costs if we'd set
1177 update_modes_lines unconditionally.
1179 Ideally, I think there should be another mechanism for fontifying
1180 buffers without "modifying" buffers, or redisplay should be
1181 smarter about updating the `*' in mode lines. --gerd */
1182 XSETBUFFER (buffer, current_buffer);
1183 window = Fget_buffer_window (buffer, Qt);
1184 if (WINDOWP (window))
1186 ++update_mode_lines;
1187 current_buffer->prevent_redisplay_optimizations_p = 1;
1190 return flag;
1193 DEFUN ("restore-buffer-modified-p", Frestore_buffer_modified_p,
1194 Srestore_buffer_modified_p, 1, 1, 0,
1195 doc: /* Like `set-buffer-modified-p', with a difference concerning redisplay.
1196 It is not ensured that mode lines will be updated to show the modified
1197 state of the current buffer. Use with care. */)
1198 (Lisp_Object flag)
1200 #ifdef CLASH_DETECTION
1201 Lisp_Object fn;
1203 /* If buffer becoming modified, lock the file.
1204 If buffer becoming unmodified, unlock the file. */
1206 fn = BVAR (current_buffer, file_truename);
1207 /* Test buffer-file-name so that binding it to nil is effective. */
1208 if (!NILP (fn) && ! NILP (BVAR (current_buffer, filename)))
1210 int already = SAVE_MODIFF < MODIFF;
1211 if (!already && !NILP (flag))
1212 lock_file (fn);
1213 else if (already && NILP (flag))
1214 unlock_file (fn);
1216 #endif /* CLASH_DETECTION */
1218 SAVE_MODIFF = NILP (flag) ? MODIFF : 0;
1219 return flag;
1222 DEFUN ("buffer-modified-tick", Fbuffer_modified_tick, Sbuffer_modified_tick,
1223 0, 1, 0,
1224 doc: /* Return BUFFER's tick counter, incremented for each change in text.
1225 Each buffer has a tick counter which is incremented each time the
1226 text in that buffer is changed. It wraps around occasionally.
1227 No argument or nil as argument means use current buffer as BUFFER. */)
1228 (register Lisp_Object buffer)
1230 register struct buffer *buf;
1231 if (NILP (buffer))
1232 buf = current_buffer;
1233 else
1235 CHECK_BUFFER (buffer);
1236 buf = XBUFFER (buffer);
1239 return make_number (BUF_MODIFF (buf));
1242 DEFUN ("buffer-chars-modified-tick", Fbuffer_chars_modified_tick,
1243 Sbuffer_chars_modified_tick, 0, 1, 0,
1244 doc: /* Return BUFFER's character-change tick counter.
1245 Each buffer has a character-change tick counter, which is set to the
1246 value of the buffer's tick counter \(see `buffer-modified-tick'), each
1247 time text in that buffer is inserted or deleted. By comparing the
1248 values returned by two individual calls of `buffer-chars-modified-tick',
1249 you can tell whether a character change occurred in that buffer in
1250 between these calls. No argument or nil as argument means use current
1251 buffer as BUFFER. */)
1252 (register Lisp_Object buffer)
1254 register struct buffer *buf;
1255 if (NILP (buffer))
1256 buf = current_buffer;
1257 else
1259 CHECK_BUFFER (buffer);
1260 buf = XBUFFER (buffer);
1263 return make_number (BUF_CHARS_MODIFF (buf));
1266 DEFUN ("rename-buffer", Frename_buffer, Srename_buffer, 1, 2,
1267 "(list (read-string \"Rename buffer (to new name): \" \
1268 nil 'buffer-name-history (buffer-name (current-buffer))) \
1269 current-prefix-arg)",
1270 doc: /* Change current buffer's name to NEWNAME (a string).
1271 If second arg UNIQUE is nil or omitted, it is an error if a
1272 buffer named NEWNAME already exists.
1273 If UNIQUE is non-nil, come up with a new name using
1274 `generate-new-buffer-name'.
1275 Interactively, you can set UNIQUE with a prefix argument.
1276 We return the name we actually gave the buffer.
1277 This does not change the name of the visited file (if any). */)
1278 (register Lisp_Object newname, Lisp_Object unique)
1280 register Lisp_Object tem, buf;
1282 CHECK_STRING (newname);
1284 if (SCHARS (newname) == 0)
1285 error ("Empty string is invalid as a buffer name");
1287 tem = Fget_buffer (newname);
1288 if (!NILP (tem))
1290 /* Don't short-circuit if UNIQUE is t. That is a useful way to
1291 rename the buffer automatically so you can create another
1292 with the original name. It makes UNIQUE equivalent to
1293 (rename-buffer (generate-new-buffer-name NEWNAME)). */
1294 if (NILP (unique) && XBUFFER (tem) == current_buffer)
1295 return BVAR (current_buffer, name);
1296 if (!NILP (unique))
1297 newname = Fgenerate_new_buffer_name (newname, BVAR (current_buffer, name));
1298 else
1299 error ("Buffer name `%s' is in use", SDATA (newname));
1302 BSET (current_buffer, name, newname);
1304 /* Catch redisplay's attention. Unless we do this, the mode lines for
1305 any windows displaying current_buffer will stay unchanged. */
1306 update_mode_lines++;
1308 XSETBUFFER (buf, current_buffer);
1309 Fsetcar (Frassq (buf, Vbuffer_alist), newname);
1310 if (NILP (BVAR (current_buffer, filename))
1311 && !NILP (BVAR (current_buffer, auto_save_file_name)))
1312 call0 (intern ("rename-auto-save-file"));
1314 /* Run buffer-list-update-hook. */
1315 if (!NILP (Vrun_hooks))
1316 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1318 /* Refetch since that last call may have done GC. */
1319 return BVAR (current_buffer, name);
1322 DEFUN ("other-buffer", Fother_buffer, Sother_buffer, 0, 3, 0,
1323 doc: /* Return most recently selected buffer other than BUFFER.
1324 Buffers not visible in windows are preferred to visible buffers, unless
1325 optional second argument VISIBLE-OK is non-nil. Ignore the argument
1326 BUFFER unless it denotes a live buffer. If the optional third argument
1327 FRAME is non-nil, use that frame's buffer list instead of the selected
1328 frame's buffer list.
1330 The buffer is found by scanning the selected or specified frame's buffer
1331 list first, followed by the list of all buffers. If no other buffer
1332 exists, return the buffer `*scratch*' (creating it if necessary). */)
1333 (register Lisp_Object buffer, Lisp_Object visible_ok, Lisp_Object frame)
1335 Lisp_Object Fset_buffer_major_mode (Lisp_Object buffer);
1336 Lisp_Object tail, buf, pred;
1337 Lisp_Object notsogood = Qnil;
1339 if (NILP (frame))
1340 frame = selected_frame;
1342 CHECK_FRAME (frame);
1344 pred = frame_buffer_predicate (frame);
1345 /* Consider buffers that have been seen in the frame first. */
1346 tail = XFRAME (frame)->buffer_list;
1347 for (; CONSP (tail); tail = XCDR (tail))
1349 buf = XCAR (tail);
1350 if (BUFFERP (buf) && !EQ (buf, buffer)
1351 && !NILP (BVAR (XBUFFER (buf), name))
1352 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' ')
1353 /* If the frame has a buffer_predicate, disregard buffers that
1354 don't fit the predicate. */
1355 && (NILP (pred) || !NILP (call1 (pred, buf))))
1357 if (!NILP (visible_ok)
1358 || NILP (Fget_buffer_window (buf, Qvisible)))
1359 return buf;
1360 else if (NILP (notsogood))
1361 notsogood = buf;
1365 /* Consider alist of all buffers next. */
1366 tail = Vbuffer_alist;
1367 for (; CONSP (tail); tail = XCDR (tail))
1369 buf = Fcdr (XCAR (tail));
1370 if (BUFFERP (buf) && !EQ (buf, buffer)
1371 && !NILP (BVAR (XBUFFER (buf), name))
1372 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' ')
1373 /* If the frame has a buffer_predicate, disregard buffers that
1374 don't fit the predicate. */
1375 && (NILP (pred) || !NILP (call1 (pred, buf))))
1377 if (!NILP (visible_ok)
1378 || NILP (Fget_buffer_window (buf, Qvisible)))
1379 return buf;
1380 else if (NILP (notsogood))
1381 notsogood = buf;
1385 if (!NILP (notsogood))
1386 return notsogood;
1387 else
1389 buf = Fget_buffer (build_string ("*scratch*"));
1390 if (NILP (buf))
1392 buf = Fget_buffer_create (build_string ("*scratch*"));
1393 Fset_buffer_major_mode (buf);
1395 return buf;
1399 /* The following function is a safe variant of Fother_buffer: It doesn't
1400 pay attention to any frame-local buffer lists, doesn't care about
1401 visibility of buffers, and doesn't evaluate any frame predicates. */
1403 Lisp_Object
1404 other_buffer_safely (Lisp_Object buffer)
1406 Lisp_Object Fset_buffer_major_mode (Lisp_Object buffer);
1407 Lisp_Object tail, buf;
1409 tail = Vbuffer_alist;
1410 for (; CONSP (tail); tail = XCDR (tail))
1412 buf = Fcdr (XCAR (tail));
1413 if (BUFFERP (buf) && !EQ (buf, buffer)
1414 && !NILP (BVAR (XBUFFER (buf), name))
1415 && (SREF (BVAR (XBUFFER (buf), name), 0) != ' '))
1416 return buf;
1419 buf = Fget_buffer (build_string ("*scratch*"));
1420 if (NILP (buf))
1422 buf = Fget_buffer_create (build_string ("*scratch*"));
1423 Fset_buffer_major_mode (buf);
1426 return buf;
1429 DEFUN ("buffer-enable-undo", Fbuffer_enable_undo, Sbuffer_enable_undo,
1430 0, 1, "",
1431 doc: /* Start keeping undo information for buffer BUFFER.
1432 No argument or nil as argument means do this for the current buffer. */)
1433 (register Lisp_Object buffer)
1435 Lisp_Object real_buffer;
1437 if (NILP (buffer))
1438 XSETBUFFER (real_buffer, current_buffer);
1439 else
1441 real_buffer = Fget_buffer (buffer);
1442 if (NILP (real_buffer))
1443 nsberror (buffer);
1446 if (EQ (BVAR (XBUFFER (real_buffer), undo_list), Qt))
1447 BSET (XBUFFER (real_buffer), undo_list, Qnil);
1449 return Qnil;
1452 /* Truncate undo list and shrink the gap of BUFFER. */
1455 compact_buffer (struct buffer *buffer)
1457 /* Verify indirection counters. */
1458 if (buffer->base_buffer)
1460 eassert (buffer->indirections == -1);
1461 eassert (buffer->base_buffer->indirections > 0);
1463 else
1464 eassert (buffer->indirections >= 0);
1466 /* Skip dead buffers, indirect buffers and buffers
1467 which aren't changed since last compaction. */
1468 if (!NILP (buffer->INTERNAL_FIELD (name))
1469 && (buffer->base_buffer == NULL)
1470 && (buffer->text->compact != buffer->text->modiff))
1472 /* If a buffer's undo list is Qt, that means that undo is
1473 turned off in that buffer. Calling truncate_undo_list on
1474 Qt tends to return NULL, which effectively turns undo back on.
1475 So don't call truncate_undo_list if undo_list is Qt. */
1476 if (!EQ (buffer->INTERNAL_FIELD (undo_list), Qt))
1477 truncate_undo_list (buffer);
1479 /* Shrink buffer gaps. */
1480 if (!buffer->text->inhibit_shrinking)
1482 /* If a buffer's gap size is more than 10% of the buffer
1483 size, or larger than 2000 bytes, then shrink it
1484 accordingly. Keep a minimum size of 20 bytes. */
1485 int size = min (2000, max (20, (buffer->text->z_byte / 10)));
1487 if (buffer->text->gap_size > size)
1489 struct buffer *save_current = current_buffer;
1490 current_buffer = buffer;
1491 make_gap (-(buffer->text->gap_size - size));
1492 current_buffer = save_current;
1495 buffer->text->compact = buffer->text->modiff;
1496 return 1;
1498 return 0;
1501 DEFUN ("kill-buffer", Fkill_buffer, Skill_buffer, 0, 1, "bKill buffer: ",
1502 doc: /* Kill the buffer specified by BUFFER-OR-NAME.
1503 The argument may be a buffer or the name of an existing buffer.
1504 Argument nil or omitted means kill the current buffer. Return t if the
1505 buffer is actually killed, nil otherwise.
1507 The functions in `kill-buffer-query-functions' are called with the
1508 buffer to be killed as the current buffer. If any of them returns nil,
1509 the buffer is not killed. The hook `kill-buffer-hook' is run before the
1510 buffer is actually killed. The buffer being killed will be current
1511 while the hook is running. Functions called by any of these hooks are
1512 supposed to not change the current buffer.
1514 Any processes that have this buffer as the `process-buffer' are killed
1515 with SIGHUP. This function calls `replace-buffer-in-windows' for
1516 cleaning up all windows currently displaying the buffer to be killed. */)
1517 (Lisp_Object buffer_or_name)
1519 Lisp_Object buffer;
1520 register struct buffer *b;
1521 register Lisp_Object tem;
1522 register struct Lisp_Marker *m;
1523 struct gcpro gcpro1;
1525 if (NILP (buffer_or_name))
1526 buffer = Fcurrent_buffer ();
1527 else
1528 buffer = Fget_buffer (buffer_or_name);
1529 if (NILP (buffer))
1530 nsberror (buffer_or_name);
1532 b = XBUFFER (buffer);
1534 /* Avoid trouble for buffer already dead. */
1535 if (NILP (BVAR (b, name)))
1536 return Qnil;
1538 /* Query if the buffer is still modified. */
1539 if (INTERACTIVE && !NILP (BVAR (b, filename))
1540 && BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
1542 GCPRO1 (buffer);
1543 tem = do_yes_or_no_p (format2 ("Buffer %s modified; kill anyway? ",
1544 BVAR (b, name), make_number (0)));
1545 UNGCPRO;
1546 if (NILP (tem))
1547 return Qnil;
1550 /* Run hooks with the buffer to be killed the current buffer. */
1552 ptrdiff_t count = SPECPDL_INDEX ();
1553 Lisp_Object arglist[1];
1555 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1556 set_buffer_internal (b);
1558 /* First run the query functions; if any query is answered no,
1559 don't kill the buffer. */
1560 arglist[0] = Qkill_buffer_query_functions;
1561 tem = Frun_hook_with_args_until_failure (1, arglist);
1562 if (NILP (tem))
1563 return unbind_to (count, Qnil);
1565 /* Then run the hooks. */
1566 Frun_hooks (1, &Qkill_buffer_hook);
1567 unbind_to (count, Qnil);
1570 /* If the hooks have killed the buffer, exit now. */
1571 if (NILP (BVAR (b, name)))
1572 return Qt;
1574 /* We have no more questions to ask. Verify that it is valid
1575 to kill the buffer. This must be done after the questions
1576 since anything can happen within do_yes_or_no_p. */
1578 /* Don't kill the minibuffer now current. */
1579 if (EQ (buffer, XWINDOW (minibuf_window)->buffer))
1580 return Qnil;
1582 /* When we kill an ordinary buffer which shares it's buffer text
1583 with indirect buffer(s), we must kill indirect buffer(s) too.
1584 We do it at this stage so nothing terrible happens if they
1585 ask questions or their hooks get errors. */
1586 if (!b->base_buffer && b->indirections > 0)
1588 struct buffer *other;
1590 GCPRO1 (buffer);
1592 FOR_EACH_BUFFER (other)
1593 if (other->base_buffer == b)
1595 Lisp_Object buf;
1596 XSETBUFFER (buf, other);
1597 Fkill_buffer (buf);
1600 UNGCPRO;
1602 /* Exit if we now have killed the base buffer (Bug#11665). */
1603 if (NILP (BVAR (b, name)))
1604 return Qt;
1607 /* Run replace_buffer_in_windows before making another buffer current
1608 since set-window-buffer-start-and-point will refuse to make another
1609 buffer current if the selected window does not show the current
1610 buffer. (Bug#10114) */
1611 replace_buffer_in_windows (buffer);
1613 /* Exit if replacing the buffer in windows has killed our buffer. */
1614 if (NILP (BVAR (b, name)))
1615 return Qt;
1617 /* Make this buffer not be current. Exit if it is the sole visible
1618 buffer. */
1619 if (b == current_buffer)
1621 tem = Fother_buffer (buffer, Qnil, Qnil);
1622 Fset_buffer (tem);
1623 if (b == current_buffer)
1624 return Qnil;
1627 /* If the buffer now current is shown in the minibuffer and our buffer
1628 is the sole other buffer give up. */
1629 XSETBUFFER (tem, current_buffer);
1630 if (EQ (tem, XWINDOW (minibuf_window)->buffer)
1631 && EQ (buffer, Fother_buffer (buffer, Qnil, Qnil)))
1632 return Qnil;
1634 /* Now there is no question: we can kill the buffer. */
1636 #ifdef CLASH_DETECTION
1637 /* Unlock this buffer's file, if it is locked. */
1638 unlock_buffer (b);
1639 #endif /* CLASH_DETECTION */
1641 GCPRO1 (buffer);
1642 kill_buffer_processes (buffer);
1643 UNGCPRO;
1645 /* Killing buffer processes may run sentinels which may have killed
1646 our buffer. */
1647 if (NILP (BVAR (b, name)))
1648 return Qt;
1650 /* These may run Lisp code and into infinite loops (if someone
1651 insisted on circular lists) so allow quitting here. */
1652 frames_discard_buffer (buffer);
1654 clear_charpos_cache (b);
1656 tem = Vinhibit_quit;
1657 Vinhibit_quit = Qt;
1658 /* Remove the buffer from the list of all buffers. */
1659 Vbuffer_alist = Fdelq (Frassq (buffer, Vbuffer_alist), Vbuffer_alist);
1660 /* If replace_buffer_in_windows didn't do its job fix that now. */
1661 replace_buffer_in_windows_safely (buffer);
1662 Vinhibit_quit = tem;
1664 /* Delete any auto-save file, if we saved it in this session.
1665 But not if the buffer is modified. */
1666 if (STRINGP (BVAR (b, auto_save_file_name))
1667 && BUF_AUTOSAVE_MODIFF (b) != 0
1668 && BUF_SAVE_MODIFF (b) < BUF_AUTOSAVE_MODIFF (b)
1669 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)
1670 && NILP (Fsymbol_value (intern ("auto-save-visited-file-name"))))
1672 Lisp_Object delete;
1673 delete = Fsymbol_value (intern ("delete-auto-save-files"));
1674 if (! NILP (delete))
1675 internal_delete_file (BVAR (b, auto_save_file_name));
1678 /* Deleting an auto-save file could have killed our buffer. */
1679 if (NILP (BVAR (b, name)))
1680 return Qt;
1682 if (b->base_buffer)
1684 /* Unchain all markers that belong to this indirect buffer.
1685 Don't unchain the markers that belong to the base buffer
1686 or its other indirect buffers. */
1687 for (m = BUF_MARKERS (b); m; )
1689 struct Lisp_Marker *next = m->next;
1690 if (m->buffer == b)
1691 unchain_marker (m);
1692 m = next;
1695 else
1697 /* Unchain all markers of this buffer and its indirect buffers.
1698 and leave them pointing nowhere. */
1699 for (m = BUF_MARKERS (b); m; )
1701 struct Lisp_Marker *next = m->next;
1702 m->buffer = 0;
1703 m->next = NULL;
1704 m = next;
1706 BUF_MARKERS (b) = NULL;
1707 set_buffer_intervals (b, NULL);
1709 /* Perhaps we should explicitly free the interval tree here... */
1712 /* Reset the local variables, so that this buffer's local values
1713 won't be protected from GC. They would be protected
1714 if they happened to remain cached in their symbols.
1715 This gets rid of them for certain. */
1716 swap_out_buffer_local_variables (b);
1717 reset_buffer_local_variables (b, 1);
1719 BSET (b, name, Qnil);
1721 BLOCK_INPUT;
1722 if (b->base_buffer)
1724 /* Notify our base buffer that we don't share the text anymore. */
1725 eassert (b->indirections == -1);
1726 b->base_buffer->indirections--;
1727 eassert (b->base_buffer->indirections >= 0);
1729 else
1730 /* No one shares our buffer text, can free it. */
1731 free_buffer_text (b);
1733 if (b->newline_cache)
1735 free_region_cache (b->newline_cache);
1736 b->newline_cache = 0;
1738 if (b->width_run_cache)
1740 free_region_cache (b->width_run_cache);
1741 b->width_run_cache = 0;
1743 BSET (b, width_table, Qnil);
1744 UNBLOCK_INPUT;
1745 BSET (b, undo_list, Qnil);
1747 /* Run buffer-list-update-hook. */
1748 if (!NILP (Vrun_hooks))
1749 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1751 return Qt;
1754 /* Move association for BUFFER to the front of buffer (a)lists. Since
1755 we do this each time BUFFER is selected visibly, the more recently
1756 selected buffers are always closer to the front of those lists. This
1757 means that other_buffer is more likely to choose a relevant buffer.
1759 Note that this moves BUFFER to the front of the buffer lists of the
1760 selected frame even if BUFFER is not shown there. If BUFFER is not
1761 shown in the selected frame, consider the present behavior a feature.
1762 `select-window' gets this right since it shows BUFFER in the selected
1763 window when calling us. */
1765 void
1766 record_buffer (Lisp_Object buffer)
1768 Lisp_Object aelt, aelt_cons, tem;
1769 register struct frame *f = XFRAME (selected_frame);
1771 CHECK_BUFFER (buffer);
1773 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
1774 Don't allow quitting since this might leave the buffer list in an
1775 inconsistent state. */
1776 tem = Vinhibit_quit;
1777 Vinhibit_quit = Qt;
1778 aelt = Frassq (buffer, Vbuffer_alist);
1779 aelt_cons = Fmemq (aelt, Vbuffer_alist);
1780 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
1781 XSETCDR (aelt_cons, Vbuffer_alist);
1782 Vbuffer_alist = aelt_cons;
1783 Vinhibit_quit = tem;
1785 /* Update buffer list of selected frame. */
1786 fset_buffer_list (f, Fcons (buffer, Fdelq (buffer, f->buffer_list)));
1787 fset_buried_buffer_list (f, Fdelq (buffer, f->buried_buffer_list));
1789 /* Run buffer-list-update-hook. */
1790 if (!NILP (Vrun_hooks))
1791 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1795 /* Move BUFFER to the end of the buffer (a)lists. Do nothing if the
1796 buffer is killed. For the selected frame's buffer list this moves
1797 BUFFER to its end even if it was never shown in that frame. If
1798 this happens we have a feature, hence `bury-buffer-internal' should be
1799 called only when BUFFER was shown in the selected frame. */
1801 DEFUN ("bury-buffer-internal", Fbury_buffer_internal, Sbury_buffer_internal,
1802 1, 1, 0,
1803 doc: /* Move BUFFER to the end of the buffer list. */)
1804 (Lisp_Object buffer)
1806 Lisp_Object aelt, aelt_cons, tem;
1807 register struct frame *f = XFRAME (selected_frame);
1809 CHECK_BUFFER (buffer);
1811 /* Update Vbuffer_alist (we know that it has an entry for BUFFER).
1812 Don't allow quitting since this might leave the buffer list in an
1813 inconsistent state. */
1814 tem = Vinhibit_quit;
1815 Vinhibit_quit = Qt;
1816 aelt = Frassq (buffer, Vbuffer_alist);
1817 aelt_cons = Fmemq (aelt, Vbuffer_alist);
1818 Vbuffer_alist = Fdelq (aelt, Vbuffer_alist);
1819 XSETCDR (aelt_cons, Qnil);
1820 Vbuffer_alist = nconc2 (Vbuffer_alist, aelt_cons);
1821 Vinhibit_quit = tem;
1823 /* Update buffer lists of selected frame. */
1824 fset_buffer_list (f, Fdelq (buffer, f->buffer_list));
1825 fset_buried_buffer_list
1826 (f, Fcons (buffer, Fdelq (buffer, f->buried_buffer_list)));
1828 /* Run buffer-list-update-hook. */
1829 if (!NILP (Vrun_hooks))
1830 call1 (Vrun_hooks, Qbuffer_list_update_hook);
1832 return Qnil;
1835 DEFUN ("set-buffer-major-mode", Fset_buffer_major_mode, Sset_buffer_major_mode, 1, 1, 0,
1836 doc: /* Set an appropriate major mode for BUFFER.
1837 For the *scratch* buffer, use `initial-major-mode', otherwise choose a mode
1838 according to `default-major-mode'.
1839 Use this function before selecting the buffer, since it may need to inspect
1840 the current buffer's major mode. */)
1841 (Lisp_Object buffer)
1843 ptrdiff_t count;
1844 Lisp_Object function;
1846 CHECK_BUFFER (buffer);
1848 if (STRINGP (BVAR (XBUFFER (buffer), name))
1849 && strcmp (SSDATA (BVAR (XBUFFER (buffer), name)), "*scratch*") == 0)
1850 function = find_symbol_value (intern ("initial-major-mode"));
1851 else
1853 function = BVAR (&buffer_defaults, major_mode);
1854 if (NILP (function)
1855 && NILP (Fget (BVAR (current_buffer, major_mode), Qmode_class)))
1856 function = BVAR (current_buffer, major_mode);
1859 if (NILP (function) || EQ (function, Qfundamental_mode))
1860 return Qnil;
1862 count = SPECPDL_INDEX ();
1864 /* To select a nonfundamental mode,
1865 select the buffer temporarily and then call the mode function. */
1867 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1869 Fset_buffer (buffer);
1870 call0 (function);
1872 return unbind_to (count, Qnil);
1875 DEFUN ("current-buffer", Fcurrent_buffer, Scurrent_buffer, 0, 0, 0,
1876 doc: /* Return the current buffer as a Lisp object. */)
1877 (void)
1879 register Lisp_Object buf;
1880 XSETBUFFER (buf, current_buffer);
1881 return buf;
1884 /* Set the current buffer to B.
1886 We previously set windows_or_buffers_changed here to invalidate
1887 global unchanged information in beg_unchanged and end_unchanged.
1888 This is no longer necessary because we now compute unchanged
1889 information on a buffer-basis. Every action affecting other
1890 windows than the selected one requires a select_window at some
1891 time, and that increments windows_or_buffers_changed. */
1893 void
1894 set_buffer_internal (register struct buffer *b)
1896 if (current_buffer != b)
1897 set_buffer_internal_1 (b);
1900 /* Set the current buffer to B, and do not set windows_or_buffers_changed.
1901 This is used by redisplay. */
1903 void
1904 set_buffer_internal_1 (register struct buffer *b)
1906 register struct buffer *old_buf;
1907 register Lisp_Object tail;
1909 #ifdef USE_MMAP_FOR_BUFFERS
1910 if (b->text->beg == NULL)
1911 enlarge_buffer_text (b, 0);
1912 #endif /* USE_MMAP_FOR_BUFFERS */
1914 if (current_buffer == b)
1915 return;
1917 old_buf = current_buffer;
1918 current_buffer = b;
1919 last_known_column_point = -1; /* invalidate indentation cache */
1921 if (old_buf)
1923 /* Put the undo list back in the base buffer, so that it appears
1924 that an indirect buffer shares the undo list of its base. */
1925 if (old_buf->base_buffer)
1926 BSET (old_buf->base_buffer, undo_list, BVAR (old_buf, undo_list));
1928 /* If the old current buffer has markers to record PT, BEGV and ZV
1929 when it is not current, update them now. */
1930 record_buffer_markers (old_buf);
1933 /* Get the undo list from the base buffer, so that it appears
1934 that an indirect buffer shares the undo list of its base. */
1935 if (b->base_buffer)
1936 BSET (b, undo_list, BVAR (b->base_buffer, undo_list));
1938 /* If the new current buffer has markers to record PT, BEGV and ZV
1939 when it is not current, fetch them now. */
1940 fetch_buffer_markers (b);
1942 /* Look down buffer's list of local Lisp variables
1943 to find and update any that forward into C variables. */
1947 for (tail = BVAR (b, local_var_alist); CONSP (tail); tail = XCDR (tail))
1949 Lisp_Object var = XCAR (XCAR (tail));
1950 struct Lisp_Symbol *sym = XSYMBOL (var);
1951 if (sym->redirect == SYMBOL_LOCALIZED /* Just to be sure. */
1952 && SYMBOL_BLV (sym)->fwd)
1953 /* Just reference the variable
1954 to cause it to become set for this buffer. */
1955 Fsymbol_value (var);
1958 /* Do the same with any others that were local to the previous buffer */
1959 while (b != old_buf && (b = old_buf, b));
1962 /* Switch to buffer B temporarily for redisplay purposes.
1963 This avoids certain things that don't need to be done within redisplay. */
1965 void
1966 set_buffer_temp (struct buffer *b)
1968 register struct buffer *old_buf;
1970 if (current_buffer == b)
1971 return;
1973 old_buf = current_buffer;
1974 current_buffer = b;
1976 /* If the old current buffer has markers to record PT, BEGV and ZV
1977 when it is not current, update them now. */
1978 record_buffer_markers (old_buf);
1980 /* If the new current buffer has markers to record PT, BEGV and ZV
1981 when it is not current, fetch them now. */
1982 fetch_buffer_markers (b);
1985 DEFUN ("set-buffer", Fset_buffer, Sset_buffer, 1, 1, 0,
1986 doc: /* Make buffer BUFFER-OR-NAME current for editing operations.
1987 BUFFER-OR-NAME may be a buffer or the name of an existing buffer. See
1988 also `save-excursion' when you want to make a buffer current
1989 temporarily. This function does not display the buffer, so its effect
1990 ends when the current command terminates. Use `switch-to-buffer' or
1991 `pop-to-buffer' to switch buffers permanently. */)
1992 (register Lisp_Object buffer_or_name)
1994 register Lisp_Object buffer;
1995 buffer = Fget_buffer (buffer_or_name);
1996 if (NILP (buffer))
1997 nsberror (buffer_or_name);
1998 if (NILP (BVAR (XBUFFER (buffer), name)))
1999 error ("Selecting deleted buffer");
2000 set_buffer_internal (XBUFFER (buffer));
2001 return buffer;
2004 /* Set the current buffer to BUFFER provided it is alive. */
2006 Lisp_Object
2007 set_buffer_if_live (Lisp_Object buffer)
2009 if (! NILP (BVAR (XBUFFER (buffer), name)))
2010 Fset_buffer (buffer);
2011 return Qnil;
2014 DEFUN ("barf-if-buffer-read-only", Fbarf_if_buffer_read_only,
2015 Sbarf_if_buffer_read_only, 0, 0, 0,
2016 doc: /* Signal a `buffer-read-only' error if the current buffer is read-only. */)
2017 (void)
2019 if (!NILP (BVAR (current_buffer, read_only))
2020 && NILP (Vinhibit_read_only))
2021 xsignal1 (Qbuffer_read_only, Fcurrent_buffer ());
2022 return Qnil;
2025 DEFUN ("erase-buffer", Ferase_buffer, Serase_buffer, 0, 0, "*",
2026 doc: /* Delete the entire contents of the current buffer.
2027 Any narrowing restriction in effect (see `narrow-to-region') is removed,
2028 so the buffer is truly empty after this. */)
2029 (void)
2031 Fwiden ();
2033 del_range (BEG, Z);
2035 current_buffer->last_window_start = 1;
2036 /* Prevent warnings, or suspension of auto saving, that would happen
2037 if future size is less than past size. Use of erase-buffer
2038 implies that the future text is not really related to the past text. */
2039 XSETFASTINT (BVAR (current_buffer, save_length), 0);
2040 return Qnil;
2043 void
2044 validate_region (register Lisp_Object *b, register Lisp_Object *e)
2046 CHECK_NUMBER_COERCE_MARKER (*b);
2047 CHECK_NUMBER_COERCE_MARKER (*e);
2049 if (XINT (*b) > XINT (*e))
2051 Lisp_Object tem;
2052 tem = *b; *b = *e; *e = tem;
2055 if (! (BEGV <= XINT (*b) && XINT (*e) <= ZV))
2056 args_out_of_range (*b, *e);
2059 /* Advance BYTE_POS up to a character boundary
2060 and return the adjusted position. */
2062 static ptrdiff_t
2063 advance_to_char_boundary (ptrdiff_t byte_pos)
2065 int c;
2067 if (byte_pos == BEG)
2068 /* Beginning of buffer is always a character boundary. */
2069 return BEG;
2071 c = FETCH_BYTE (byte_pos);
2072 if (! CHAR_HEAD_P (c))
2074 /* We should advance BYTE_POS only when C is a constituent of a
2075 multibyte sequence. */
2076 ptrdiff_t orig_byte_pos = byte_pos;
2080 byte_pos--;
2081 c = FETCH_BYTE (byte_pos);
2083 while (! CHAR_HEAD_P (c) && byte_pos > BEG);
2084 INC_POS (byte_pos);
2085 if (byte_pos < orig_byte_pos)
2086 byte_pos = orig_byte_pos;
2087 /* If C is a constituent of a multibyte sequence, BYTE_POS was
2088 surely advance to the correct character boundary. If C is
2089 not, BYTE_POS was unchanged. */
2092 return byte_pos;
2095 DEFUN ("buffer-swap-text", Fbuffer_swap_text, Sbuffer_swap_text,
2096 1, 1, 0,
2097 doc: /* Swap the text between current buffer and BUFFER. */)
2098 (Lisp_Object buffer)
2100 struct buffer *other_buffer;
2101 CHECK_BUFFER (buffer);
2102 other_buffer = XBUFFER (buffer);
2104 if (NILP (BVAR (other_buffer, name)))
2105 error ("Cannot swap a dead buffer's text");
2107 /* Actually, it probably works just fine.
2108 * if (other_buffer == current_buffer)
2109 * error ("Cannot swap a buffer's text with itself"); */
2111 /* Actually, this may be workable as well, tho probably only if they're
2112 *both* indirect. */
2113 if (other_buffer->base_buffer
2114 || current_buffer->base_buffer)
2115 error ("Cannot swap indirect buffers's text");
2117 { /* This is probably harder to make work. */
2118 struct buffer *other;
2119 FOR_EACH_BUFFER (other)
2120 if (other->base_buffer == other_buffer
2121 || other->base_buffer == current_buffer)
2122 error ("One of the buffers to swap has indirect buffers");
2125 #define swapfield(field, type) \
2126 do { \
2127 type tmp##field = other_buffer->field; \
2128 other_buffer->field = current_buffer->field; \
2129 current_buffer->field = tmp##field; \
2130 } while (0)
2131 #define swapfield_(field, type) \
2132 do { \
2133 type tmp##field = BVAR (other_buffer, field); \
2134 BSET (other_buffer, field, BVAR (current_buffer, field)); \
2135 BSET (current_buffer, field, tmp##field); \
2136 } while (0)
2138 swapfield (own_text, struct buffer_text);
2139 eassert (current_buffer->text == &current_buffer->own_text);
2140 eassert (other_buffer->text == &other_buffer->own_text);
2141 #ifdef REL_ALLOC
2142 r_alloc_reset_variable ((void **) &current_buffer->own_text.beg,
2143 (void **) &other_buffer->own_text.beg);
2144 r_alloc_reset_variable ((void **) &other_buffer->own_text.beg,
2145 (void **) &current_buffer->own_text.beg);
2146 #endif /* REL_ALLOC */
2148 swapfield (pt, ptrdiff_t);
2149 swapfield (pt_byte, ptrdiff_t);
2150 swapfield (begv, ptrdiff_t);
2151 swapfield (begv_byte, ptrdiff_t);
2152 swapfield (zv, ptrdiff_t);
2153 swapfield (zv_byte, ptrdiff_t);
2154 eassert (!current_buffer->base_buffer);
2155 eassert (!other_buffer->base_buffer);
2156 swapfield (indirections, ptrdiff_t);
2157 current_buffer->clip_changed = 1; other_buffer->clip_changed = 1;
2158 swapfield (newline_cache, struct region_cache *);
2159 swapfield (width_run_cache, struct region_cache *);
2160 current_buffer->prevent_redisplay_optimizations_p = 1;
2161 other_buffer->prevent_redisplay_optimizations_p = 1;
2162 swapfield (overlays_before, struct Lisp_Overlay *);
2163 swapfield (overlays_after, struct Lisp_Overlay *);
2164 swapfield (overlay_center, ptrdiff_t);
2165 swapfield_ (undo_list, Lisp_Object);
2166 swapfield_ (mark, Lisp_Object);
2167 swapfield_ (enable_multibyte_characters, Lisp_Object);
2168 swapfield_ (bidi_display_reordering, Lisp_Object);
2169 swapfield_ (bidi_paragraph_direction, Lisp_Object);
2170 /* FIXME: Not sure what we should do with these *_marker fields.
2171 Hopefully they're just nil anyway. */
2172 swapfield_ (pt_marker, Lisp_Object);
2173 swapfield_ (begv_marker, Lisp_Object);
2174 swapfield_ (zv_marker, Lisp_Object);
2175 BSET (current_buffer, point_before_scroll, Qnil);
2176 BSET (other_buffer, point_before_scroll, Qnil);
2178 current_buffer->text->modiff++; other_buffer->text->modiff++;
2179 current_buffer->text->chars_modiff++; other_buffer->text->chars_modiff++;
2180 current_buffer->text->overlay_modiff++; other_buffer->text->overlay_modiff++;
2181 current_buffer->text->beg_unchanged = current_buffer->text->gpt;
2182 current_buffer->text->end_unchanged = current_buffer->text->gpt;
2183 other_buffer->text->beg_unchanged = other_buffer->text->gpt;
2184 other_buffer->text->end_unchanged = other_buffer->text->gpt;
2186 struct Lisp_Marker *m;
2187 for (m = BUF_MARKERS (current_buffer); m; m = m->next)
2188 if (m->buffer == other_buffer)
2189 m->buffer = current_buffer;
2190 else
2191 /* Since there's no indirect buffer in sight, markers on
2192 BUF_MARKERS(buf) should either be for `buf' or dead. */
2193 eassert (!m->buffer);
2194 for (m = BUF_MARKERS (other_buffer); m; m = m->next)
2195 if (m->buffer == current_buffer)
2196 m->buffer = other_buffer;
2197 else
2198 /* Since there's no indirect buffer in sight, markers on
2199 BUF_MARKERS(buf) should either be for `buf' or dead. */
2200 eassert (!m->buffer);
2202 { /* Some of the C code expects that w->buffer == w->pointm->buffer.
2203 So since we just swapped the markers between the two buffers, we need
2204 to undo the effect of this swap for window markers. */
2205 Lisp_Object w = Fselected_window (), ws = Qnil;
2206 Lisp_Object buf1, buf2;
2207 XSETBUFFER (buf1, current_buffer); XSETBUFFER (buf2, other_buffer);
2209 while (NILP (Fmemq (w, ws)))
2211 ws = Fcons (w, ws);
2212 if (MARKERP (XWINDOW (w)->pointm)
2213 && (EQ (XWINDOW (w)->buffer, buf1)
2214 || EQ (XWINDOW (w)->buffer, buf2)))
2215 Fset_marker (XWINDOW (w)->pointm,
2216 make_number
2217 (BUF_BEGV (XBUFFER (XWINDOW (w)->buffer))),
2218 XWINDOW (w)->buffer);
2219 w = Fnext_window (w, Qt, Qt);
2223 if (current_buffer->text->intervals)
2224 (eassert (EQ (current_buffer->text->intervals->up.obj, buffer)),
2225 XSETBUFFER (current_buffer->text->intervals->up.obj, current_buffer));
2226 if (other_buffer->text->intervals)
2227 (eassert (EQ (other_buffer->text->intervals->up.obj, Fcurrent_buffer ())),
2228 XSETBUFFER (other_buffer->text->intervals->up.obj, other_buffer));
2230 return Qnil;
2233 DEFUN ("set-buffer-multibyte", Fset_buffer_multibyte, Sset_buffer_multibyte,
2234 1, 1, 0,
2235 doc: /* Set the multibyte flag of the current buffer to FLAG.
2236 If FLAG is t, this makes the buffer a multibyte buffer.
2237 If FLAG is nil, this makes the buffer a single-byte buffer.
2238 In these cases, the buffer contents remain unchanged as a sequence of
2239 bytes but the contents viewed as characters do change.
2240 If FLAG is `to', this makes the buffer a multibyte buffer by changing
2241 all eight-bit bytes to eight-bit characters.
2242 If the multibyte flag was really changed, undo information of the
2243 current buffer is cleared. */)
2244 (Lisp_Object flag)
2246 struct Lisp_Marker *tail, *markers;
2247 struct buffer *other;
2248 ptrdiff_t begv, zv;
2249 int narrowed = (BEG != BEGV || Z != ZV);
2250 int modified_p = !NILP (Fbuffer_modified_p (Qnil));
2251 Lisp_Object old_undo = BVAR (current_buffer, undo_list);
2252 struct gcpro gcpro1;
2254 if (current_buffer->base_buffer)
2255 error ("Cannot do `set-buffer-multibyte' on an indirect buffer");
2257 /* Do nothing if nothing actually changes. */
2258 if (NILP (flag) == NILP (BVAR (current_buffer, enable_multibyte_characters)))
2259 return flag;
2261 GCPRO1 (old_undo);
2263 /* Don't record these buffer changes. We will put a special undo entry
2264 instead. */
2265 BSET (current_buffer, undo_list, Qt);
2267 /* If the cached position is for this buffer, clear it out. */
2268 clear_charpos_cache (current_buffer);
2270 if (NILP (flag))
2271 begv = BEGV_BYTE, zv = ZV_BYTE;
2272 else
2273 begv = BEGV, zv = ZV;
2275 if (narrowed)
2276 Fwiden ();
2278 if (NILP (flag))
2280 ptrdiff_t pos, stop;
2281 unsigned char *p;
2283 /* Do this first, so it can use CHAR_TO_BYTE
2284 to calculate the old correspondences. */
2285 set_intervals_multibyte (0);
2287 BSET (current_buffer, enable_multibyte_characters, Qnil);
2289 Z = Z_BYTE;
2290 BEGV = BEGV_BYTE;
2291 ZV = ZV_BYTE;
2292 GPT = GPT_BYTE;
2293 TEMP_SET_PT_BOTH (PT_BYTE, PT_BYTE);
2296 for (tail = BUF_MARKERS (current_buffer); tail; tail = tail->next)
2297 tail->charpos = tail->bytepos;
2299 /* Convert multibyte form of 8-bit characters to unibyte. */
2300 pos = BEG;
2301 stop = GPT;
2302 p = BEG_ADDR;
2303 while (1)
2305 int c, bytes;
2307 if (pos == stop)
2309 if (pos == Z)
2310 break;
2311 p = GAP_END_ADDR;
2312 stop = Z;
2314 if (ASCII_BYTE_P (*p))
2315 p++, pos++;
2316 else if (CHAR_BYTE8_HEAD_P (*p))
2318 c = STRING_CHAR_AND_LENGTH (p, bytes);
2319 /* Delete all bytes for this 8-bit character but the
2320 last one, and change the last one to the character
2321 code. */
2322 bytes--;
2323 del_range_2 (pos, pos, pos + bytes, pos + bytes, 0);
2324 p = GAP_END_ADDR;
2325 *p++ = c;
2326 pos++;
2327 if (begv > pos)
2328 begv -= bytes;
2329 if (zv > pos)
2330 zv -= bytes;
2331 stop = Z;
2333 else
2335 bytes = BYTES_BY_CHAR_HEAD (*p);
2336 p += bytes, pos += bytes;
2339 if (narrowed)
2340 Fnarrow_to_region (make_number (begv), make_number (zv));
2342 else
2344 ptrdiff_t pt = PT;
2345 ptrdiff_t pos, stop;
2346 unsigned char *p, *pend;
2348 /* Be sure not to have a multibyte sequence striding over the GAP.
2349 Ex: We change this: "...abc\302 _GAP_ \241def..."
2350 to: "...abc _GAP_ \302\241def..." */
2352 if (EQ (flag, Qt)
2353 && GPT_BYTE > 1 && GPT_BYTE < Z_BYTE
2354 && ! CHAR_HEAD_P (*(GAP_END_ADDR)))
2356 unsigned char *q = GPT_ADDR - 1;
2358 while (! CHAR_HEAD_P (*q) && q > BEG_ADDR) q--;
2359 if (LEADING_CODE_P (*q))
2361 ptrdiff_t new_gpt = GPT_BYTE - (GPT_ADDR - q);
2363 move_gap_both (new_gpt, new_gpt);
2367 /* Make the buffer contents valid as multibyte by converting
2368 8-bit characters to multibyte form. */
2369 pos = BEG;
2370 stop = GPT;
2371 p = BEG_ADDR;
2372 pend = GPT_ADDR;
2373 while (1)
2375 int bytes;
2377 if (pos == stop)
2379 if (pos == Z)
2380 break;
2381 p = GAP_END_ADDR;
2382 pend = Z_ADDR;
2383 stop = Z;
2386 if (ASCII_BYTE_P (*p))
2387 p++, pos++;
2388 else if (EQ (flag, Qt)
2389 && ! CHAR_BYTE8_HEAD_P (*p)
2390 && (bytes = MULTIBYTE_LENGTH (p, pend)) > 0)
2391 p += bytes, pos += bytes;
2392 else
2394 unsigned char tmp[MAX_MULTIBYTE_LENGTH];
2395 int c;
2397 c = BYTE8_TO_CHAR (*p);
2398 bytes = CHAR_STRING (c, tmp);
2399 *p = tmp[0];
2400 TEMP_SET_PT_BOTH (pos + 1, pos + 1);
2401 bytes--;
2402 insert_1_both ((char *) tmp + 1, bytes, bytes, 1, 0, 0);
2403 /* Now the gap is after the just inserted data. */
2404 pos = GPT;
2405 p = GAP_END_ADDR;
2406 if (pos <= begv)
2407 begv += bytes;
2408 if (pos <= zv)
2409 zv += bytes;
2410 if (pos <= pt)
2411 pt += bytes;
2412 pend = Z_ADDR;
2413 stop = Z;
2417 if (pt != PT)
2418 TEMP_SET_PT (pt);
2420 if (narrowed)
2421 Fnarrow_to_region (make_number (begv), make_number (zv));
2423 /* Do this first, so that chars_in_text asks the right question.
2424 set_intervals_multibyte needs it too. */
2425 BSET (current_buffer, enable_multibyte_characters, Qt);
2427 GPT_BYTE = advance_to_char_boundary (GPT_BYTE);
2428 GPT = chars_in_text (BEG_ADDR, GPT_BYTE - BEG_BYTE) + BEG;
2430 Z = chars_in_text (GAP_END_ADDR, Z_BYTE - GPT_BYTE) + GPT;
2432 BEGV_BYTE = advance_to_char_boundary (BEGV_BYTE);
2433 if (BEGV_BYTE > GPT_BYTE)
2434 BEGV = chars_in_text (GAP_END_ADDR, BEGV_BYTE - GPT_BYTE) + GPT;
2435 else
2436 BEGV = chars_in_text (BEG_ADDR, BEGV_BYTE - BEG_BYTE) + BEG;
2438 ZV_BYTE = advance_to_char_boundary (ZV_BYTE);
2439 if (ZV_BYTE > GPT_BYTE)
2440 ZV = chars_in_text (GAP_END_ADDR, ZV_BYTE - GPT_BYTE) + GPT;
2441 else
2442 ZV = chars_in_text (BEG_ADDR, ZV_BYTE - BEG_BYTE) + BEG;
2445 ptrdiff_t byte = advance_to_char_boundary (PT_BYTE);
2446 ptrdiff_t position;
2448 if (byte > GPT_BYTE)
2449 position = chars_in_text (GAP_END_ADDR, byte - GPT_BYTE) + GPT;
2450 else
2451 position = chars_in_text (BEG_ADDR, byte - BEG_BYTE) + BEG;
2452 TEMP_SET_PT_BOTH (position, byte);
2455 tail = markers = BUF_MARKERS (current_buffer);
2457 /* This prevents BYTE_TO_CHAR (that is, buf_bytepos_to_charpos) from
2458 getting confused by the markers that have not yet been updated.
2459 It is also a signal that it should never create a marker. */
2460 BUF_MARKERS (current_buffer) = NULL;
2462 for (; tail; tail = tail->next)
2464 tail->bytepos = advance_to_char_boundary (tail->bytepos);
2465 tail->charpos = BYTE_TO_CHAR (tail->bytepos);
2468 /* Make sure no markers were put on the chain
2469 while the chain value was incorrect. */
2470 if (BUF_MARKERS (current_buffer))
2471 abort ();
2473 BUF_MARKERS (current_buffer) = markers;
2475 /* Do this last, so it can calculate the new correspondences
2476 between chars and bytes. */
2477 set_intervals_multibyte (1);
2480 if (!EQ (old_undo, Qt))
2482 /* Represent all the above changes by a special undo entry. */
2483 BSET (current_buffer, undo_list,
2484 Fcons (list3 (Qapply,
2485 intern ("set-buffer-multibyte"),
2486 NILP (flag) ? Qt : Qnil),
2487 old_undo));
2490 UNGCPRO;
2492 /* Changing the multibyteness of a buffer means that all windows
2493 showing that buffer must be updated thoroughly. */
2494 current_buffer->prevent_redisplay_optimizations_p = 1;
2495 ++windows_or_buffers_changed;
2497 /* Copy this buffer's new multibyte status
2498 into all of its indirect buffers. */
2499 FOR_EACH_BUFFER (other)
2500 if (other->base_buffer == current_buffer && !NILP (BVAR (other, name)))
2502 BVAR (other, enable_multibyte_characters)
2503 = BVAR (current_buffer, enable_multibyte_characters);
2504 other->prevent_redisplay_optimizations_p = 1;
2507 /* Restore the modifiedness of the buffer. */
2508 if (!modified_p && !NILP (Fbuffer_modified_p (Qnil)))
2509 Fset_buffer_modified_p (Qnil);
2511 /* Update coding systems of this buffer's process (if any). */
2513 Lisp_Object process;
2515 process = Fget_buffer_process (Fcurrent_buffer ());
2516 if (PROCESSP (process))
2517 setup_process_coding_systems (process);
2520 return flag;
2523 DEFUN ("kill-all-local-variables", Fkill_all_local_variables,
2524 Skill_all_local_variables, 0, 0, 0,
2525 doc: /* Switch to Fundamental mode by killing current buffer's local variables.
2526 Most local variable bindings are eliminated so that the default values
2527 become effective once more. Also, the syntax table is set from
2528 `standard-syntax-table', the local keymap is set to nil,
2529 and the abbrev table from `fundamental-mode-abbrev-table'.
2530 This function also forces redisplay of the mode line.
2532 Every function to select a new major mode starts by
2533 calling this function.
2535 As a special exception, local variables whose names have
2536 a non-nil `permanent-local' property are not eliminated by this function.
2538 The first thing this function does is run
2539 the normal hook `change-major-mode-hook'. */)
2540 (void)
2542 Frun_hooks (1, &Qchange_major_mode_hook);
2544 /* Make sure none of the bindings in local_var_alist
2545 remain swapped in, in their symbols. */
2547 swap_out_buffer_local_variables (current_buffer);
2549 /* Actually eliminate all local bindings of this buffer. */
2551 reset_buffer_local_variables (current_buffer, 0);
2553 /* Force mode-line redisplay. Useful here because all major mode
2554 commands call this function. */
2555 update_mode_lines++;
2557 return Qnil;
2560 /* Make sure no local variables remain set up with buffer B
2561 for their current values. */
2563 static void
2564 swap_out_buffer_local_variables (struct buffer *b)
2566 Lisp_Object oalist, alist, buffer;
2568 XSETBUFFER (buffer, b);
2569 oalist = BVAR (b, local_var_alist);
2571 for (alist = oalist; CONSP (alist); alist = XCDR (alist))
2573 Lisp_Object sym = XCAR (XCAR (alist));
2574 eassert (XSYMBOL (sym)->redirect == SYMBOL_LOCALIZED);
2575 /* Need not do anything if some other buffer's binding is
2576 now cached. */
2577 if (EQ (SYMBOL_BLV (XSYMBOL (sym))->where, buffer))
2579 /* Symbol is set up for this buffer's old local value:
2580 swap it out! */
2581 swap_in_global_binding (XSYMBOL (sym));
2586 /* Find all the overlays in the current buffer that contain position POS.
2587 Return the number found, and store them in a vector in *VEC_PTR.
2588 Store in *LEN_PTR the size allocated for the vector.
2589 Store in *NEXT_PTR the next position after POS where an overlay starts,
2590 or ZV if there are no more overlays between POS and ZV.
2591 Store in *PREV_PTR the previous position before POS where an overlay ends,
2592 or where an overlay starts which ends at or after POS;
2593 or BEGV if there are no such overlays from BEGV to POS.
2594 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2596 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2597 when this function is called.
2599 If EXTEND is non-zero, we make the vector bigger if necessary.
2600 If EXTEND is zero, we never extend the vector,
2601 and we store only as many overlays as will fit.
2602 But we still return the total number of overlays.
2604 If CHANGE_REQ is true, then any position written into *PREV_PTR or
2605 *NEXT_PTR is guaranteed to be not equal to POS, unless it is the
2606 default (BEGV or ZV). */
2608 ptrdiff_t
2609 overlays_at (EMACS_INT pos, int extend, Lisp_Object **vec_ptr,
2610 ptrdiff_t *len_ptr,
2611 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr, int change_req)
2613 Lisp_Object overlay, start, end;
2614 struct Lisp_Overlay *tail;
2615 ptrdiff_t idx = 0;
2616 ptrdiff_t len = *len_ptr;
2617 Lisp_Object *vec = *vec_ptr;
2618 ptrdiff_t next = ZV;
2619 ptrdiff_t prev = BEGV;
2620 int inhibit_storing = 0;
2622 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2624 ptrdiff_t startpos, endpos;
2626 XSETMISC (overlay, tail);
2628 start = OVERLAY_START (overlay);
2629 end = OVERLAY_END (overlay);
2630 endpos = OVERLAY_POSITION (end);
2631 if (endpos < pos)
2633 if (prev < endpos)
2634 prev = endpos;
2635 break;
2637 startpos = OVERLAY_POSITION (start);
2638 /* This one ends at or after POS
2639 so its start counts for PREV_PTR if it's before POS. */
2640 if (prev < startpos && startpos < pos)
2641 prev = startpos;
2642 if (endpos == pos)
2643 continue;
2644 if (startpos <= pos)
2646 if (idx == len)
2648 /* The supplied vector is full.
2649 Either make it bigger, or don't store any more in it. */
2650 if (extend)
2652 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2653 sizeof *vec);
2654 *vec_ptr = vec;
2655 len = *len_ptr;
2657 else
2658 inhibit_storing = 1;
2661 if (!inhibit_storing)
2662 vec[idx] = overlay;
2663 /* Keep counting overlays even if we can't return them all. */
2664 idx++;
2666 else if (startpos < next)
2667 next = startpos;
2670 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2672 ptrdiff_t startpos, endpos;
2674 XSETMISC (overlay, tail);
2676 start = OVERLAY_START (overlay);
2677 end = OVERLAY_END (overlay);
2678 startpos = OVERLAY_POSITION (start);
2679 if (pos < startpos)
2681 if (startpos < next)
2682 next = startpos;
2683 break;
2685 endpos = OVERLAY_POSITION (end);
2686 if (pos < endpos)
2688 if (idx == len)
2690 if (extend)
2692 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2693 sizeof *vec);
2694 *vec_ptr = vec;
2695 len = *len_ptr;
2697 else
2698 inhibit_storing = 1;
2701 if (!inhibit_storing)
2702 vec[idx] = overlay;
2703 idx++;
2705 if (startpos < pos && startpos > prev)
2706 prev = startpos;
2708 else if (endpos < pos && endpos > prev)
2709 prev = endpos;
2710 else if (endpos == pos && startpos > prev
2711 && (!change_req || startpos < pos))
2712 prev = startpos;
2715 if (next_ptr)
2716 *next_ptr = next;
2717 if (prev_ptr)
2718 *prev_ptr = prev;
2719 return idx;
2722 /* Find all the overlays in the current buffer that overlap the range
2723 BEG-END, or are empty at BEG, or are empty at END provided END
2724 denotes the position at the end of the current buffer.
2726 Return the number found, and store them in a vector in *VEC_PTR.
2727 Store in *LEN_PTR the size allocated for the vector.
2728 Store in *NEXT_PTR the next position after POS where an overlay starts,
2729 or ZV if there are no more overlays.
2730 Store in *PREV_PTR the previous position before POS where an overlay ends,
2731 or BEGV if there are no previous overlays.
2732 NEXT_PTR and/or PREV_PTR may be 0, meaning don't store that info.
2734 *VEC_PTR and *LEN_PTR should contain a valid vector and size
2735 when this function is called.
2737 If EXTEND is non-zero, we make the vector bigger if necessary.
2738 If EXTEND is zero, we never extend the vector,
2739 and we store only as many overlays as will fit.
2740 But we still return the total number of overlays. */
2742 static ptrdiff_t
2743 overlays_in (EMACS_INT beg, EMACS_INT end, int extend,
2744 Lisp_Object **vec_ptr, ptrdiff_t *len_ptr,
2745 ptrdiff_t *next_ptr, ptrdiff_t *prev_ptr)
2747 Lisp_Object overlay, ostart, oend;
2748 struct Lisp_Overlay *tail;
2749 ptrdiff_t idx = 0;
2750 ptrdiff_t len = *len_ptr;
2751 Lisp_Object *vec = *vec_ptr;
2752 ptrdiff_t next = ZV;
2753 ptrdiff_t prev = BEGV;
2754 int inhibit_storing = 0;
2755 int end_is_Z = end == Z;
2757 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2759 ptrdiff_t startpos, endpos;
2761 XSETMISC (overlay, tail);
2763 ostart = OVERLAY_START (overlay);
2764 oend = OVERLAY_END (overlay);
2765 endpos = OVERLAY_POSITION (oend);
2766 if (endpos < beg)
2768 if (prev < endpos)
2769 prev = endpos;
2770 break;
2772 startpos = OVERLAY_POSITION (ostart);
2773 /* Count an interval if it overlaps the range, is empty at the
2774 start of the range, or is empty at END provided END denotes the
2775 end of the buffer. */
2776 if ((beg < endpos && startpos < end)
2777 || (startpos == endpos
2778 && (beg == endpos || (end_is_Z && endpos == end))))
2780 if (idx == len)
2782 /* The supplied vector is full.
2783 Either make it bigger, or don't store any more in it. */
2784 if (extend)
2786 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2787 sizeof *vec);
2788 *vec_ptr = vec;
2789 len = *len_ptr;
2791 else
2792 inhibit_storing = 1;
2795 if (!inhibit_storing)
2796 vec[idx] = overlay;
2797 /* Keep counting overlays even if we can't return them all. */
2798 idx++;
2800 else if (startpos < next)
2801 next = startpos;
2804 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2806 ptrdiff_t startpos, endpos;
2808 XSETMISC (overlay, tail);
2810 ostart = OVERLAY_START (overlay);
2811 oend = OVERLAY_END (overlay);
2812 startpos = OVERLAY_POSITION (ostart);
2813 if (end < startpos)
2815 if (startpos < next)
2816 next = startpos;
2817 break;
2819 endpos = OVERLAY_POSITION (oend);
2820 /* Count an interval if it overlaps the range, is empty at the
2821 start of the range, or is empty at END provided END denotes the
2822 end of the buffer. */
2823 if ((beg < endpos && startpos < end)
2824 || (startpos == endpos
2825 && (beg == endpos || (end_is_Z && endpos == end))))
2827 if (idx == len)
2829 if (extend)
2831 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2832 sizeof *vec);
2833 *vec_ptr = vec;
2834 len = *len_ptr;
2836 else
2837 inhibit_storing = 1;
2840 if (!inhibit_storing)
2841 vec[idx] = overlay;
2842 idx++;
2844 else if (endpos < beg && endpos > prev)
2845 prev = endpos;
2848 if (next_ptr)
2849 *next_ptr = next;
2850 if (prev_ptr)
2851 *prev_ptr = prev;
2852 return idx;
2856 /* Return non-zero if there exists an overlay with a non-nil
2857 `mouse-face' property overlapping OVERLAY. */
2860 mouse_face_overlay_overlaps (Lisp_Object overlay)
2862 ptrdiff_t start = OVERLAY_POSITION (OVERLAY_START (overlay));
2863 ptrdiff_t end = OVERLAY_POSITION (OVERLAY_END (overlay));
2864 ptrdiff_t n, i, size;
2865 Lisp_Object *v, tem;
2867 size = 10;
2868 v = alloca (size * sizeof *v);
2869 n = overlays_in (start, end, 0, &v, &size, NULL, NULL);
2870 if (n > size)
2872 v = alloca (n * sizeof *v);
2873 overlays_in (start, end, 0, &v, &n, NULL, NULL);
2876 for (i = 0; i < n; ++i)
2877 if (!EQ (v[i], overlay)
2878 && (tem = Foverlay_get (overlay, Qmouse_face),
2879 !NILP (tem)))
2880 break;
2882 return i < n;
2887 /* Fast function to just test if we're at an overlay boundary. */
2889 overlay_touches_p (ptrdiff_t pos)
2891 Lisp_Object overlay;
2892 struct Lisp_Overlay *tail;
2894 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
2896 ptrdiff_t endpos;
2898 XSETMISC (overlay ,tail);
2899 eassert (OVERLAYP (overlay));
2901 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
2902 if (endpos < pos)
2903 break;
2904 if (endpos == pos || OVERLAY_POSITION (OVERLAY_START (overlay)) == pos)
2905 return 1;
2908 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
2910 ptrdiff_t startpos;
2912 XSETMISC (overlay, tail);
2913 eassert (OVERLAYP (overlay));
2915 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
2916 if (pos < startpos)
2917 break;
2918 if (startpos == pos || OVERLAY_POSITION (OVERLAY_END (overlay)) == pos)
2919 return 1;
2921 return 0;
2924 struct sortvec
2926 Lisp_Object overlay;
2927 ptrdiff_t beg, end;
2928 EMACS_INT priority;
2931 static int
2932 compare_overlays (const void *v1, const void *v2)
2934 const struct sortvec *s1 = (const struct sortvec *) v1;
2935 const struct sortvec *s2 = (const struct sortvec *) v2;
2936 if (s1->priority != s2->priority)
2937 return s1->priority < s2->priority ? -1 : 1;
2938 if (s1->beg != s2->beg)
2939 return s1->beg < s2->beg ? -1 : 1;
2940 if (s1->end != s2->end)
2941 return s2->end < s1->end ? -1 : 1;
2942 /* Avoid the non-determinism of qsort by choosing an arbitrary ordering
2943 between "equal" overlays. The result can still change between
2944 invocations of Emacs, but it won't change in the middle of
2945 `find_field' (bug#6830). */
2946 if (XHASH (s1->overlay) != XHASH (s2->overlay))
2947 return XHASH (s1->overlay) < XHASH (s2->overlay) ? -1 : 1;
2948 return 0;
2951 /* Sort an array of overlays by priority. The array is modified in place.
2952 The return value is the new size; this may be smaller than the original
2953 size if some of the overlays were invalid or were window-specific. */
2954 ptrdiff_t
2955 sort_overlays (Lisp_Object *overlay_vec, ptrdiff_t noverlays, struct window *w)
2957 ptrdiff_t i, j;
2958 struct sortvec *sortvec = alloca (noverlays * sizeof *sortvec);
2960 /* Put the valid and relevant overlays into sortvec. */
2962 for (i = 0, j = 0; i < noverlays; i++)
2964 Lisp_Object tem;
2965 Lisp_Object overlay;
2967 overlay = overlay_vec[i];
2968 if (OVERLAYP (overlay)
2969 && OVERLAY_POSITION (OVERLAY_START (overlay)) > 0
2970 && OVERLAY_POSITION (OVERLAY_END (overlay)) > 0)
2972 /* If we're interested in a specific window, then ignore
2973 overlays that are limited to some other window. */
2974 if (w)
2976 Lisp_Object window;
2978 window = Foverlay_get (overlay, Qwindow);
2979 if (WINDOWP (window) && XWINDOW (window) != w)
2980 continue;
2983 /* This overlay is good and counts: put it into sortvec. */
2984 sortvec[j].overlay = overlay;
2985 sortvec[j].beg = OVERLAY_POSITION (OVERLAY_START (overlay));
2986 sortvec[j].end = OVERLAY_POSITION (OVERLAY_END (overlay));
2987 tem = Foverlay_get (overlay, Qpriority);
2988 if (INTEGERP (tem))
2989 sortvec[j].priority = XINT (tem);
2990 else
2991 sortvec[j].priority = 0;
2992 j++;
2995 noverlays = j;
2997 /* Sort the overlays into the proper order: increasing priority. */
2999 if (noverlays > 1)
3000 qsort (sortvec, noverlays, sizeof (struct sortvec), compare_overlays);
3002 for (i = 0; i < noverlays; i++)
3003 overlay_vec[i] = sortvec[i].overlay;
3004 return (noverlays);
3007 struct sortstr
3009 Lisp_Object string, string2;
3010 ptrdiff_t size;
3011 EMACS_INT priority;
3014 struct sortstrlist
3016 struct sortstr *buf; /* An array that expands as needed; never freed. */
3017 ptrdiff_t size; /* Allocated length of that array. */
3018 ptrdiff_t used; /* How much of the array is currently in use. */
3019 ptrdiff_t bytes; /* Total length of the strings in buf. */
3022 /* Buffers for storing information about the overlays touching a given
3023 position. These could be automatic variables in overlay_strings, but
3024 it's more efficient to hold onto the memory instead of repeatedly
3025 allocating and freeing it. */
3026 static struct sortstrlist overlay_heads, overlay_tails;
3027 static unsigned char *overlay_str_buf;
3029 /* Allocated length of overlay_str_buf. */
3030 static ptrdiff_t overlay_str_len;
3032 /* A comparison function suitable for passing to qsort. */
3033 static int
3034 cmp_for_strings (const void *as1, const void *as2)
3036 struct sortstr *s1 = (struct sortstr *)as1;
3037 struct sortstr *s2 = (struct sortstr *)as2;
3038 if (s1->size != s2->size)
3039 return s2->size < s1->size ? -1 : 1;
3040 if (s1->priority != s2->priority)
3041 return s1->priority < s2->priority ? -1 : 1;
3042 return 0;
3045 static void
3046 record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
3047 Lisp_Object str2, Lisp_Object pri, ptrdiff_t size)
3049 ptrdiff_t nbytes;
3051 if (ssl->used == ssl->size)
3052 ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
3053 ssl->buf[ssl->used].string = str;
3054 ssl->buf[ssl->used].string2 = str2;
3055 ssl->buf[ssl->used].size = size;
3056 ssl->buf[ssl->used].priority = (INTEGERP (pri) ? XINT (pri) : 0);
3057 ssl->used++;
3059 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3060 nbytes = SCHARS (str);
3061 else if (! STRING_MULTIBYTE (str))
3062 nbytes = count_size_as_multibyte (SDATA (str),
3063 SBYTES (str));
3064 else
3065 nbytes = SBYTES (str);
3067 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3068 memory_full (SIZE_MAX);
3069 ssl->bytes += nbytes;
3071 if (STRINGP (str2))
3073 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3074 nbytes = SCHARS (str2);
3075 else if (! STRING_MULTIBYTE (str2))
3076 nbytes = count_size_as_multibyte (SDATA (str2),
3077 SBYTES (str2));
3078 else
3079 nbytes = SBYTES (str2);
3081 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
3082 memory_full (SIZE_MAX);
3083 ssl->bytes += nbytes;
3087 /* Return the concatenation of the strings associated with overlays that
3088 begin or end at POS, ignoring overlays that are specific to a window
3089 other than W. The strings are concatenated in the appropriate order:
3090 shorter overlays nest inside longer ones, and higher priority inside
3091 lower. Normally all of the after-strings come first, but zero-sized
3092 overlays have their after-strings ride along with the before-strings
3093 because it would look strange to print them inside-out.
3095 Returns the string length, and stores the contents indirectly through
3096 PSTR, if that variable is non-null. The string may be overwritten by
3097 subsequent calls. */
3099 ptrdiff_t
3100 overlay_strings (ptrdiff_t pos, struct window *w, unsigned char **pstr)
3102 Lisp_Object overlay, window, str;
3103 struct Lisp_Overlay *ov;
3104 ptrdiff_t startpos, endpos;
3105 int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
3107 overlay_heads.used = overlay_heads.bytes = 0;
3108 overlay_tails.used = overlay_tails.bytes = 0;
3109 for (ov = current_buffer->overlays_before; ov; ov = ov->next)
3111 XSETMISC (overlay, ov);
3112 eassert (OVERLAYP (overlay));
3114 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3115 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3116 if (endpos < pos)
3117 break;
3118 if (endpos != pos && startpos != pos)
3119 continue;
3120 window = Foverlay_get (overlay, Qwindow);
3121 if (WINDOWP (window) && XWINDOW (window) != w)
3122 continue;
3123 if (startpos == pos
3124 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3125 record_overlay_string (&overlay_heads, str,
3126 (startpos == endpos
3127 ? Foverlay_get (overlay, Qafter_string)
3128 : Qnil),
3129 Foverlay_get (overlay, Qpriority),
3130 endpos - startpos);
3131 else if (endpos == pos
3132 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3133 record_overlay_string (&overlay_tails, str, Qnil,
3134 Foverlay_get (overlay, Qpriority),
3135 endpos - startpos);
3137 for (ov = current_buffer->overlays_after; ov; ov = ov->next)
3139 XSETMISC (overlay, ov);
3140 eassert (OVERLAYP (overlay));
3142 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3143 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3144 if (startpos > pos)
3145 break;
3146 if (endpos != pos && startpos != pos)
3147 continue;
3148 window = Foverlay_get (overlay, Qwindow);
3149 if (WINDOWP (window) && XWINDOW (window) != w)
3150 continue;
3151 if (startpos == pos
3152 && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str)))
3153 record_overlay_string (&overlay_heads, str,
3154 (startpos == endpos
3155 ? Foverlay_get (overlay, Qafter_string)
3156 : Qnil),
3157 Foverlay_get (overlay, Qpriority),
3158 endpos - startpos);
3159 else if (endpos == pos
3160 && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str)))
3161 record_overlay_string (&overlay_tails, str, Qnil,
3162 Foverlay_get (overlay, Qpriority),
3163 endpos - startpos);
3165 if (overlay_tails.used > 1)
3166 qsort (overlay_tails.buf, overlay_tails.used, sizeof (struct sortstr),
3167 cmp_for_strings);
3168 if (overlay_heads.used > 1)
3169 qsort (overlay_heads.buf, overlay_heads.used, sizeof (struct sortstr),
3170 cmp_for_strings);
3171 if (overlay_heads.bytes || overlay_tails.bytes)
3173 Lisp_Object tem;
3174 ptrdiff_t i;
3175 unsigned char *p;
3176 ptrdiff_t total;
3178 if (INT_ADD_OVERFLOW (overlay_heads.bytes, overlay_tails.bytes))
3179 memory_full (SIZE_MAX);
3180 total = overlay_heads.bytes + overlay_tails.bytes;
3181 if (total > overlay_str_len)
3182 overlay_str_buf = xpalloc (overlay_str_buf, &overlay_str_len,
3183 total - overlay_str_len, -1, 1);
3185 p = overlay_str_buf;
3186 for (i = overlay_tails.used; --i >= 0;)
3188 ptrdiff_t nbytes;
3189 tem = overlay_tails.buf[i].string;
3190 nbytes = copy_text (SDATA (tem), p,
3191 SBYTES (tem),
3192 STRING_MULTIBYTE (tem), multibyte);
3193 p += nbytes;
3195 for (i = 0; i < overlay_heads.used; ++i)
3197 ptrdiff_t nbytes;
3198 tem = overlay_heads.buf[i].string;
3199 nbytes = copy_text (SDATA (tem), p,
3200 SBYTES (tem),
3201 STRING_MULTIBYTE (tem), multibyte);
3202 p += nbytes;
3203 tem = overlay_heads.buf[i].string2;
3204 if (STRINGP (tem))
3206 nbytes = copy_text (SDATA (tem), p,
3207 SBYTES (tem),
3208 STRING_MULTIBYTE (tem), multibyte);
3209 p += nbytes;
3212 if (p != overlay_str_buf + total)
3213 abort ();
3214 if (pstr)
3215 *pstr = overlay_str_buf;
3216 return total;
3218 return 0;
3221 /* Shift overlays in BUF's overlay lists, to center the lists at POS. */
3223 void
3224 recenter_overlay_lists (struct buffer *buf, ptrdiff_t pos)
3226 Lisp_Object overlay, beg, end;
3227 struct Lisp_Overlay *prev, *tail, *next;
3229 /* See if anything in overlays_before should move to overlays_after. */
3231 /* We don't strictly need prev in this loop; it should always be nil.
3232 But we use it for symmetry and in case that should cease to be true
3233 with some future change. */
3234 prev = NULL;
3235 for (tail = buf->overlays_before; tail; prev = tail, tail = next)
3237 next = tail->next;
3238 XSETMISC (overlay, tail);
3239 eassert (OVERLAYP (overlay));
3241 beg = OVERLAY_START (overlay);
3242 end = OVERLAY_END (overlay);
3244 if (OVERLAY_POSITION (end) > pos)
3246 /* OVERLAY needs to be moved. */
3247 ptrdiff_t where = OVERLAY_POSITION (beg);
3248 struct Lisp_Overlay *other, *other_prev;
3250 /* Splice the cons cell TAIL out of overlays_before. */
3251 if (prev)
3252 prev->next = next;
3253 else
3254 set_buffer_overlays_before (buf, next);
3256 /* Search thru overlays_after for where to put it. */
3257 other_prev = NULL;
3258 for (other = buf->overlays_after; other;
3259 other_prev = other, other = other->next)
3261 Lisp_Object otherbeg, otheroverlay;
3263 XSETMISC (otheroverlay, other);
3264 eassert (OVERLAYP (otheroverlay));
3266 otherbeg = OVERLAY_START (otheroverlay);
3267 if (OVERLAY_POSITION (otherbeg) >= where)
3268 break;
3271 /* Add TAIL to overlays_after before OTHER. */
3272 tail->next = other;
3273 if (other_prev)
3274 other_prev->next = tail;
3275 else
3276 set_buffer_overlays_after (buf, tail);
3277 tail = prev;
3279 else
3280 /* We've reached the things that should stay in overlays_before.
3281 All the rest of overlays_before must end even earlier,
3282 so stop now. */
3283 break;
3286 /* See if anything in overlays_after should be in overlays_before. */
3287 prev = NULL;
3288 for (tail = buf->overlays_after; tail; prev = tail, tail = next)
3290 next = tail->next;
3291 XSETMISC (overlay, tail);
3292 eassert (OVERLAYP (overlay));
3294 beg = OVERLAY_START (overlay);
3295 end = OVERLAY_END (overlay);
3297 /* Stop looking, when we know that nothing further
3298 can possibly end before POS. */
3299 if (OVERLAY_POSITION (beg) > pos)
3300 break;
3302 if (OVERLAY_POSITION (end) <= pos)
3304 /* OVERLAY needs to be moved. */
3305 ptrdiff_t where = OVERLAY_POSITION (end);
3306 struct Lisp_Overlay *other, *other_prev;
3308 /* Splice the cons cell TAIL out of overlays_after. */
3309 if (prev)
3310 prev->next = next;
3311 else
3312 set_buffer_overlays_after (buf, next);
3314 /* Search thru overlays_before for where to put it. */
3315 other_prev = NULL;
3316 for (other = buf->overlays_before; other;
3317 other_prev = other, other = other->next)
3319 Lisp_Object otherend, otheroverlay;
3321 XSETMISC (otheroverlay, other);
3322 eassert (OVERLAYP (otheroverlay));
3324 otherend = OVERLAY_END (otheroverlay);
3325 if (OVERLAY_POSITION (otherend) <= where)
3326 break;
3329 /* Add TAIL to overlays_before before OTHER. */
3330 tail->next = other;
3331 if (other_prev)
3332 other_prev->next = tail;
3333 else
3334 set_buffer_overlays_before (buf, tail);
3335 tail = prev;
3339 buf->overlay_center = pos;
3342 void
3343 adjust_overlays_for_insert (ptrdiff_t pos, ptrdiff_t length)
3345 /* After an insertion, the lists are still sorted properly,
3346 but we may need to update the value of the overlay center. */
3347 if (current_buffer->overlay_center >= pos)
3348 current_buffer->overlay_center += length;
3351 void
3352 adjust_overlays_for_delete (ptrdiff_t pos, ptrdiff_t length)
3354 if (current_buffer->overlay_center < pos)
3355 /* The deletion was to our right. No change needed; the before- and
3356 after-lists are still consistent. */
3358 else if (current_buffer->overlay_center - pos > length)
3359 /* The deletion was to our left. We need to adjust the center value
3360 to account for the change in position, but the lists are consistent
3361 given the new value. */
3362 current_buffer->overlay_center -= length;
3363 else
3364 /* We're right in the middle. There might be things on the after-list
3365 that now belong on the before-list. Recentering will move them,
3366 and also update the center point. */
3367 recenter_overlay_lists (current_buffer, pos);
3370 /* Fix up overlays that were garbled as a result of permuting markers
3371 in the range START through END. Any overlay with at least one
3372 endpoint in this range will need to be unlinked from the overlay
3373 list and reinserted in its proper place.
3374 Such an overlay might even have negative size at this point.
3375 If so, we'll make the overlay empty. */
3376 void
3377 fix_start_end_in_overlays (register ptrdiff_t start, register ptrdiff_t end)
3379 Lisp_Object overlay;
3380 struct Lisp_Overlay *before_list IF_LINT (= NULL);
3381 struct Lisp_Overlay *after_list IF_LINT (= NULL);
3382 /* These are either nil, indicating that before_list or after_list
3383 should be assigned, or the cons cell the cdr of which should be
3384 assigned. */
3385 struct Lisp_Overlay *beforep = NULL, *afterp = NULL;
3386 /* 'Parent', likewise, indicates a cons cell or
3387 current_buffer->overlays_before or overlays_after, depending
3388 which loop we're in. */
3389 struct Lisp_Overlay *tail, *parent;
3390 ptrdiff_t startpos, endpos;
3392 /* This algorithm shifts links around instead of consing and GCing.
3393 The loop invariant is that before_list (resp. after_list) is a
3394 well-formed list except that its last element, the CDR of beforep
3395 (resp. afterp) if beforep (afterp) isn't nil or before_list
3396 (after_list) if it is, is still uninitialized. So it's not a bug
3397 that before_list isn't initialized, although it may look
3398 strange. */
3399 for (parent = NULL, tail = current_buffer->overlays_before; tail;)
3401 XSETMISC (overlay, tail);
3403 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3404 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3406 /* If the overlay is backwards, make it empty. */
3407 if (endpos < startpos)
3409 startpos = endpos;
3410 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3411 Qnil);
3414 if (endpos < start)
3415 break;
3417 if (endpos < end
3418 || (startpos >= start && startpos < end))
3420 /* Add it to the end of the wrong list. Later on,
3421 recenter_overlay_lists will move it to the right place. */
3422 if (endpos < current_buffer->overlay_center)
3424 if (!afterp)
3425 after_list = tail;
3426 else
3427 afterp->next = tail;
3428 afterp = tail;
3430 else
3432 if (!beforep)
3433 before_list = tail;
3434 else
3435 beforep->next = tail;
3436 beforep = tail;
3438 if (!parent)
3439 set_buffer_overlays_before (current_buffer, tail->next);
3440 else
3441 parent->next = tail->next;
3442 tail = tail->next;
3444 else
3445 parent = tail, tail = parent->next;
3447 for (parent = NULL, tail = current_buffer->overlays_after; tail;)
3449 XSETMISC (overlay, tail);
3451 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
3452 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
3454 /* If the overlay is backwards, make it empty. */
3455 if (endpos < startpos)
3457 startpos = endpos;
3458 Fset_marker (OVERLAY_START (overlay), make_number (startpos),
3459 Qnil);
3462 if (startpos >= end)
3463 break;
3465 if (startpos >= start
3466 || (endpos >= start && endpos < end))
3468 if (endpos < current_buffer->overlay_center)
3470 if (!afterp)
3471 after_list = tail;
3472 else
3473 afterp->next = tail;
3474 afterp = tail;
3476 else
3478 if (!beforep)
3479 before_list = tail;
3480 else
3481 beforep->next = tail;
3482 beforep = tail;
3484 if (!parent)
3485 set_buffer_overlays_after (current_buffer, tail->next);
3486 else
3487 parent->next = tail->next;
3488 tail = tail->next;
3490 else
3491 parent = tail, tail = parent->next;
3494 /* Splice the constructed (wrong) lists into the buffer's lists,
3495 and let the recenter function make it sane again. */
3496 if (beforep)
3498 beforep->next = current_buffer->overlays_before;
3499 set_buffer_overlays_before (current_buffer, before_list);
3501 recenter_overlay_lists (current_buffer, current_buffer->overlay_center);
3503 if (afterp)
3505 afterp->next = current_buffer->overlays_after;
3506 set_buffer_overlays_after (current_buffer, after_list);
3508 recenter_overlay_lists (current_buffer, current_buffer->overlay_center);
3511 /* We have two types of overlay: the one whose ending marker is
3512 after-insertion-marker (this is the usual case) and the one whose
3513 ending marker is before-insertion-marker. When `overlays_before'
3514 contains overlays of the latter type and the former type in this
3515 order and both overlays end at inserting position, inserting a text
3516 increases only the ending marker of the latter type, which results
3517 in incorrect ordering of `overlays_before'.
3519 This function fixes ordering of overlays in the slot
3520 `overlays_before' of the buffer *BP. Before the insertion, `point'
3521 was at PREV, and now is at POS. */
3523 void
3524 fix_overlays_before (struct buffer *bp, ptrdiff_t prev, ptrdiff_t pos)
3526 /* If parent is nil, replace overlays_before; otherwise, parent->next. */
3527 struct Lisp_Overlay *tail = bp->overlays_before, *parent = NULL, *right_pair;
3528 Lisp_Object tem;
3529 ptrdiff_t end IF_LINT (= 0);
3531 /* After the insertion, the several overlays may be in incorrect
3532 order. The possibility is that, in the list `overlays_before',
3533 an overlay which ends at POS appears after an overlay which ends
3534 at PREV. Since POS is greater than PREV, we must fix the
3535 ordering of these overlays, by moving overlays ends at POS before
3536 the overlays ends at PREV. */
3538 /* At first, find a place where disordered overlays should be linked
3539 in. It is where an overlay which end before POS exists. (i.e. an
3540 overlay whose ending marker is after-insertion-marker if disorder
3541 exists). */
3542 while (tail
3543 && (XSETMISC (tem, tail),
3544 (end = OVERLAY_POSITION (OVERLAY_END (tem))) >= pos))
3546 parent = tail;
3547 tail = tail->next;
3550 /* If we don't find such an overlay,
3551 or the found one ends before PREV,
3552 or the found one is the last one in the list,
3553 we don't have to fix anything. */
3554 if (!tail || end < prev || !tail->next)
3555 return;
3557 right_pair = parent;
3558 parent = tail;
3559 tail = tail->next;
3561 /* Now, end position of overlays in the list TAIL should be before
3562 or equal to PREV. In the loop, an overlay which ends at POS is
3563 moved ahead to the place indicated by the CDR of RIGHT_PAIR. If
3564 we found an overlay which ends before PREV, the remaining
3565 overlays are in correct order. */
3566 while (tail)
3568 XSETMISC (tem, tail);
3569 end = OVERLAY_POSITION (OVERLAY_END (tem));
3571 if (end == pos)
3572 { /* This overlay is disordered. */
3573 struct Lisp_Overlay *found = tail;
3575 /* Unlink the found overlay. */
3576 tail = found->next;
3577 parent->next = tail;
3578 /* Move an overlay at RIGHT_PLACE to the next of the found one,
3579 and link it into the right place. */
3580 if (!right_pair)
3582 found->next = bp->overlays_before;
3583 set_buffer_overlays_before (bp, found);
3585 else
3587 found->next = right_pair->next;
3588 right_pair->next = found;
3591 else if (end == prev)
3593 parent = tail;
3594 tail = tail->next;
3596 else /* No more disordered overlay. */
3597 break;
3601 DEFUN ("overlayp", Foverlayp, Soverlayp, 1, 1, 0,
3602 doc: /* Return t if OBJECT is an overlay. */)
3603 (Lisp_Object object)
3605 return (OVERLAYP (object) ? Qt : Qnil);
3608 DEFUN ("make-overlay", Fmake_overlay, Smake_overlay, 2, 5, 0,
3609 doc: /* Create a new overlay with range BEG to END in BUFFER.
3610 If omitted, BUFFER defaults to the current buffer.
3611 BEG and END may be integers or markers.
3612 The fourth arg FRONT-ADVANCE, if non-nil, makes the marker
3613 for the front of the overlay advance when text is inserted there
3614 \(which means the text *is not* included in the overlay).
3615 The fifth arg REAR-ADVANCE, if non-nil, makes the marker
3616 for the rear of the overlay advance when text is inserted there
3617 \(which means the text *is* included in the overlay). */)
3618 (Lisp_Object beg, Lisp_Object end, Lisp_Object buffer, Lisp_Object front_advance, Lisp_Object rear_advance)
3620 Lisp_Object overlay;
3621 struct buffer *b;
3623 if (NILP (buffer))
3624 XSETBUFFER (buffer, current_buffer);
3625 else
3626 CHECK_BUFFER (buffer);
3627 if (MARKERP (beg)
3628 && ! EQ (Fmarker_buffer (beg), buffer))
3629 error ("Marker points into wrong buffer");
3630 if (MARKERP (end)
3631 && ! EQ (Fmarker_buffer (end), buffer))
3632 error ("Marker points into wrong buffer");
3634 CHECK_NUMBER_COERCE_MARKER (beg);
3635 CHECK_NUMBER_COERCE_MARKER (end);
3637 if (XINT (beg) > XINT (end))
3639 Lisp_Object temp;
3640 temp = beg; beg = end; end = temp;
3643 b = XBUFFER (buffer);
3645 beg = Fset_marker (Fmake_marker (), beg, buffer);
3646 end = Fset_marker (Fmake_marker (), end, buffer);
3648 if (!NILP (front_advance))
3649 XMARKER (beg)->insertion_type = 1;
3650 if (!NILP (rear_advance))
3651 XMARKER (end)->insertion_type = 1;
3653 overlay = build_overlay (beg, end, Qnil);
3655 /* Put the new overlay on the wrong list. */
3656 end = OVERLAY_END (overlay);
3657 if (OVERLAY_POSITION (end) < b->overlay_center)
3659 if (b->overlays_after)
3660 XOVERLAY (overlay)->next = b->overlays_after;
3661 set_buffer_overlays_after (b, XOVERLAY (overlay));
3663 else
3665 if (b->overlays_before)
3666 XOVERLAY (overlay)->next = b->overlays_before;
3667 set_buffer_overlays_before (b, XOVERLAY (overlay));
3670 /* This puts it in the right list, and in the right order. */
3671 recenter_overlay_lists (b, b->overlay_center);
3673 /* We don't need to redisplay the region covered by the overlay, because
3674 the overlay has no properties at the moment. */
3676 return overlay;
3679 /* Mark a section of BUF as needing redisplay because of overlays changes. */
3681 static void
3682 modify_overlay (struct buffer *buf, ptrdiff_t start, ptrdiff_t end)
3684 if (start > end)
3686 ptrdiff_t temp = start;
3687 start = end;
3688 end = temp;
3691 BUF_COMPUTE_UNCHANGED (buf, start, end);
3693 /* If this is a buffer not in the selected window,
3694 we must do other windows. */
3695 if (buf != XBUFFER (XWINDOW (selected_window)->buffer))
3696 windows_or_buffers_changed = 1;
3697 /* If multiple windows show this buffer, we must do other windows. */
3698 else if (buffer_shared > 1)
3699 windows_or_buffers_changed = 1;
3700 /* If we modify an overlay at the end of the buffer, we cannot
3701 be sure that window end is still valid. */
3702 else if (end >= ZV && start <= ZV)
3703 windows_or_buffers_changed = 1;
3705 ++BUF_OVERLAY_MODIFF (buf);
3708 /* Remove OVERLAY from LIST. */
3710 static struct Lisp_Overlay *
3711 unchain_overlay (struct Lisp_Overlay *list, struct Lisp_Overlay *overlay)
3713 register struct Lisp_Overlay *tail, **prev = &list;
3715 for (tail = list; tail; prev = &tail->next, tail = *prev)
3716 if (tail == overlay)
3718 *prev = overlay->next;
3719 overlay->next = NULL;
3720 break;
3722 return list;
3725 /* Remove OVERLAY from both overlay lists of B. */
3727 static void
3728 unchain_both (struct buffer *b, Lisp_Object overlay)
3730 struct Lisp_Overlay *ov = XOVERLAY (overlay);
3732 set_buffer_overlays_before (b, unchain_overlay (b->overlays_before, ov));
3733 set_buffer_overlays_after (b, unchain_overlay (b->overlays_after, ov));
3734 eassert (XOVERLAY (overlay)->next == NULL);
3737 DEFUN ("move-overlay", Fmove_overlay, Smove_overlay, 3, 4, 0,
3738 doc: /* Set the endpoints of OVERLAY to BEG and END in BUFFER.
3739 If BUFFER is omitted, leave OVERLAY in the same buffer it inhabits now.
3740 If BUFFER is omitted, and OVERLAY is in no buffer, put it in the current
3741 buffer. */)
3742 (Lisp_Object overlay, Lisp_Object beg, Lisp_Object end, Lisp_Object buffer)
3744 struct buffer *b, *ob = 0;
3745 Lisp_Object obuffer;
3746 ptrdiff_t count = SPECPDL_INDEX ();
3747 ptrdiff_t n_beg, n_end, o_beg IF_LINT (= 0), o_end IF_LINT (= 0);
3749 CHECK_OVERLAY (overlay);
3750 if (NILP (buffer))
3751 buffer = Fmarker_buffer (OVERLAY_START (overlay));
3752 if (NILP (buffer))
3753 XSETBUFFER (buffer, current_buffer);
3754 CHECK_BUFFER (buffer);
3756 if (NILP (Fbuffer_live_p (buffer)))
3757 error ("Attempt to move overlay to a dead buffer");
3759 if (MARKERP (beg)
3760 && ! EQ (Fmarker_buffer (beg), buffer))
3761 error ("Marker points into wrong buffer");
3762 if (MARKERP (end)
3763 && ! EQ (Fmarker_buffer (end), buffer))
3764 error ("Marker points into wrong buffer");
3766 CHECK_NUMBER_COERCE_MARKER (beg);
3767 CHECK_NUMBER_COERCE_MARKER (end);
3769 if (XINT (beg) > XINT (end))
3771 Lisp_Object temp;
3772 temp = beg; beg = end; end = temp;
3775 specbind (Qinhibit_quit, Qt);
3777 obuffer = Fmarker_buffer (OVERLAY_START (overlay));
3778 b = XBUFFER (buffer);
3780 if (!NILP (obuffer))
3782 ob = XBUFFER (obuffer);
3784 o_beg = OVERLAY_POSITION (OVERLAY_START (overlay));
3785 o_end = OVERLAY_POSITION (OVERLAY_END (overlay));
3787 unchain_both (ob, overlay);
3790 /* Set the overlay boundaries, which may clip them. */
3791 Fset_marker (OVERLAY_START (overlay), beg, buffer);
3792 Fset_marker (OVERLAY_END (overlay), end, buffer);
3794 n_beg = marker_position (OVERLAY_START (overlay));
3795 n_end = marker_position (OVERLAY_END (overlay));
3797 /* If the overlay has changed buffers, do a thorough redisplay. */
3798 if (!EQ (buffer, obuffer))
3800 /* Redisplay where the overlay was. */
3801 if (ob)
3802 modify_overlay (ob, o_beg, o_end);
3804 /* Redisplay where the overlay is going to be. */
3805 modify_overlay (b, n_beg, n_end);
3807 else
3808 /* Redisplay the area the overlay has just left, or just enclosed. */
3810 if (o_beg == n_beg)
3811 modify_overlay (b, o_end, n_end);
3812 else if (o_end == n_end)
3813 modify_overlay (b, o_beg, n_beg);
3814 else
3815 modify_overlay (b, min (o_beg, n_beg), max (o_end, n_end));
3818 /* Delete the overlay if it is empty after clipping and has the
3819 evaporate property. */
3820 if (n_beg == n_end && !NILP (Foverlay_get (overlay, Qevaporate)))
3821 return unbind_to (count, Fdelete_overlay (overlay));
3823 /* Put the overlay into the new buffer's overlay lists, first on the
3824 wrong list. */
3825 if (n_end < b->overlay_center)
3827 XOVERLAY (overlay)->next = b->overlays_after;
3828 set_buffer_overlays_after (b, XOVERLAY (overlay));
3830 else
3832 XOVERLAY (overlay)->next = b->overlays_before;
3833 set_buffer_overlays_before (b, XOVERLAY (overlay));
3836 /* This puts it in the right list, and in the right order. */
3837 recenter_overlay_lists (b, b->overlay_center);
3839 return unbind_to (count, overlay);
3842 DEFUN ("delete-overlay", Fdelete_overlay, Sdelete_overlay, 1, 1, 0,
3843 doc: /* Delete the overlay OVERLAY from its buffer. */)
3844 (Lisp_Object overlay)
3846 Lisp_Object buffer;
3847 struct buffer *b;
3848 ptrdiff_t count = SPECPDL_INDEX ();
3850 CHECK_OVERLAY (overlay);
3852 buffer = Fmarker_buffer (OVERLAY_START (overlay));
3853 if (NILP (buffer))
3854 return Qnil;
3856 b = XBUFFER (buffer);
3857 specbind (Qinhibit_quit, Qt);
3859 unchain_both (b, overlay);
3860 drop_overlay (b, XOVERLAY (overlay));
3862 /* When deleting an overlay with before or after strings, turn off
3863 display optimizations for the affected buffer, on the basis that
3864 these strings may contain newlines. This is easier to do than to
3865 check for that situation during redisplay. */
3866 if (!windows_or_buffers_changed
3867 && (!NILP (Foverlay_get (overlay, Qbefore_string))
3868 || !NILP (Foverlay_get (overlay, Qafter_string))))
3869 b->prevent_redisplay_optimizations_p = 1;
3871 return unbind_to (count, Qnil);
3874 /* Overlay dissection functions. */
3876 DEFUN ("overlay-start", Foverlay_start, Soverlay_start, 1, 1, 0,
3877 doc: /* Return the position at which OVERLAY starts. */)
3878 (Lisp_Object overlay)
3880 CHECK_OVERLAY (overlay);
3882 return (Fmarker_position (OVERLAY_START (overlay)));
3885 DEFUN ("overlay-end", Foverlay_end, Soverlay_end, 1, 1, 0,
3886 doc: /* Return the position at which OVERLAY ends. */)
3887 (Lisp_Object overlay)
3889 CHECK_OVERLAY (overlay);
3891 return (Fmarker_position (OVERLAY_END (overlay)));
3894 DEFUN ("overlay-buffer", Foverlay_buffer, Soverlay_buffer, 1, 1, 0,
3895 doc: /* Return the buffer OVERLAY belongs to.
3896 Return nil if OVERLAY has been deleted. */)
3897 (Lisp_Object overlay)
3899 CHECK_OVERLAY (overlay);
3901 return Fmarker_buffer (OVERLAY_START (overlay));
3904 DEFUN ("overlay-properties", Foverlay_properties, Soverlay_properties, 1, 1, 0,
3905 doc: /* Return a list of the properties on OVERLAY.
3906 This is a copy of OVERLAY's plist; modifying its conses has no effect on
3907 OVERLAY. */)
3908 (Lisp_Object overlay)
3910 CHECK_OVERLAY (overlay);
3912 return Fcopy_sequence (XOVERLAY (overlay)->plist);
3916 DEFUN ("overlays-at", Foverlays_at, Soverlays_at, 1, 1, 0,
3917 doc: /* Return a list of the overlays that contain the character at POS. */)
3918 (Lisp_Object pos)
3920 ptrdiff_t len, noverlays;
3921 Lisp_Object *overlay_vec;
3922 Lisp_Object result;
3924 CHECK_NUMBER_COERCE_MARKER (pos);
3926 len = 10;
3927 /* We can't use alloca here because overlays_at can call xrealloc. */
3928 overlay_vec = xmalloc (len * sizeof *overlay_vec);
3930 /* Put all the overlays we want in a vector in overlay_vec.
3931 Store the length in len. */
3932 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
3933 0, 0, 0);
3935 /* Make a list of them all. */
3936 result = Flist (noverlays, overlay_vec);
3938 xfree (overlay_vec);
3939 return result;
3942 DEFUN ("overlays-in", Foverlays_in, Soverlays_in, 2, 2, 0,
3943 doc: /* Return a list of the overlays that overlap the region BEG ... END.
3944 Overlap means that at least one character is contained within the overlay
3945 and also contained within the specified region.
3946 Empty overlays are included in the result if they are located at BEG,
3947 between BEG and END, or at END provided END denotes the position at the
3948 end of the buffer. */)
3949 (Lisp_Object beg, Lisp_Object end)
3951 ptrdiff_t len, noverlays;
3952 Lisp_Object *overlay_vec;
3953 Lisp_Object result;
3955 CHECK_NUMBER_COERCE_MARKER (beg);
3956 CHECK_NUMBER_COERCE_MARKER (end);
3958 len = 10;
3959 overlay_vec = xmalloc (len * sizeof *overlay_vec);
3961 /* Put all the overlays we want in a vector in overlay_vec.
3962 Store the length in len. */
3963 noverlays = overlays_in (XINT (beg), XINT (end), 1, &overlay_vec, &len,
3964 NULL, NULL);
3966 /* Make a list of them all. */
3967 result = Flist (noverlays, overlay_vec);
3969 xfree (overlay_vec);
3970 return result;
3973 DEFUN ("next-overlay-change", Fnext_overlay_change, Snext_overlay_change,
3974 1, 1, 0,
3975 doc: /* Return the next position after POS where an overlay starts or ends.
3976 If there are no overlay boundaries from POS to (point-max),
3977 the value is (point-max). */)
3978 (Lisp_Object pos)
3980 ptrdiff_t i, len, noverlays;
3981 ptrdiff_t endpos;
3982 Lisp_Object *overlay_vec;
3984 CHECK_NUMBER_COERCE_MARKER (pos);
3986 len = 10;
3987 overlay_vec = xmalloc (len * sizeof *overlay_vec);
3989 /* Put all the overlays we want in a vector in overlay_vec.
3990 Store the length in len.
3991 endpos gets the position where the next overlay starts. */
3992 noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
3993 &endpos, 0, 1);
3995 /* If any of these overlays ends before endpos,
3996 use its ending point instead. */
3997 for (i = 0; i < noverlays; i++)
3999 Lisp_Object oend;
4000 ptrdiff_t oendpos;
4002 oend = OVERLAY_END (overlay_vec[i]);
4003 oendpos = OVERLAY_POSITION (oend);
4004 if (oendpos < endpos)
4005 endpos = oendpos;
4008 xfree (overlay_vec);
4009 return make_number (endpos);
4012 DEFUN ("previous-overlay-change", Fprevious_overlay_change,
4013 Sprevious_overlay_change, 1, 1, 0,
4014 doc: /* Return the previous position before POS where an overlay starts or ends.
4015 If there are no overlay boundaries from (point-min) to POS,
4016 the value is (point-min). */)
4017 (Lisp_Object pos)
4019 ptrdiff_t prevpos;
4020 Lisp_Object *overlay_vec;
4021 ptrdiff_t len;
4023 CHECK_NUMBER_COERCE_MARKER (pos);
4025 /* At beginning of buffer, we know the answer;
4026 avoid bug subtracting 1 below. */
4027 if (XINT (pos) == BEGV)
4028 return pos;
4030 len = 10;
4031 overlay_vec = xmalloc (len * sizeof *overlay_vec);
4033 /* Put all the overlays we want in a vector in overlay_vec.
4034 Store the length in len.
4035 prevpos gets the position of the previous change. */
4036 overlays_at (XINT (pos), 1, &overlay_vec, &len,
4037 0, &prevpos, 1);
4039 xfree (overlay_vec);
4040 return make_number (prevpos);
4043 /* These functions are for debugging overlays. */
4045 DEFUN ("overlay-lists", Foverlay_lists, Soverlay_lists, 0, 0, 0,
4046 doc: /* Return a pair of lists giving all the overlays of the current buffer.
4047 The car has all the overlays before the overlay center;
4048 the cdr has all the overlays after the overlay center.
4049 Recentering overlays moves overlays between these lists.
4050 The lists you get are copies, so that changing them has no effect.
4051 However, the overlays you get are the real objects that the buffer uses. */)
4052 (void)
4054 struct Lisp_Overlay *ol;
4055 Lisp_Object before = Qnil, after = Qnil, tmp;
4057 for (ol = current_buffer->overlays_before; ol; ol = ol->next)
4059 XSETMISC (tmp, ol);
4060 before = Fcons (tmp, before);
4062 for (ol = current_buffer->overlays_after; ol; ol = ol->next)
4064 XSETMISC (tmp, ol);
4065 after = Fcons (tmp, after);
4068 return Fcons (Fnreverse (before), Fnreverse (after));
4071 DEFUN ("overlay-recenter", Foverlay_recenter, Soverlay_recenter, 1, 1, 0,
4072 doc: /* Recenter the overlays of the current buffer around position POS.
4073 That makes overlay lookup faster for positions near POS (but perhaps slower
4074 for positions far away from POS). */)
4075 (Lisp_Object pos)
4077 ptrdiff_t p;
4078 CHECK_NUMBER_COERCE_MARKER (pos);
4080 p = clip_to_bounds (PTRDIFF_MIN, XINT (pos), PTRDIFF_MAX);
4081 recenter_overlay_lists (current_buffer, p);
4082 return Qnil;
4085 DEFUN ("overlay-get", Foverlay_get, Soverlay_get, 2, 2, 0,
4086 doc: /* Get the property of overlay OVERLAY with property name PROP. */)
4087 (Lisp_Object overlay, Lisp_Object prop)
4089 CHECK_OVERLAY (overlay);
4090 return lookup_char_property (XOVERLAY (overlay)->plist, prop, 0);
4093 DEFUN ("overlay-put", Foverlay_put, Soverlay_put, 3, 3, 0,
4094 doc: /* Set one property of overlay OVERLAY: give property PROP value VALUE.
4095 VALUE will be returned.*/)
4096 (Lisp_Object overlay, Lisp_Object prop, Lisp_Object value)
4098 Lisp_Object tail, buffer;
4099 int changed;
4101 CHECK_OVERLAY (overlay);
4103 buffer = Fmarker_buffer (OVERLAY_START (overlay));
4105 for (tail = XOVERLAY (overlay)->plist;
4106 CONSP (tail) && CONSP (XCDR (tail));
4107 tail = XCDR (XCDR (tail)))
4108 if (EQ (XCAR (tail), prop))
4110 changed = !EQ (XCAR (XCDR (tail)), value);
4111 XSETCAR (XCDR (tail), value);
4112 goto found;
4114 /* It wasn't in the list, so add it to the front. */
4115 changed = !NILP (value);
4116 set_overlay_plist
4117 (overlay, Fcons (prop, Fcons (value, XOVERLAY (overlay)->plist)));
4118 found:
4119 if (! NILP (buffer))
4121 if (changed)
4122 modify_overlay (XBUFFER (buffer),
4123 marker_position (OVERLAY_START (overlay)),
4124 marker_position (OVERLAY_END (overlay)));
4125 if (EQ (prop, Qevaporate) && ! NILP (value)
4126 && (OVERLAY_POSITION (OVERLAY_START (overlay))
4127 == OVERLAY_POSITION (OVERLAY_END (overlay))))
4128 Fdelete_overlay (overlay);
4131 return value;
4134 /* Subroutine of report_overlay_modification. */
4136 /* Lisp vector holding overlay hook functions to call.
4137 Vector elements come in pairs.
4138 Each even-index element is a list of hook functions.
4139 The following odd-index element is the overlay they came from.
4141 Before the buffer change, we fill in this vector
4142 as we call overlay hook functions.
4143 After the buffer change, we get the functions to call from this vector.
4144 This way we always call the same functions before and after the change. */
4145 static Lisp_Object last_overlay_modification_hooks;
4147 /* Number of elements actually used in last_overlay_modification_hooks. */
4148 static ptrdiff_t last_overlay_modification_hooks_used;
4150 /* Add one functionlist/overlay pair
4151 to the end of last_overlay_modification_hooks. */
4153 static void
4154 add_overlay_mod_hooklist (Lisp_Object functionlist, Lisp_Object overlay)
4156 ptrdiff_t oldsize = ASIZE (last_overlay_modification_hooks);
4158 if (oldsize - 1 <= last_overlay_modification_hooks_used)
4159 last_overlay_modification_hooks =
4160 larger_vector (last_overlay_modification_hooks, 2, -1);
4161 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4162 functionlist); last_overlay_modification_hooks_used++;
4163 ASET (last_overlay_modification_hooks, last_overlay_modification_hooks_used,
4164 overlay); last_overlay_modification_hooks_used++;
4167 /* Run the modification-hooks of overlays that include
4168 any part of the text in START to END.
4169 If this change is an insertion, also
4170 run the insert-before-hooks of overlay starting at END,
4171 and the insert-after-hooks of overlay ending at START.
4173 This is called both before and after the modification.
4174 AFTER is nonzero when we call after the modification.
4176 ARG1, ARG2, ARG3 are arguments to pass to the hook functions.
4177 When AFTER is nonzero, they are the start position,
4178 the position after the inserted new text,
4179 and the length of deleted or replaced old text. */
4181 void
4182 report_overlay_modification (Lisp_Object start, Lisp_Object end, int after,
4183 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4185 Lisp_Object prop, overlay;
4186 struct Lisp_Overlay *tail;
4187 /* 1 if this change is an insertion. */
4188 int insertion = (after ? XFASTINT (arg3) == 0 : EQ (start, end));
4189 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4191 overlay = Qnil;
4192 tail = NULL;
4194 /* We used to run the functions as soon as we found them and only register
4195 them in last_overlay_modification_hooks for the purpose of the `after'
4196 case. But running elisp code as we traverse the list of overlays is
4197 painful because the list can be modified by the elisp code so we had to
4198 copy at several places. We now simply do a read-only traversal that
4199 only collects the functions to run and we run them afterwards. It's
4200 simpler, especially since all the code was already there. -stef */
4202 if (!after)
4204 /* We are being called before a change.
4205 Scan the overlays to find the functions to call. */
4206 last_overlay_modification_hooks_used = 0;
4207 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4209 ptrdiff_t startpos, endpos;
4210 Lisp_Object ostart, oend;
4212 XSETMISC (overlay, tail);
4214 ostart = OVERLAY_START (overlay);
4215 oend = OVERLAY_END (overlay);
4216 endpos = OVERLAY_POSITION (oend);
4217 if (XFASTINT (start) > endpos)
4218 break;
4219 startpos = OVERLAY_POSITION (ostart);
4220 if (insertion && (XFASTINT (start) == startpos
4221 || XFASTINT (end) == startpos))
4223 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4224 if (!NILP (prop))
4225 add_overlay_mod_hooklist (prop, overlay);
4227 if (insertion && (XFASTINT (start) == endpos
4228 || XFASTINT (end) == endpos))
4230 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4231 if (!NILP (prop))
4232 add_overlay_mod_hooklist (prop, overlay);
4234 /* Test for intersecting intervals. This does the right thing
4235 for both insertion and deletion. */
4236 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4238 prop = Foverlay_get (overlay, Qmodification_hooks);
4239 if (!NILP (prop))
4240 add_overlay_mod_hooklist (prop, overlay);
4244 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4246 ptrdiff_t startpos, endpos;
4247 Lisp_Object ostart, oend;
4249 XSETMISC (overlay, tail);
4251 ostart = OVERLAY_START (overlay);
4252 oend = OVERLAY_END (overlay);
4253 startpos = OVERLAY_POSITION (ostart);
4254 endpos = OVERLAY_POSITION (oend);
4255 if (XFASTINT (end) < startpos)
4256 break;
4257 if (insertion && (XFASTINT (start) == startpos
4258 || XFASTINT (end) == startpos))
4260 prop = Foverlay_get (overlay, Qinsert_in_front_hooks);
4261 if (!NILP (prop))
4262 add_overlay_mod_hooklist (prop, overlay);
4264 if (insertion && (XFASTINT (start) == endpos
4265 || XFASTINT (end) == endpos))
4267 prop = Foverlay_get (overlay, Qinsert_behind_hooks);
4268 if (!NILP (prop))
4269 add_overlay_mod_hooklist (prop, overlay);
4271 /* Test for intersecting intervals. This does the right thing
4272 for both insertion and deletion. */
4273 if (XFASTINT (end) > startpos && XFASTINT (start) < endpos)
4275 prop = Foverlay_get (overlay, Qmodification_hooks);
4276 if (!NILP (prop))
4277 add_overlay_mod_hooklist (prop, overlay);
4282 GCPRO4 (overlay, arg1, arg2, arg3);
4284 /* Call the functions recorded in last_overlay_modification_hooks.
4285 First copy the vector contents, in case some of these hooks
4286 do subsequent modification of the buffer. */
4287 ptrdiff_t size = last_overlay_modification_hooks_used;
4288 Lisp_Object *copy = alloca (size * sizeof *copy);
4289 ptrdiff_t i;
4291 memcpy (copy, XVECTOR (last_overlay_modification_hooks)->contents,
4292 size * word_size);
4293 gcpro1.var = copy;
4294 gcpro1.nvars = size;
4296 for (i = 0; i < size;)
4298 Lisp_Object prop_i, overlay_i;
4299 prop_i = copy[i++];
4300 overlay_i = copy[i++];
4301 call_overlay_mod_hooks (prop_i, overlay_i, after, arg1, arg2, arg3);
4304 UNGCPRO;
4307 static void
4308 call_overlay_mod_hooks (Lisp_Object list, Lisp_Object overlay, int after,
4309 Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
4311 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4313 GCPRO4 (list, arg1, arg2, arg3);
4315 while (CONSP (list))
4317 if (NILP (arg3))
4318 call4 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2);
4319 else
4320 call5 (XCAR (list), overlay, after ? Qt : Qnil, arg1, arg2, arg3);
4321 list = XCDR (list);
4323 UNGCPRO;
4326 /* Delete any zero-sized overlays at position POS, if the `evaporate'
4327 property is set. */
4328 void
4329 evaporate_overlays (ptrdiff_t pos)
4331 Lisp_Object overlay, hit_list;
4332 struct Lisp_Overlay *tail;
4334 hit_list = Qnil;
4335 if (pos <= current_buffer->overlay_center)
4336 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
4338 ptrdiff_t endpos;
4339 XSETMISC (overlay, tail);
4340 endpos = OVERLAY_POSITION (OVERLAY_END (overlay));
4341 if (endpos < pos)
4342 break;
4343 if (endpos == pos && OVERLAY_POSITION (OVERLAY_START (overlay)) == pos
4344 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4345 hit_list = Fcons (overlay, hit_list);
4347 else
4348 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
4350 ptrdiff_t startpos;
4351 XSETMISC (overlay, tail);
4352 startpos = OVERLAY_POSITION (OVERLAY_START (overlay));
4353 if (startpos > pos)
4354 break;
4355 if (startpos == pos && OVERLAY_POSITION (OVERLAY_END (overlay)) == pos
4356 && ! NILP (Foverlay_get (overlay, Qevaporate)))
4357 hit_list = Fcons (overlay, hit_list);
4359 for (; CONSP (hit_list); hit_list = XCDR (hit_list))
4360 Fdelete_overlay (XCAR (hit_list));
4363 /* Somebody has tried to store a value with an unacceptable type
4364 in the slot with offset OFFSET. */
4366 void
4367 buffer_slot_type_mismatch (Lisp_Object newval, int type)
4369 Lisp_Object predicate;
4371 switch (type)
4373 case_Lisp_Int: predicate = Qintegerp; break;
4374 case Lisp_String: predicate = Qstringp; break;
4375 case Lisp_Symbol: predicate = Qsymbolp; break;
4376 default: abort ();
4379 wrong_type_argument (predicate, newval);
4383 /***********************************************************************
4384 Allocation with mmap
4385 ***********************************************************************/
4387 #ifdef USE_MMAP_FOR_BUFFERS
4389 #include <sys/types.h>
4390 #include <sys/mman.h>
4392 #ifndef MAP_ANON
4393 #ifdef MAP_ANONYMOUS
4394 #define MAP_ANON MAP_ANONYMOUS
4395 #else
4396 #define MAP_ANON 0
4397 #endif
4398 #endif
4400 #ifndef MAP_FAILED
4401 #define MAP_FAILED ((void *) -1)
4402 #endif
4404 #include <stdio.h>
4406 #if MAP_ANON == 0
4407 #include <fcntl.h>
4408 #endif
4410 #include "coding.h"
4413 /* Memory is allocated in regions which are mapped using mmap(2).
4414 The current implementation lets the system select mapped
4415 addresses; we're not using MAP_FIXED in general, except when
4416 trying to enlarge regions.
4418 Each mapped region starts with a mmap_region structure, the user
4419 area starts after that structure, aligned to MEM_ALIGN.
4421 +-----------------------+
4422 | struct mmap_info + |
4423 | padding |
4424 +-----------------------+
4425 | user data |
4428 +-----------------------+ */
4430 struct mmap_region
4432 /* User-specified size. */
4433 size_t nbytes_specified;
4435 /* Number of bytes mapped */
4436 size_t nbytes_mapped;
4438 /* Pointer to the location holding the address of the memory
4439 allocated with the mmap'd block. The variable actually points
4440 after this structure. */
4441 void **var;
4443 /* Next and previous in list of all mmap'd regions. */
4444 struct mmap_region *next, *prev;
4447 /* Doubly-linked list of mmap'd regions. */
4449 static struct mmap_region *mmap_regions;
4451 /* File descriptor for mmap. If we don't have anonymous mapping,
4452 /dev/zero will be opened on it. */
4454 static int mmap_fd;
4456 /* Temporary storage for mmap_set_vars, see there. */
4458 static struct mmap_region *mmap_regions_1;
4459 static int mmap_fd_1;
4461 /* Page size on this system. */
4463 static int mmap_page_size;
4465 /* 1 means mmap has been initialized. */
4467 static int mmap_initialized_p;
4469 /* Value is X rounded up to the next multiple of N. */
4471 #define ROUND(X, N) (((X) + (N) - 1) / (N) * (N))
4473 /* Size of mmap_region structure plus padding. */
4475 #define MMAP_REGION_STRUCT_SIZE \
4476 ROUND (sizeof (struct mmap_region), MEM_ALIGN)
4478 /* Given a pointer P to the start of the user-visible part of a mapped
4479 region, return a pointer to the start of the region. */
4481 #define MMAP_REGION(P) \
4482 ((struct mmap_region *) ((char *) (P) - MMAP_REGION_STRUCT_SIZE))
4484 /* Given a pointer P to the start of a mapped region, return a pointer
4485 to the start of the user-visible part of the region. */
4487 #define MMAP_USER_AREA(P) \
4488 ((void *) ((char *) (P) + MMAP_REGION_STRUCT_SIZE))
4490 #define MEM_ALIGN sizeof (double)
4492 /* Predicate returning true if part of the address range [START .. END]
4493 is currently mapped. Used to prevent overwriting an existing
4494 memory mapping.
4496 Default is to conservatively assume the address range is occupied by
4497 something else. This can be overridden by system configuration
4498 files if system-specific means to determine this exists. */
4500 #ifndef MMAP_ALLOCATED_P
4501 #define MMAP_ALLOCATED_P(start, end) 1
4502 #endif
4504 /* Perform necessary initializations for the use of mmap. */
4506 static void
4507 mmap_init (void)
4509 #if MAP_ANON == 0
4510 /* The value of mmap_fd is initially 0 in temacs, and -1
4511 in a dumped Emacs. */
4512 if (mmap_fd <= 0)
4514 /* No anonymous mmap -- we need the file descriptor. */
4515 mmap_fd = open ("/dev/zero", O_RDONLY);
4516 if (mmap_fd == -1)
4517 fatal ("Cannot open /dev/zero: %s", emacs_strerror (errno));
4519 #endif /* MAP_ANON == 0 */
4521 if (mmap_initialized_p)
4522 return;
4523 mmap_initialized_p = 1;
4525 #if MAP_ANON != 0
4526 mmap_fd = -1;
4527 #endif
4529 mmap_page_size = getpagesize ();
4532 /* Return a region overlapping address range START...END, or null if
4533 none. END is not including, i.e. the last byte in the range
4534 is at END - 1. */
4536 static struct mmap_region *
4537 mmap_find (void *start, void *end)
4539 struct mmap_region *r;
4540 char *s = (char *) start, *e = (char *) end;
4542 for (r = mmap_regions; r; r = r->next)
4544 char *rstart = (char *) r;
4545 char *rend = rstart + r->nbytes_mapped;
4547 if (/* First byte of range, i.e. START, in this region? */
4548 (s >= rstart && s < rend)
4549 /* Last byte of range, i.e. END - 1, in this region? */
4550 || (e > rstart && e <= rend)
4551 /* First byte of this region in the range? */
4552 || (rstart >= s && rstart < e)
4553 /* Last byte of this region in the range? */
4554 || (rend > s && rend <= e))
4555 break;
4558 return r;
4562 /* Unmap a region. P is a pointer to the start of the user-araa of
4563 the region. Value is non-zero if successful. */
4565 static int
4566 mmap_free_1 (struct mmap_region *r)
4568 if (r->next)
4569 r->next->prev = r->prev;
4570 if (r->prev)
4571 r->prev->next = r->next;
4572 else
4573 mmap_regions = r->next;
4575 if (munmap (r, r->nbytes_mapped) == -1)
4577 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4578 return 0;
4581 return 1;
4585 /* Enlarge region R by NPAGES pages. NPAGES < 0 means shrink R.
4586 Value is non-zero if successful. */
4588 static int
4589 mmap_enlarge (struct mmap_region *r, int npages)
4591 char *region_end = (char *) r + r->nbytes_mapped;
4592 size_t nbytes;
4593 int success = 0;
4595 if (npages < 0)
4597 /* Unmap pages at the end of the region. */
4598 nbytes = - npages * mmap_page_size;
4599 if (munmap (region_end - nbytes, nbytes) == -1)
4600 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4601 else
4603 r->nbytes_mapped -= nbytes;
4604 success = 1;
4607 else if (npages > 0)
4609 nbytes = npages * mmap_page_size;
4611 /* Try to map additional pages at the end of the region. We
4612 cannot do this if the address range is already occupied by
4613 something else because mmap deletes any previous mapping.
4614 I'm not sure this is worth doing, let's see. */
4615 if (!MMAP_ALLOCATED_P (region_end, region_end + nbytes))
4617 void *p;
4619 p = mmap (region_end, nbytes, PROT_READ | PROT_WRITE,
4620 MAP_ANON | MAP_PRIVATE | MAP_FIXED, mmap_fd, 0);
4621 if (p == MAP_FAILED)
4622 ; /* fprintf (stderr, "mmap: %s\n", emacs_strerror (errno)); */
4623 else if (p != region_end)
4625 /* Kernels are free to choose a different address. In
4626 that case, unmap what we've mapped above; we have
4627 no use for it. */
4628 if (munmap (p, nbytes) == -1)
4629 fprintf (stderr, "munmap: %s\n", emacs_strerror (errno));
4631 else
4633 r->nbytes_mapped += nbytes;
4634 success = 1;
4639 return success;
4643 /* Set or reset variables holding references to mapped regions. If
4644 RESTORE_P is zero, set all variables to null. If RESTORE_P is
4645 non-zero, set all variables to the start of the user-areas
4646 of mapped regions.
4648 This function is called from Fdump_emacs to ensure that the dumped
4649 Emacs doesn't contain references to memory that won't be mapped
4650 when Emacs starts. */
4652 void
4653 mmap_set_vars (int restore_p)
4655 struct mmap_region *r;
4657 if (restore_p)
4659 mmap_regions = mmap_regions_1;
4660 mmap_fd = mmap_fd_1;
4661 for (r = mmap_regions; r; r = r->next)
4662 *r->var = MMAP_USER_AREA (r);
4664 else
4666 for (r = mmap_regions; r; r = r->next)
4667 *r->var = NULL;
4668 mmap_regions_1 = mmap_regions;
4669 mmap_regions = NULL;
4670 mmap_fd_1 = mmap_fd;
4671 mmap_fd = -1;
4676 /* Allocate a block of storage large enough to hold NBYTES bytes of
4677 data. A pointer to the data is returned in *VAR. VAR is thus the
4678 address of some variable which will use the data area.
4680 The allocation of 0 bytes is valid.
4682 If we can't allocate the necessary memory, set *VAR to null, and
4683 return null. */
4685 static void *
4686 mmap_alloc (void **var, size_t nbytes)
4688 void *p;
4689 size_t map;
4691 mmap_init ();
4693 map = ROUND (nbytes + MMAP_REGION_STRUCT_SIZE, mmap_page_size);
4694 p = mmap (NULL, map, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
4695 mmap_fd, 0);
4697 if (p == MAP_FAILED)
4699 if (errno != ENOMEM)
4700 fprintf (stderr, "mmap: %s\n", emacs_strerror (errno));
4701 p = NULL;
4703 else
4705 struct mmap_region *r = (struct mmap_region *) p;
4707 r->nbytes_specified = nbytes;
4708 r->nbytes_mapped = map;
4709 r->var = var;
4710 r->prev = NULL;
4711 r->next = mmap_regions;
4712 if (r->next)
4713 r->next->prev = r;
4714 mmap_regions = r;
4716 p = MMAP_USER_AREA (p);
4719 return *var = p;
4723 /* Free a block of relocatable storage whose data is pointed to by
4724 PTR. Store 0 in *PTR to show there's no block allocated. */
4726 static void
4727 mmap_free (void **var)
4729 mmap_init ();
4731 if (*var)
4733 mmap_free_1 (MMAP_REGION (*var));
4734 *var = NULL;
4739 /* Given a pointer at address VAR to data allocated with mmap_alloc,
4740 resize it to size NBYTES. Change *VAR to reflect the new block,
4741 and return this value. If more memory cannot be allocated, then
4742 leave *VAR unchanged, and return null. */
4744 static void *
4745 mmap_realloc (void **var, size_t nbytes)
4747 void *result;
4749 mmap_init ();
4751 if (*var == NULL)
4752 result = mmap_alloc (var, nbytes);
4753 else if (nbytes == 0)
4755 mmap_free (var);
4756 result = mmap_alloc (var, nbytes);
4758 else
4760 struct mmap_region *r = MMAP_REGION (*var);
4761 size_t room = r->nbytes_mapped - MMAP_REGION_STRUCT_SIZE;
4763 if (room < nbytes)
4765 /* Must enlarge. */
4766 void *old_ptr = *var;
4768 /* Try to map additional pages at the end of the region.
4769 If that fails, allocate a new region, copy data
4770 from the old region, then free it. */
4771 if (mmap_enlarge (r, (ROUND (nbytes - room, mmap_page_size)
4772 / mmap_page_size)))
4774 r->nbytes_specified = nbytes;
4775 *var = result = old_ptr;
4777 else if (mmap_alloc (var, nbytes))
4779 memcpy (*var, old_ptr, r->nbytes_specified);
4780 mmap_free_1 (MMAP_REGION (old_ptr));
4781 result = *var;
4782 r = MMAP_REGION (result);
4783 r->nbytes_specified = nbytes;
4785 else
4787 *var = old_ptr;
4788 result = NULL;
4791 else if (room - nbytes >= mmap_page_size)
4793 /* Shrinking by at least a page. Let's give some
4794 memory back to the system.
4796 The extra parens are to make the division happens first,
4797 on positive values, so we know it will round towards
4798 zero. */
4799 mmap_enlarge (r, - ((room - nbytes) / mmap_page_size));
4800 result = *var;
4801 r->nbytes_specified = nbytes;
4803 else
4805 /* Leave it alone. */
4806 result = *var;
4807 r->nbytes_specified = nbytes;
4811 return result;
4815 #endif /* USE_MMAP_FOR_BUFFERS */
4819 /***********************************************************************
4820 Buffer-text Allocation
4821 ***********************************************************************/
4823 /* Allocate NBYTES bytes for buffer B's text buffer. */
4825 static void
4826 alloc_buffer_text (struct buffer *b, ptrdiff_t nbytes)
4828 void *p;
4830 BLOCK_INPUT;
4831 #if defined USE_MMAP_FOR_BUFFERS
4832 p = mmap_alloc ((void **) &b->text->beg, nbytes);
4833 #elif defined REL_ALLOC
4834 p = r_alloc ((void **) &b->text->beg, nbytes);
4835 #else
4836 p = xmalloc (nbytes);
4837 #endif
4839 if (p == NULL)
4841 UNBLOCK_INPUT;
4842 memory_full (nbytes);
4845 b->text->beg = (unsigned char *) p;
4846 UNBLOCK_INPUT;
4849 /* Enlarge buffer B's text buffer by DELTA bytes. DELTA < 0 means
4850 shrink it. */
4852 void
4853 enlarge_buffer_text (struct buffer *b, ptrdiff_t delta)
4855 void *p;
4856 ptrdiff_t nbytes = (BUF_Z_BYTE (b) - BUF_BEG_BYTE (b) + BUF_GAP_SIZE (b) + 1
4857 + delta);
4858 BLOCK_INPUT;
4859 #if defined USE_MMAP_FOR_BUFFERS
4860 p = mmap_realloc ((void **) &b->text->beg, nbytes);
4861 #elif defined REL_ALLOC
4862 p = r_re_alloc ((void **) &b->text->beg, nbytes);
4863 #else
4864 p = xrealloc (b->text->beg, nbytes);
4865 #endif
4867 if (p == NULL)
4869 UNBLOCK_INPUT;
4870 memory_full (nbytes);
4873 BUF_BEG_ADDR (b) = (unsigned char *) p;
4874 UNBLOCK_INPUT;
4878 /* Free buffer B's text buffer. */
4880 static void
4881 free_buffer_text (struct buffer *b)
4883 BLOCK_INPUT;
4885 #if defined USE_MMAP_FOR_BUFFERS
4886 mmap_free ((void **) &b->text->beg);
4887 #elif defined REL_ALLOC
4888 r_alloc_free ((void **) &b->text->beg);
4889 #else
4890 xfree (b->text->beg);
4891 #endif
4893 BUF_BEG_ADDR (b) = NULL;
4894 UNBLOCK_INPUT;
4899 /***********************************************************************
4900 Initialization
4901 ***********************************************************************/
4903 void
4904 init_buffer_once (void)
4906 int idx;
4907 /* If you add, remove, or reorder Lisp_Objects in a struct buffer, make
4908 sure that this is still correct. Otherwise, mark_vectorlike may not
4909 trace all Lisp_Objects in buffer_defaults and buffer_local_symbols. */
4910 const int pvecsize
4911 = (offsetof (struct buffer, own_text) - header_size) / word_size;
4913 memset (buffer_permanent_local_flags, 0, sizeof buffer_permanent_local_flags);
4915 /* Make sure all markable slots in buffer_defaults
4916 are initialized reasonably, so mark_buffer won't choke. */
4917 reset_buffer (&buffer_defaults);
4918 eassert (EQ (BVAR (&buffer_defaults, name), make_number (0)));
4919 reset_buffer_local_variables (&buffer_defaults, 1);
4920 eassert (EQ (BVAR (&buffer_local_symbols, name), make_number (0)));
4921 reset_buffer (&buffer_local_symbols);
4922 reset_buffer_local_variables (&buffer_local_symbols, 1);
4923 /* Prevent GC from getting confused. */
4924 buffer_defaults.text = &buffer_defaults.own_text;
4925 buffer_local_symbols.text = &buffer_local_symbols.own_text;
4926 /* No one will share the text with these buffers, but let's play it safe. */
4927 buffer_defaults.indirections = 0;
4928 buffer_local_symbols.indirections = 0;
4929 set_buffer_intervals (&buffer_defaults, NULL);
4930 set_buffer_intervals (&buffer_local_symbols, NULL);
4931 XSETPVECTYPESIZE (&buffer_defaults, PVEC_BUFFER, pvecsize);
4932 XSETBUFFER (Vbuffer_defaults, &buffer_defaults);
4933 XSETPVECTYPESIZE (&buffer_local_symbols, PVEC_BUFFER, pvecsize);
4934 XSETBUFFER (Vbuffer_local_symbols, &buffer_local_symbols);
4936 /* Set up the default values of various buffer slots. */
4937 /* Must do these before making the first buffer! */
4939 /* real setup is done in bindings.el */
4940 BSET (&buffer_defaults, mode_line_format, build_pure_c_string ("%-"));
4941 BSET (&buffer_defaults, header_line_format, Qnil);
4942 BSET (&buffer_defaults, abbrev_mode, Qnil);
4943 BSET (&buffer_defaults, overwrite_mode, Qnil);
4944 BSET (&buffer_defaults, case_fold_search, Qt);
4945 BSET (&buffer_defaults, auto_fill_function, Qnil);
4946 BSET (&buffer_defaults, selective_display, Qnil);
4947 BSET (&buffer_defaults, selective_display_ellipses, Qt);
4948 BSET (&buffer_defaults, abbrev_table, Qnil);
4949 BSET (&buffer_defaults, display_table, Qnil);
4950 BSET (&buffer_defaults, undo_list, Qnil);
4951 BSET (&buffer_defaults, mark_active, Qnil);
4952 BSET (&buffer_defaults, file_format, Qnil);
4953 BSET (&buffer_defaults, auto_save_file_format, Qt);
4954 set_buffer_overlays_before (&buffer_defaults, NULL);
4955 set_buffer_overlays_after (&buffer_defaults, NULL);
4956 buffer_defaults.overlay_center = BEG;
4958 XSETFASTINT (BVAR (&buffer_defaults, tab_width), 8);
4959 BSET (&buffer_defaults, truncate_lines, Qnil);
4960 BSET (&buffer_defaults, word_wrap, Qnil);
4961 BSET (&buffer_defaults, ctl_arrow, Qt);
4962 BSET (&buffer_defaults, bidi_display_reordering, Qt);
4963 BSET (&buffer_defaults, bidi_paragraph_direction, Qnil);
4964 BSET (&buffer_defaults, cursor_type, Qt);
4965 BSET (&buffer_defaults, extra_line_spacing, Qnil);
4966 BSET (&buffer_defaults, cursor_in_non_selected_windows, Qt);
4968 BSET (&buffer_defaults, enable_multibyte_characters, Qt);
4969 BSET (&buffer_defaults, buffer_file_coding_system, Qnil);
4970 XSETFASTINT (BVAR (&buffer_defaults, fill_column), 70);
4971 XSETFASTINT (BVAR (&buffer_defaults, left_margin), 0);
4972 BSET (&buffer_defaults, cache_long_line_scans, Qnil);
4973 BSET (&buffer_defaults, file_truename, Qnil);
4974 XSETFASTINT (BVAR (&buffer_defaults, display_count), 0);
4975 XSETFASTINT (BVAR (&buffer_defaults, left_margin_cols), 0);
4976 XSETFASTINT (BVAR (&buffer_defaults, right_margin_cols), 0);
4977 BSET (&buffer_defaults, left_fringe_width, Qnil);
4978 BSET (&buffer_defaults, right_fringe_width, Qnil);
4979 BSET (&buffer_defaults, fringes_outside_margins, Qnil);
4980 BSET (&buffer_defaults, scroll_bar_width, Qnil);
4981 BSET (&buffer_defaults, vertical_scroll_bar_type, Qt);
4982 BSET (&buffer_defaults, indicate_empty_lines, Qnil);
4983 BSET (&buffer_defaults, indicate_buffer_boundaries, Qnil);
4984 BSET (&buffer_defaults, fringe_indicator_alist, Qnil);
4985 BSET (&buffer_defaults, fringe_cursor_alist, Qnil);
4986 BSET (&buffer_defaults, scroll_up_aggressively, Qnil);
4987 BSET (&buffer_defaults, scroll_down_aggressively, Qnil);
4988 BSET (&buffer_defaults, display_time, Qnil);
4990 /* Assign the local-flags to the slots that have default values.
4991 The local flag is a bit that is used in the buffer
4992 to say that it has its own local value for the slot.
4993 The local flag bits are in the local_var_flags slot of the buffer. */
4995 /* Nothing can work if this isn't true */
4996 { verify (sizeof (EMACS_INT) == word_size); }
4998 /* 0 means not a lisp var, -1 means always local, else mask */
4999 memset (&buffer_local_flags, 0, sizeof buffer_local_flags);
5000 BSET (&buffer_local_flags, filename, make_number (-1));
5001 BSET (&buffer_local_flags, directory, make_number (-1));
5002 BSET (&buffer_local_flags, backed_up, make_number (-1));
5003 BSET (&buffer_local_flags, save_length, make_number (-1));
5004 BSET (&buffer_local_flags, auto_save_file_name, make_number (-1));
5005 BSET (&buffer_local_flags, read_only, make_number (-1));
5006 BSET (&buffer_local_flags, major_mode, make_number (-1));
5007 BSET (&buffer_local_flags, mode_name, make_number (-1));
5008 BSET (&buffer_local_flags, undo_list, make_number (-1));
5009 BSET (&buffer_local_flags, mark_active, make_number (-1));
5010 BSET (&buffer_local_flags, point_before_scroll, make_number (-1));
5011 BSET (&buffer_local_flags, file_truename, make_number (-1));
5012 BSET (&buffer_local_flags, invisibility_spec, make_number (-1));
5013 BSET (&buffer_local_flags, file_format, make_number (-1));
5014 BSET (&buffer_local_flags, auto_save_file_format, make_number (-1));
5015 BSET (&buffer_local_flags, display_count, make_number (-1));
5016 BSET (&buffer_local_flags, display_time, make_number (-1));
5017 BSET (&buffer_local_flags, enable_multibyte_characters, make_number (-1));
5019 idx = 1;
5020 XSETFASTINT (BVAR (&buffer_local_flags, mode_line_format), idx); ++idx;
5021 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_mode), idx); ++idx;
5022 XSETFASTINT (BVAR (&buffer_local_flags, overwrite_mode), idx); ++idx;
5023 XSETFASTINT (BVAR (&buffer_local_flags, case_fold_search), idx); ++idx;
5024 XSETFASTINT (BVAR (&buffer_local_flags, auto_fill_function), idx); ++idx;
5025 XSETFASTINT (BVAR (&buffer_local_flags, selective_display), idx); ++idx;
5026 XSETFASTINT (BVAR (&buffer_local_flags, selective_display_ellipses), idx); ++idx;
5027 XSETFASTINT (BVAR (&buffer_local_flags, tab_width), idx); ++idx;
5028 XSETFASTINT (BVAR (&buffer_local_flags, truncate_lines), idx); ++idx;
5029 XSETFASTINT (BVAR (&buffer_local_flags, word_wrap), idx); ++idx;
5030 XSETFASTINT (BVAR (&buffer_local_flags, ctl_arrow), idx); ++idx;
5031 XSETFASTINT (BVAR (&buffer_local_flags, fill_column), idx); ++idx;
5032 XSETFASTINT (BVAR (&buffer_local_flags, left_margin), idx); ++idx;
5033 XSETFASTINT (BVAR (&buffer_local_flags, abbrev_table), idx); ++idx;
5034 XSETFASTINT (BVAR (&buffer_local_flags, display_table), idx); ++idx;
5035 XSETFASTINT (BVAR (&buffer_local_flags, syntax_table), idx); ++idx;
5036 XSETFASTINT (BVAR (&buffer_local_flags, cache_long_line_scans), idx); ++idx;
5037 XSETFASTINT (BVAR (&buffer_local_flags, category_table), idx); ++idx;
5038 XSETFASTINT (BVAR (&buffer_local_flags, bidi_display_reordering), idx); ++idx;
5039 XSETFASTINT (BVAR (&buffer_local_flags, bidi_paragraph_direction), idx); ++idx;
5040 XSETFASTINT (BVAR (&buffer_local_flags, buffer_file_coding_system), idx);
5041 /* Make this one a permanent local. */
5042 buffer_permanent_local_flags[idx++] = 1;
5043 XSETFASTINT (BVAR (&buffer_local_flags, left_margin_cols), idx); ++idx;
5044 XSETFASTINT (BVAR (&buffer_local_flags, right_margin_cols), idx); ++idx;
5045 XSETFASTINT (BVAR (&buffer_local_flags, left_fringe_width), idx); ++idx;
5046 XSETFASTINT (BVAR (&buffer_local_flags, right_fringe_width), idx); ++idx;
5047 XSETFASTINT (BVAR (&buffer_local_flags, fringes_outside_margins), idx); ++idx;
5048 XSETFASTINT (BVAR (&buffer_local_flags, scroll_bar_width), idx); ++idx;
5049 XSETFASTINT (BVAR (&buffer_local_flags, vertical_scroll_bar_type), idx); ++idx;
5050 XSETFASTINT (BVAR (&buffer_local_flags, indicate_empty_lines), idx); ++idx;
5051 XSETFASTINT (BVAR (&buffer_local_flags, indicate_buffer_boundaries), idx); ++idx;
5052 XSETFASTINT (BVAR (&buffer_local_flags, fringe_indicator_alist), idx); ++idx;
5053 XSETFASTINT (BVAR (&buffer_local_flags, fringe_cursor_alist), idx); ++idx;
5054 XSETFASTINT (BVAR (&buffer_local_flags, scroll_up_aggressively), idx); ++idx;
5055 XSETFASTINT (BVAR (&buffer_local_flags, scroll_down_aggressively), idx); ++idx;
5056 XSETFASTINT (BVAR (&buffer_local_flags, header_line_format), idx); ++idx;
5057 XSETFASTINT (BVAR (&buffer_local_flags, cursor_type), idx); ++idx;
5058 XSETFASTINT (BVAR (&buffer_local_flags, extra_line_spacing), idx); ++idx;
5059 XSETFASTINT (BVAR (&buffer_local_flags, cursor_in_non_selected_windows), idx); ++idx;
5061 /* Need more room? */
5062 if (idx >= MAX_PER_BUFFER_VARS)
5063 abort ();
5064 last_per_buffer_idx = idx;
5066 Vbuffer_alist = Qnil;
5067 current_buffer = 0;
5068 all_buffers = 0;
5070 QSFundamental = build_pure_c_string ("Fundamental");
5072 Qfundamental_mode = intern_c_string ("fundamental-mode");
5073 BSET (&buffer_defaults, major_mode, Qfundamental_mode);
5075 Qmode_class = intern_c_string ("mode-class");
5077 Qprotected_field = intern_c_string ("protected-field");
5079 Qpermanent_local = intern_c_string ("permanent-local");
5081 Qkill_buffer_hook = intern_c_string ("kill-buffer-hook");
5082 Fput (Qkill_buffer_hook, Qpermanent_local, Qt);
5084 /* super-magic invisible buffer */
5085 Vprin1_to_string_buffer = Fget_buffer_create (build_pure_c_string (" prin1"));
5086 Vbuffer_alist = Qnil;
5088 Fset_buffer (Fget_buffer_create (build_pure_c_string ("*scratch*")));
5090 inhibit_modification_hooks = 0;
5093 void
5094 init_buffer (void)
5096 char *pwd;
5097 Lisp_Object temp;
5098 ptrdiff_t len;
5100 #ifdef USE_MMAP_FOR_BUFFERS
5102 /* When using the ralloc implementation based on mmap(2), buffer
5103 text pointers will have been set to null in the dumped Emacs.
5104 Map new memory. */
5105 struct buffer *b;
5107 FOR_EACH_BUFFER (b)
5108 if (b->text->beg == NULL)
5109 enlarge_buffer_text (b, 0);
5111 #endif /* USE_MMAP_FOR_BUFFERS */
5113 Fset_buffer (Fget_buffer_create (build_string ("*scratch*")));
5114 if (NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
5115 Fset_buffer_multibyte (Qnil);
5117 pwd = get_current_dir_name ();
5119 if (!pwd)
5120 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5122 /* Maybe this should really use some standard subroutine
5123 whose definition is filename syntax dependent. */
5124 len = strlen (pwd);
5125 if (!(IS_DIRECTORY_SEP (pwd[len - 1])))
5127 /* Grow buffer to add directory separator and '\0'. */
5128 pwd = realloc (pwd, len + 2);
5129 if (!pwd)
5130 fatal ("`get_current_dir_name' failed: %s\n", strerror (errno));
5131 pwd[len] = DIRECTORY_SEP;
5132 pwd[len + 1] = '\0';
5133 len++;
5136 BSET (current_buffer, directory, make_unibyte_string (pwd, len));
5137 if (! NILP (BVAR (&buffer_defaults, enable_multibyte_characters)))
5138 /* At this moment, we still don't know how to decode the
5139 directory name. So, we keep the bytes in multibyte form so
5140 that ENCODE_FILE correctly gets the original bytes. */
5141 BSET (current_buffer, directory,
5142 string_to_multibyte (BVAR (current_buffer, directory)));
5144 /* Add /: to the front of the name
5145 if it would otherwise be treated as magic. */
5146 temp = Ffind_file_name_handler (BVAR (current_buffer, directory), Qt);
5147 if (! NILP (temp)
5148 /* If the default dir is just /, TEMP is non-nil
5149 because of the ange-ftp completion handler.
5150 However, it is not necessary to turn / into /:/.
5151 So avoid doing that. */
5152 && strcmp ("/", SSDATA (BVAR (current_buffer, directory))))
5153 BSET (current_buffer, directory,
5154 concat2 (build_string ("/:"), BVAR (current_buffer, directory)));
5156 temp = get_minibuffer (0);
5157 BSET (XBUFFER (temp), directory, BVAR (current_buffer, directory));
5159 free (pwd);
5162 /* Similar to defvar_lisp but define a variable whose value is the Lisp
5163 Object stored in the current buffer. address is the address of the slot
5164 in the buffer that is current now. */
5166 /* TYPE is nil for a general Lisp variable.
5167 An integer specifies a type; then only Lisp values
5168 with that type code are allowed (except that nil is allowed too).
5169 LNAME is the Lisp-level variable name.
5170 VNAME is the name of the buffer slot.
5171 DOC is a dummy where you write the doc string as a comment. */
5172 #define DEFVAR_PER_BUFFER(lname, vname, type, doc) \
5173 do { \
5174 static struct Lisp_Buffer_Objfwd bo_fwd; \
5175 defvar_per_buffer (&bo_fwd, lname, vname, type); \
5176 } while (0)
5178 static void
5179 defvar_per_buffer (struct Lisp_Buffer_Objfwd *bo_fwd, const char *namestring,
5180 Lisp_Object *address, Lisp_Object type)
5182 struct Lisp_Symbol *sym;
5183 int offset;
5185 sym = XSYMBOL (intern (namestring));
5186 offset = (char *)address - (char *)current_buffer;
5188 bo_fwd->type = Lisp_Fwd_Buffer_Obj;
5189 bo_fwd->offset = offset;
5190 bo_fwd->slottype = type;
5191 sym->declared_special = 1;
5192 sym->redirect = SYMBOL_FORWARDED;
5194 /* I tried to do the job without a cast, but it seems impossible.
5195 union Lisp_Fwd *fwd; &(fwd->u_buffer_objfwd) = bo_fwd; */
5196 SET_SYMBOL_FWD (sym, (union Lisp_Fwd *)bo_fwd);
5198 XSETSYMBOL (PER_BUFFER_SYMBOL (offset), sym);
5200 if (PER_BUFFER_IDX (offset) == 0)
5201 /* Did a DEFVAR_PER_BUFFER without initializing the corresponding
5202 slot of buffer_local_flags */
5203 abort ();
5207 /* initialize the buffer routines */
5208 void
5209 syms_of_buffer (void)
5211 staticpro (&last_overlay_modification_hooks);
5212 last_overlay_modification_hooks
5213 = Fmake_vector (make_number (10), Qnil);
5215 staticpro (&Vbuffer_defaults);
5216 staticpro (&Vbuffer_local_symbols);
5217 staticpro (&Qfundamental_mode);
5218 staticpro (&Qmode_class);
5219 staticpro (&QSFundamental);
5220 staticpro (&Vbuffer_alist);
5221 staticpro (&Qprotected_field);
5222 staticpro (&Qpermanent_local);
5223 staticpro (&Qkill_buffer_hook);
5225 DEFSYM (Qpermanent_local_hook, "permanent-local-hook");
5226 DEFSYM (Qoverlayp, "overlayp");
5227 DEFSYM (Qevaporate, "evaporate");
5228 DEFSYM (Qmodification_hooks, "modification-hooks");
5229 DEFSYM (Qinsert_in_front_hooks, "insert-in-front-hooks");
5230 DEFSYM (Qinsert_behind_hooks, "insert-behind-hooks");
5231 DEFSYM (Qget_file_buffer, "get-file-buffer");
5232 DEFSYM (Qpriority, "priority");
5233 DEFSYM (Qbefore_string, "before-string");
5234 DEFSYM (Qafter_string, "after-string");
5235 DEFSYM (Qfirst_change_hook, "first-change-hook");
5236 DEFSYM (Qbefore_change_functions, "before-change-functions");
5237 DEFSYM (Qafter_change_functions, "after-change-functions");
5238 DEFSYM (Qkill_buffer_query_functions, "kill-buffer-query-functions");
5240 Fput (Qprotected_field, Qerror_conditions,
5241 listn (CONSTYPE_PURE, 2, Qprotected_field, Qerror));
5242 Fput (Qprotected_field, Qerror_message,
5243 build_pure_c_string ("Attempt to modify a protected field"));
5245 DEFVAR_BUFFER_DEFAULTS ("default-mode-line-format",
5246 mode_line_format,
5247 doc: /* Default value of `mode-line-format' for buffers that don't override it.
5248 This is the same as (default-value 'mode-line-format). */);
5250 DEFVAR_BUFFER_DEFAULTS ("default-header-line-format",
5251 header_line_format,
5252 doc: /* Default value of `header-line-format' for buffers that don't override it.
5253 This is the same as (default-value 'header-line-format). */);
5255 DEFVAR_BUFFER_DEFAULTS ("default-cursor-type", cursor_type,
5256 doc: /* Default value of `cursor-type' for buffers that don't override it.
5257 This is the same as (default-value 'cursor-type). */);
5259 DEFVAR_BUFFER_DEFAULTS ("default-line-spacing",
5260 extra_line_spacing,
5261 doc: /* Default value of `line-spacing' for buffers that don't override it.
5262 This is the same as (default-value 'line-spacing). */);
5264 DEFVAR_BUFFER_DEFAULTS ("default-cursor-in-non-selected-windows",
5265 cursor_in_non_selected_windows,
5266 doc: /* Default value of `cursor-in-non-selected-windows'.
5267 This is the same as (default-value 'cursor-in-non-selected-windows). */);
5269 DEFVAR_BUFFER_DEFAULTS ("default-abbrev-mode",
5270 abbrev_mode,
5271 doc: /* Default value of `abbrev-mode' for buffers that do not override it.
5272 This is the same as (default-value 'abbrev-mode). */);
5274 DEFVAR_BUFFER_DEFAULTS ("default-ctl-arrow",
5275 ctl_arrow,
5276 doc: /* Default value of `ctl-arrow' for buffers that do not override it.
5277 This is the same as (default-value 'ctl-arrow). */);
5279 DEFVAR_BUFFER_DEFAULTS ("default-enable-multibyte-characters",
5280 enable_multibyte_characters,
5281 doc: /* Default value of `enable-multibyte-characters' for buffers not overriding it.
5282 This is the same as (default-value 'enable-multibyte-characters). */);
5284 DEFVAR_BUFFER_DEFAULTS ("default-buffer-file-coding-system",
5285 buffer_file_coding_system,
5286 doc: /* Default value of `buffer-file-coding-system' for buffers not overriding it.
5287 This is the same as (default-value 'buffer-file-coding-system). */);
5289 DEFVAR_BUFFER_DEFAULTS ("default-truncate-lines",
5290 truncate_lines,
5291 doc: /* Default value of `truncate-lines' for buffers that do not override it.
5292 This is the same as (default-value 'truncate-lines). */);
5294 DEFVAR_BUFFER_DEFAULTS ("default-fill-column",
5295 fill_column,
5296 doc: /* Default value of `fill-column' for buffers that do not override it.
5297 This is the same as (default-value 'fill-column). */);
5299 DEFVAR_BUFFER_DEFAULTS ("default-left-margin",
5300 left_margin,
5301 doc: /* Default value of `left-margin' for buffers that do not override it.
5302 This is the same as (default-value 'left-margin). */);
5304 DEFVAR_BUFFER_DEFAULTS ("default-tab-width",
5305 tab_width,
5306 doc: /* Default value of `tab-width' for buffers that do not override it.
5307 This is the same as (default-value 'tab-width). */);
5309 DEFVAR_BUFFER_DEFAULTS ("default-case-fold-search",
5310 case_fold_search,
5311 doc: /* Default value of `case-fold-search' for buffers that don't override it.
5312 This is the same as (default-value 'case-fold-search). */);
5314 DEFVAR_BUFFER_DEFAULTS ("default-left-margin-width",
5315 left_margin_cols,
5316 doc: /* Default value of `left-margin-width' for buffers that don't override it.
5317 This is the same as (default-value 'left-margin-width). */);
5319 DEFVAR_BUFFER_DEFAULTS ("default-right-margin-width",
5320 right_margin_cols,
5321 doc: /* Default value of `right-margin-width' for buffers that don't override it.
5322 This is the same as (default-value 'right-margin-width). */);
5324 DEFVAR_BUFFER_DEFAULTS ("default-left-fringe-width",
5325 left_fringe_width,
5326 doc: /* Default value of `left-fringe-width' for buffers that don't override it.
5327 This is the same as (default-value 'left-fringe-width). */);
5329 DEFVAR_BUFFER_DEFAULTS ("default-right-fringe-width",
5330 right_fringe_width,
5331 doc: /* Default value of `right-fringe-width' for buffers that don't override it.
5332 This is the same as (default-value 'right-fringe-width). */);
5334 DEFVAR_BUFFER_DEFAULTS ("default-fringes-outside-margins",
5335 fringes_outside_margins,
5336 doc: /* Default value of `fringes-outside-margins' for buffers that don't override it.
5337 This is the same as (default-value 'fringes-outside-margins). */);
5339 DEFVAR_BUFFER_DEFAULTS ("default-scroll-bar-width",
5340 scroll_bar_width,
5341 doc: /* Default value of `scroll-bar-width' for buffers that don't override it.
5342 This is the same as (default-value 'scroll-bar-width). */);
5344 DEFVAR_BUFFER_DEFAULTS ("default-vertical-scroll-bar",
5345 vertical_scroll_bar_type,
5346 doc: /* Default value of `vertical-scroll-bar' for buffers that don't override it.
5347 This is the same as (default-value 'vertical-scroll-bar). */);
5349 DEFVAR_BUFFER_DEFAULTS ("default-indicate-empty-lines",
5350 indicate_empty_lines,
5351 doc: /* Default value of `indicate-empty-lines' for buffers that don't override it.
5352 This is the same as (default-value 'indicate-empty-lines). */);
5354 DEFVAR_BUFFER_DEFAULTS ("default-indicate-buffer-boundaries",
5355 indicate_buffer_boundaries,
5356 doc: /* Default value of `indicate-buffer-boundaries' for buffers that don't override it.
5357 This is the same as (default-value 'indicate-buffer-boundaries). */);
5359 DEFVAR_BUFFER_DEFAULTS ("default-fringe-indicator-alist",
5360 fringe_indicator_alist,
5361 doc: /* Default value of `fringe-indicator-alist' for buffers that don't override it.
5362 This is the same as (default-value 'fringe-indicator-alist'). */);
5364 DEFVAR_BUFFER_DEFAULTS ("default-fringe-cursor-alist",
5365 fringe_cursor_alist,
5366 doc: /* Default value of `fringe-cursor-alist' for buffers that don't override it.
5367 This is the same as (default-value 'fringe-cursor-alist'). */);
5369 DEFVAR_BUFFER_DEFAULTS ("default-scroll-up-aggressively",
5370 scroll_up_aggressively,
5371 doc: /* Default value of `scroll-up-aggressively'.
5372 This value applies in buffers that don't have their own local values.
5373 This is the same as (default-value 'scroll-up-aggressively). */);
5375 DEFVAR_BUFFER_DEFAULTS ("default-scroll-down-aggressively",
5376 scroll_down_aggressively,
5377 doc: /* Default value of `scroll-down-aggressively'.
5378 This value applies in buffers that don't have their own local values.
5379 This is the same as (default-value 'scroll-down-aggressively). */);
5381 DEFVAR_PER_BUFFER ("header-line-format",
5382 &BVAR (current_buffer, header_line_format),
5383 Qnil,
5384 doc: /* Analogous to `mode-line-format', but controls the header line.
5385 The header line appears, optionally, at the top of a window;
5386 the mode line appears at the bottom. */);
5388 DEFVAR_PER_BUFFER ("mode-line-format", &BVAR (current_buffer, mode_line_format),
5389 Qnil,
5390 doc: /* Template for displaying mode line for current buffer.
5392 The value may be nil, a string, a symbol or a list.
5394 A value of nil means don't display a mode line.
5396 For any symbol other than t or nil, the symbol's value is processed as
5397 a mode line construct. As a special exception, if that value is a
5398 string, the string is processed verbatim, without handling any
5399 %-constructs (see below). Also, unless the symbol has a non-nil
5400 `risky-local-variable' property, all properties in any strings, as
5401 well as all :eval and :propertize forms in the value, are ignored.
5403 A list whose car is a string or list is processed by processing each
5404 of the list elements recursively, as separate mode line constructs,
5405 and concatenating the results.
5407 A list of the form `(:eval FORM)' is processed by evaluating FORM and
5408 using the result as a mode line construct. Be careful--FORM should
5409 not load any files, because that can cause an infinite recursion.
5411 A list of the form `(:propertize ELT PROPS...)' is processed by
5412 processing ELT as the mode line construct, and adding the text
5413 properties PROPS to the result.
5415 A list whose car is a symbol is processed by examining the symbol's
5416 value, and, if that value is non-nil, processing the cadr of the list
5417 recursively; and if that value is nil, processing the caddr of the
5418 list recursively.
5420 A list whose car is an integer is processed by processing the cadr of
5421 the list, and padding (if the number is positive) or truncating (if
5422 negative) to the width specified by that number.
5424 A string is printed verbatim in the mode line except for %-constructs:
5425 %b -- print buffer name. %f -- print visited file name.
5426 %F -- print frame name.
5427 %* -- print %, * or hyphen. %+ -- print *, % or hyphen.
5428 %& is like %*, but ignore read-only-ness.
5429 % means buffer is read-only and * means it is modified.
5430 For a modified read-only buffer, %* gives % and %+ gives *.
5431 %s -- print process status. %l -- print the current line number.
5432 %c -- print the current column number (this makes editing slower).
5433 To make the column number update correctly in all cases,
5434 `column-number-mode' must be non-nil.
5435 %i -- print the size of the buffer.
5436 %I -- like %i, but use k, M, G, etc., to abbreviate.
5437 %p -- print percent of buffer above top of window, or Top, Bot or All.
5438 %P -- print percent of buffer above bottom of window, perhaps plus Top,
5439 or print Bottom or All.
5440 %n -- print Narrow if appropriate.
5441 %t -- visited file is text or binary (if OS supports this distinction).
5442 %z -- print mnemonics of keyboard, terminal, and buffer coding systems.
5443 %Z -- like %z, but including the end-of-line format.
5444 %e -- print error message about full memory.
5445 %@ -- print @ or hyphen. @ means that default-directory is on a
5446 remote machine.
5447 %[ -- print one [ for each recursive editing level. %] similar.
5448 %% -- print %. %- -- print infinitely many dashes.
5449 Decimal digits after the % specify field width to which to pad. */);
5451 DEFVAR_BUFFER_DEFAULTS ("default-major-mode", major_mode,
5452 doc: /* Value of `major-mode' for new buffers. */);
5454 DEFVAR_PER_BUFFER ("major-mode", &BVAR (current_buffer, major_mode),
5455 make_number (Lisp_Symbol),
5456 doc: /* Symbol for current buffer's major mode.
5457 The default value (normally `fundamental-mode') affects new buffers.
5458 A value of nil means to use the current buffer's major mode, provided
5459 it is not marked as "special".
5461 When a mode is used by default, `find-file' switches to it before it
5462 reads the contents into the buffer and before it finishes setting up
5463 the buffer. Thus, the mode and its hooks should not expect certain
5464 variables such as `buffer-read-only' and `buffer-file-coding-system'
5465 to be set up. */);
5467 DEFVAR_PER_BUFFER ("mode-name", &BVAR (current_buffer, mode_name),
5468 Qnil,
5469 doc: /* Pretty name of current buffer's major mode.
5470 Usually a string, but can use any of the constructs for `mode-line-format',
5471 which see.
5472 Format with `format-mode-line' to produce a string value. */);
5474 DEFVAR_PER_BUFFER ("local-abbrev-table", &BVAR (current_buffer, abbrev_table), Qnil,
5475 doc: /* Local (mode-specific) abbrev table of current buffer. */);
5477 DEFVAR_PER_BUFFER ("abbrev-mode", &BVAR (current_buffer, abbrev_mode), Qnil,
5478 doc: /* Non-nil if Abbrev mode is enabled.
5479 Use the command `abbrev-mode' to change this variable. */);
5481 DEFVAR_PER_BUFFER ("case-fold-search", &BVAR (current_buffer, case_fold_search),
5482 Qnil,
5483 doc: /* Non-nil if searches and matches should ignore case. */);
5485 DEFVAR_PER_BUFFER ("fill-column", &BVAR (current_buffer, fill_column),
5486 make_number (Lisp_Int0),
5487 doc: /* Column beyond which automatic line-wrapping should happen.
5488 Interactively, you can set the buffer local value using \\[set-fill-column]. */);
5490 DEFVAR_PER_BUFFER ("left-margin", &BVAR (current_buffer, left_margin),
5491 make_number (Lisp_Int0),
5492 doc: /* Column for the default `indent-line-function' to indent to.
5493 Linefeed indents to this column in Fundamental mode. */);
5495 DEFVAR_PER_BUFFER ("tab-width", &BVAR (current_buffer, tab_width),
5496 make_number (Lisp_Int0),
5497 doc: /* Distance between tab stops (for display of tab characters), in columns.
5498 This should be an integer greater than zero. */);
5500 DEFVAR_PER_BUFFER ("ctl-arrow", &BVAR (current_buffer, ctl_arrow), Qnil,
5501 doc: /* Non-nil means display control chars with uparrow.
5502 A value of nil means use backslash and octal digits.
5503 This variable does not apply to characters whose display is specified
5504 in the current display table (if there is one). */);
5506 DEFVAR_PER_BUFFER ("enable-multibyte-characters",
5507 &BVAR (current_buffer, enable_multibyte_characters),
5508 Qnil,
5509 doc: /* Non-nil means the buffer contents are regarded as multi-byte characters.
5510 Otherwise they are regarded as unibyte. This affects the display,
5511 file I/O and the behavior of various editing commands.
5513 This variable is buffer-local but you cannot set it directly;
5514 use the function `set-buffer-multibyte' to change a buffer's representation.
5515 See also Info node `(elisp)Text Representations'. */);
5516 XSYMBOL (intern_c_string ("enable-multibyte-characters"))->constant = 1;
5518 DEFVAR_PER_BUFFER ("buffer-file-coding-system",
5519 &BVAR (current_buffer, buffer_file_coding_system), Qnil,
5520 doc: /* Coding system to be used for encoding the buffer contents on saving.
5521 This variable applies to saving the buffer, and also to `write-region'
5522 and other functions that use `write-region'.
5523 It does not apply to sending output to subprocesses, however.
5525 If this is nil, the buffer is saved without any code conversion
5526 unless some coding system is specified in `file-coding-system-alist'
5527 for the buffer file.
5529 If the text to be saved cannot be encoded as specified by this variable,
5530 an alternative encoding is selected by `select-safe-coding-system', which see.
5532 The variable `coding-system-for-write', if non-nil, overrides this variable.
5534 This variable is never applied to a way of decoding a file while reading it. */);
5536 DEFVAR_PER_BUFFER ("bidi-display-reordering",
5537 &BVAR (current_buffer, bidi_display_reordering), Qnil,
5538 doc: /* Non-nil means reorder bidirectional text for display in the visual order. */);
5540 DEFVAR_PER_BUFFER ("bidi-paragraph-direction",
5541 &BVAR (current_buffer, bidi_paragraph_direction), Qnil,
5542 doc: /* If non-nil, forces directionality of text paragraphs in the buffer.
5544 If this is nil (the default), the direction of each paragraph is
5545 determined by the first strong directional character of its text.
5546 The values of `right-to-left' and `left-to-right' override that.
5547 Any other value is treated as nil.
5549 This variable has no effect unless the buffer's value of
5550 \`bidi-display-reordering' is non-nil. */);
5552 DEFVAR_PER_BUFFER ("truncate-lines", &BVAR (current_buffer, truncate_lines), Qnil,
5553 doc: /* Non-nil means do not display continuation lines.
5554 Instead, give each line of text just one screen line.
5556 Note that this is overridden by the variable
5557 `truncate-partial-width-windows' if that variable is non-nil
5558 and this buffer is not full-frame width.
5560 Minibuffers set this variable to nil. */);
5562 DEFVAR_PER_BUFFER ("word-wrap", &BVAR (current_buffer, word_wrap), Qnil,
5563 doc: /* Non-nil means to use word-wrapping for continuation lines.
5564 When word-wrapping is on, continuation lines are wrapped at the space
5565 or tab character nearest to the right window edge.
5566 If nil, continuation lines are wrapped at the right screen edge.
5568 This variable has no effect if long lines are truncated (see
5569 `truncate-lines' and `truncate-partial-width-windows'). If you use
5570 word-wrapping, you might want to reduce the value of
5571 `truncate-partial-width-windows', since wrapping can make text readable
5572 in narrower windows.
5574 Instead of setting this variable directly, most users should use
5575 Visual Line mode . Visual Line mode, when enabled, sets `word-wrap'
5576 to t, and additionally redefines simple editing commands to act on
5577 visual lines rather than logical lines. See the documentation of
5578 `visual-line-mode'. */);
5580 DEFVAR_PER_BUFFER ("default-directory", &BVAR (current_buffer, directory),
5581 make_number (Lisp_String),
5582 doc: /* Name of default directory of current buffer. Should end with slash.
5583 To interactively change the default directory, use command `cd'. */);
5585 DEFVAR_PER_BUFFER ("auto-fill-function", &BVAR (current_buffer, auto_fill_function),
5586 Qnil,
5587 doc: /* Function called (if non-nil) to perform auto-fill.
5588 It is called after self-inserting any character specified in
5589 the `auto-fill-chars' table.
5590 NOTE: This variable is not a hook;
5591 its value may not be a list of functions. */);
5593 DEFVAR_PER_BUFFER ("buffer-file-name", &BVAR (current_buffer, filename),
5594 make_number (Lisp_String),
5595 doc: /* Name of file visited in current buffer, or nil if not visiting a file. */);
5597 DEFVAR_PER_BUFFER ("buffer-file-truename", &BVAR (current_buffer, file_truename),
5598 make_number (Lisp_String),
5599 doc: /* Abbreviated truename of file visited in current buffer, or nil if none.
5600 The truename of a file is calculated by `file-truename'
5601 and then abbreviated with `abbreviate-file-name'. */);
5603 DEFVAR_PER_BUFFER ("buffer-auto-save-file-name",
5604 &BVAR (current_buffer, auto_save_file_name),
5605 make_number (Lisp_String),
5606 doc: /* Name of file for auto-saving current buffer.
5607 If it is nil, that means don't auto-save this buffer. */);
5609 DEFVAR_PER_BUFFER ("buffer-read-only", &BVAR (current_buffer, read_only), Qnil,
5610 doc: /* Non-nil if this buffer is read-only. */);
5612 DEFVAR_PER_BUFFER ("buffer-backed-up", &BVAR (current_buffer, backed_up), Qnil,
5613 doc: /* Non-nil if this buffer's file has been backed up.
5614 Backing up is done before the first time the file is saved. */);
5616 DEFVAR_PER_BUFFER ("buffer-saved-size", &BVAR (current_buffer, save_length),
5617 make_number (Lisp_Int0),
5618 doc: /* Length of current buffer when last read in, saved or auto-saved.
5619 0 initially.
5620 -1 means auto-saving turned off until next real save.
5622 If you set this to -2, that means don't turn off auto-saving in this buffer
5623 if its text size shrinks. If you use `buffer-swap-text' on a buffer,
5624 you probably should set this to -2 in that buffer. */);
5626 DEFVAR_PER_BUFFER ("selective-display", &BVAR (current_buffer, selective_display),
5627 Qnil,
5628 doc: /* Non-nil enables selective display.
5629 An integer N as value means display only lines
5630 that start with less than N columns of space.
5631 A value of t means that the character ^M makes itself and
5632 all the rest of the line invisible; also, when saving the buffer
5633 in a file, save the ^M as a newline. */);
5635 DEFVAR_PER_BUFFER ("selective-display-ellipses",
5636 &BVAR (current_buffer, selective_display_ellipses),
5637 Qnil,
5638 doc: /* Non-nil means display ... on previous line when a line is invisible. */);
5640 DEFVAR_PER_BUFFER ("overwrite-mode", &BVAR (current_buffer, overwrite_mode), Qnil,
5641 doc: /* Non-nil if self-insertion should replace existing text.
5642 The value should be one of `overwrite-mode-textual',
5643 `overwrite-mode-binary', or nil.
5644 If it is `overwrite-mode-textual', self-insertion still
5645 inserts at the end of a line, and inserts when point is before a tab,
5646 until the tab is filled in.
5647 If `overwrite-mode-binary', self-insertion replaces newlines and tabs too. */);
5649 DEFVAR_PER_BUFFER ("buffer-display-table", &BVAR (current_buffer, display_table),
5650 Qnil,
5651 doc: /* Display table that controls display of the contents of current buffer.
5653 If this variable is nil, the value of `standard-display-table' is used.
5654 Each window can have its own, overriding display table, see
5655 `set-window-display-table' and `window-display-table'.
5657 The display table is a char-table created with `make-display-table'.
5658 A char-table is an array indexed by character codes. Normal array
5659 primitives `aref' and `aset' can be used to access elements of a char-table.
5661 Each of the char-table elements control how to display the corresponding
5662 text character: the element at index C in the table says how to display
5663 the character whose code is C. Each element should be a vector of
5664 characters or nil. The value nil means display the character in the
5665 default fashion; otherwise, the characters from the vector are delivered
5666 to the screen instead of the original character.
5668 For example, (aset buffer-display-table ?X [?Y]) tells Emacs
5669 to display a capital Y instead of each X character.
5671 In addition, a char-table has six extra slots to control the display of:
5673 the end of a truncated screen line (extra-slot 0, a single character);
5674 the end of a continued line (extra-slot 1, a single character);
5675 the escape character used to display character codes in octal
5676 (extra-slot 2, a single character);
5677 the character used as an arrow for control characters (extra-slot 3,
5678 a single character);
5679 the decoration indicating the presence of invisible lines (extra-slot 4,
5680 a vector of characters);
5681 the character used to draw the border between side-by-side windows
5682 (extra-slot 5, a single character).
5684 See also the functions `display-table-slot' and `set-display-table-slot'. */);
5686 DEFVAR_PER_BUFFER ("left-margin-width", &BVAR (current_buffer, left_margin_cols),
5687 Qnil,
5688 doc: /* Width of left marginal area for display of a buffer.
5689 A value of nil means no marginal area. */);
5691 DEFVAR_PER_BUFFER ("right-margin-width", &BVAR (current_buffer, right_margin_cols),
5692 Qnil,
5693 doc: /* Width of right marginal area for display of a buffer.
5694 A value of nil means no marginal area. */);
5696 DEFVAR_PER_BUFFER ("left-fringe-width", &BVAR (current_buffer, left_fringe_width),
5697 Qnil,
5698 doc: /* Width of this buffer's left fringe (in pixels).
5699 A value of 0 means no left fringe is shown in this buffer's window.
5700 A value of nil means to use the left fringe width from the window's frame. */);
5702 DEFVAR_PER_BUFFER ("right-fringe-width", &BVAR (current_buffer, right_fringe_width),
5703 Qnil,
5704 doc: /* Width of this buffer's right fringe (in pixels).
5705 A value of 0 means no right fringe is shown in this buffer's window.
5706 A value of nil means to use the right fringe width from the window's frame. */);
5708 DEFVAR_PER_BUFFER ("fringes-outside-margins", &BVAR (current_buffer, fringes_outside_margins),
5709 Qnil,
5710 doc: /* Non-nil means to display fringes outside display margins.
5711 A value of nil means to display fringes between margins and buffer text. */);
5713 DEFVAR_PER_BUFFER ("scroll-bar-width", &BVAR (current_buffer, scroll_bar_width),
5714 Qnil,
5715 doc: /* Width of this buffer's scroll bars in pixels.
5716 A value of nil means to use the scroll bar width from the window's frame. */);
5718 DEFVAR_PER_BUFFER ("vertical-scroll-bar", &BVAR (current_buffer, vertical_scroll_bar_type),
5719 Qnil,
5720 doc: /* Position of this buffer's vertical scroll bar.
5721 The value takes effect whenever you tell a window to display this buffer;
5722 for instance, with `set-window-buffer' or when `display-buffer' displays it.
5724 A value of `left' or `right' means put the vertical scroll bar at that side
5725 of the window; a value of nil means don't show any vertical scroll bars.
5726 A value of t (the default) means do whatever the window's frame specifies. */);
5728 DEFVAR_PER_BUFFER ("indicate-empty-lines",
5729 &BVAR (current_buffer, indicate_empty_lines), Qnil,
5730 doc: /* Visually indicate empty lines after the buffer end.
5731 If non-nil, a bitmap is displayed in the left fringe of a window on
5732 window-systems. */);
5734 DEFVAR_PER_BUFFER ("indicate-buffer-boundaries",
5735 &BVAR (current_buffer, indicate_buffer_boundaries), Qnil,
5736 doc: /* Visually indicate buffer boundaries and scrolling.
5737 If non-nil, the first and last line of the buffer are marked in the fringe
5738 of a window on window-systems with angle bitmaps, or if the window can be
5739 scrolled, the top and bottom line of the window are marked with up and down
5740 arrow bitmaps.
5742 If value is a symbol `left' or `right', both angle and arrow bitmaps
5743 are displayed in the left or right fringe, resp. Any other value
5744 that doesn't look like an alist means display the angle bitmaps in
5745 the left fringe but no arrows.
5747 You can exercise more precise control by using an alist as the
5748 value. Each alist element (INDICATOR . POSITION) specifies
5749 where to show one of the indicators. INDICATOR is one of `top',
5750 `bottom', `up', `down', or t, which specifies the default position,
5751 and POSITION is one of `left', `right', or nil, meaning do not show
5752 this indicator.
5754 For example, ((top . left) (t . right)) places the top angle bitmap in
5755 left fringe, the bottom angle bitmap in right fringe, and both arrow
5756 bitmaps in right fringe. To show just the angle bitmaps in the left
5757 fringe, but no arrow bitmaps, use ((top . left) (bottom . left)). */);
5759 DEFVAR_PER_BUFFER ("fringe-indicator-alist",
5760 &BVAR (current_buffer, fringe_indicator_alist), Qnil,
5761 doc: /* Mapping from logical to physical fringe indicator bitmaps.
5762 The value is an alist where each element (INDICATOR . BITMAPS)
5763 specifies the fringe bitmaps used to display a specific logical
5764 fringe indicator.
5766 INDICATOR specifies the logical indicator type which is one of the
5767 following symbols: `truncation' , `continuation', `overlay-arrow',
5768 `top', `bottom', `top-bottom', `up', `down', empty-line', or `unknown'.
5770 BITMAPS is a list of symbols (LEFT RIGHT [LEFT1 RIGHT1]) which specifies
5771 the actual bitmap shown in the left or right fringe for the logical
5772 indicator. LEFT and RIGHT are the bitmaps shown in the left and/or
5773 right fringe for the specific indicator. The LEFT1 or RIGHT1 bitmaps
5774 are used only for the `bottom' and `top-bottom' indicators when the
5775 last (only) line has no final newline. BITMAPS may also be a single
5776 symbol which is used in both left and right fringes. */);
5778 DEFVAR_PER_BUFFER ("fringe-cursor-alist",
5779 &BVAR (current_buffer, fringe_cursor_alist), Qnil,
5780 doc: /* Mapping from logical to physical fringe cursor bitmaps.
5781 The value is an alist where each element (CURSOR . BITMAP)
5782 specifies the fringe bitmaps used to display a specific logical
5783 cursor type in the fringe.
5785 CURSOR specifies the logical cursor type which is one of the following
5786 symbols: `box' , `hollow', `bar', `hbar', or `hollow-small'. The last
5787 one is used to show a hollow cursor on narrow lines display lines
5788 where the normal hollow cursor will not fit.
5790 BITMAP is the corresponding fringe bitmap shown for the logical
5791 cursor type. */);
5793 DEFVAR_PER_BUFFER ("scroll-up-aggressively",
5794 &BVAR (current_buffer, scroll_up_aggressively), Qnil,
5795 doc: /* How far to scroll windows upward.
5796 If you move point off the bottom, the window scrolls automatically.
5797 This variable controls how far it scrolls. The value nil, the default,
5798 means scroll to center point. A fraction means scroll to put point
5799 that fraction of the window's height from the bottom of the window.
5800 When the value is 0.0, point goes at the bottom line, which in the
5801 simple case that you moved off with C-f means scrolling just one line.
5802 1.0 means point goes at the top, so that in that simple case, the
5803 window scrolls by a full window height. Meaningful values are
5804 between 0.0 and 1.0, inclusive. */);
5806 DEFVAR_PER_BUFFER ("scroll-down-aggressively",
5807 &BVAR (current_buffer, scroll_down_aggressively), Qnil,
5808 doc: /* How far to scroll windows downward.
5809 If you move point off the top, the window scrolls automatically.
5810 This variable controls how far it scrolls. The value nil, the default,
5811 means scroll to center point. A fraction means scroll to put point
5812 that fraction of the window's height from the top of the window.
5813 When the value is 0.0, point goes at the top line, which in the
5814 simple case that you moved off with C-b means scrolling just one line.
5815 1.0 means point goes at the bottom, so that in that simple case, the
5816 window scrolls by a full window height. Meaningful values are
5817 between 0.0 and 1.0, inclusive. */);
5819 /*DEFVAR_LISP ("debug-check-symbol", &Vcheck_symbol,
5820 "Don't ask.");
5823 DEFVAR_LISP ("before-change-functions", Vbefore_change_functions,
5824 doc: /* List of functions to call before each text change.
5825 Two arguments are passed to each function: the positions of
5826 the beginning and end of the range of old text to be changed.
5827 \(For an insertion, the beginning and end are at the same place.)
5828 No information is given about the length of the text after the change.
5830 Buffer changes made while executing the `before-change-functions'
5831 don't call any before-change or after-change functions.
5832 That's because `inhibit-modification-hooks' is temporarily set non-nil.
5834 If an unhandled error happens in running these functions,
5835 the variable's value remains nil. That prevents the error
5836 from happening repeatedly and making Emacs nonfunctional. */);
5837 Vbefore_change_functions = Qnil;
5839 DEFVAR_LISP ("after-change-functions", Vafter_change_functions,
5840 doc: /* List of functions to call after each text change.
5841 Three arguments are passed to each function: the positions of
5842 the beginning and end of the range of changed text,
5843 and the length in bytes of the pre-change text replaced by that range.
5844 \(For an insertion, the pre-change length is zero;
5845 for a deletion, that length is the number of bytes deleted,
5846 and the post-change beginning and end are at the same place.)
5848 Buffer changes made while executing the `after-change-functions'
5849 don't call any before-change or after-change functions.
5850 That's because `inhibit-modification-hooks' is temporarily set non-nil.
5852 If an unhandled error happens in running these functions,
5853 the variable's value remains nil. That prevents the error
5854 from happening repeatedly and making Emacs nonfunctional. */);
5855 Vafter_change_functions = Qnil;
5857 DEFVAR_LISP ("first-change-hook", Vfirst_change_hook,
5858 doc: /* A list of functions to call before changing a buffer which is unmodified.
5859 The functions are run using the `run-hooks' function. */);
5860 Vfirst_change_hook = Qnil;
5862 DEFVAR_PER_BUFFER ("buffer-undo-list", &BVAR (current_buffer, undo_list), Qnil,
5863 doc: /* List of undo entries in current buffer.
5864 Recent changes come first; older changes follow newer.
5866 An entry (BEG . END) represents an insertion which begins at
5867 position BEG and ends at position END.
5869 An entry (TEXT . POSITION) represents the deletion of the string TEXT
5870 from (abs POSITION). If POSITION is positive, point was at the front
5871 of the text being deleted; if negative, point was at the end.
5873 An entry (t HIGH LOW USEC PSEC) indicates that the buffer was previously
5874 unmodified; (HIGH LOW USEC PSEC) is in the same style as (current-time)
5875 and is the visited file's modification time, as of that time. If the
5876 modification time of the most recent save is different, this entry is
5877 obsolete.
5879 An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
5880 was modified between BEG and END. PROPERTY is the property name,
5881 and VALUE is the old value.
5883 An entry (apply FUN-NAME . ARGS) means undo the change with
5884 \(apply FUN-NAME ARGS).
5886 An entry (apply DELTA BEG END FUN-NAME . ARGS) supports selective undo
5887 in the active region. BEG and END is the range affected by this entry
5888 and DELTA is the number of bytes added or deleted in that range by
5889 this change.
5891 An entry (MARKER . DISTANCE) indicates that the marker MARKER
5892 was adjusted in position by the offset DISTANCE (an integer).
5894 An entry of the form POSITION indicates that point was at the buffer
5895 location given by the integer. Undoing an entry of this form places
5896 point at POSITION.
5898 Entries with value `nil' mark undo boundaries. The undo command treats
5899 the changes between two undo boundaries as a single step to be undone.
5901 If the value of the variable is t, undo information is not recorded. */);
5903 DEFVAR_PER_BUFFER ("mark-active", &BVAR (current_buffer, mark_active), Qnil,
5904 doc: /* Non-nil means the mark and region are currently active in this buffer. */);
5906 DEFVAR_PER_BUFFER ("cache-long-line-scans", &BVAR (current_buffer, cache_long_line_scans), Qnil,
5907 doc: /* Non-nil means that Emacs should use caches to handle long lines more quickly.
5909 Normally, the line-motion functions work by scanning the buffer for
5910 newlines. Columnar operations (like `move-to-column' and
5911 `compute-motion') also work by scanning the buffer, summing character
5912 widths as they go. This works well for ordinary text, but if the
5913 buffer's lines are very long (say, more than 500 characters), these
5914 motion functions will take longer to execute. Emacs may also take
5915 longer to update the display.
5917 If `cache-long-line-scans' is non-nil, these motion functions cache the
5918 results of their scans, and consult the cache to avoid rescanning
5919 regions of the buffer until the text is modified. The caches are most
5920 beneficial when they prevent the most searching---that is, when the
5921 buffer contains long lines and large regions of characters with the
5922 same, fixed screen width.
5924 When `cache-long-line-scans' is non-nil, processing short lines will
5925 become slightly slower (because of the overhead of consulting the
5926 cache), and the caches will use memory roughly proportional to the
5927 number of newlines and characters whose screen width varies.
5929 The caches require no explicit maintenance; their accuracy is
5930 maintained internally by the Emacs primitives. Enabling or disabling
5931 the cache should not affect the behavior of any of the motion
5932 functions; it should only affect their performance. */);
5934 DEFVAR_PER_BUFFER ("point-before-scroll", &BVAR (current_buffer, point_before_scroll), Qnil,
5935 doc: /* Value of point before the last series of scroll operations, or nil. */);
5937 DEFVAR_PER_BUFFER ("buffer-file-format", &BVAR (current_buffer, file_format), Qnil,
5938 doc: /* List of formats to use when saving this buffer.
5939 Formats are defined by `format-alist'. This variable is
5940 set when a file is visited. */);
5942 DEFVAR_PER_BUFFER ("buffer-auto-save-file-format",
5943 &BVAR (current_buffer, auto_save_file_format), Qnil,
5944 doc: /* Format in which to write auto-save files.
5945 Should be a list of symbols naming formats that are defined in `format-alist'.
5946 If it is t, which is the default, auto-save files are written in the
5947 same format as a regular save would use. */);
5949 DEFVAR_PER_BUFFER ("buffer-invisibility-spec",
5950 &BVAR (current_buffer, invisibility_spec), Qnil,
5951 doc: /* Invisibility spec of this buffer.
5952 The default is t, which means that text is invisible
5953 if it has a non-nil `invisible' property.
5954 If the value is a list, a text character is invisible if its `invisible'
5955 property is an element in that list (or is a list with members in common).
5956 If an element is a cons cell of the form (PROP . ELLIPSIS),
5957 then characters with property value PROP are invisible,
5958 and they have an ellipsis as well if ELLIPSIS is non-nil. */);
5960 DEFVAR_PER_BUFFER ("buffer-display-count",
5961 &BVAR (current_buffer, display_count), Qnil,
5962 doc: /* A number incremented each time this buffer is displayed in a window.
5963 The function `set-window-buffer' increments it. */);
5965 DEFVAR_PER_BUFFER ("buffer-display-time",
5966 &BVAR (current_buffer, display_time), Qnil,
5967 doc: /* Time stamp updated each time this buffer is displayed in a window.
5968 The function `set-window-buffer' updates this variable
5969 to the value obtained by calling `current-time'.
5970 If the buffer has never been shown in a window, the value is nil. */);
5972 DEFVAR_LISP ("transient-mark-mode", Vtransient_mark_mode,
5973 doc: /* Non-nil if Transient Mark mode is enabled.
5974 See the command `transient-mark-mode' for a description of this minor mode.
5976 Non-nil also enables highlighting of the region whenever the mark is active.
5977 The variable `highlight-nonselected-windows' controls whether to highlight
5978 all windows or just the selected window.
5980 Lisp programs may give this variable certain special values:
5982 - A value of `lambda' enables Transient Mark mode temporarily.
5983 It is disabled again after any subsequent action that would
5984 normally deactivate the mark (e.g. buffer modification).
5986 - A value of (only . OLDVAL) enables Transient Mark mode
5987 temporarily. After any subsequent point motion command that is
5988 not shift-translated, or any other action that would normally
5989 deactivate the mark (e.g. buffer modification), the value of
5990 `transient-mark-mode' is set to OLDVAL. */);
5991 Vtransient_mark_mode = Qnil;
5993 DEFVAR_LISP ("inhibit-read-only", Vinhibit_read_only,
5994 doc: /* Non-nil means disregard read-only status of buffers or characters.
5995 If the value is t, disregard `buffer-read-only' and all `read-only'
5996 text properties. If the value is a list, disregard `buffer-read-only'
5997 and disregard a `read-only' text property if the property value
5998 is a member of the list. */);
5999 Vinhibit_read_only = Qnil;
6001 DEFVAR_PER_BUFFER ("cursor-type", &BVAR (current_buffer, cursor_type), Qnil,
6002 doc: /* Cursor to use when this buffer is in the selected window.
6003 Values are interpreted as follows:
6005 t use the cursor specified for the frame
6006 nil don't display a cursor
6007 box display a filled box cursor
6008 hollow display a hollow box cursor
6009 bar display a vertical bar cursor with default width
6010 (bar . WIDTH) display a vertical bar cursor with width WIDTH
6011 hbar display a horizontal bar cursor with default height
6012 (hbar . HEIGHT) display a horizontal bar cursor with height HEIGHT
6013 ANYTHING ELSE display a hollow box cursor
6015 When the buffer is displayed in a non-selected window, the
6016 cursor's appearance is instead controlled by the variable
6017 `cursor-in-non-selected-windows'. */);
6019 DEFVAR_PER_BUFFER ("line-spacing",
6020 &BVAR (current_buffer, extra_line_spacing), Qnil,
6021 doc: /* Additional space to put between lines when displaying a buffer.
6022 The space is measured in pixels, and put below lines on graphic displays,
6023 see `display-graphic-p'.
6024 If value is a floating point number, it specifies the spacing relative
6025 to the default frame line height. A value of nil means add no extra space. */);
6027 DEFVAR_PER_BUFFER ("cursor-in-non-selected-windows",
6028 &BVAR (current_buffer, cursor_in_non_selected_windows), Qnil,
6029 doc: /* Non-nil means show a cursor in non-selected windows.
6030 If nil, only shows a cursor in the selected window.
6031 If t, displays a cursor related to the usual cursor type
6032 \(a solid box becomes hollow, a bar becomes a narrower bar).
6033 You can also specify the cursor type as in the `cursor-type' variable.
6034 Use Custom to set this variable and update the display." */);
6036 DEFVAR_LISP ("kill-buffer-query-functions", Vkill_buffer_query_functions,
6037 doc: /* List of functions called with no args to query before killing a buffer.
6038 The buffer being killed will be current while the functions are running.
6040 If any of them returns nil, the buffer is not killed. Functions run by
6041 this hook are supposed to not change the current buffer. */);
6042 Vkill_buffer_query_functions = Qnil;
6044 DEFVAR_LISP ("change-major-mode-hook", Vchange_major_mode_hook,
6045 doc: /* Normal hook run before changing the major mode of a buffer.
6046 The function `kill-all-local-variables' runs this before doing anything else. */);
6047 Vchange_major_mode_hook = Qnil;
6048 DEFSYM (Qchange_major_mode_hook, "change-major-mode-hook");
6050 DEFVAR_LISP ("buffer-list-update-hook", Vbuffer_list_update_hook,
6051 doc: /* Hook run when the buffer list changes.
6052 Functions running this hook are `get-buffer-create',
6053 `make-indirect-buffer', `rename-buffer', `kill-buffer',
6054 and `bury-buffer-internal'. */);
6055 Vbuffer_list_update_hook = Qnil;
6056 DEFSYM (Qbuffer_list_update_hook, "buffer-list-update-hook");
6058 defsubr (&Sbuffer_live_p);
6059 defsubr (&Sbuffer_list);
6060 defsubr (&Sget_buffer);
6061 defsubr (&Sget_file_buffer);
6062 defsubr (&Sget_buffer_create);
6063 defsubr (&Smake_indirect_buffer);
6064 defsubr (&Sgenerate_new_buffer_name);
6065 defsubr (&Sbuffer_name);
6066 defsubr (&Sbuffer_file_name);
6067 defsubr (&Sbuffer_base_buffer);
6068 defsubr (&Sbuffer_local_value);
6069 defsubr (&Sbuffer_local_variables);
6070 defsubr (&Sbuffer_modified_p);
6071 defsubr (&Sset_buffer_modified_p);
6072 defsubr (&Sbuffer_modified_tick);
6073 defsubr (&Sbuffer_chars_modified_tick);
6074 defsubr (&Srename_buffer);
6075 defsubr (&Sother_buffer);
6076 defsubr (&Sbuffer_enable_undo);
6077 defsubr (&Skill_buffer);
6078 defsubr (&Sbury_buffer_internal);
6079 defsubr (&Sset_buffer_major_mode);
6080 defsubr (&Scurrent_buffer);
6081 defsubr (&Sset_buffer);
6082 defsubr (&Sbarf_if_buffer_read_only);
6083 defsubr (&Serase_buffer);
6084 defsubr (&Sbuffer_swap_text);
6085 defsubr (&Sset_buffer_multibyte);
6086 defsubr (&Skill_all_local_variables);
6088 defsubr (&Soverlayp);
6089 defsubr (&Smake_overlay);
6090 defsubr (&Sdelete_overlay);
6091 defsubr (&Smove_overlay);
6092 defsubr (&Soverlay_start);
6093 defsubr (&Soverlay_end);
6094 defsubr (&Soverlay_buffer);
6095 defsubr (&Soverlay_properties);
6096 defsubr (&Soverlays_at);
6097 defsubr (&Soverlays_in);
6098 defsubr (&Snext_overlay_change);
6099 defsubr (&Sprevious_overlay_change);
6100 defsubr (&Soverlay_recenter);
6101 defsubr (&Soverlay_lists);
6102 defsubr (&Soverlay_get);
6103 defsubr (&Soverlay_put);
6104 defsubr (&Srestore_buffer_modified_p);
6107 void
6108 keys_of_buffer (void)
6110 initial_define_key (control_x_map, 'b', "switch-to-buffer");
6111 initial_define_key (control_x_map, 'k', "kill-buffer");
6113 /* This must not be in syms_of_buffer, because Qdisabled is not
6114 initialized when that function gets called. */
6115 Fput (intern_c_string ("erase-buffer"), Qdisabled, Qt);