Coverity: UNINIT: CID 395
[sxemacs] / src / extents.c
1 /* Copyright (c) 1994, 1995 Free Software Foundation, Inc.
2    Copyright (c) 1995 Sun Microsystems, Inc.
3    Copyright (c) 1995, 1996, 2000 Ben Wing.
4
5 This file is part of SXEmacs
6
7 SXEmacs 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 SXEmacs 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 this program.  If not, see <http://www.gnu.org/licenses/>. */
19
20
21 /* Synched up with: Not in FSF. */
22
23 /* This file has been Mule-ized. */
24
25 /* Written by Ben Wing <ben@xemacs.org>.
26
27    [Originally written by some people at Lucid.
28    Hacked on by jwz.
29    Start/end-open stuff added by John Rose (john.rose@eng.sun.com).
30    Rewritten from scratch by Ben Wing, December 1994.] */
31
32 /* Commentary:
33
34    Extents are regions over a buffer, with a start and an end position
35    denoting the region of the buffer included in the extent.  In
36    addition, either end can be closed or open, meaning that the endpoint
37    is or is not logically included in the extent.  Insertion of a character
38    at a closed endpoint causes the character to go inside the extent;
39    insertion at an open endpoint causes the character to go outside.
40
41    Extent endpoints are stored using memory indices (see insdel.c),
42    to minimize the amount of adjusting that needs to be done when
43    characters are inserted or deleted.
44
45    (Formerly, extent endpoints at the gap could be either before or
46    after the gap, depending on the open/closedness of the endpoint.
47    The intent of this was to make it so that insertions would
48    automatically go inside or out of extents as necessary with no
49    further work needing to be done.  It didn't work out that way,
50    however, and just ended up complexifying and buggifying all the
51    rest of the code.)
52
53    Extents are compared using memory indices.  There are two orderings
54    for extents and both orders are kept current at all times.  The normal
55    or "display" order is as follows:
56
57    Extent A is "less than" extent B, that is, earlier in the display order,
58    if:    A-start < B-start,
59    or if: A-start = B-start, and A-end > B-end
60
61    So if two extents begin at the same position, the larger of them is the
62    earlier one in the display order (EXTENT_LESS is true).
63
64    For the e-order, the same thing holds: Extent A is "less than" extent B
65    in e-order, that is, later in the buffer,
66    if:    A-end < B-end,
67    or if: A-end = B-end, and A-start > B-start
68
69    So if two extents end at the same position, the smaller of them is the
70    earlier one in the e-order (EXTENT_E_LESS is true).
71
72    The display order and the e-order are complementary orders: any
73    theorem about the display order also applies to the e-order if you
74    swap all occurrences of "display order" and "e-order", "less than"
75    and "greater than", and "extent start" and "extent end".
76
77    Extents can be zero-length, and will end up that way if their endpoints
78    are explicitly set that way or if their detachable property is nil
79    and all the text in the extent is deleted. (The exception is open-open
80    zero-length extents, which are barred from existing because there is
81    no sensible way to define their properties.  Deletion of the text in
82    an open-open extent causes it to be converted into a closed-open
83    extent.)  Zero-length extents are primarily used to represent
84    annotations, and behave as follows:
85
86    1) Insertion at the position of a zero-length extent expands the extent
87    if both endpoints are closed; goes after the extent if it is closed-open;
88    and goes before the extent if it is open-closed.
89
90    2) Deletion of a character on a side of a zero-length extent whose
91    corresponding endpoint is closed causes the extent to be detached if
92    it is detachable; if the extent is not detachable or the corresponding
93    endpoint is open, the extent remains in the buffer, moving as necessary.
94
95    Note that closed-open, non-detachable zero-length extents behave exactly
96    like markers and that open-closed, non-detachable zero-length extents
97    behave like the "point-type" marker in Mule.
98
99    #### The following information is wrong in places.
100
101    More about the different orders:
102    --------------------------------
103
104    The extents in a buffer are ordered by "display order" because that
105    is that order that the redisplay mechanism needs to process them in.
106    The e-order is an auxiliary ordering used to facilitate operations
107    over extents.  The operations that can be performed on the ordered
108    list of extents in a buffer are
109
110    1) Locate where an extent would go if inserted into the list.
111    2) Insert an extent into the list.
112    3) Remove an extent from the list.
113    4) Map over all the extents that overlap a range.
114
115    (4) requires being able to determine the first and last extents
116    that overlap a range.
117
118    NOTE: "overlap" is used as follows:
119
120    -- two ranges overlap if they have at least one point in common.
121       Whether the endpoints are open or closed makes a difference here.
122    -- a point overlaps a range if the point is contained within the
123       range; this is equivalent to treating a point P as the range
124       [P, P].
125    -- In the case of an *extent* overlapping a point or range, the
126       extent is normally treated as having closed endpoints.  This
127       applies consistently in the discussion of stacks of extents
128       and such below.  Note that this definition of overlap is not
129       necessarily consistent with the extents that `map-extents'
130       maps over, since `map-extents' sometimes pays attention to
131       whether the endpoints of an extents are open or closed.
132       But for our purposes, it greatly simplifies things to treat
133       all extents as having closed endpoints.
134
135    First, define >, <, <=, etc. as applied to extents to mean
136      comparison according to the display order.  Comparison between an
137      extent E and an index I means comparison between E and the range
138      [I, I].
139    Also define e>, e<, e<=, etc. to mean comparison according to the
140      e-order.
141    For any range R, define R(0) to be the starting index of the range
142      and R(1) to be the ending index of the range.
143    For any extent E, define E(next) to be the extent directly following
144      E, and E(prev) to be the extent directly preceding E.  Assume
145      E(next) and E(prev) can be determined from E in constant time.
146      (This is because we store the extent list as a doubly linked
147      list.)
148    Similarly, define E(e-next) and E(e-prev) to be the extents
149      directly following and preceding E in the e-order.
150
151    Now:
152
153    Let R be a range.
154    Let F be the first extent overlapping R.
155    Let L be the last extent overlapping R.
156
157    Theorem 1: R(1) lies between L and L(next), i.e. L <= R(1) < L(next).
158
159    This follows easily from the definition of display order.  The
160    basic reason that this theorem applies is that the display order
161    sorts by increasing starting index.
162
163    Therefore, we can determine L just by looking at where we would
164    insert R(1) into the list, and if we know F and are moving forward
165    over extents, we can easily determine when we've hit L by comparing
166    the extent we're at to R(1).
167
168    Theorem 2: F(e-prev) e< [1, R(0)] e<= F.
169
170    This is the analog of Theorem 1, and applies because the e-order
171    sorts by increasing ending index.
172
173    Therefore, F can be found in the same amount of time as operation (1),
174    i.e. the time that it takes to locate where an extent would go if
175    inserted into the e-order list.
176
177    If the lists were stored as balanced binary trees, then operation (1)
178    would take logarithmic time, which is usually quite fast.  However,
179    currently they're stored as simple doubly-linked lists, and instead
180    we do some caching to try to speed things up.
181
182    Define a "stack of extents" (or "SOE") as the set of extents
183    (ordered in the display order) that overlap an index I, together with
184    the SOE's "previous" extent, which is an extent that precedes I in
185    the e-order. (Hopefully there will not be very many extents between
186    I and the previous extent.)
187
188    Now:
189
190    Let I be an index, let S be the stack of extents on I, let F be
191    the first extent in S, and let P be S's previous extent.
192
193    Theorem 3: The first extent in S is the first extent that overlaps
194    any range [I, J].
195
196    Proof: Any extent that overlaps [I, J] but does not include I must
197    have a start index > I, and thus be greater than any extent in S.
198
199    Therefore, finding the first extent that overlaps a range R is the
200    same as finding the first extent that overlaps R(0).
201
202    Theorem 4: Let I2 be an index such that I2 > I, and let F2 be the
203    first extent that overlaps I2.  Then, either F2 is in S or F2 is
204    greater than any extent in S.
205
206    Proof: If F2 does not include I then its start index is greater
207    than I and thus it is greater than any extent in S, including F.
208    Otherwise, F2 includes I and thus is in S, and thus F2 >= F.
209
210 */
211
212 #include <config.h>
213 #include "lisp.h"
214
215 #include "buffer.h"
216 #include "debug.h"
217 #include "ui/device.h"
218 #include "elhash.h"
219 #include "extents.h"
220 #include "ui/faces.h"
221 #include "ui/frame.h"
222 #include "ui/glyphs.h"
223 #include "ui/insdel.h"
224 #include "ui/keymap.h"
225 #include "opaque.h"
226 #include "process.h"
227 #include "ui/redisplay.h"
228 #include "ui/gutter.h"
229
230 /* ------------------------------- */
231 /*            gap array            */
232 /* ------------------------------- */
233
234 /* Note that this object is not extent-specific and should perhaps be
235    moved into another file. */
236
237 typedef struct gap_array_marker_s *gap_array_marker_t;
238 typedef struct gap_array_s *gap_array_t;
239
240 /* Holds a marker that moves as elements in the array are inserted and
241    deleted, similar to standard markers. */
242
243 struct gap_array_marker_s {
244         int pos;
245         gap_array_marker_t next;
246 };
247
248 /* Holds a "gap array", which is an array of elements with a gap located
249    in it.  Insertions and deletions with a high degree of locality
250    are very fast, essentially in constant time.  Array positions as
251    used and returned in the gap array functions are independent of
252    the gap. */
253
254 struct gap_array_s {
255         char *array;
256         int gap;
257         int gapsize;
258         int numels;
259         int elsize;
260         gap_array_marker_t markers;
261 };
262
263 #if !defined HAVE_BDWGC || !defined EF_USE_BDWGC
264 static gap_array_marker_t gap_array_marker_freelist;
265 #endif  /* !BDWGC */
266
267 /* Convert a "memory position" (i.e. taking the gap into account) into
268    the address of the element at (i.e. after) that position.  "Memory
269    positions" are only used internally and are of type Memind.
270    "Array positions" are used externally and are of type int. */
271 #define GAP_ARRAY_MEMEL_ADDR(ga, memel) ((ga)->array + (ga)->elsize*(memel))
272
273 /* Number of elements currently in a gap array */
274 #define GAP_ARRAY_NUM_ELS(ga) ((ga)->numels)
275
276 #define GAP_ARRAY_ARRAY_TO_MEMORY_POS(ga, pos)                  \
277         ((pos) <= (ga)->gap ? (pos) : (pos) + (ga)->gapsize)
278
279 #define GAP_ARRAY_MEMORY_TO_ARRAY_POS(ga, pos)                  \
280         ((pos) <= (ga)->gap ? (pos) : (pos) - (ga)->gapsize)
281
282 /* Convert an array position into the address of the element at
283    (i.e. after) that position. */
284 #define GAP_ARRAY_EL_ADDR(ga, pos)                                      \
285         ((pos) < (ga)->gap                                              \
286          ? GAP_ARRAY_MEMEL_ADDR(ga, pos)                                \
287          : GAP_ARRAY_MEMEL_ADDR(ga, (pos) + (ga)->gapsize))
288
289 /* ------------------------------- */
290 /*          extent list            */
291 /* ------------------------------- */
292
293 typedef struct extent_list_marker_s *extent_list_marker_t;
294 typedef struct extent_list_s *extent_list_t;
295
296 struct extent_list_marker_s {
297         gap_array_marker_t m;
298         int endp;
299         extent_list_marker_t next;
300 };
301
302 struct extent_list_s {
303         gap_array_t start;
304         gap_array_t end;
305         extent_list_marker_t markers;
306 };
307
308 #if !defined HAVE_BDWGC || !defined EF_USE_BDWGC
309 static extent_list_marker_t extent_list_marker_freelist;
310 #endif  /* !BDWGC */
311
312 #define EXTENT_LESS_VALS(e,st,nd)               \
313         ((extent_start (e) < (st)) ||           \
314          ((extent_start (e) == (st)) &&         \
315           (extent_end (e) > (nd))))
316
317 #define EXTENT_EQUAL_VALS(e,st,nd)              \
318         ((extent_start (e) == (st)) &&          \
319          (extent_end (e) == (nd)))
320
321 #define EXTENT_LESS_EQUAL_VALS(e,st,nd)         \
322         ((extent_start (e) < (st)) ||           \
323          ((extent_start (e) == (st)) &&         \
324           (extent_end (e) >= (nd))))
325
326 /* Is extent E1 less than extent E2 in the display order? */
327 #define EXTENT_LESS(e1,e2)                                              \
328         EXTENT_LESS_VALS (e1, extent_start (e2), extent_end (e2))
329
330 /* Is extent E1 equal to extent E2? */
331 #define EXTENT_EQUAL(e1,e2)                                             \
332         EXTENT_EQUAL_VALS (e1, extent_start (e2), extent_end (e2))
333
334 /* Is extent E1 less than or equal to extent E2 in the display order? */
335 #define EXTENT_LESS_EQUAL(e1,e2)                                        \
336         EXTENT_LESS_EQUAL_VALS (e1, extent_start (e2), extent_end (e2))
337
338 #define EXTENT_E_LESS_VALS(e,st,nd)             \
339         ((extent_end (e) < (nd)) ||             \
340          ((extent_end (e) == (nd)) &&           \
341           (extent_start (e) > (st))))
342
343 #define EXTENT_E_LESS_EQUAL_VALS(e,st,nd)       \
344         ((extent_end (e) < (nd)) ||             \
345          ((extent_end (e) == (nd)) &&           \
346           (extent_start (e) >= (st))))
347
348 /* Is extent E1 less than extent E2 in the e-order? */
349 #define EXTENT_E_LESS(e1,e2)                                            \
350         EXTENT_E_LESS_VALS(e1, extent_start (e2), extent_end (e2))
351
352 /* Is extent E1 less than or equal to extent E2 in the e-order? */
353 #define EXTENT_E_LESS_EQUAL(e1,e2)                                      \
354         EXTENT_E_LESS_EQUAL_VALS (e1, extent_start (e2), extent_end (e2))
355
356 #define EXTENT_GAP_ARRAY_AT(ga, pos) (*(EXTENT*)GAP_ARRAY_EL_ADDR(ga, pos))
357
358 /* ------------------------------- */
359 /*    auxiliary extent structure   */
360 /* ------------------------------- */
361
362 struct extent_auxiliary extent_auxiliary_defaults;
363
364 /* ------------------------------- */
365 /*     buffer-extent primitives    */
366 /* ------------------------------- */
367 typedef struct extent_stack_s *extent_stack_t;
368
369 struct extent_stack_s {
370         extent_list_t extents;
371         /* Position of stack of extents.  EXTENTS is the list of
372            all extents that overlap this position.  This position
373            can be -1 if the stack of extents is invalid (this
374            happens when a buffer is first created or a string's
375            stack of extents is created [a string's stack of extents
376            is nuked when a GC occurs, to conserve memory]). */
377         Memind pos;
378 };
379
380 /* ------------------------------- */
381 /*           map-extents           */
382 /* ------------------------------- */
383
384 typedef int Endpoint_Index;
385
386 #define memind_to_startind(x, start_open)               \
387         ((Endpoint_Index) (((x) << 1) + !!(start_open)))
388 #define memind_to_endind(x, end_open)                   \
389         ((Endpoint_Index) (((x) << 1) - !!(end_open)))
390
391 /* Combination macros */
392 #define bytind_to_startind(buf, x, start_open)                  \
393         memind_to_startind (bytind_to_memind (buf, x), start_open)
394 #define bytind_to_endind(buf, x, end_open)                      \
395         memind_to_endind (bytind_to_memind (buf, x), end_open)
396
397 /* ------------------------------- */
398 /*    buffer-or-string primitives  */
399 /* ------------------------------- */
400
401 /* Similar for Bytinds and start/end indices. */
402
403 #define buffer_or_string_bytind_to_startind(obj, ind, start_open)       \
404         memind_to_startind(buffer_or_string_bytind_to_memind (obj, ind), \
405                            start_open)
406
407 #define buffer_or_string_bytind_to_endind(obj, ind, end_open)           \
408         memind_to_endind(buffer_or_string_bytind_to_memind (obj, ind),  \
409                          end_open)
410
411 /* ------------------------------- */
412 /*      Lisp-level functions       */
413 /* ------------------------------- */
414
415 /* flags for decode_extent() */
416 #define DE_MUST_HAVE_BUFFER 1
417 #define DE_MUST_BE_ATTACHED 2
418
419 Lisp_Object Vlast_highlighted_extent;
420 Fixnum mouse_highlight_priority;
421
422 Lisp_Object Qextentp;
423 Lisp_Object Qextent_live_p;
424
425 Lisp_Object Qall_extents_closed;
426 Lisp_Object Qall_extents_open;
427 Lisp_Object Qall_extents_closed_open;
428 Lisp_Object Qall_extents_open_closed;
429 Lisp_Object Qstart_in_region;
430 Lisp_Object Qend_in_region;
431 Lisp_Object Qstart_and_end_in_region;
432 Lisp_Object Qstart_or_end_in_region;
433 Lisp_Object Qnegate_in_region;
434
435 Lisp_Object Qdetached;
436 Lisp_Object Qdestroyed;
437 Lisp_Object Qbegin_glyph;
438 Lisp_Object Qend_glyph;
439 Lisp_Object Qstart_open;
440 Lisp_Object Qend_open;
441 Lisp_Object Qstart_closed;
442 Lisp_Object Qend_closed;
443 Lisp_Object Qread_only;
444 /* Qhighlight defined in general.c */
445 Lisp_Object Qunique;
446 Lisp_Object Qduplicable;
447 Lisp_Object Qdetachable;
448 Lisp_Object Qpriority;
449 Lisp_Object Qmouse_face;
450 Lisp_Object Qinitial_redisplay_function;
451
452 /* This exists only for backwards compatibility. */
453 Lisp_Object Qglyph_layout;
454 Lisp_Object Qbegin_glyph_layout, Qend_glyph_layout;
455 Lisp_Object Qoutside_margin;
456 Lisp_Object Qinside_margin;
457 Lisp_Object Qwhitespace;
458 /* Qtext defined in general.c */
459
460 Lisp_Object Qcopy_function;
461 Lisp_Object Qpaste_function;
462
463 /* The idea here is that if we're given a list of faces, we
464    need to "memoize" this so that two lists of faces that are `equal'
465    turn into the same object.  When `set-extent-face' is called, we
466    "memoize" into a list of actual faces; when `extent-face' is called,
467    we do a reverse lookup to get the list of symbols. */
468
469 static Lisp_Object canonicalize_extent_property(Lisp_Object prop,
470                                                 Lisp_Object value);
471 Lisp_Object Vextent_face_memoize_hash_table;
472 Lisp_Object Vextent_face_reverse_memoize_hash_table;
473 Lisp_Object Vextent_face_reusable_list;
474 /* FSFmacs bogosity */
475 Lisp_Object Vdefault_text_properties;
476
477 EXFUN(Fextent_properties, 1);
478 EXFUN(Fset_extent_property, 3);
479
480 /* if true, we don't want to set any redisplay flags on modeline extent
481    changes */
482 int in_modeline_generation;
483 \f
484 /************************************************************************/
485 /*                       Generalized gap array                          */
486 /************************************************************************/
487
488 /* This generalizes the "array with a gap" model used to store buffer
489    characters.  This is based on the stuff in insdel.c and should
490    probably be merged with it.  This is not extent-specific and should
491    perhaps be moved into a separate file. */
492
493 /* ------------------------------- */
494 /*        internal functions       */
495 /* ------------------------------- */
496
497 /* Adjust the gap array markers in the range (FROM, TO].  Parallel to
498    adjust_markers() in insdel.c. */
499
500 static void
501 gap_array_adjust_markers(gap_array_t ga, Memind from, Memind to, int amount)
502 {
503         gap_array_marker_t m;
504
505         for (m = ga->markers; m; m = m->next) {
506                 m->pos = do_marker_adjustment(m->pos, from, to, amount);
507         }
508         return;
509 }
510
511 /* Move the gap to array position POS.  Parallel to move_gap() in
512    insdel.c but somewhat simplified. */
513
514 static void
515 gap_array_move_gap(gap_array_t ga, int pos)
516 {
517         int gap = ga->gap;
518         int gapsize = ga->gapsize;
519
520         assert(ga->array);
521         if (pos < gap) {
522                 memmove(GAP_ARRAY_MEMEL_ADDR(ga, pos + gapsize),
523                         GAP_ARRAY_MEMEL_ADDR(ga, pos),
524                         (gap - pos) * ga->elsize);
525                 gap_array_adjust_markers(ga, (Memind) pos, (Memind) gap,
526                                          gapsize);
527         } else if (pos > gap) {
528                 memmove(GAP_ARRAY_MEMEL_ADDR(ga, gap),
529                         GAP_ARRAY_MEMEL_ADDR(ga, gap + gapsize),
530                         (pos - gap) * ga->elsize);
531                 gap_array_adjust_markers(ga, (Memind) (gap + gapsize),
532                                          (Memind) (pos + gapsize), -gapsize);
533         }
534         ga->gap = pos;
535         return;
536 }
537
538 /* Make the gap INCREMENT characters longer.  Parallel to make_gap() in
539    insdel.c. */
540
541 static void
542 gap_array_make_gap(gap_array_t ga, int increment)
543 {
544         char *ptr = ga->array;
545         int real_gap_loc;
546         int old_gap_size;
547
548         /* If we have to get more space, get enough to last a while.  We use
549            a geometric progression that saves on realloc space. */
550         increment += 100 + ga->numels / 8;
551
552         ptr = (char*)xrealloc(ptr,
553                               (ga->numels + ga->gapsize +
554                                increment) * ga->elsize);
555         if (ptr == 0) {
556                 memory_full();
557         }
558         ga->array = ptr;
559
560         real_gap_loc = ga->gap;
561         old_gap_size = ga->gapsize;
562
563         /* Call the newly allocated space a gap at the end of the whole
564            space.  */
565         ga->gap = ga->numels + ga->gapsize;
566         ga->gapsize = increment;
567
568         /* Move the new gap down to be consecutive with the end of the old one.
569            This adjusts the markers properly too.  */
570         gap_array_move_gap(ga, real_gap_loc + old_gap_size);
571
572         /* Now combine the two into one large gap.  */
573         ga->gapsize += old_gap_size;
574         ga->gap = real_gap_loc;
575         return;
576 }
577
578 /* ------------------------------- */
579 /*        external functions       */
580 /* ------------------------------- */
581
582 /* Insert NUMELS elements (pointed to by ELPTR) into the specified
583    gap array at POS. */
584
585 static void
586 gap_array_insert_els(gap_array_t ga, int pos, void *elptr, int numels)
587 {
588         assert(pos >= 0 && pos <= ga->numels);
589         if (ga->gapsize < numels) {
590                 gap_array_make_gap(ga, numels - ga->gapsize);
591         }
592         if (pos != ga->gap) {
593                 gap_array_move_gap(ga, pos);
594         }
595         memcpy(GAP_ARRAY_MEMEL_ADDR(ga, ga->gap), (char *)elptr,
596                numels * ga->elsize);
597         ga->gapsize -= numels;
598         ga->gap += numels;
599         ga->numels += numels;
600         /* This is the equivalent of insert-before-markers.
601
602            #### Should only happen if marker is "moves forward at insert" type.
603          */
604
605         gap_array_adjust_markers(ga, pos - 1, pos, numels);
606         return;
607 }
608
609 /* Delete NUMELS elements from the specified gap array, starting at FROM. */
610
611 static void
612 gap_array_delete_els(gap_array_t ga, int from, int numdel)
613 {
614         int to = from + numdel;
615         int gapsize = ga->gapsize;
616
617         assert(from >= 0);
618         assert(numdel >= 0);
619         assert(to <= ga->numels);
620
621         /* Make sure the gap is somewhere in or next to what we are deleting.  */
622         if (to < ga->gap) {
623                 gap_array_move_gap(ga, to);
624         }
625         if (from > ga->gap) {
626                 gap_array_move_gap(ga, from);
627         }
628         /* Relocate all markers pointing into the new, larger gap
629            to point at the end of the text before the gap.  */
630         gap_array_adjust_markers(ga, to + gapsize, to + gapsize,
631                                  -numdel - gapsize);
632
633         ga->gapsize += numdel;
634         ga->numels -= numdel;
635         ga->gap = from;
636         return;
637 }
638
639 static gap_array_marker_t
640 gap_array_make_marker(gap_array_t ga, int pos)
641 {
642         gap_array_marker_t m;
643
644         assert(pos >= 0 && pos <= ga->numels);
645 #if defined HAVE_BDWGC && defined EF_USE_BDWGC
646         m = xnew(struct gap_array_marker_s);
647 #else  /* !BDWGC */
648         if (gap_array_marker_freelist) {
649                 m = gap_array_marker_freelist;
650                 gap_array_marker_freelist = gap_array_marker_freelist->next;
651         } else {
652                 m = xnew(struct gap_array_marker_s);
653         }
654 #endif  /* BDWGC */
655
656         m->pos = GAP_ARRAY_ARRAY_TO_MEMORY_POS(ga, pos);
657         m->next = ga->markers;
658         ga->markers = m;
659         return m;
660 }
661
662 static void
663 gap_array_delete_marker(gap_array_t ga, gap_array_marker_t m)
664 {
665         volatile gap_array_marker_t p, prev;
666
667         for (prev = 0, p = ga->markers; p && p != m; prev = p, p = p->next);
668         if (UNLIKELY(p == NULL)) {
669                 return;
670         }
671         assert(p);
672         if (prev) {
673                 prev->next = p->next;
674         } else {
675                 ga->markers = p->next;
676         }
677 #if defined HAVE_BDWGC && defined EF_USE_BDWGC
678         xfree(m);
679 #else  /* !BDWGC */
680         m->next = gap_array_marker_freelist;
681         m->pos = 0xDEADBEEF;
682         gap_array_marker_freelist = m;
683 #endif  /* BDWGC */
684         return;
685 }
686
687 static void
688 gap_array_delete_all_markers(gap_array_t ga)
689 {
690         for (volatile gap_array_marker_t p = ga->markers, next; p; p = next) {
691                 next = p->next;
692 #if defined HAVE_BDWGC && defined EF_USE_BDWGC
693                 xfree(p);
694 #else  /* !BDWGC */
695                 p->next = gap_array_marker_freelist;
696                 p->pos = 0xDEADBEEF;
697                 gap_array_marker_freelist = p;
698 #endif  /* BDWGC */
699         }
700         ga->markers = NULL;
701         return;
702 }
703
704 static void
705 gap_array_move_marker(gap_array_t ga, gap_array_marker_t m, int pos)
706 {
707         assert(pos >= 0 && pos <= ga->numels);
708         m->pos = GAP_ARRAY_ARRAY_TO_MEMORY_POS(ga, pos);
709 }
710
711 #define gap_array_marker_pos(ga, m)                     \
712         GAP_ARRAY_MEMORY_TO_ARRAY_POS (ga, (m)->pos)
713
714 static gap_array_t
715 make_gap_array(int elsize)
716 {
717         gap_array_t ga = xnew_and_zero(struct gap_array_s);
718         ga->elsize = elsize;
719         return ga;
720 }
721
722 static void
723 free_gap_array(gap_array_t ga)
724 {
725         if (ga->array) {
726                 xfree(ga->array);
727         }
728         gap_array_delete_all_markers(ga);
729         xfree(ga);
730         return;
731 }
732 \f
733 /************************************************************************/
734 /*                       Extent list primitives                         */
735 /************************************************************************/
736
737 /* A list of extents is maintained as a double gap array: one gap array
738    is ordered by start index (the "display order") and the other is
739    ordered by end index (the "e-order").  Note that positions in an
740    extent list should logically be conceived of as referring *to*
741    a particular extent (as is the norm in programs) rather than
742    sitting between two extents.  Note also that callers of these
743    functions should not be aware of the fact that the extent list is
744    implemented as an array, except for the fact that positions are
745    integers (this should be generalized to handle integers and linked
746    list equally well).
747 */
748
749 /* Number of elements in an extent list */
750 #define extent_list_num_els(el) GAP_ARRAY_NUM_ELS(el->start)
751
752 /* Return the position at which EXTENT is located in the specified extent
753    list (in the display order if ENDP is 0, in the e-order otherwise).
754    If the extent is not found, the position where the extent would
755    be inserted is returned.  If ENDP is 0, the insertion would go after
756    all other equal extents.  If ENDP is not 0, the insertion would go
757    before all other equal extents.  If FOUNDP is not 0, then whether
758    the extent was found will get written into it. */
759
760 static int
761 extent_list_locate(extent_list_t el, EXTENT extent, int endp, bool *foundp)
762 {
763         gap_array_t ga = endp ? el->end : el->start;
764         int left = 0, right = GAP_ARRAY_NUM_ELS(ga);
765         int oldfoundpos, foundpos;
766         bool found;
767
768         while (left != right) {
769                 /* RIGHT might not point to a valid extent (i.e. it's at the end
770                    of the list), so NEWPOS must round down. */
771                 unsigned int newpos = (left + right) >> 1;
772                 EXTENT e = EXTENT_GAP_ARRAY_AT(ga, (int)newpos);
773
774                 if (endp ? EXTENT_E_LESS(e, extent) : EXTENT_LESS(e, extent)) {
775                         left = newpos + 1;
776                 } else {
777                         right = newpos;
778                 }
779         }
780
781         /* Now we're at the beginning of all equal extents. */
782         found = false;
783         oldfoundpos = foundpos = left;
784         while (foundpos < GAP_ARRAY_NUM_ELS(ga)) {
785                 EXTENT e = EXTENT_GAP_ARRAY_AT(ga, foundpos);
786                 if (e == extent) {
787                         found = 1;
788                         break;
789                 }
790                 if (!EXTENT_EQUAL(e, extent)) {
791                         break;
792                 }
793                 foundpos++;
794         }
795         if (foundp) {
796                 *foundp = found;
797         }
798         if (found || !endp) {
799                 return foundpos;
800         } else {
801                 return oldfoundpos;
802         }
803 }
804
805 /* Return the position of the first extent that begins at or after POS
806    (or ends at or after POS, if ENDP is not 0).
807
808    An out-of-range value for POS is allowed, and guarantees that the
809    position at the beginning or end of the extent list is returned. */
810
811 static int
812 extent_list_locate_from_pos(extent_list_t el, Memind pos, int endp)
813 {
814         struct extent fake_extent;
815         /*
816
817            Note that if we search for [POS, POS], then we get the following:
818
819            -- if ENDP is 0, then all extents whose start position is <= POS
820            lie before the returned position, and all extents whose start
821            position is > POS lie at or after the returned position.
822
823            -- if ENDP is not 0, then all extents whose end position is < POS
824            lie before the returned position, and all extents whose end
825            position is >= POS lie at or after the returned position.
826
827          */
828         set_extent_start(&fake_extent, endp ? pos : pos - 1);
829         set_extent_end(&fake_extent, endp ? pos : pos - 1);
830         return extent_list_locate(el, &fake_extent, endp, 0);
831 }
832
833 /* Return the extent at POS. */
834
835 static EXTENT
836 extent_list_at(extent_list_t el, Memind pos, int endp)
837 {
838         gap_array_t ga = endp ? el->end : el->start;
839
840         assert(pos >= 0 && pos < GAP_ARRAY_NUM_ELS(ga));
841         return EXTENT_GAP_ARRAY_AT(ga, pos);
842 }
843
844 /* Insert an extent into an extent list. */
845
846 static void
847 extent_list_insert(extent_list_t el, EXTENT extent)
848 {
849         int pos;
850         bool foundp;
851
852         pos = extent_list_locate(el, extent, 0, &foundp);
853         assert(!foundp);
854         gap_array_insert_els(el->start, pos, &extent, 1);
855         pos = extent_list_locate(el, extent, 1, &foundp);
856         assert(!foundp);
857         gap_array_insert_els(el->end, pos, &extent, 1);
858         return;
859 }
860
861 /* Delete an extent from an extent list. */
862
863 static void
864 extent_list_delete(extent_list_t el, EXTENT extent)
865 {
866         int pos;
867         bool foundp;
868
869         pos = extent_list_locate(el, extent, 0, &foundp);
870         assert(foundp);
871         gap_array_delete_els(el->start, pos, 1);
872         pos = extent_list_locate(el, extent, 1, &foundp);
873         assert(foundp);
874         gap_array_delete_els(el->end, pos, 1);
875         return;
876 }
877
878 static void
879 extent_list_delete_all(extent_list_t el)
880 {
881         gap_array_delete_els(el->start, 0, GAP_ARRAY_NUM_ELS(el->start));
882         gap_array_delete_els(el->end, 0, GAP_ARRAY_NUM_ELS(el->end));
883         return;
884 }
885
886 static extent_list_marker_t
887 extent_list_make_marker(extent_list_t el, int pos, int endp)
888 {
889         extent_list_marker_t m;
890
891 #if defined HAVE_BDWGC && defined EF_USE_BDWGC
892         m = xnew(struct extent_list_marker_s);
893 #else  /* !BDWGC */
894         if (extent_list_marker_freelist) {
895                 m = extent_list_marker_freelist;
896                 extent_list_marker_freelist = extent_list_marker_freelist->next;
897         } else {
898                 m = xnew(struct extent_list_marker_s);
899         }
900 #endif  /* BDWGC */
901
902         m->m = gap_array_make_marker(endp ? el->end : el->start, pos);
903         m->endp = endp;
904         m->next = el->markers;
905         el->markers = m;
906         return m;
907 }
908
909 #define extent_list_move_marker(el, mkr, pos)                           \
910         gap_array_move_marker((mkr)->endp                               \
911                               ? (el)->end                               \
912                               : (el)->start, (mkr)->m, pos)
913
914 static void
915 extent_list_delete_marker(extent_list_t el, extent_list_marker_t m)
916 {
917         extent_list_marker_t p, prev;
918
919         for (prev = 0, p = el->markers; p && p != m; prev = p, p = p->next);
920         assert(p);
921         if (prev) {
922                 prev->next = p->next;
923         } else {
924                 el->markers = p->next;
925         }
926 #if defined HAVE_BDWGC && defined EF_USE_BDWGC
927         xfree(m);
928 #else  /* !BDWGC */
929         m->next = extent_list_marker_freelist;
930         extent_list_marker_freelist = m;
931 #endif  /* BDWGC */
932         gap_array_delete_marker(m->endp ? el->end : el->start, m->m);
933         return;
934 }
935
936 #define extent_list_marker_pos(el, mkr)                                 \
937         gap_array_marker_pos ((mkr)->endp                               \
938                               ? (el)->end                               \
939                               : (el)->start, (mkr)->m)
940
941 static extent_list_t
942 allocate_extent_list(void)
943 {
944         extent_list_t el = xnew(struct extent_list_s);
945         el->start = make_gap_array(sizeof(EXTENT));
946         el->end = make_gap_array(sizeof(EXTENT));
947         el->markers = 0;
948         return el;
949 }
950
951 static void
952 free_extent_list(extent_list_t el)
953 {
954         free_gap_array(el->start);
955         free_gap_array(el->end);
956         xfree(el);
957         return;
958 }
959 \f
960 /************************************************************************/
961 /*                       Auxiliary extent structure                     */
962 /************************************************************************/
963
964 static Lisp_Object mark_extent_auxiliary(Lisp_Object obj)
965 {
966         struct extent_auxiliary *data = XEXTENT_AUXILIARY(obj);
967         mark_object(data->begin_glyph);
968         mark_object(data->end_glyph);
969         mark_object(data->invisible);
970         mark_object(data->children);
971         mark_object(data->read_only);
972         mark_object(data->mouse_face);
973         mark_object(data->initial_redisplay_function);
974         mark_object(data->before_change_functions);
975         mark_object(data->after_change_functions);
976         return data->parent;
977 }
978
979 DEFINE_LRECORD_IMPLEMENTATION("extent-auxiliary", extent_auxiliary,
980                               mark_extent_auxiliary, internal_object_printer,
981                               0, 0, 0, 0, struct extent_auxiliary);
982
983 void allocate_extent_auxiliary(EXTENT ext)
984 {
985         Lisp_Object extent_aux;
986         struct extent_auxiliary *data =
987                 alloc_lcrecord_type(struct extent_auxiliary,
988                                     &lrecord_extent_auxiliary);
989
990         copy_lcrecord(data, &extent_auxiliary_defaults);
991         XSETEXTENT_AUXILIARY(extent_aux, data);
992         ext->plist = Fcons(extent_aux, ext->plist);
993         ext->flags.has_aux = 1;
994         return;
995 }
996 \f
997 /************************************************************************/
998 /*                         Extent info structure                        */
999 /************************************************************************/
1000
1001 /* An extent-info structure consists of a list of the buffer or string's
1002    extents and a "stack of extents" that lists all of the extents over
1003    a particular position.  The stack-of-extents info is used for
1004    optimization purposes -- it basically caches some info that might
1005    be expensive to compute.  Certain otherwise hard computations are easy
1006    given the stack of extents over a particular position, and if the
1007    stack of extents over a nearby position is known (because it was
1008    calculated at some prior point in time), it's easy to move the stack
1009    of extents to the proper position.
1010
1011    Given that the stack of extents is an optimization, and given that
1012    it requires memory, a string's stack of extents is wiped out each
1013    time a garbage collection occurs.  Therefore, any time you retrieve
1014    the stack of extents, it might not be there.  If you need it to
1015    be there, use the _force version.
1016
1017    Similarly, a string may or may not have an extent_info structure.
1018    (Generally it won't if there haven't been any extents added to the
1019    string.) So use the _force version if you need the extent_info
1020    structure to be there. */
1021
1022 static extent_stack_t allocate_soe(void);
1023 static void free_soe(extent_stack_t);
1024 static void soe_invalidate(Lisp_Object obj);
1025
1026 #if !defined HAVE_BDWGC || !defined EF_USE_BDWGC
1027 static Lisp_Object
1028 mark_extent_info(Lisp_Object obj)
1029 {
1030         struct extent_info *data = (struct extent_info *)XEXTENT_INFO(obj);
1031         int i;
1032         extent_list_t list = data->extents;
1033
1034         /* Vbuffer_defaults and Vbuffer_local_symbols are buffer-like
1035            objects that are created specially and never have their extent
1036            list initialized (or rather, it is set to zero in
1037            nuke_all_buffer_slots()).  However, these objects get
1038            garbage-collected so we have to deal.
1039
1040            (Also the list can be zero when we're dealing with a destroyed
1041            buffer.) */
1042
1043         if (list) {
1044                 for (i = 0; i < extent_list_num_els(list); i++) {
1045                         struct extent *extent = extent_list_at(list, i, 0);
1046                         Lisp_Object exobj;
1047
1048                         XSETEXTENT(exobj, extent);
1049                         mark_object(exobj);
1050                 }
1051         }
1052
1053         return Qnil;
1054 }
1055
1056 static void
1057 finalize_extent_info(void *header, int for_disksave)
1058 {
1059         struct extent_info *data = (struct extent_info *)header;
1060
1061         if (for_disksave)
1062                 return;
1063
1064         if (data->soe) {
1065                 free_soe(data->soe);
1066                 data->soe = 0;
1067         }
1068         if (data->extents) {
1069                 free_extent_list(data->extents);
1070                 data->extents = 0;
1071         }
1072 }
1073 #else  /* BDWGC */
1074 /* just define dummies */
1075 static Lisp_Object
1076 mark_extent_info(Lisp_Object SXE_UNUSED(obj))
1077 {
1078         return Qnil;
1079 }
1080
1081 static void
1082 finalize_extent_info(void *SXE_UNUSED(header), int SXE_UNUSED(for_disksave))
1083 {
1084         return;
1085 }
1086 #endif  /* !BDWGC */
1087
1088 DEFINE_LRECORD_IMPLEMENTATION("extent-info", extent_info,
1089                               mark_extent_info, internal_object_printer,
1090                               finalize_extent_info, 0, 0, 0,
1091                               struct extent_info);
1092 \f
1093 static Lisp_Object
1094 allocate_extent_info(void)
1095 {
1096         Lisp_Object extent_info;
1097         struct extent_info *data =
1098                 alloc_lcrecord_type(struct extent_info, &lrecord_extent_info);
1099
1100         XSETEXTENT_INFO(extent_info, data);
1101         data->extents = allocate_extent_list();
1102         data->soe = 0;
1103         return extent_info;
1104 }
1105
1106 void
1107 flush_cached_extent_info(Lisp_Object extent_info)
1108 {
1109         struct extent_info *data = XEXTENT_INFO(extent_info);
1110
1111         if (data->soe) {
1112                 free_soe(data->soe);
1113                 data->soe = 0;
1114         }
1115 }
1116 \f
1117 /************************************************************************/
1118 /*                    Buffer/string extent primitives                   */
1119 /************************************************************************/
1120
1121 /* The functions in this section are the ONLY ones that should know
1122    about the internal implementation of the extent lists.  Other functions
1123    should only know that there are two orderings on extents, the "display"
1124    order (sorted by start position, basically) and the e-order (sorted
1125    by end position, basically), and that certain operations are provided
1126    to manipulate the list. */
1127
1128 /* ------------------------------- */
1129 /*        basic primitives         */
1130 /* ------------------------------- */
1131
1132 static Lisp_Object
1133 decode_buffer_or_string(Lisp_Object object)
1134 {
1135         if (LIKELY(NILP(object))) {
1136                 XSETBUFFER(object, current_buffer);
1137         } else if (BUFFERP(object)) {
1138                 CHECK_LIVE_BUFFER(object);
1139         } else if (STRINGP(object)) {
1140                 ;
1141         } else {
1142                 dead_wrong_type_argument(Qbuffer_or_string_p, object);
1143         }
1144         return object;
1145 }
1146
1147 EXTENT extent_ancestor_1(EXTENT e)
1148 {
1149         while (e->flags.has_parent) {
1150                 /* There should be no circularities except in case of a logic
1151                    error somewhere in the extent code */
1152                 e = XEXTENT(XEXTENT_AUXILIARY(XCAR(e->plist))->parent);
1153         }
1154         return e;
1155 }
1156
1157 /* Given an extent object (string or buffer or nil), return its extent info.
1158    This may be 0 for a string. */
1159
1160 static struct extent_info*
1161 buffer_or_string_extent_info(Lisp_Object object)
1162 {
1163         if (STRINGP(object)) {
1164                 Lisp_Object plist = XSTRING(object)->plist;
1165                 if (!CONSP(plist) || !EXTENT_INFOP(XCAR(plist))) {
1166                         return NULL;
1167                 }
1168                 return XEXTENT_INFO(XCAR(plist));
1169         } else if (NILP(object)) {
1170                 return NULL;
1171         } else {
1172                 return XEXTENT_INFO(XBUFFER(object)->extent_info);
1173         }
1174 }
1175
1176 /* Given a string or buffer, return its extent list.  This may be
1177    0 for a string. */
1178
1179 static extent_list_t
1180 buffer_or_string_extent_list(Lisp_Object object)
1181 {
1182         struct extent_info *info = buffer_or_string_extent_info(object);
1183
1184         if (!info) {
1185                 return 0;
1186         }
1187         return info->extents;
1188 }
1189
1190 /* Given a string or buffer, return its extent info.  If it's not there,
1191    create it. */
1192
1193 static struct extent_info*
1194 buffer_or_string_extent_info_force(Lisp_Object object)
1195 {
1196         struct extent_info *info = buffer_or_string_extent_info(object);
1197
1198         if (!info) {
1199                 Lisp_Object extent_info;
1200
1201                 /* should never happen for buffers --
1202                    the only buffers without an extent
1203                    info are those after finalization,
1204                    destroyed buffers, or special
1205                    Lisp-inaccessible buffer objects. */
1206                 assert(STRINGP(object));
1207
1208                 extent_info = allocate_extent_info();
1209                 XSTRING(object)->plist =
1210                         Fcons(extent_info, XSTRING(object)->plist);
1211                 return XEXTENT_INFO(extent_info);
1212         }
1213         return info;
1214 }
1215
1216 /* Detach all the extents in OBJECT.  Called from redisplay. */
1217
1218 void
1219 detach_all_extents(Lisp_Object object)
1220 {
1221         struct extent_info *data = buffer_or_string_extent_info(object);
1222
1223         if (data) {
1224                 if (data->extents) {
1225                         for (int i = 0;
1226                              i < extent_list_num_els(data->extents);
1227                              i++) {
1228                                 EXTENT e = extent_list_at(data->extents, i, 0);
1229                                 /* No need to do detach_extent().  Just nuke the
1230                                    damn things, which results in the equivalent
1231                                    but faster. */
1232                                 set_extent_start(e, -1);
1233                                 set_extent_end(e, -1);
1234                         }
1235                         /* But we need to clear all the lists containing extents
1236                            or havoc will result. */
1237                         extent_list_delete_all(data->extents);
1238                 }
1239                 soe_invalidate(object);
1240         }
1241         return;
1242 }
1243
1244 void
1245 init_buffer_extents(struct buffer *b)
1246 {
1247         b->extent_info = allocate_extent_info();
1248         return;
1249 }
1250
1251 void
1252 uninit_buffer_extents(struct buffer *b)
1253 {
1254         struct extent_info *data = XEXTENT_INFO(b->extent_info);
1255
1256         /* Don't destroy the extents here -- there may still be children
1257            extents pointing to the extents. */
1258         detach_all_extents(make_buffer(b));
1259         finalize_extent_info(data, 0);
1260         return;
1261 }
1262
1263 /* Retrieve the extent list that an extent is a member of; the
1264    return value will never be 0 except in destroyed buffers (in which
1265    case the only extents that can refer to this buffer are detached
1266    ones). */
1267
1268 #define extent_extent_list(e) buffer_or_string_extent_list (extent_object (e))
1269
1270 /* ------------------------------- */
1271 /*        stack of extents         */
1272 /* ------------------------------- */
1273
1274 #ifdef ERROR_CHECK_EXTENTS
1275
1276 void
1277 sledgehammer_extent_check(Lisp_Object object)
1278 {
1279         extent_list_t el = buffer_or_string_extent_list(object);
1280         struct buffer *buf = 0;
1281
1282         if (!el) {
1283                 return;
1284         }
1285         if (BUFFERP(object)) {
1286                 buf = XBUFFER(object);
1287         }
1288         for (int endp = 0; endp < 2; endp++) {
1289                 for (int i = 1; i < extent_list_num_els(el); i++) {
1290                         EXTENT e1 = extent_list_at(el, i - 1, endp);
1291                         EXTENT e2 = extent_list_at(el, i, endp);
1292                         if (buf) {
1293                                 assert(extent_start(e1) <= buf->text->gpt ||
1294                                        extent_start(e1) >
1295                                        buf->text->gpt + buf->text->gap_size);
1296                                 assert(extent_end(e1) <= buf->text->gpt
1297                                        || extent_end(e1) >
1298                                        buf->text->gpt + buf->text->gap_size);
1299                         }
1300                         assert(extent_start(e1) <= extent_end(e1));
1301                         assert(endp
1302                                ? (EXTENT_E_LESS_EQUAL(e1, e2))
1303                                : (EXTENT_LESS_EQUAL(e1, e2)));
1304                 }
1305         }
1306 }
1307
1308 #endif  /* ERROR_CHECK_EXTENTS */
1309
1310 static extent_stack_t
1311 buffer_or_string_stack_of_extents(Lisp_Object object)
1312 {
1313         struct extent_info *info = buffer_or_string_extent_info(object);
1314         if (!info) {
1315                 return NULL;
1316         }
1317         return info->soe;
1318 }
1319
1320 static extent_stack_t
1321 buffer_or_string_stack_of_extents_force(Lisp_Object object)
1322 {
1323         struct extent_info *info = buffer_or_string_extent_info_force(object);
1324         if (!info->soe) {
1325                 info->soe = allocate_soe();
1326         }
1327         return info->soe;
1328 }
1329
1330 /* #define SOE_DEBUG */
1331
1332 #ifdef SOE_DEBUG
1333
1334 static void print_extent_1(char *buf, Lisp_Object extent);
1335
1336 static void
1337 print_extent_2(EXTENT e)
1338 {
1339         Lisp_Object extent;
1340         char buf[200];
1341
1342         XSETEXTENT(extent, e);
1343         print_extent_1(buf, extent);
1344         fputs(buf, stdout);
1345 }
1346
1347 static void
1348 soe_dump(Lisp_Object obj)
1349 {
1350         int i;
1351         extent_stack_t soe = buffer_or_string_stack_of_extents(obj);
1352         extent_list_t sel;
1353         int endp;
1354
1355         if (!soe) {
1356                 printf("No SOE");
1357                 return;
1358         }
1359         sel = soe->extents;
1360         printf("SOE pos is %d (memind %d)\n",
1361                soe->pos < 0 ? soe->pos :
1362                buffer_or_string_memind_to_bytind(obj, soe->pos), soe->pos);
1363         for (endp = 0; endp < 2; endp++) {
1364                 printf(endp ? "SOE end:" : "SOE start:");
1365                 for (i = 0; i < extent_list_num_els(sel); i++) {
1366                         EXTENT e = extent_list_at(sel, i, endp);
1367                         putchar('\t');
1368                         print_extent_2(e);
1369                 }
1370                 putchar('\n');
1371         }
1372         putchar('\n');
1373 }
1374
1375 #endif  /* SOE_DEBUG */
1376
1377 /* Insert EXTENT into OBJ's stack of extents, if necessary. */
1378
1379 static void
1380 soe_insert(Lisp_Object obj, EXTENT extent)
1381 {
1382         extent_stack_t soe = buffer_or_string_stack_of_extents(obj);
1383
1384 #ifdef SOE_DEBUG
1385         printf("Inserting into SOE: ");
1386         print_extent_2(extent);
1387         putchar('\n');
1388 #endif
1389         if (!soe || soe->pos < extent_start(extent) ||
1390             soe->pos > extent_end(extent)) {
1391 #ifdef SOE_DEBUG
1392                 printf("(not needed)\n\n");
1393 #endif
1394                 return;
1395         }
1396         extent_list_insert(soe->extents, extent);
1397 #ifdef SOE_DEBUG
1398         puts("SOE afterwards is:");
1399         soe_dump(obj);
1400 #endif
1401         return;
1402 }
1403
1404 /* Delete EXTENT from OBJ's stack of extents, if necessary. */
1405
1406 static void
1407 soe_delete(Lisp_Object obj, EXTENT extent)
1408 {
1409         extent_stack_t soe = buffer_or_string_stack_of_extents(obj);
1410
1411 #ifdef SOE_DEBUG
1412         printf("Deleting from SOE: ");
1413         print_extent_2(extent);
1414         putchar('\n');
1415 #endif
1416         if (!soe || soe->pos < extent_start(extent) ||
1417             soe->pos > extent_end(extent)) {
1418 #ifdef SOE_DEBUG
1419                 puts("(not needed)\n");
1420 #endif
1421                 return;
1422         }
1423         extent_list_delete(soe->extents, extent);
1424 #ifdef SOE_DEBUG
1425         puts("SOE afterwards is:");
1426         soe_dump(obj);
1427 #endif
1428         return;
1429 }
1430
1431 /* Move OBJ's stack of extents to lie over the specified position. */
1432
1433 static void
1434 soe_move(Lisp_Object obj, Memind pos)
1435 {
1436         extent_stack_t soe = buffer_or_string_stack_of_extents_force(obj);
1437         extent_list_t sel = soe->extents;
1438         int numsoe = extent_list_num_els(sel);
1439         extent_list_t bel = buffer_or_string_extent_list(obj);
1440         int direction;
1441         int endp;
1442
1443 #ifdef ERROR_CHECK_EXTENTS
1444         assert(bel);
1445 #endif
1446
1447 #ifdef SOE_DEBUG
1448         printf("Moving SOE from %d (memind %d) to %d (memind %d)\n",
1449                soe->pos < 0 ? soe->pos :
1450                buffer_or_string_memind_to_bytind(obj, soe->pos), soe->pos,
1451                buffer_or_string_memind_to_bytind(obj, pos), pos);
1452 #endif
1453         if (soe->pos < pos) {
1454                 direction = 1;
1455                 endp = 0;
1456         } else if (soe->pos > pos) {
1457                 direction = -1;
1458                 endp = 1;
1459         } else {
1460 #ifdef SOE_DEBUG
1461                 puts("(not needed)\n");
1462 #endif
1463                 return;
1464         }
1465
1466         /* For DIRECTION = 1: Any extent that overlaps POS is either in the
1467            SOE (if the extent starts at or before SOE->POS) or is greater
1468            (in the display order) than any extent in the SOE (if it starts
1469            after SOE->POS).
1470
1471            For DIRECTION = -1: Any extent that overlaps POS is either in the
1472            SOE (if the extent ends at or after SOE->POS) or is less (in the
1473            e-order) than any extent in the SOE (if it ends before SOE->POS).
1474
1475            We proceed in two stages:
1476
1477            1) delete all extents in the SOE that don't overlap POS.
1478            2) insert all extents into the SOE that start (or end, when
1479            DIRECTION = -1) in (SOE->POS, POS] and that overlap
1480            POS. (Don't include SOE->POS in the range because those
1481            extents would already be in the SOE.)
1482          */
1483
1484         /* STAGE 1. */
1485
1486         if (numsoe > 0) {
1487                 /* Delete all extents in the SOE that don't overlap POS.
1488                    This is all extents that end before (or start after,
1489                    if DIRECTION = -1) POS.
1490                  */
1491
1492                 /* Deleting extents from the SOE is tricky because it changes
1493                    the positions of extents.  If we are deleting in the forward
1494                    direction we have to call extent_list_at() on the same position
1495                    over and over again because positions after the deleted element
1496                    get shifted back by 1.  To make life simplest, we delete forward
1497                    irrespective of DIRECTION.
1498                  */
1499                 int start, end;
1500                 int i;
1501
1502                 if (direction > 0) {
1503                         start = 0;
1504                         end = extent_list_locate_from_pos(sel, pos, 1);
1505                 } else {
1506                         start = extent_list_locate_from_pos(sel, pos + 1, 0);
1507                         end = numsoe;
1508                 }
1509
1510                 for (i = start; i < end; i++) {
1511                         extent_list_delete(
1512                                 sel, extent_list_at(sel, start, !endp));
1513                 }
1514         }
1515
1516         /* STAGE 2. */
1517
1518         {
1519                 int start_pos;
1520
1521                 if (direction < 0) {
1522                         start_pos =
1523                                 extent_list_locate_from_pos(
1524                                         bel, soe->pos, endp) - 1;
1525                 } else {
1526                         start_pos =
1527                                 extent_list_locate_from_pos(
1528                                         bel, soe->pos + 1, endp);
1529                 }
1530
1531                 for (; start_pos >= 0 && start_pos < extent_list_num_els(bel);
1532                      start_pos += direction) {
1533                         EXTENT e = extent_list_at(bel, start_pos, endp);
1534                         if ((direction > 0)
1535                             ? (extent_start(e) > pos)
1536                             : (extent_end(e) < pos)) {
1537                                 /* All further extents lie on the far side of
1538                                    POS and thus can't overlap. */
1539                                 break;  
1540                         }
1541                         if ((direction > 0)
1542                             ? (extent_end(e) >= pos)
1543                             : (extent_start(e) <= pos)) {
1544                                 extent_list_insert(sel, e);
1545                         }
1546                 }
1547         }
1548
1549         soe->pos = pos;
1550 #ifdef SOE_DEBUG
1551         puts("SOE afterwards is:");
1552         soe_dump(obj);
1553 #endif
1554         return;
1555 }
1556
1557 static void
1558 soe_invalidate(Lisp_Object obj)
1559 {
1560         extent_stack_t soe = buffer_or_string_stack_of_extents(obj);
1561
1562         if (soe) {
1563                 extent_list_delete_all(soe->extents);
1564                 soe->pos = -1;
1565         }
1566         return;
1567 }
1568
1569 static extent_stack_t
1570 allocate_soe(void)
1571 {
1572         extent_stack_t soe = xnew_and_zero(struct extent_stack_s);
1573         soe->extents = allocate_extent_list();
1574         soe->pos = -1;
1575         return soe;
1576 }
1577
1578 static void
1579 free_soe(extent_stack_t soe)
1580 {
1581         free_extent_list(soe->extents);
1582         xfree(soe);
1583         return;
1584 }
1585
1586 /* ------------------------------- */
1587 /*        other primitives         */
1588 /* ------------------------------- */
1589
1590 /* Return the start (endp == 0) or end (endp == 1) of an extent as
1591    a byte index.  If you want the value as a memory index, use
1592    extent_endpoint().  If you want the value as a buffer position,
1593    use extent_endpoint_bufpos(). */
1594
1595 static Bytind extent_endpoint_bytind(EXTENT extent, int endp)
1596 {
1597         assert(EXTENT_LIVE_P(extent));
1598         assert(!extent_detached_p(extent));
1599         {
1600                 Memind i = endp ? extent_end(extent) : extent_start(extent);
1601                 Lisp_Object obj = extent_object(extent);
1602                 return buffer_or_string_memind_to_bytind(obj, i);
1603         }
1604 }
1605
1606 static Bufpos extent_endpoint_bufpos(EXTENT extent, int endp)
1607 {
1608         assert(EXTENT_LIVE_P(extent));
1609         assert(!extent_detached_p(extent));
1610         {
1611                 Memind i = endp ? extent_end(extent) : extent_start(extent);
1612                 Lisp_Object obj = extent_object(extent);
1613                 return buffer_or_string_memind_to_bufpos(obj, i);
1614         }
1615 }
1616
1617 /* A change to an extent occurred that will change the display, so
1618    notify redisplay.  Maybe also recurse over all the extent's
1619    descendants. */
1620
1621 static void
1622 extent_changed_for_redisplay(EXTENT extent, int descendants_too,
1623                              int invisibility_change)
1624 {
1625         Lisp_Object object;
1626         Lisp_Object rest;
1627
1628         /* we could easily encounter a detached extent while traversing the
1629            children, but we should never be able to encounter a dead extent. */
1630         assert(EXTENT_LIVE_P(extent));
1631
1632         if (descendants_too) {
1633                 Lisp_Object children = extent_children(extent);
1634
1635                 if (!NILP(children)) {
1636                         /* first mark all of the extent's children.  We will
1637                            lose big-time if there are any circularities here, so
1638                            we sure as hell better ensure that there aren't. */
1639                         LIST_LOOP(rest, XWEAK_LIST_LIST(children)) {
1640                                 extent_changed_for_redisplay(
1641                                         XEXTENT(XCAR(rest)), 1,
1642                                         invisibility_change);
1643                         }
1644                 }
1645         }
1646
1647         /* now mark the extent itself. */
1648
1649         object = extent_object(extent);
1650
1651         if (extent_detached_p(extent)) {
1652                 return;
1653
1654         } else if (STRINGP(object)) {
1655                 /* #### Changes to string extents can affect redisplay if they
1656                    are in the modeline or in the gutters.
1657
1658                    If the extent is in some generated-modeline-string: when we
1659                    change an extent in generated-modeline-string, this changes
1660                    its parent, which is in `modeline-format', so we should force
1661                    the modeline to be updated.  But how to determine whether a
1662                    string is a `generated-modeline-string'?  Looping through all
1663                    buffers is not very efficient.  Should we add all
1664                    `generated-modeline-string' strings to a hash table?  Maybe
1665                    efficiency is not the greatest concern here and there's no
1666                    big loss in looping over the buffers.
1667
1668                    If the extent is in a gutter we mark the gutter as
1669                    changed. This means (a) we can update extents in the gutters
1670                    when we need it. (b) we don't have to update the gutters when
1671                    only extents attached to buffers have changed. */
1672
1673                 if (!in_modeline_generation) {
1674                         MARK_EXTENTS_CHANGED;
1675                 }
1676                 gutter_extent_signal_changed_region_maybe(
1677                         object,
1678                         extent_endpoint_bufpos(extent, 0),
1679                         extent_endpoint_bufpos(extent, 1));
1680
1681         } else if (BUFFERP(object)) {
1682                 struct buffer *b;
1683                 b = XBUFFER(object);
1684                 BUF_FACECHANGE(b)++;
1685                 MARK_EXTENTS_CHANGED;
1686                 if (invisibility_change) {
1687                         MARK_CLIP_CHANGED;
1688                 }
1689                 buffer_extent_signal_changed_region(
1690                         b,
1691                         extent_endpoint_bufpos(extent, 0),
1692                         extent_endpoint_bufpos(extent, 1));
1693         }
1694 }
1695
1696 /* A change to an extent occurred that might affect redisplay.
1697    This is called when properties such as the endpoints, the layout,
1698    or the priority changes.  Redisplay will be affected only if
1699    the extent has any displayable attributes. */
1700
1701 static void
1702 extent_maybe_changed_for_redisplay(EXTENT extent, int descendants_too,
1703                                    int invisibility_change)
1704 {
1705         /* Retrieve the ancestor for efficiency */
1706         EXTENT anc = extent_ancestor(extent);
1707         if (!NILP(extent_face(anc)) ||
1708             !NILP(extent_begin_glyph(anc)) ||
1709             !NILP(extent_end_glyph(anc)) ||
1710             !NILP(extent_mouse_face(anc)) ||
1711             !NILP(extent_invisible(anc)) ||
1712             !NILP(extent_initial_redisplay_function(anc)) ||
1713             invisibility_change)
1714                 extent_changed_for_redisplay(extent, descendants_too,
1715                                              invisibility_change);
1716 }
1717
1718 static EXTENT
1719 make_extent_detached(Lisp_Object object)
1720 {
1721         EXTENT extent = allocate_extent();
1722
1723         assert(NILP(object) || STRINGP(object) ||
1724                (BUFFERP(object) && BUFFER_LIVE_P(XBUFFER(object))));
1725         extent_object(extent) = object;
1726         /* Now make sure the extent info exists. */
1727         if (!NILP(object)) {
1728                 buffer_or_string_extent_info_force(object);
1729         }
1730         return extent;
1731 }
1732
1733 /* A "real" extent is any extent other than the internal (not-user-visible)
1734    extents used by `map-extents'. */
1735
1736 static EXTENT
1737 real_extent_at_forward(extent_list_t el, int pos, int endp)
1738 {
1739         for (; pos < extent_list_num_els(el); pos++) {
1740                 EXTENT e = extent_list_at(el, pos, endp);
1741                 if (!extent_internal_p(e)) {
1742                         return e;
1743                 }
1744         }
1745         return NULL;
1746 }
1747
1748 static EXTENT
1749 real_extent_at_backward(extent_list_t el, int pos, int endp)
1750 {
1751         for (; pos >= 0; pos--) {
1752                 EXTENT e = extent_list_at(el, pos, endp);
1753                 if (!extent_internal_p(e)) {
1754                         return e;
1755                 }
1756         }
1757         return NULL;
1758 }
1759
1760 static EXTENT
1761 extent_first(Lisp_Object obj)
1762 {
1763         extent_list_t el = buffer_or_string_extent_list(obj);
1764
1765         if (!el) {
1766                 return NULL;
1767         }
1768         return real_extent_at_forward(el, 0, 0);
1769 }
1770
1771 #ifdef DEBUG_SXEMACS
1772 static EXTENT
1773 extent_e_first(Lisp_Object obj)
1774 {
1775         extent_list_t el = buffer_or_string_extent_list(obj);
1776
1777         if (!el) {
1778                 return 0;
1779         }
1780         return real_extent_at_forward(el, 0, 1);
1781 }
1782 #endif  /* DEBUG_SXEMACS */
1783
1784 static EXTENT
1785 extent_next(EXTENT e)
1786 {
1787         extent_list_t el = extent_extent_list(e);
1788         bool foundp;
1789         int pos = extent_list_locate(el, e, 0, &foundp);
1790         assert(foundp);
1791         return real_extent_at_forward(el, pos + 1, 0);
1792 }
1793
1794 #ifdef DEBUG_SXEMACS
1795 static EXTENT
1796 extent_e_next(EXTENT e)
1797 {
1798         extent_list_t el = extent_extent_list(e);
1799         bool foundp;
1800         int pos = extent_list_locate(el, e, 1, &foundp);
1801         assert(foundp);
1802         return real_extent_at_forward(el, pos + 1, 1);
1803 }
1804 #endif  /* DEBUG_SXEMACS */
1805
1806 static EXTENT
1807 extent_last(Lisp_Object obj)
1808 {
1809         extent_list_t el = buffer_or_string_extent_list(obj);
1810
1811         if (!el) {
1812                 return 0;
1813         }
1814         return real_extent_at_backward(el, extent_list_num_els(el) - 1, 0);
1815 }
1816
1817 #ifdef DEBUG_SXEMACS
1818 static EXTENT
1819 extent_e_last(Lisp_Object obj)
1820 {
1821         extent_list_t el = buffer_or_string_extent_list(obj);
1822
1823         if (!el) {
1824                 return 0;
1825         }
1826         return real_extent_at_backward(el, extent_list_num_els(el) - 1, 1);
1827 }
1828 #endif  /* DEBUG_SXEMACS */
1829
1830 static EXTENT
1831 extent_previous(EXTENT e)
1832 {
1833         extent_list_t el = extent_extent_list(e);
1834         bool foundp;
1835         int pos = extent_list_locate(el, e, 0, &foundp);
1836         assert(foundp);
1837         return real_extent_at_backward(el, pos - 1, 0);
1838 }
1839
1840 #ifdef DEBUG_SXEMACS
1841 static EXTENT
1842 extent_e_previous(EXTENT e)
1843 {
1844         extent_list_t el = extent_extent_list(e);
1845         bool foundp;
1846         int pos = extent_list_locate(el, e, 1, &foundp);
1847         assert(foundp);
1848         return real_extent_at_backward(el, pos - 1, 1);
1849 }
1850 #endif  /* DEBUG_SXEMACS */
1851
1852 static void
1853 extent_attach(EXTENT extent)
1854 {
1855         extent_list_t el = extent_extent_list(extent);
1856
1857         extent_list_insert(el, extent);
1858         soe_insert(extent_object(extent), extent);
1859         /* only this extent changed */
1860         extent_maybe_changed_for_redisplay(
1861                 extent, 0, !NILP(extent_invisible(extent)));
1862         return;
1863 }
1864
1865 static void
1866 extent_detach(EXTENT extent)
1867 {
1868         extent_list_t el;
1869
1870         if (extent_detached_p(extent)) {
1871                 return;
1872         }
1873         el = extent_extent_list(extent);
1874
1875         /* call this before messing with the extent. */
1876         extent_maybe_changed_for_redisplay(
1877                 extent, 0, !NILP(extent_invisible(extent)));
1878         extent_list_delete(el, extent);
1879         soe_delete(extent_object(extent), extent);
1880         set_extent_start(extent, -1);
1881         set_extent_end(extent, -1);
1882         return;
1883 }
1884
1885 /* ------------------------------- */
1886 /*        map-extents et al.       */
1887 /* ------------------------------- */
1888
1889 /* Returns true iff map_extents() would visit the given extent.
1890    See the comments at map_extents() for info on the overlap rule.
1891    Assumes that all validation on the extent and buffer positions has
1892    already been performed (see Fextent_in_region_p ()).
1893  */
1894 static bool
1895 extent_in_region_p(EXTENT extent, Bytind from, Bytind to, unsigned int flags)
1896 {
1897         Lisp_Object obj = extent_object(extent);
1898         Endpoint_Index start, end, exs, exe;
1899         int start_open, end_open;
1900         unsigned int all_extents_flags = flags & ME_ALL_EXTENTS_MASK;
1901         unsigned int in_region_flags = flags & ME_IN_REGION_MASK;
1902         int retval;
1903
1904         /* A zero-length region is treated as closed-closed. */
1905         if (from == to) {
1906                 flags |= ME_END_CLOSED;
1907                 flags &= ~ME_START_OPEN;
1908         }
1909
1910         /* So is a zero-length extent. */
1911         if (extent_start(extent) == extent_end(extent)) {
1912                 start_open = 0, end_open = 0;
1913         } else if (LIKELY(all_extents_flags == 0)) {
1914                 /* `all_extents_flags' will almost always be zero. */
1915                 start_open = extent_start_open_p(extent);
1916                 end_open = extent_end_open_p(extent);
1917         } else {
1918                 switch (all_extents_flags) {
1919                 case ME_ALL_EXTENTS_CLOSED:
1920                         start_open = 0, end_open = 0;
1921                         break;
1922                 case ME_ALL_EXTENTS_OPEN:
1923                         start_open = 1, end_open = 1;
1924                         break;
1925                 case ME_ALL_EXTENTS_CLOSED_OPEN:
1926                         start_open = 0, end_open = 1;
1927                         break;
1928                 case ME_ALL_EXTENTS_OPEN_CLOSED:
1929                         start_open = 1, end_open = 0;
1930                         break;
1931                 default:
1932                         abort();
1933                         return false;
1934                 }
1935         }
1936         start = buffer_or_string_bytind_to_startind(obj, from,
1937                                                     flags & ME_START_OPEN);
1938         end = buffer_or_string_bytind_to_endind(obj, to,
1939                                                 !(flags & ME_END_CLOSED));
1940         exs = memind_to_startind(extent_start(extent), start_open);
1941         exe = memind_to_endind(extent_end(extent), end_open);
1942
1943         /* It's easy to determine whether an extent lies *outside* the
1944            region -- just determine whether it's completely before
1945            or completely after the region.  Reject all such extents, so
1946            we're now left with only the extents that overlap the region.
1947          */
1948
1949         if (exs > end || exe < start) {
1950                 return false;
1951         }
1952         /* See if any further restrictions are called for. */
1953         /* in_region_flags will almost always be zero. */
1954         if (in_region_flags == 0) {
1955                 retval = 1;
1956         } else {
1957                 switch (in_region_flags) {
1958                 case ME_START_IN_REGION:
1959                         retval = start <= exs && exs <= end;
1960                         break;
1961                 case ME_END_IN_REGION:
1962                         retval = start <= exe && exe <= end;
1963                         break;
1964                 case ME_START_AND_END_IN_REGION:
1965                         retval = start <= exs && exe <= end;
1966                         break;
1967                 case ME_START_OR_END_IN_REGION:
1968                         retval = (start <= exs && exs <= end) ||
1969                                 (start <= exe && exe <= end);
1970                         break;
1971                 default:
1972                         abort();
1973                         return false;
1974                 }
1975         }
1976         return flags & ME_NEGATE_IN_REGION ? !retval : retval;
1977 }
1978
1979 struct map_extents_struct {
1980         extent_list_t el;
1981         extent_list_marker_t mkr;
1982         EXTENT range;
1983 };
1984
1985 static Lisp_Object
1986 map_extents_unwind(Lisp_Object obj)
1987 {
1988         struct map_extents_struct *closure =
1989                 (struct map_extents_struct *)get_opaque_ptr(obj);
1990         free_opaque_ptr(obj);
1991         if (closure->range) {
1992                 extent_detach(closure->range);
1993         }
1994         if (closure->mkr) {
1995                 extent_list_delete_marker(closure->el, closure->mkr);
1996         }
1997         return Qnil;
1998 }
1999
2000 /* This is the guts of `map-extents' and the other functions that
2001    map over extents.  In theory the operation of this function is
2002    simple: just figure out what extents we're mapping over, and
2003    call the function on each one of them in the range.  Unfortunately
2004    there are a wide variety of things that the mapping function
2005    might do, and we have to be very tricky to avoid getting messed
2006    up.  Furthermore, this function needs to be very fast (it is
2007    called multiple times every time text is inserted or deleted
2008    from a buffer), and so we can't always afford the overhead of
2009    dealing with all the possible things that the mapping function
2010    might do; thus, there are many flags that can be specified
2011    indicating what the mapping function might or might not do.
2012
2013    The result of all this is that this is the most complicated
2014    function in this file.  Change it at your own risk!
2015
2016    A potential simplification to the logic below is to determine
2017    all the extents that the mapping function should be called on
2018    before any calls are actually made and save them in an array.
2019    That introduces its own complications, however (the array
2020    needs to be marked for garbage-collection, and a static array
2021    cannot be used because map_extents() needs to be reentrant).
2022    Furthermore, the results might be a little less sensible than
2023    the logic below. */
2024
2025 static void
2026 map_extents_bytind(Bytind from, Bytind to, map_extents_fun fn, void *arg,
2027                    Lisp_Object obj, EXTENT after, unsigned int flags)
2028 {
2029         Memind st, en;          /* range we're mapping over */
2030         EXTENT range = 0;       /* extent for this, if ME_MIGHT_MODIFY_TEXT */
2031         extent_list_t el = 0;   /* extent list we're iterating over */
2032         extent_list_marker_t posm = 0;  /* marker for extent list,
2033                                            if ME_MIGHT_MODIFY_EXTENTS */
2034         /* count and struct for unwind-protect, if ME_MIGHT_THROW */
2035         int count = 0;
2036         struct map_extents_struct closure;
2037
2038 #ifdef ERROR_CHECK_EXTENTS
2039         assert(from <= to);
2040         assert(from >= buffer_or_string_absolute_begin_byte(obj) &&
2041                from <= buffer_or_string_absolute_end_byte(obj) &&
2042                to >= buffer_or_string_absolute_begin_byte(obj) &&
2043                to <= buffer_or_string_absolute_end_byte(obj));
2044 #endif
2045
2046         if (after) {
2047                 assert(EQ(obj, extent_object(after)));
2048                 assert(!extent_detached_p(after));
2049         }
2050
2051         el = buffer_or_string_extent_list(obj);
2052         if (!el || !extent_list_num_els(el))
2053                 return;
2054         el = 0;
2055
2056         st = buffer_or_string_bytind_to_memind(obj, from);
2057         en = buffer_or_string_bytind_to_memind(obj, to);
2058
2059         if (flags & ME_MIGHT_MODIFY_TEXT) {
2060                 /* The mapping function might change the text in the buffer,
2061                    so make an internal extent to hold the range we're mapping
2062                    over. */
2063                 range = make_extent_detached(obj);
2064                 set_extent_start(range, st);
2065                 set_extent_end(range, en);
2066                 range->flags.start_open = flags & ME_START_OPEN;
2067                 range->flags.end_open = !(flags & ME_END_CLOSED);
2068                 range->flags.internal = 1;
2069                 range->flags.detachable = 0;
2070                 extent_attach(range);
2071         }
2072
2073         if (flags & ME_MIGHT_THROW) {
2074                 /* The mapping function might throw past us so we need to use an
2075                    unwind_protect() to eliminate the internal extent and range
2076                    that we use. */
2077                 count = specpdl_depth();
2078                 closure.range = range;
2079                 closure.mkr = 0;
2080                 record_unwind_protect(map_extents_unwind,
2081                                       make_opaque_ptr(&closure));
2082         }
2083
2084         /* ---------- Figure out where we start and what direction
2085            we move in.  This is the trickiest part of this
2086            function. ---------- */
2087
2088         /* If ME_START_IN_REGION, ME_END_IN_REGION or ME_START_AND_END_IN_REGION
2089            was specified and ME_NEGATE_IN_REGION was not specified, our job
2090            is simple because of the presence of the display order and e-order.
2091            (Note that theoretically do something similar for
2092            ME_START_OR_END_IN_REGION, but that would require more trickiness
2093            than it's worth to avoid hitting the same extent twice.)
2094
2095            In the general case, all the extents that overlap a range can be
2096            divided into two classes: those whose start position lies within
2097            the range (including the range's end but not including the
2098            range's start), and those that overlap the start position,
2099            i.e. those in the SOE for the start position.  Or equivalently,
2100            the extents can be divided into those whose end position lies
2101            within the range and those in the SOE for the end position.  Note
2102            that for this purpose we treat both the range and all extents in
2103            the buffer as closed on both ends.  If this is not what the ME_
2104            flags specified, then we've mapped over a few too many extents,
2105            but no big deal because extent_in_region_p() will filter them
2106            out.   Ideally, we could move the SOE to the closer of the range's
2107            two ends and work forwards or backwards from there.  However, in
2108            order to make the semantics of the AFTER argument work out, we
2109            have to always go in the same direction; so we choose to always
2110            move the SOE to the start position.
2111
2112            When it comes time to do the SOE stage, we first call soe_move()
2113            so that the SOE gets set up.  Note that the SOE might get
2114            changed while we are mapping over its contents.  If we can
2115            guarantee that the SOE won't get moved to a new position, we
2116            simply need to put a marker in the SOE and we will track deletions
2117            and insertions of extents in the SOE.  If the SOE might get moved,
2118            however (this would happen as a result of a recursive invocation
2119            of map-extents or a call to a redisplay-type function), then
2120            trying to track its changes is hopeless, so we just keep a
2121            marker to the first (or last) extent in the SOE and use that as
2122            our bound.
2123
2124            Finally, if DONT_USE_SOE is defined, we don't use the SOE at all
2125            and instead just map from the beginning of the buffer.  This is
2126            used for testing purposes and allows the SOE to be calculated
2127            using map_extents() instead of the other way around. */
2128
2129         {
2130                 int range_flag; /* ME_*_IN_REGION subset of flags */
2131                 int do_soe_stage = 0;   /* Are we mapping over the SOE? */
2132                 /* Does the range stage map over start or end positions? */
2133                 int range_endp;
2134                 /* If type == 0, we include the start position in the range
2135                    stage mapping.
2136                    If type == 1, we exclude the start position in the range
2137                    stage mapping.
2138                    If type == 2, we begin at range_start_pos, an extent-list
2139                    position.
2140                  */
2141                 int range_start_type = 0;
2142                 int range_start_pos = 0;
2143                 int stage;
2144
2145                 range_flag = flags & ME_IN_REGION_MASK;
2146                 if ((range_flag == ME_START_IN_REGION ||
2147                      range_flag == ME_START_AND_END_IN_REGION) &&
2148                     !(flags & ME_NEGATE_IN_REGION)) {
2149                         /* map over start position in [range-start, range-end].
2150                            No SOE stage. */
2151                         range_endp = 0;
2152                 } else if (range_flag == ME_END_IN_REGION
2153                            && !(flags & ME_NEGATE_IN_REGION)) {
2154                         /* map over end position in [range-start, range-end].
2155                            No SOE stage. */
2156                         range_endp = 1;
2157                 } else {
2158                         /* Need to include the SOE extents. */
2159 #ifdef DONT_USE_SOE
2160                         /* Just brute-force it: start from the beginning. */
2161                         range_endp = 0;
2162                         range_start_type = 2;
2163                         range_start_pos = 0;
2164 #else
2165                         extent_stack_t soe =
2166                                 buffer_or_string_stack_of_extents_force(obj);
2167                         int numsoe;
2168
2169                         /* Move the SOE to the closer end of the range.  This
2170                            dictates whether we map over start positions or end
2171                            positions. */
2172                         range_endp = 0;
2173                         soe_move(obj, st);
2174                         numsoe = extent_list_num_els(soe->extents);
2175                         if (numsoe) {
2176                                 if (flags & ME_MIGHT_MOVE_SOE) {
2177                                         bool foundp;
2178                                         /* Can't map over SOE, so just extend
2179                                            range to cover the SOE. */
2180                                         EXTENT e = extent_list_at(
2181                                                 soe->extents, 0, 0);
2182                                         range_start_pos = extent_list_locate
2183                                                 (buffer_or_string_extent_list
2184                                                  (obj), e, 0, &foundp);
2185                                         assert(foundp);
2186                                         range_start_type = 2;
2187                                 } else {
2188                                         /* We can map over the SOE. */
2189                                         do_soe_stage = 1;
2190                                         range_start_type = 1;
2191                                 }
2192                         } else {
2193                                 /* No extents in the SOE to map over, so we act
2194                                    just as if ME_START_IN_REGION or
2195                                    ME_END_IN_REGION was specified.  RANGE_ENDP
2196                                    already specified so no need to do anything
2197                                    else. */
2198                         }
2199                 }
2200 #endif
2201
2202                 /* ---------- Now loop over the extents. ---------- */
2203
2204                 /* We combine the code for the two stages because much of it
2205                    overlaps. */
2206                 for (stage = 0; stage < 2; stage++) {
2207                         int pos = 0;    /* Position in extent list */
2208
2209                         /* First set up start conditions */
2210                         if (stage == 0) {       /* The SOE stage */
2211                                 if (!do_soe_stage)
2212                                         continue;
2213                                 el = buffer_or_string_stack_of_extents_force
2214                                     (obj)->extents;
2215                                 /* We will always be looping over start extents
2216                                    here. */
2217                                 assert(!range_endp);
2218                                 pos = 0;
2219                         } else {        /* The range stage */
2220                                 el = buffer_or_string_extent_list(obj);
2221                                 switch (range_start_type) {
2222                                 case 0:
2223                                         pos = extent_list_locate_from_pos
2224                                                 (el, st, range_endp);
2225                                         break;
2226                                 case 1:
2227                                         pos = extent_list_locate_from_pos
2228                                                 (el, st + 1, range_endp);
2229                                         break;
2230                                 case 2:
2231                                         pos = range_start_pos;
2232                                         break;
2233                                 default:
2234                                         break;
2235                                 }
2236                         }
2237
2238                         if (flags & ME_MIGHT_MODIFY_EXTENTS) {
2239                                 /* Create a marker to track changes to the
2240                                    extent list */
2241                                 if (posm)
2242                                         /* Delete the marker used in the SOE
2243                                            stage. */
2244                                         extent_list_delete_marker
2245                                                 (buffer_or_string_stack_of_extents_force
2246                                                  (obj)->extents, posm);
2247                                 posm = extent_list_make_marker(
2248                                         el, pos, range_endp);
2249                                 /* tell the unwind function about the marker. */
2250                                 closure.el = el;
2251                                 closure.mkr = posm;
2252                         }
2253
2254                         /* Now loop! */
2255                         for (;;) {
2256                                 EXTENT e;
2257                                 Lisp_Object obj2;
2258
2259                                 /* ----- update position in extent list
2260                                    and fetch next extent ----- */
2261
2262                                 if (posm) {
2263                                         /* fetch POS again to track extent
2264                                            insertions or deletions */
2265                                         pos = extent_list_marker_pos(el, posm);
2266                                 }
2267                                 if (pos >= extent_list_num_els(el)) {
2268                                         break;
2269                                 }
2270                                 e = extent_list_at(el, pos, range_endp);
2271                                 pos++;
2272                                 if (posm) {
2273                                         /* now point the marker to the next one
2274                                            we're going to process.  This ensures
2275                                            graceful behavior if this extent is
2276                                            deleted. */
2277                                         extent_list_move_marker(el, posm, pos);
2278                                 }
2279                                 /* ----- deal with internal extents ----- */
2280
2281                                 if (extent_internal_p(e)) {
2282                                         if (!(flags & ME_INCLUDE_INTERNAL)) {
2283                                                 continue;
2284                                         } else if (e == range) {
2285                                                 /* We're processing internal
2286                                                    extents and we've come across
2287                                                    our own special range extent.
2288                                                    (This happens only in
2289                                                    adjust_extents*() and
2290                                                    process_extents*(), which
2291                                                    handle text insertion and
2292                                                    deletion.) We need to omit
2293                                                    processing of this extent;
2294                                                    otherwise we will probably
2295                                                    end up prematurely
2296                                                    terminating this loop. */
2297                                                 continue;
2298                                         }
2299                                 }
2300
2301                                 /* ----- deal with AFTER condition ----- */
2302
2303                                 if (after) {
2304                                         /* if e > after, then we can stop
2305                                            skipping extents. */
2306                                         if (EXTENT_LESS(after, e)) {
2307                                                 after = 0;
2308                                         } else {
2309                                                 /* otherwise, skip this
2310                                                    extent. */
2311                                                 continue;
2312                                         }
2313                                 }
2314
2315                                 /* ----- stop if we're completely outside the
2316                                          range ----- */
2317
2318                                 /* fetch ST and EN again to track text
2319                                    insertions or deletions */
2320                                 if (range) {
2321                                         st = extent_start(range);
2322                                         en = extent_end(range);
2323                                 }
2324                                 if (extent_endpoint(e, range_endp) > en) {
2325                                         /* Can't be mapping over SOE because all
2326                                            extents in there should overlap ST */
2327                                         assert(stage == 1);
2328                                         break;
2329                                 }
2330
2331                                 /* ----- Now actually call the function ----- */
2332
2333                                 obj2 = extent_object(e);
2334                                 if (extent_in_region_p(
2335                                             e,
2336                                             buffer_or_string_memind_to_bytind
2337                                             (obj2, st),
2338                                             buffer_or_string_memind_to_bytind
2339                                             (obj2, en), flags)) {
2340                                         if ((*fn) (e, arg)) {
2341                                                 /* Function wants us to stop
2342                                                    mapping. */
2343                                                 stage = 1;
2344                                                 /* so outer for loop will
2345                                                    terminate */
2346                                                 break;
2347                                         }
2348                                 }
2349                         }
2350                 }
2351                 /* ---------- Finished looping. ---------- */
2352         }
2353
2354         if (flags & ME_MIGHT_THROW) {
2355                 /* This deletes the range extent and frees the marker. */
2356                 unbind_to(count, Qnil);
2357         } else {
2358                 /* Delete them ourselves */
2359                 if (range) {
2360                         extent_detach(range);
2361                 }
2362                 if (posm) {
2363                         extent_list_delete_marker(el, posm);
2364                 }
2365         }
2366 }
2367
2368 void
2369 map_extents(Bufpos from, Bufpos to, map_extents_fun fn,
2370             void *arg, Lisp_Object obj, EXTENT after, unsigned int flags)
2371 {
2372         map_extents_bytind(buffer_or_string_bufpos_to_bytind(obj, from),
2373                            buffer_or_string_bufpos_to_bytind(obj, to), fn, arg,
2374                            obj, after, flags);
2375 }
2376
2377 /* ------------------------------- */
2378 /*         adjust_extents()        */
2379 /* ------------------------------- */
2380
2381 /* Add AMOUNT to all extent endpoints in the range (FROM, TO].  This
2382    happens whenever the gap is moved or (under Mule) a character in a
2383    string is substituted for a different-length one.  The reason for
2384    this is that extent endpoints behave just like markers (all memory
2385    indices do) and this adjustment correct for markers -- see
2386    adjust_markers().  Note that it is important that we visit all
2387    extent endpoints in the range, irrespective of whether the
2388    endpoints are open or closed.
2389
2390    We could use map_extents() for this (and in fact the function
2391    was originally written that way), but the gap is in an incoherent
2392    state when this function is called and this function plays
2393    around with extent endpoints without detaching and reattaching
2394    the extents (this is provably correct and saves lots of time),
2395    so for safety we make it just look at the extent lists directly. */
2396
2397 void
2398 adjust_extents(Lisp_Object obj, Memind from, Memind to, int amount)
2399 {
2400         int endp;
2401         int pos;
2402         int startpos[2];
2403         extent_list_t el;
2404         extent_stack_t soe;
2405
2406 #ifdef ERROR_CHECK_EXTENTS
2407         sledgehammer_extent_check(obj);
2408 #endif
2409         el = buffer_or_string_extent_list(obj);
2410
2411         if (!el || !extent_list_num_els(el)) {
2412                 return;
2413         }
2414         /* IMPORTANT! Compute the starting positions of the extents to
2415            modify BEFORE doing any modification!  Otherwise the starting
2416            position for the second time through the loop might get
2417            incorrectly calculated (I got bit by this bug real bad). */
2418         startpos[0] = extent_list_locate_from_pos(el, from + 1, 0);
2419         startpos[1] = extent_list_locate_from_pos(el, from + 1, 1);
2420         for (endp = 0; endp < 2; endp++) {
2421                 for (pos = startpos[endp]; pos < extent_list_num_els(el);
2422                      pos++) {
2423                         EXTENT e = extent_list_at(el, pos, endp);
2424                         if (extent_endpoint(e, endp) > to) {
2425                                 break;
2426                         }
2427                         set_extent_endpoint(
2428                                 e,
2429                                 do_marker_adjustment(
2430                                         extent_endpoint(e, endp),
2431                                         from, to, amount),
2432                                 endp);
2433                 }
2434         }
2435
2436         /* The index for the buffer's SOE is a memory index and thus
2437            needs to be adjusted like a marker. */
2438         soe = buffer_or_string_stack_of_extents(obj);
2439         if (soe && soe->pos >= 0) {
2440                 soe->pos = do_marker_adjustment(soe->pos, from, to, amount);
2441         }
2442         return;
2443 }
2444
2445 /* ------------------------------- */
2446 /*  adjust_extents_for_deletion()  */
2447 /* ------------------------------- */
2448
2449 struct adjust_extents_for_deletion_arg {
2450         EXTENT_dynarr *list;
2451 };
2452
2453 static int adjust_extents_for_deletion_mapper(EXTENT extent, void *arg)
2454 {
2455         struct adjust_extents_for_deletion_arg *closure =
2456                 (struct adjust_extents_for_deletion_arg *)arg;
2457
2458         Dynarr_add(closure->list, extent);
2459         /* continue mapping */
2460         return 0;
2461 }
2462
2463 /* For all extent endpoints in the range (FROM, TO], move them to the beginning
2464    of the new gap.   Note that it is important that we visit all extent
2465    endpoints in the range, irrespective of whether the endpoints are open or
2466    closed.
2467
2468    This function deals with weird stuff such as the fact that extents
2469    may get reordered.
2470
2471    There is no string correspondent for this because you can't
2472    delete characters from a string.
2473  */
2474
2475 void
2476 adjust_extents_for_deletion(Lisp_Object object, Bytind from,
2477                             Bytind to, int gapsize, int numdel, int movegapsize)
2478 {
2479         struct adjust_extents_for_deletion_arg closure;
2480         int i;
2481         Memind adjust_to = (Memind) (to + gapsize);
2482         Bytecount amount = -numdel - movegapsize;
2483         Memind oldsoe = 0, newsoe = 0;
2484         extent_stack_t soe = buffer_or_string_stack_of_extents(object);
2485
2486 #ifdef ERROR_CHECK_EXTENTS
2487         sledgehammer_extent_check(object);
2488 #endif
2489         closure.list = Dynarr_new(EXTENT);
2490
2491         /* We're going to be playing weird games below with extents and the SOE
2492            and such, so compute the list now of all the extents that we're going
2493            to muck with.  If we do the mapping and adjusting together, things
2494            can get all screwed up. */
2495
2496         map_extents_bytind(from, to, adjust_extents_for_deletion_mapper,
2497                            (void *)&closure, object, 0,
2498                            /* extent endpoints move like markers regardless
2499                               of their open/closeness. */
2500                            ME_ALL_EXTENTS_CLOSED | ME_END_CLOSED |
2501                            ME_START_OR_END_IN_REGION | ME_INCLUDE_INTERNAL);
2502
2503         /*
2504            Old and new values for the SOE's position. (It gets adjusted
2505            like a marker, just like extent endpoints.)
2506          */
2507
2508         if (soe) {
2509                 oldsoe = soe->pos;
2510                 if (soe->pos >= 0) {
2511                         newsoe = do_marker_adjustment(
2512                                 soe->pos, adjust_to, adjust_to, amount);
2513                 } else {
2514                         newsoe = soe->pos;
2515                 }
2516         }
2517
2518         for (i = 0; i < Dynarr_length(closure.list); i++) {
2519                 EXTENT extent = Dynarr_at(closure.list, i);
2520                 Memind new_start = extent_start(extent);
2521                 Memind new_end = extent_end(extent);
2522
2523                 /* do_marker_adjustment() will not adjust values that should not
2524                    be adjusted.  We're passing the same funky arguments to
2525                    do_marker_adjustment() as buffer_delete_range() does. */
2526                 new_start = do_marker_adjustment(
2527                         new_start, adjust_to, adjust_to, amount);
2528                 new_end = do_marker_adjustment(
2529                         new_end, adjust_to, adjust_to, amount);
2530
2531                 /* We need to be very careful here so that the SOE doesn't get
2532                    corrupted.  We are shrinking extents out of the deleted
2533                    region and simultaneously moving the SOE's pos out of the
2534                    deleted region, so the SOE should contain the same extents at
2535                    the end as at the beginning.  However, extents may get
2536                    reordered by this process, so we have to operate by pulling
2537                    the extents out of the buffer and SOE, changing their bounds,
2538                    and then reinserting them.  In order for the SOE not to get
2539                    screwed up, we have to make sure that the SOE's pos points to
2540                    its old location whenever we pull an extent out, and points
2541                    to its new location whenever we put the extent back in.
2542                  */
2543
2544                 if (new_start != extent_start(extent) ||
2545                     new_end != extent_end(extent)) {
2546                         extent_detach(extent);
2547                         set_extent_start(extent, new_start);
2548                         set_extent_end(extent, new_end);
2549                         if (soe) {
2550                                 soe->pos = newsoe;
2551                         }
2552                         extent_attach(extent);
2553                         if (soe) {
2554                                 soe->pos = oldsoe;
2555                         }
2556                 }
2557         }
2558
2559         if (soe) {
2560                 soe->pos = newsoe;
2561         }
2562
2563 #ifdef ERROR_CHECK_EXTENTS
2564         sledgehammer_extent_check(object);
2565 #endif
2566         Dynarr_free(closure.list);
2567         return;
2568 }
2569
2570 /* ------------------------------- */
2571 /*         extent fragments        */
2572 /* ------------------------------- */
2573
2574 /* Imagine that the buffer is divided up into contiguous,
2575    nonoverlapping "runs" of text such that no extent
2576    starts or ends within a run (extents that abut the
2577    run don't count).
2578
2579    An extent fragment is a structure that holds data about
2580    the run that contains a particular buffer position (if
2581    the buffer position is at the junction of two runs, the
2582    run after the position is used) -- the beginning and
2583    end of the run, a list of all of the extents in that
2584    run, the "merged face" that results from merging all of
2585    the faces corresponding to those extents, the begin and
2586    end glyphs at the beginning of the run, etc.  This is
2587    the information that redisplay needs in order to
2588    display this run.
2589
2590    Extent fragments have to be very quick to update to
2591    a new buffer position when moving linearly through
2592    the buffer.  They rely on the stack-of-extents code,
2593    which does the heavy-duty algorithmic work of determining
2594    which extents overly a particular position. */
2595
2596 /* This function returns the position of the beginning of
2597    the first run that begins after POS, or returns POS if
2598    there are no such runs. */
2599
2600 static Bytind
2601 extent_find_end_of_run(Lisp_Object obj, Bytind pos, int outside_accessible)
2602 {
2603         extent_list_t sel;
2604         extent_list_t bel = buffer_or_string_extent_list(obj);
2605         Bytind pos1, pos2;
2606         int elind1, elind2;
2607         Memind mempos = buffer_or_string_bytind_to_memind(obj, pos);
2608         Bytind limit = outside_accessible ?
2609             buffer_or_string_absolute_end_byte(obj) :
2610             buffer_or_string_accessible_end_byte(obj);
2611
2612         if (!bel || !extent_list_num_els(bel)) {
2613                 return limit;
2614         }
2615         sel = buffer_or_string_stack_of_extents_force(obj)->extents;
2616         soe_move(obj, mempos);
2617
2618         /* Find the first start position after POS. */
2619         elind1 = extent_list_locate_from_pos(bel, mempos + 1, 0);
2620         if (elind1 < extent_list_num_els(bel)) {
2621                 pos1 = buffer_or_string_memind_to_bytind(
2622                         obj, extent_start(extent_list_at(bel, elind1, 0)));
2623         } else {
2624                 pos1 = limit;
2625         }
2626
2627         /* Find the first end position after POS.  The extent corresponding
2628            to this position is either in the SOE or is greater than or
2629            equal to POS1, so we just have to look in the SOE. */
2630         elind2 = extent_list_locate_from_pos(sel, mempos + 1, 1);
2631         if (elind2 < extent_list_num_els(sel)) {
2632                 pos2 = buffer_or_string_memind_to_bytind(
2633                         obj, extent_end(extent_list_at(sel, elind2, 1)));
2634         } else {
2635                 pos2 = limit;
2636         }
2637         return min(min(pos1, pos2), limit);
2638 }
2639
2640 static Bytind
2641 extent_find_beginning_of_run(Lisp_Object obj, Bytind pos,
2642                              int outside_accessible)
2643 {
2644         extent_list_t sel;
2645         extent_list_t bel = buffer_or_string_extent_list(obj);
2646         Bytind pos1, pos2;
2647         int elind1, elind2;
2648         Memind mempos = buffer_or_string_bytind_to_memind(obj, pos);
2649         Bytind limit = outside_accessible
2650                 ? buffer_or_string_absolute_begin_byte(obj)
2651                 : buffer_or_string_accessible_begin_byte(obj);
2652
2653         if (!bel || !extent_list_num_els(bel)) {
2654                 return limit;
2655         }
2656         sel = buffer_or_string_stack_of_extents_force(obj)->extents;
2657         soe_move(obj, mempos);
2658
2659         /* Find the first end position before POS. */
2660         elind1 = extent_list_locate_from_pos(bel, mempos, 1);
2661         if (elind1 > 0) {
2662                 pos1 = buffer_or_string_memind_to_bytind(
2663                         obj, extent_end(extent_list_at(bel, elind1 - 1, 1)));
2664         } else {
2665                 pos1 = limit;
2666         }
2667         /* Find the first start position before POS.  The extent corresponding
2668            to this position is either in the SOE or is less than or
2669            equal to POS1, so we just have to look in the SOE. */
2670         elind2 = extent_list_locate_from_pos(sel, mempos, 0);
2671         if (elind2 > 0) {
2672                 pos2 = buffer_or_string_memind_to_bytind(
2673                         obj, extent_start(extent_list_at(sel, elind2 - 1, 0)));
2674         } else {
2675                 pos2 = limit;
2676         }
2677         return max(max(pos1, pos2), limit);
2678 }
2679
2680 struct extent_fragment*
2681 extent_fragment_new(Lisp_Object buffer_or_string, struct frame *frm)
2682 {
2683         struct extent_fragment *ef = xnew_and_zero(struct extent_fragment);
2684
2685         ef->object = buffer_or_string;
2686         ef->frm = frm;
2687         ef->extents = Dynarr_new(EXTENT);
2688         ef->glyphs = Dynarr_new(glyph_block);
2689
2690         return ef;
2691 }
2692
2693 void extent_fragment_delete(struct extent_fragment *ef)
2694 {
2695         Dynarr_free(ef->extents);
2696         Dynarr_free(ef->glyphs);
2697         xfree(ef);
2698 }
2699
2700 static int
2701 extent_priority_sort_function(const void *humpty, const void *dumpty)
2702 {
2703         const EXTENT foo = *(const EXTENT *)humpty;
2704         const EXTENT bar = *(const EXTENT *)dumpty;
2705         if (extent_priority(foo) < extent_priority(bar)) {
2706                 return -1;
2707         }
2708         return extent_priority(foo) > extent_priority(bar);
2709 }
2710
2711 static void
2712 extent_fragment_sort_by_priority(EXTENT_dynarr * extarr)
2713 {
2714         int i;
2715
2716         /* Sort our copy of the stack by extent_priority.  We use a bubble
2717            sort here because it's going to be faster than qsort() for small
2718            numbers of extents (less than 10 or so), and 99.999% of the time
2719            there won't ever be more extents than this in the stack. */
2720         if (Dynarr_length(extarr) < 10) {
2721                 for (i = 1; i < Dynarr_length(extarr); i++) {
2722                         int j = i - 1;
2723                         while (j >= 0 &&
2724                                (extent_priority(Dynarr_at(extarr, j)) >
2725                                 extent_priority(Dynarr_at(extarr, j + 1)))) {
2726                                 EXTENT tmp = Dynarr_at(extarr, j);
2727                                 Dynarr_at(extarr, j) = Dynarr_at(extarr, j + 1);
2728                                 Dynarr_at(extarr, j + 1) = tmp;
2729                                 j--;
2730                         }
2731                 }
2732         } else {
2733                 /* But some loser programs mess up and may create a large number
2734                    of extents overlapping the same spot.  This will result in
2735                    catastrophic behavior if we use the bubble sort above. */
2736                 qsort(Dynarr_atp(extarr, 0), Dynarr_length(extarr),
2737                       sizeof(EXTENT), extent_priority_sort_function);
2738         }
2739 }
2740
2741 /* If PROP is the `invisible' property of an extent,
2742    this is 1 if the extent should be treated as invisible.  */
2743
2744 #define EXTENT_PROP_MEANS_INVISIBLE(buf, prop)                  \
2745   (EQ (buf->invisibility_spec, Qt)                              \
2746    ? ! NILP (prop)                                              \
2747    : invisible_p (prop, buf->invisibility_spec))
2748
2749 /* If PROP is the `invisible' property of a extent,
2750    this is 1 if the extent should be treated as invisible
2751    and should have an ellipsis.  */
2752
2753 #define EXTENT_PROP_MEANS_INVISIBLE_WITH_ELLIPSIS(buf, prop)    \
2754   (EQ (buf->invisibility_spec, Qt)                              \
2755    ? 0                                                          \
2756    : invisible_ellipsis_p (prop, buf->invisibility_spec))
2757
2758 /* This is like a combination of memq and assq.
2759    Return 1 if PROPVAL appears as an element of LIST
2760    or as the car of an element of LIST.
2761    If PROPVAL is a list, compare each element against LIST
2762    in that way, and return 1 if any element of PROPVAL is found in LIST.
2763    Otherwise return 0.
2764    This function cannot quit.  */
2765
2766 static int
2767 invisible_p(REGISTER Lisp_Object propval, Lisp_Object list)
2768 {
2769         REGISTER Lisp_Object tail, proptail;
2770         for (tail = list; CONSP(tail); tail = XCDR(tail)) {
2771                 REGISTER Lisp_Object tem;
2772                 tem = XCAR(tail);
2773                 if (EQ(propval, tem))
2774                         return 1;
2775                 if (CONSP(tem) && EQ(propval, XCAR(tem)))
2776                         return 1;
2777         }
2778         if (CONSP(propval)) {
2779                 for (proptail = propval; CONSP(proptail);
2780                      proptail = XCDR(proptail)) {
2781                         Lisp_Object propelt;
2782                         propelt = XCAR(proptail);
2783                         for (tail = list; CONSP(tail); tail = XCDR(tail)) {
2784                                 REGISTER Lisp_Object tem;
2785                                 tem = XCAR(tail);
2786                                 if (EQ(propelt, tem)) {
2787                                         return 1;
2788                                 }
2789                                 if (CONSP(tem) && EQ(propelt, XCAR(tem))) {
2790                                         return 1;
2791                                 }
2792                         }
2793                 }
2794         }
2795         return 0;
2796 }
2797
2798 /* Return 1 if PROPVAL appears as the car of an element of LIST
2799    and the cdr of that element is non-nil.
2800    If PROPVAL is a list, check each element of PROPVAL in that way,
2801    and the first time some element is found,
2802    return 1 if the cdr of that element is non-nil.
2803    Otherwise return 0.
2804    This function cannot quit.  */
2805
2806 static int
2807 invisible_ellipsis_p(REGISTER Lisp_Object propval, Lisp_Object list)
2808 {
2809         REGISTER Lisp_Object tail, proptail;
2810
2811         for (tail = list; CONSP(tail); tail = XCDR(tail)) {
2812                 REGISTER Lisp_Object tem;
2813                 tem = XCAR(tail);
2814                 if (CONSP(tem) && EQ(propval, XCAR(tem))) {
2815                         return !NILP(XCDR(tem));
2816                 }
2817         }
2818         if (CONSP(propval)) {
2819                 for (proptail = propval; CONSP(proptail);
2820                      proptail = XCDR(proptail)) {
2821                         Lisp_Object propelt;
2822                         propelt = XCAR(proptail);
2823                         for (tail = list; CONSP(tail); tail = XCDR(tail)) {
2824                                 REGISTER Lisp_Object tem;
2825                                 tem = XCAR(tail);
2826                                 if (CONSP(tem) && EQ(propelt, XCAR(tem))) {
2827                                         return !NILP(XCDR(tem));
2828                                 }
2829                         }
2830                 }
2831         }
2832         return 0;
2833 }
2834
2835 face_index
2836 extent_fragment_update(struct window * w, struct extent_fragment * ef,
2837                        Bytind pos, Lisp_Object last_glyph)
2838 {
2839         int i, j;
2840         int seen_glyph = NILP(last_glyph) ? 1 : 0;
2841         extent_list_t sel =
2842                 buffer_or_string_stack_of_extents_force(ef->object)->extents;
2843         EXTENT lhe = 0;
2844         struct extent dummy_lhe_extent;
2845         Memind mempos = buffer_or_string_bytind_to_memind(ef->object, pos);
2846         glyph_block_dynarr *glyphs; /* List of glyphs to post process */
2847         int invis_before = 0;  /* Exiting an invisible extent.  */
2848         int invis_after = 0;   /* Entering an invisible extent. */
2849         int insert_empty = 0;  /* Position to insert empty extent glyphs  */
2850         int queuing_begin = 0;  /* Queuing begin glyphs. */
2851
2852 #ifdef ERROR_CHECK_EXTENTS
2853         assert(pos >= buffer_or_string_accessible_begin_byte(ef->object)
2854                && pos <= buffer_or_string_accessible_end_byte(ef->object));
2855 #endif
2856
2857         Dynarr_reset(ef->extents);
2858         Dynarr_reset(ef->glyphs);
2859
2860         ef->previously_invisible = ef->invisible;
2861         if (ef->invisible) {
2862                 if (ef->invisible_ellipses)
2863                         ef->invisible_ellipses_already_displayed = 1;
2864         } else {
2865                 ef->invisible_ellipses_already_displayed = 0;
2866         }
2867         ef->invisible = 0;
2868         ef->invisible_ellipses = 0;
2869
2870         /* Set up the begin and end positions. */
2871         ef->pos = pos;
2872         ef->end = extent_find_end_of_run(ef->object, pos, 0);
2873
2874         /* Note that extent_find_end_of_run() already moved the SOE for us. */
2875         /* soe_move (ef->object, mempos); */
2876
2877         /* We tried determining all the charsets used in the run here,
2878            but that fails even if we only do the current line -- display
2879            tables or non-printable characters might cause other charsets
2880            to be used. */
2881
2882         /* Determine whether the last-highlighted-extent is present. */
2883         if (EXTENTP(Vlast_highlighted_extent))
2884                 lhe = XEXTENT(Vlast_highlighted_extent);
2885
2886         /* Now add all extents that overlap the character after POS and
2887            have a non-nil face.  Also check if the character is
2888            invisible.  We also queue begin and end glyphs of extents
2889            that being/end at just before POS.  These are ordered as
2890            follows. 1) end glyphs of non-empty extents in reverse
2891            display order.  2) begin glyphs of empty extents.  3) end
2892            glyphs of empty extents.  4) begin glyphs of non-empty
2893            extents in display order.  Empty extents are shown nested,
2894            but the invisibility property of an empty extent is
2895            ignored and not used to determine whether an 'interior'
2896            empty extent's glyphs should be shown or not.  */
2897         glyphs = Dynarr_new(glyph_block);
2898         for (i = 0; i < extent_list_num_els(sel); i++) {
2899                 EXTENT e = extent_list_at(sel, i, 0);
2900                 int zero_width = extent_start(e) == extent_end(e);
2901                 Lisp_Object invis_prop = extent_invisible(e);
2902                 Lisp_Object glyph;
2903
2904                 if (extent_start(e) == mempos) {
2905                         /* The extent starts here.  If we are queuing
2906                            end glyphs, we should display all the end
2907                            glyphs we've pushed.  */
2908
2909                         if (!queuing_begin) {
2910                                 /* Append any already seen end glyphs */
2911                                 for (j = Dynarr_length(glyphs); j--;) {
2912                                         struct glyph_block *gbp
2913                                           = Dynarr_atp(glyphs, j);
2914                         
2915                                         if (seen_glyph)
2916                                                 Dynarr_add(ef->glyphs, *gbp);
2917                                         else if (EQ(gbp->glyph, last_glyph))
2918                                                 seen_glyph = 1;
2919                                 }
2920
2921                                 /* Pop the end glyphs just displayed. */
2922                                 Dynarr_set_size(glyphs, 0);
2923                                 /* We are now queuing begin glyphs. */
2924                                 queuing_begin = 1;
2925                                 /* And will insert empty extent glyphs
2926                                    just here.  */
2927                                 insert_empty = Dynarr_length (ef->glyphs);
2928                         }
2929
2930                         glyph = extent_begin_glyph(e);
2931                         
2932                         if (!NILP(glyph)) {
2933                                 struct glyph_block gb;
2934
2935                                 memset(&gb,0,sizeof(gb));
2936
2937                                 gb.glyph = glyph;
2938                                 gb.active = 0; /* BEGIN_GLYPH */
2939                                 gb.width = 0;
2940                                 XSETEXTENT(gb.extent, e);
2941                     
2942                                 if (zero_width) {
2943                                         if (insert_empty
2944                                             == Dynarr_length (ef->glyphs))
2945                                                 Dynarr_add (ef->glyphs, gb);
2946                                         else
2947                                                 Dynarr_insert_many
2948                                                   (ef->glyphs, &gb,
2949                                                    1, insert_empty);
2950                                 } else if (!invis_after) 
2951                                         Dynarr_add (glyphs, gb);
2952                         }
2953                 }
2954                 
2955                 if (extent_end(e) == mempos) {
2956                         /* The extend ends here.  Push the end glyph.  */
2957                         glyph = extent_end_glyph(e);
2958
2959                         if (!NILP (glyph)) {
2960                                 struct glyph_block gb;
2961
2962                                 gb.width = gb.findex = 0; /* just init */
2963                                 gb.glyph = glyph;
2964                                 gb.active = 1; /* END_GLYPH */
2965                                 XSETEXTENT(gb.extent, e);
2966
2967                                 if (zero_width)
2968                                   Dynarr_add (ef->glyphs, gb);
2969                                 else if (!invis_before)
2970                                   Dynarr_add(glyphs, gb);
2971                         }
2972                         /* If this extent is not empty, any inner
2973                            extents ending here will not be visible.  */
2974                         if (extent_start (e) < mempos && !NILP (invis_prop))
2975                           invis_before = 1;
2976                 }
2977                 
2978                 if (extent_end(e) > mempos) {
2979                         /* This extent covers POS. */
2980                         if (!NILP(invis_prop)) {
2981                                 invis_after = 1;
2982                                 /* If this extend spans POS, all
2983                                    glyphs are invisible.  */
2984                                 if (extent_start (e) < mempos)
2985                                         Dynarr_set_size (glyphs, 0);
2986                           
2987                                 if (!BUFFERP(ef->object))
2988                                         /* #### no `string-invisibility-spec' */
2989                                         ef->invisible = 1;
2990                                 else {
2991                                         if (!ef->
2992                                             invisible_ellipses_already_displayed
2993                                             &&
2994                                             EXTENT_PROP_MEANS_INVISIBLE_WITH_ELLIPSIS
2995                                             (XBUFFER(ef->object), invis_prop)) {
2996                                                 ef->invisible = 1;
2997                                                 ef->invisible_ellipses = 1;
2998                                         } else if (EXTENT_PROP_MEANS_INVISIBLE
2999                                                    (XBUFFER(ef->object),
3000                                                     invis_prop))
3001                                                 ef->invisible = 1;
3002                                 }
3003                         }
3004
3005                         /* Remember that one of the extents in the list might be
3006                            our dummy extent representing the highlighting that
3007                            is attached to some other extent that is currently
3008                            mouse-highlighted.  When an extent is
3009                            mouse-highlighted, it is as if there are two extents
3010                            there, of potentially different priorities: the
3011                            extent being highlighted, with whatever face and
3012                            priority it has; and an ephemeral extent in the
3013                            `mouse-face' face with `mouse-highlight-priority'.
3014                          */
3015
3016                         if (!NILP(extent_face(e)))
3017                                 Dynarr_add(ef->extents, e);
3018                         if (e == lhe) {
3019                                 Lisp_Object f;
3020                                 /* zeroing isn't really necessary; we only deref
3021                                    `priority' and `face' */
3022                                 xzero(dummy_lhe_extent);
3023                                 set_extent_priority(&dummy_lhe_extent,
3024                                                     mouse_highlight_priority);
3025                                 /* Need to break up the following expression,
3026                                    due to an */
3027                                 /* error in the Digital UNIX 3.2g C compiler
3028                                    (Digital */
3029                                 /* UNIX Compiler Driver 3.11). */
3030                                 f = extent_mouse_face(lhe);
3031                                 extent_face(&dummy_lhe_extent) = f;
3032                                 Dynarr_add(ef->extents, &dummy_lhe_extent);
3033                         }
3034                         /* since we are looping anyway, we might as well do this
3035                            here */
3036                         if ((!NILP(extent_initial_redisplay_function(e))) &&
3037                             !extent_in_red_event_p(e)) {
3038                                 Lisp_Object function =
3039                                         extent_initial_redisplay_function(e);
3040                                 Lisp_Object obj;
3041
3042                                 /* print_extent_2 (e);
3043                                    printf ("\n"); */
3044
3045                                 /* FIXME: One should probably inhibit the
3046                                    displaying of this extent to reduce
3047                                    flicker */
3048                                 extent_in_red_event_p(e) = 1;
3049
3050                                 /* call the function */
3051                                 XSETEXTENT(obj, e);
3052                                 if (!NILP(function)) {
3053                                         Fenqueue_eval_event(function, obj);
3054                                 }
3055                         }
3056                 }
3057         }
3058
3059         if (!queuing_begin) {
3060                 /* Append end glyphs in reverse order */
3061                 for (j = Dynarr_length(glyphs); j--;) {
3062                         struct glyph_block *gbp = Dynarr_atp(glyphs, j);
3063             
3064                         if (seen_glyph)
3065                                 Dynarr_add(ef->glyphs, *gbp);
3066                         else if (EQ(gbp->glyph, last_glyph))
3067                                 seen_glyph = 1;
3068                 }
3069         } else {
3070                 if (!seen_glyph) {
3071                         /* Scan the zero length glyphs and see where we
3072                            start a glyph that has not been displayed yet.  */
3073                         for (j = insert_empty;
3074                              j != Dynarr_length (ef->glyphs); j++) {
3075                                 struct glyph_block *gbp
3076                                         = Dynarr_atp(ef->glyphs, j);
3077                     
3078                                 if (EQ(gbp->glyph, last_glyph)) {
3079                                         seen_glyph = 1;
3080                                         j++;
3081                                         break;
3082                                 }
3083                         }
3084                         Dynarr_delete_many (ef->glyphs, insert_empty,
3085                                             j - insert_empty);
3086                 }
3087
3088                 /* Now copy the begin glyphs. */
3089                 for (j = 0; j != Dynarr_length (glyphs); j++) {
3090                         struct glyph_block *gbp = Dynarr_atp(glyphs, j);
3091                 
3092                         if (seen_glyph)
3093                                 Dynarr_add(ef->glyphs, *gbp);
3094                         else if (EQ(gbp->glyph, last_glyph))
3095                                 seen_glyph = 1;
3096                 }
3097         }
3098
3099         Dynarr_free(glyphs);
3100
3101         extent_fragment_sort_by_priority(ef->extents);
3102
3103         /* Now merge the faces together into a single face.  The code to
3104            do this is in faces.c because it involves manipulating faces. */
3105         return get_extent_fragment_face_cache_index(w, ef);
3106 }
3107 \f
3108 /************************************************************************/
3109 /*                      extent-object methods                           */
3110 /************************************************************************/
3111
3112 /* These are the basic helper functions for handling the allocation of
3113    extent objects.  They are similar to the functions for other
3114    lrecord objects.  allocate_extent() is in alloc.c, not here. */
3115
3116 static Lisp_Object mark_extent(Lisp_Object obj)
3117 {
3118         struct extent *extent = XEXTENT(obj);
3119
3120         mark_object(extent_object(extent));
3121         mark_object(extent_no_chase_normal_field(extent, face));
3122         return extent->plist;
3123 }
3124
3125 static void
3126 print_extent_1(Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
3127 {
3128         EXTENT ext = XEXTENT(obj);
3129         EXTENT anc = extent_ancestor(ext);
3130         Lisp_Object tail;
3131         char buf[100], *bp = buf;
3132         int sz;
3133
3134         /* Retrieve the ancestor and use it, for faster retrieval of properties */
3135
3136         if (!NILP(extent_begin_glyph(anc)))
3137                 *bp++ = '*';
3138         *bp++ = (extent_start_open_p(anc) ? '(' : '[');
3139         if (extent_detached_p(ext))
3140                 strncpy(bp, "detached", sizeof(buf)-1);
3141         else {
3142                 sz=snprintf(bp, sizeof(buf)-2, "%ld, %ld",
3143                             XINT(Fextent_start_position(obj)),
3144                             XINT(Fextent_end_position(obj)));
3145                 assert(sz>=0 && (size_t)sz<(sizeof(buf)-2));
3146         }
3147         bp += strlen(bp);
3148         *bp++ = (extent_end_open_p(anc) ? ')' : ']');
3149         if (!NILP(extent_end_glyph(anc)))
3150                 *bp++ = '*';
3151         *bp++ = ' ';
3152
3153         if (!NILP(extent_read_only(anc)))
3154                 *bp++ = '%';
3155         if (!NILP(extent_mouse_face(anc)))
3156                 *bp++ = 'H';
3157         if (extent_unique_p(anc))
3158                 *bp++ = 'U';
3159         else if (extent_duplicable_p(anc))
3160                 *bp++ = 'D';
3161         if (!NILP(extent_invisible(anc)))
3162                 *bp++ = 'I';
3163
3164         if (!NILP(extent_read_only(anc)) || !NILP(extent_mouse_face(anc)) ||
3165             extent_unique_p(anc) ||
3166             extent_duplicable_p(anc) || !NILP(extent_invisible(anc)))
3167                 *bp++ = ' ';
3168         *bp = '\0';
3169         write_c_string(buf, printcharfun);
3170
3171         tail = extent_plist_slot(anc);
3172
3173         for (; !NILP(tail); tail = Fcdr(Fcdr(tail))) {
3174                 Lisp_Object v = XCAR(XCDR(tail));
3175                 if (NILP(v))
3176                         continue;
3177                 print_internal(XCAR(tail), printcharfun, escapeflag);
3178                 write_c_string(" ", printcharfun);
3179         }
3180
3181         write_fmt_str(printcharfun, "0x%lx", (long)ext);
3182 }
3183
3184 static void
3185 print_extent(Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
3186 {
3187         if (escapeflag) {
3188                 const char *title = "";
3189                 const char *name = "";
3190                 const char *posttitle = "";
3191                 Lisp_Object obj2 = Qnil;
3192
3193                 /* Destroyed extents have 't' in the object field, causing
3194                    extent_object() to abort (maybe). */
3195                 if (EXTENT_LIVE_P(XEXTENT(obj)))
3196                         obj2 = extent_object(XEXTENT(obj));
3197
3198                 if (NILP(obj2))
3199                         title = "no buffer";
3200                 else if (BUFFERP(obj2)) {
3201                         if (BUFFER_LIVE_P(XBUFFER(obj2))) {
3202                                 title = "buffer ";
3203                                 name =
3204                                     (char *)XSTRING_DATA(XBUFFER(obj2)->name);
3205                         } else {
3206                                 title = "Killed Buffer";
3207                                 name = "";
3208                         }
3209                 } else {
3210                         assert(STRINGP(obj2));
3211                         title = "string \"";
3212                         posttitle = "\"";
3213                         name = (char *)XSTRING_DATA(obj2);
3214                 }
3215
3216                 if (print_readably) {
3217                         if (!EXTENT_LIVE_P(XEXTENT(obj))) {
3218                                 error("printing unreadable object "
3219                                       "#<destroyed extent>");
3220                         } else {
3221                                 error("printing unreadable object "
3222                                       "#<extent %p>", XEXTENT(obj));
3223                         }
3224                 }
3225
3226                 if (!EXTENT_LIVE_P(XEXTENT(obj))) {
3227                         write_c_string("#<destroyed extent", printcharfun);
3228                 } else {
3229                         write_c_string("#<extent ", printcharfun);
3230                         print_extent_1(obj, printcharfun, escapeflag);
3231                         write_c_string(extent_detached_p(XEXTENT(obj))
3232                                        ? " from " : " in ", printcharfun);
3233                         write_fmt_string(printcharfun, "%s%s%s", title, name, posttitle);
3234                 }
3235         } else {
3236                 if (print_readably)
3237                         error("printing unreadable object #<extent>");
3238                 write_c_string("#<extent", printcharfun);
3239         }
3240         write_c_string(">", printcharfun);
3241 }
3242
3243 static int properties_equal(EXTENT e1, EXTENT e2, int depth)
3244 {
3245         /* When this function is called, all indirections have been followed.
3246            Thus, the indirection checks in the various macros below will not
3247            amount to anything, and could be removed.  However, the time
3248            savings would probably not be significant. */
3249         if (!(EQ(extent_face(e1), extent_face(e2)) &&
3250               extent_priority(e1) == extent_priority(e2) &&
3251               internal_equal(extent_begin_glyph(e1), extent_begin_glyph(e2),
3252                              depth + 1) &&
3253               internal_equal(extent_end_glyph(e1), extent_end_glyph(e2),
3254                              depth + 1)))
3255                 return 0;
3256
3257         /* compare the bit flags. */
3258         {
3259                 /* The has_aux field should not be relevant. */
3260                 int e1_has_aux = e1->flags.has_aux;
3261                 int e2_has_aux = e2->flags.has_aux;
3262                 int value;
3263
3264                 e1->flags.has_aux = e2->flags.has_aux = 0;
3265                 value = memcmp(&e1->flags, &e2->flags, sizeof(e1->flags));
3266                 e1->flags.has_aux = e1_has_aux;
3267                 e2->flags.has_aux = e2_has_aux;
3268                 if (value)
3269                         return 0;
3270         }
3271
3272         /* compare the random elements of the plists. */
3273         return !plists_differ(extent_no_chase_plist(e1),
3274                               extent_no_chase_plist(e2), 0, 0, depth + 1);
3275 }
3276
3277 static int extent_equal(Lisp_Object obj1, Lisp_Object obj2, int depth)
3278 {
3279         struct extent *e1 = XEXTENT(obj1);
3280         struct extent *e2 = XEXTENT(obj2);
3281         return
3282             (extent_start(e1) == extent_start(e2) &&
3283              extent_end(e1) == extent_end(e2) &&
3284              internal_equal(extent_object(e1), extent_object(e2), depth + 1) &&
3285              properties_equal(extent_ancestor(e1), extent_ancestor(e2), depth));
3286 }
3287
3288 static unsigned long extent_hash(Lisp_Object obj, int depth)
3289 {
3290         struct extent *e = XEXTENT(obj);
3291         /* No need to hash all of the elements; that would take too long.
3292            Just hash the most common ones. */
3293         return HASH3(extent_start(e), extent_end(e),
3294                      internal_hash(extent_object(e), depth + 1));
3295 }
3296
3297 static const struct lrecord_description extent_description[] = {
3298         {XD_LISP_OBJECT, offsetof(struct extent, object)},
3299         {XD_LISP_OBJECT, offsetof(struct extent, flags.face)},
3300         {XD_LISP_OBJECT, offsetof(struct extent, plist)},
3301         {XD_END}
3302 };
3303
3304 static Lisp_Object extent_getprop(Lisp_Object obj, Lisp_Object prop)
3305 {
3306         return Fextent_property(obj, prop, Qunbound);
3307 }
3308
3309 static int extent_putprop(Lisp_Object obj, Lisp_Object prop, Lisp_Object value)
3310 {
3311         Fset_extent_property(obj, prop, value);
3312         return 1;
3313 }
3314
3315 static int extent_remprop(Lisp_Object obj, Lisp_Object prop)
3316 {
3317         EXTENT ext = XEXTENT(obj);
3318
3319         /* This list is taken from Fset_extent_property, and should be kept
3320            in synch.  */
3321         if (EQ(prop, Qread_only)
3322             || EQ(prop, Qunique)
3323             || EQ(prop, Qduplicable)
3324             || EQ(prop, Qinvisible)
3325             || EQ(prop, Qdetachable)
3326             || EQ(prop, Qdetached)
3327             || EQ(prop, Qdestroyed)
3328             || EQ(prop, Qpriority)
3329             || EQ(prop, Qface)
3330             || EQ(prop, Qinitial_redisplay_function)
3331             || EQ(prop, Qafter_change_functions)
3332             || EQ(prop, Qbefore_change_functions)
3333             || EQ(prop, Qmouse_face)
3334             || EQ(prop, Qhighlight)
3335             || EQ(prop, Qbegin_glyph_layout)
3336             || EQ(prop, Qend_glyph_layout)
3337             || EQ(prop, Qglyph_layout)
3338             || EQ(prop, Qbegin_glyph)
3339             || EQ(prop, Qend_glyph)
3340             || EQ(prop, Qstart_open)
3341             || EQ(prop, Qend_open)
3342             || EQ(prop, Qstart_closed)
3343             || EQ(prop, Qend_closed)
3344             || EQ(prop, Qkeymap)) {
3345                 /* #### Is this correct, anyway?  */
3346                 return -1;
3347         }
3348
3349         return external_remprop(extent_plist_addr(ext), prop, 0, ERROR_ME);
3350 }
3351
3352 static Lisp_Object extent_plist(Lisp_Object obj)
3353 {
3354         return Fextent_properties(obj);
3355 }
3356
3357 DEFINE_BASIC_LRECORD_IMPLEMENTATION_WITH_PROPS("extent", extent,
3358                                                mark_extent, print_extent,
3359                                                /* NOTE: If you declare a
3360                                                   finalization method here,
3361                                                   it will NOT be called.
3362                                                   Shaft city. */
3363                                                0,
3364                                                extent_equal, extent_hash,
3365                                                extent_description,
3366                                                extent_getprop, extent_putprop,
3367                                                extent_remprop, extent_plist,
3368                                                struct extent);
3369 \f
3370 /************************************************************************/
3371 /*                      basic extent accessors                          */
3372 /************************************************************************/
3373
3374 /* These functions are for checking externally-passed extent objects
3375    and returning an extent's basic properties, which include the
3376    buffer the extent is associated with, the endpoints of the extent's
3377    range, the open/closed-ness of those endpoints, and whether the
3378    extent is detached.  Manipulating these properties requires
3379    manipulating the ordered lists that hold extents; thus, functions
3380    to do that are in a later section. */
3381
3382 /* Given a Lisp_Object that is supposed to be an extent, make sure it
3383    is OK and return an extent pointer.  Extents can be in one of four
3384    states:
3385
3386    1) destroyed
3387    2) detached and not associated with a buffer
3388    3) detached and associated with a buffer
3389    4) attached to a buffer
3390
3391    If FLAGS is 0, types 2-4 are allowed.  If FLAGS is DE_MUST_HAVE_BUFFER,
3392    types 3-4 are allowed.  If FLAGS is DE_MUST_BE_ATTACHED, only type 4
3393    is allowed.
3394    */
3395
3396 static EXTENT decode_extent(Lisp_Object extent_obj, unsigned int flags)
3397 {
3398         EXTENT extent;
3399         Lisp_Object obj;
3400
3401         CHECK_LIVE_EXTENT(extent_obj);
3402         extent = XEXTENT(extent_obj);
3403         obj = extent_object(extent);
3404
3405         /* the following condition will fail if we're dealing with a freed extent */
3406         assert(NILP(obj) || BUFFERP(obj) || STRINGP(obj));
3407
3408         if (flags & DE_MUST_BE_ATTACHED)
3409                 flags |= DE_MUST_HAVE_BUFFER;
3410
3411         /* if buffer is dead, then convert extent to have no buffer. */
3412         if (BUFFERP(obj) && !BUFFER_LIVE_P(XBUFFER(obj)))
3413                 obj = extent_object(extent) = Qnil;
3414
3415         assert(!NILP(obj) || extent_detached_p(extent));
3416
3417         if ((NILP(obj) && (flags & DE_MUST_HAVE_BUFFER))
3418             || (extent_detached_p(extent) && (flags & DE_MUST_BE_ATTACHED))) {
3419                 invalid_argument("extent doesn't belong to a buffer or string",
3420                                  extent_obj);
3421         }
3422
3423         return extent;
3424 }
3425
3426 /* Note that the returned value is a buffer position, not a byte index. */
3427
3428 static Lisp_Object extent_endpoint_external(Lisp_Object extent_obj, int endp)
3429 {
3430         EXTENT extent = decode_extent(extent_obj, 0);
3431
3432         if (extent_detached_p(extent))
3433                 return Qnil;
3434         else
3435                 return make_int(extent_endpoint_bufpos(extent, endp));
3436 }
3437
3438 DEFUN("extentp", Fextentp, 1, 1, 0,     /*
3439 Return t if OBJECT is an extent.
3440 */
3441       (object))
3442 {
3443         return EXTENTP(object) ? Qt : Qnil;
3444 }
3445
3446 DEFUN("extent-live-p", Fextent_live_p, 1, 1, 0, /*
3447 Return t if OBJECT is an extent that has not been destroyed.
3448 */
3449       (object))
3450 {
3451         return EXTENTP(object) && EXTENT_LIVE_P(XEXTENT(object)) ? Qt : Qnil;
3452 }
3453
3454 DEFUN("extent-detached-p", Fextent_detached_p, 1, 1, 0, /*
3455 Return t if EXTENT is detached.
3456 */
3457       (extent))
3458 {
3459         return extent_detached_p(decode_extent(extent, 0)) ? Qt : Qnil;
3460 }
3461
3462 DEFUN("extent-object", Fextent_object, 1, 1, 0, /*
3463 Return object (buffer or string) that EXTENT refers to.
3464 */
3465       (extent))
3466 {
3467         return extent_object(decode_extent(extent, 0));
3468 }
3469
3470 DEFUN("extent-start-position", Fextent_start_position, 1, 1, 0, /*
3471 Return start position of EXTENT, or nil if EXTENT is detached.
3472 */
3473       (extent))
3474 {
3475         return extent_endpoint_external(extent, 0);
3476 }
3477
3478 DEFUN("extent-end-position", Fextent_end_position, 1, 1, 0,     /*
3479 Return end position of EXTENT, or nil if EXTENT is detached.
3480 */
3481       (extent))
3482 {
3483         return extent_endpoint_external(extent, 1);
3484 }
3485
3486 DEFUN("extent-length", Fextent_length, 1, 1, 0, /*
3487 Return length of EXTENT in characters.
3488 */
3489       (extent))
3490 {
3491         EXTENT e = decode_extent(extent, DE_MUST_BE_ATTACHED);
3492         return make_int(extent_endpoint_bufpos(e, 1)
3493                         - extent_endpoint_bufpos(e, 0));
3494 }
3495
3496 DEFUN("next-extent", Fnext_extent, 1, 1, 0,     /*
3497 Find next extent after EXTENT.
3498 If EXTENT is a buffer return the first extent in the buffer; likewise
3499 for strings.
3500 Extents in a buffer are ordered in what is called the "display"
3501 order, which sorts by increasing start positions and then by *decreasing*
3502 end positions.
3503 If you want to perform an operation on a series of extents, use
3504 `map-extents' instead of this function; it is much more efficient.
3505 The primary use of this function should be to enumerate all the
3506 extents in a buffer.
3507 Note: The display order is not necessarily the order that `map-extents'
3508 processes extents in!
3509 */
3510       (extent))
3511 {
3512         Lisp_Object val;
3513         EXTENT next;
3514
3515         if (EXTENTP(extent))
3516                 next = extent_next(decode_extent(extent, DE_MUST_BE_ATTACHED));
3517         else
3518                 next = extent_first(decode_buffer_or_string(extent));
3519
3520         if (!next)
3521                 return Qnil;
3522         XSETEXTENT(val, next);
3523         return val;
3524 }
3525
3526 DEFUN("previous-extent", Fprevious_extent, 1, 1, 0,     /*
3527 Find last extent before EXTENT.
3528 If EXTENT is a buffer return the last extent in the buffer; likewise
3529 for strings.
3530 This function is analogous to `next-extent'.
3531 */
3532       (extent))
3533 {
3534         Lisp_Object val;
3535         EXTENT prev;
3536
3537         if (EXTENTP(extent))
3538                 prev =
3539                     extent_previous(decode_extent(extent, DE_MUST_BE_ATTACHED));
3540         else
3541                 prev = extent_last(decode_buffer_or_string(extent));
3542
3543         if (!prev)
3544                 return Qnil;
3545         XSETEXTENT(val, prev);
3546         return val;
3547 }
3548
3549 #ifdef DEBUG_SXEMACS
3550
3551 DEFUN("next-e-extent", Fnext_e_extent, 1, 1, 0, /*
3552 Find next extent after EXTENT using the "e" order.
3553 If EXTENT is a buffer return the first extent in the buffer; likewise
3554 for strings.
3555 */
3556       (extent))
3557 {
3558         Lisp_Object val;
3559         EXTENT next;
3560
3561         if (EXTENTP(extent))
3562                 next =
3563                     extent_e_next(decode_extent(extent, DE_MUST_BE_ATTACHED));
3564         else
3565                 next = extent_e_first(decode_buffer_or_string(extent));
3566
3567         if (!next)
3568                 return Qnil;
3569         XSETEXTENT(val, next);
3570         return val;
3571 }
3572
3573 DEFUN("previous-e-extent", Fprevious_e_extent, 1, 1, 0, /*
3574 Find last extent before EXTENT using the "e" order.
3575 If EXTENT is a buffer return the last extent in the buffer; likewise
3576 for strings.
3577 This function is analogous to `next-e-extent'.
3578 */
3579       (extent))
3580 {
3581         Lisp_Object val;
3582         EXTENT prev;
3583
3584         if (EXTENTP(extent))
3585                 prev =
3586                     extent_e_previous(decode_extent
3587                                       (extent, DE_MUST_BE_ATTACHED));
3588         else
3589                 prev = extent_e_last(decode_buffer_or_string(extent));
3590
3591         if (!prev)
3592                 return Qnil;
3593         XSETEXTENT(val, prev);
3594         return val;
3595 }
3596
3597 #endif
3598
3599 DEFUN("next-extent-change", Fnext_extent_change, 1, 2, 0,       /*
3600 Return the next position after POS where an extent begins or ends.
3601 If POS is at the end of the buffer or string, POS will be returned;
3602 otherwise a position greater than POS will always be returned.
3603 If OBJECT is nil, the current buffer is assumed.
3604 */
3605       (pos, object))
3606 {
3607         Lisp_Object obj = decode_buffer_or_string(object);
3608         Bytind bpos;
3609
3610         bpos =
3611             get_buffer_or_string_pos_byte(obj, pos, GB_ALLOW_PAST_ACCESSIBLE);
3612         bpos = extent_find_end_of_run(obj, bpos, 1);
3613         return make_int(buffer_or_string_bytind_to_bufpos(obj, bpos));
3614 }
3615
3616 DEFUN("previous-extent-change", Fprevious_extent_change, 1, 2, 0,       /*
3617 Return the last position before POS where an extent begins or ends.
3618 If POS is at the beginning of the buffer or string, POS will be returned;
3619 otherwise a position less than POS will always be returned.
3620 If OBJECT is nil, the current buffer is assumed.
3621 */
3622       (pos, object))
3623 {
3624      &nbs