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