neovm-core 0.0.1

Core runtime structures for NeoVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
//! Text properties system for buffers.
//!
//! Text properties are key-value pairs attached to ranges of text within a
//! buffer. They are indexed by interval start boundaries, with each interval
//! carrying a set of properties. When a property is set on a range, existing
//! intervals are split at the boundaries and the property is applied to all
//! affected intervals. Adjacent intervals with identical property sets are
//! merged to keep the interval map compact.

use std::collections::{BTreeMap, HashMap};

use crate::emacs_core::value::{Value, equal_value};
use crate::gc_trace::GcTrace;

// ---------------------------------------------------------------------------
// PropertyInterval
// ---------------------------------------------------------------------------

/// A single text property interval: [start, end) with properties.
///
/// Each interval covers a half-open byte range and holds a map of named
/// properties.  Properties are stored internally in a HashMap for efficient
/// lookup, but also maintain an insertion-order list so that serialization
/// to plists is deterministic (matching GNU Emacs's prepend-based ordering).
#[derive(Clone, Debug)]
pub struct PropertyInterval {
    /// Byte position where this interval starts (inclusive).
    pub start: usize,
    /// Byte position where this interval ends (exclusive).
    pub end: usize,
    /// The property map for this interval.
    pub properties: HashMap<String, Value>,
    /// Property names in insertion order (most recently added first,
    /// matching GNU Emacs's prepend semantics).
    pub(crate) key_order: Vec<String>,
}

impl PropertyInterval {
    fn new(start: usize, end: usize) -> Self {
        Self {
            start,
            end,
            properties: HashMap::new(),
            key_order: Vec::new(),
        }
    }

    pub fn with_properties(start: usize, end: usize, properties: HashMap<String, Value>) -> Self {
        let key_order: Vec<String> = properties.keys().cloned().collect();
        Self {
            start,
            end,
            properties,
            key_order,
        }
    }

    /// Insert or update a property, maintaining key_order.
    /// New properties are prepended (matching GNU Emacs behavior).
    /// Returns true if the property was actually changed.
    fn insert_property(&mut self, name: &str, value: Value) -> bool {
        let already_equal = self
            .properties
            .get(name)
            .map_or(false, |existing| equal_value(existing, &value, 0));
        if already_equal {
            return false;
        }
        let is_new = !self.properties.contains_key(name);
        self.properties.insert(name.to_string(), value);
        if is_new {
            // Prepend new properties (GNU Emacs behavior)
            self.key_order.insert(0, name.to_string());
        }
        true
    }

    /// Remove a property by name.
    fn remove_property(&mut self, name: &str) -> Option<Value> {
        let result = self.properties.remove(name);
        if result.is_some() {
            self.key_order.retain(|k| k != name);
        }
        result
    }

    /// Returns true if the interval has no properties.
    fn is_empty_props(&self) -> bool {
        self.properties.is_empty()
    }

    /// Iterate properties in insertion order (most recently added first).
    pub fn ordered_properties(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.key_order
            .iter()
            .filter_map(move |k| self.properties.get(k).map(|v| (k.as_str(), v)))
    }
}

// ---------------------------------------------------------------------------
// Helper: compare two property maps for structural equality
// ---------------------------------------------------------------------------

fn props_equal(a: &HashMap<String, Value>, b: &HashMap<String, Value>) -> bool {
    if a.len() != b.len() {
        return false;
    }
    for (key, val_a) in a {
        match b.get(key) {
            Some(val_b) => {
                if !equal_value(val_a, val_b, 0) {
                    return false;
                }
            }
            None => return false,
        }
    }
    true
}

// ---------------------------------------------------------------------------
// TextPropertyTable
// ---------------------------------------------------------------------------

/// Manages text properties for a buffer.
///
/// Internally stores a start-boundary-indexed, non-overlapping set of
/// [`PropertyInterval`]s. Intervals with empty property sets may exist
/// transiently but are cleaned up during merge passes.
#[derive(Clone)]
pub struct TextPropertyTable {
    intervals: BTreeMap<usize, PropertyInterval>,
}

impl TextPropertyTable {
    /// Create an empty property table.
    pub fn new() -> Self {
        Self {
            intervals: BTreeMap::new(),
        }
    }

    /// Set a property on the byte range `[start, end)`.
    ///
    /// Any existing intervals that overlap the range are split at the
    /// boundaries, and the named property is set on all intervals within
    /// the range. Adjacent intervals with identical properties are then
    /// merged.
    ///
    /// Returns `true` if any property value was actually changed (or added),
    /// `false` if all intervals already had the property with an equal value.
    pub fn put_property(&mut self, start: usize, end: usize, name: &str, value: Value) -> bool {
        if start >= end {
            return false;
        }

        self.split_at(start);
        self.split_at(end);

        // Ensure there is coverage for the entire [start, end) range.
        self.ensure_coverage(start, end);

        let mut changed = false;
        let keys: Vec<usize> = self
            .intervals
            .range(start..end)
            .map(|(&key, _)| key)
            .collect();
        for key in keys {
            if let Some(interval) = self.intervals.get_mut(&key)
                && interval.insert_property(name, value)
            {
                changed = true;
            }
        }

        self.merge_adjacent();
        changed
    }

    /// Get a single property at a byte position.
    pub fn get_property(&self, pos: usize, name: &str) -> Option<&Value> {
        self.interval_containing(pos)
            .and_then(|interval| interval.properties.get(name))
    }

    /// Get all properties at a byte position.
    pub fn get_properties(&self, pos: usize) -> HashMap<String, Value> {
        self.interval_containing(pos)
            .map(|interval| interval.properties.clone())
            .unwrap_or_default()
    }

    /// Get all properties at a byte position in insertion order (most recently added first).
    /// Returns a list of (name, value) pairs in the order matching GNU Emacs plist output.
    pub fn get_properties_ordered(&self, pos: usize) -> Vec<(String, Value)> {
        self.interval_containing(pos)
            .map(|interval| {
                interval
                    .ordered_properties()
                    .map(|(k, v)| (k.to_string(), *v))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Remove a single named property from the byte range `[start, end)`.
    /// Returns `true` if any property was actually removed, `false` otherwise.
    pub fn remove_property(&mut self, start: usize, end: usize, name: &str) -> bool {
        if start >= end {
            return false;
        }

        self.split_at(start);
        self.split_at(end);

        let mut removed = false;
        let keys: Vec<usize> = self
            .intervals
            .range(start..end)
            .map(|(&key, _)| key)
            .collect();
        for key in keys {
            if let Some(interval) = self.intervals.get_mut(&key)
                && interval.remove_property(name).is_some()
            {
                removed = true;
            }
        }

        // Remove empty intervals and merge adjacent.
        self.cleanup();
        self.merge_adjacent();
        removed
    }

    /// Remove all properties from the byte range `[start, end)`.
    pub fn remove_all_properties(&mut self, start: usize, end: usize) {
        if start >= end {
            return;
        }

        self.split_at(start);
        self.split_at(end);

        let keys: Vec<usize> = self
            .intervals
            .range(start..end)
            .map(|(&key, _)| key)
            .collect();
        for key in keys {
            if let Some(interval) = self.intervals.get_mut(&key) {
                interval.properties.clear();
                interval.key_order.clear();
            }
        }

        self.cleanup();
        self.merge_adjacent();
    }

    /// Return the next position at or after `pos` where any text property
    /// changes, or `None` if there is no change after `pos`.
    pub fn next_property_change(&self, pos: usize) -> Option<usize> {
        if let Some(interval) = self.interval_containing(pos) {
            return Some(interval.end);
        }
        self.intervals
            .range((std::ops::Bound::Excluded(pos), std::ops::Bound::Unbounded))
            .next()
            .map(|(_, interval)| interval.start)
    }

    /// Return the previous position before `pos` where any text property
    /// changes, or `None` if there is no change before `pos`.
    pub fn previous_property_change(&self, pos: usize) -> Option<usize> {
        if let Some(interval) = self.interval_containing(pos.saturating_sub(1))
            && pos <= interval.end
            && interval.start < pos
        {
            return Some(interval.start);
        }
        self.intervals
            .range(..pos)
            .next_back()
            .map(|(_, interval)| interval.end)
    }

    /// Adjust all intervals after text is inserted at `pos` with `len` bytes.
    ///
    /// Matches GNU Emacs `adjust_intervals_for_insertion` (intervals.c:802):
    ///
    /// - Intervals starting AFTER the insertion point are shifted right.
    /// - An interval whose interior CONTAINS the insertion point is SPLIT
    ///   around the inserted range, leaving the newly inserted text without
    ///   inherited properties.
    /// - An interval whose START equals `pos` is shifted right (the inserted
    ///   text goes BEFORE this interval, not inside it).
    /// - `insert-and-inherit` and related commands compute stickiness-aware
    ///   inherited properties separately after the structural split.
    pub fn adjust_for_insert(&mut self, pos: usize, len: usize) {
        if len == 0 {
            return;
        }
        let mut shifted = BTreeMap::new();
        for interval in self.intervals_snapshot() {
            if interval.start == pos {
                let mut shifted_interval = interval;
                shifted_interval.start += len;
                shifted_interval.end += len;
                shifted.insert(shifted_interval.start, shifted_interval);
            } else if interval.start > pos {
                let mut shifted_interval = interval;
                shifted_interval.start += len;
                shifted_interval.end += len;
                shifted.insert(shifted_interval.start, shifted_interval);
            } else if interval.end > pos {
                let mut left = interval.clone();
                left.end = pos;
                if left.start < left.end {
                    shifted.insert(left.start, left);
                }

                let mut right = interval;
                right.start = pos + len;
                right.end += len;
                if right.start < right.end {
                    shifted.insert(right.start, right);
                }
            } else {
                shifted.insert(interval.start, interval);
            }
        }
        self.intervals = shifted;
    }

    /// Adjust all intervals after text in `[start, end)` is deleted.
    ///
    /// Intervals inside the deleted range are removed or truncated.
    /// Intervals after the deleted range are shifted left.
    pub fn adjust_for_delete(&mut self, start: usize, end: usize) {
        if start >= end {
            return;
        }
        let len = end - start;
        let mut shifted = BTreeMap::new();

        for mut interval in self.intervals_snapshot() {
            if interval.start >= end {
                interval.start -= len;
                interval.end -= len;
            } else if interval.end <= start {
            } else if interval.start >= start && interval.end <= end {
                continue;
            } else if interval.start < start && interval.end > end {
                interval.end -= len;
            } else if interval.start < start {
                interval.end = start;
            } else {
                interval.start = start;
                interval.end -= len;
            }
            shifted.insert(interval.start, interval);
        }
        self.intervals = shifted;
        self.merge_adjacent();
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    /// Split any interval that spans `pos` into two intervals at `pos`.
    fn split_at(&mut self, pos: usize) {
        let Some((&start, interval)) = self.intervals.range(..pos).next_back() else {
            return;
        };
        if !(interval.start < pos && pos < interval.end) {
            return;
        }

        let second = PropertyInterval {
            start: pos,
            end: interval.end,
            properties: interval.properties.clone(),
            key_order: interval.key_order.clone(),
        };
        if let Some(first) = self.intervals.get_mut(&start) {
            first.end = pos;
        }
        self.intervals.insert(pos, second);
    }

    /// Ensure that the entire range `[start, end)` is covered by intervals.
    /// Fill any gaps with empty-property intervals.
    fn ensure_coverage(&mut self, start: usize, end: usize) {
        let mut gaps = Vec::new();
        let mut cursor = start;

        for interval in self.intervals.values() {
            if interval.start >= end {
                break;
            }
            if interval.end <= cursor {
                continue;
            }
            if interval.start > cursor {
                gaps.push((cursor, interval.start));
            }
            if interval.end > cursor {
                cursor = interval.end;
            }
        }
        if cursor < end {
            gaps.push((cursor, end));
        }

        for (gap_start, gap_end) in gaps {
            self.intervals
                .insert(gap_start, PropertyInterval::new(gap_start, gap_end));
        }
    }

    /// Remove intervals with no properties.
    fn cleanup(&mut self) {
        self.intervals.retain(|_, iv| !iv.is_empty_props());
    }

    /// Merge adjacent intervals that have identical property maps.
    fn merge_adjacent(&mut self) {
        if self.intervals.len() < 2 {
            return;
        }

        let mut merged = BTreeMap::new();
        let mut current: Option<PropertyInterval> = None;

        for interval in self.intervals.values().cloned() {
            match current.take() {
                None => current = Some(interval),
                Some(mut active) => {
                    if active.end == interval.start
                        && props_equal(&active.properties, &interval.properties)
                    {
                        active.end = interval.end;
                        current = Some(active);
                    } else {
                        merged.insert(active.start, active);
                        current = Some(interval);
                    }
                }
            }
        }
        if let Some(interval) = current {
            merged.insert(interval.start, interval);
        }
        self.intervals = merged;
    }

    fn interval_containing(&self, pos: usize) -> Option<&PropertyInterval> {
        let (_, interval) = self.intervals.range(..=pos).next_back()?;
        (interval.start <= pos && pos < interval.end).then_some(interval)
    }

    /// Expose a stable interval snapshot for iteration (GC tracing, printing, etc.).
    pub fn intervals_snapshot(&self) -> Vec<PropertyInterval> {
        self.intervals.values().cloned().collect()
    }

    /// Returns true if there are no intervals (no properties).
    pub fn is_empty(&self) -> bool {
        self.intervals.is_empty()
    }

    /// Extract a sub-range `[start, end)` of the property table,
    /// shifting all positions to be 0-based relative to `start`.
    pub fn slice(&self, start: usize, end: usize) -> TextPropertyTable {
        if start >= end {
            return TextPropertyTable::new();
        }
        let mut result = BTreeMap::new();
        for iv in self.intervals.values() {
            if iv.end <= start || iv.start >= end {
                continue;
            }
            let new_start = iv.start.max(start) - start;
            let new_end = iv.end.min(end) - start;
            if new_start < new_end && !iv.properties.is_empty() {
                result.insert(
                    new_start,
                    PropertyInterval {
                        start: new_start,
                        end: new_end,
                        properties: iv.properties.clone(),
                        key_order: iv.key_order.clone(),
                    },
                );
            }
        }
        TextPropertyTable { intervals: result }
    }

    /// Append another table's intervals shifted by `byte_offset`.
    pub fn append_shifted(&mut self, other: &TextPropertyTable, byte_offset: usize) {
        for iv in other.intervals.values() {
            if iv.properties.is_empty() {
                continue;
            }
            let start = iv.start + byte_offset;
            self.intervals.insert(
                start,
                PropertyInterval {
                    start,
                    end: iv.end + byte_offset,
                    properties: iv.properties.clone(),
                    key_order: iv.key_order.clone(),
                },
            );
        }
        self.merge_adjacent();
    }

    // pdump accessors
    pub(crate) fn dump_intervals(&self) -> Vec<PropertyInterval> {
        self.intervals_snapshot()
    }
    pub(crate) fn from_dump(intervals: Vec<PropertyInterval>) -> Self {
        Self {
            intervals: intervals
                .into_iter()
                .map(|interval| (interval.start, interval))
                .collect(),
        }
    }
}

impl Default for TextPropertyTable {
    fn default() -> Self {
        Self::new()
    }
}

impl GcTrace for TextPropertyTable {
    fn trace_roots(&self, roots: &mut Vec<Value>) {
        for interval in self.intervals.values() {
            for value in interval.properties.values() {
                roots.push(*value);
            }
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------------
    // Basic put/get
    // -----------------------------------------------------------------------

    #[test]
    fn put_and_get_basic() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 5, "face", Value::symbol("bold"));

        assert!(table.get_property(0, "face").is_some());
        assert!(table.get_property(2, "face").is_some());
        assert!(table.get_property(4, "face").is_some());
        assert!(table.get_property(5, "face").is_none()); // exclusive end
    }

    #[test]
    fn get_property_returns_correct_value() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        let val = table.get_property(5, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "bold")
        );
    }

    #[test]
    fn get_property_nonexistent_name() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        assert!(table.get_property(5, "syntax-table").is_none());
    }

    #[test]
    fn get_properties_returns_all() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(0, 10, "help-echo", Value::string("tooltip"));
        let props = table.get_properties(5);
        assert_eq!(props.len(), 2);
        assert!(props.contains_key("face"));
        assert!(props.contains_key("help-echo"));
    }

    #[test]
    fn get_property_outside_any_interval() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));
        assert!(table.get_property(0, "face").is_none());
        assert!(table.get_property(3, "face").is_none());
        assert!(table.get_property(10, "face").is_none());
        assert!(table.get_property(15, "face").is_none());
    }

    // -----------------------------------------------------------------------
    // Overlapping ranges
    // -----------------------------------------------------------------------

    #[test]
    fn overlapping_put_splits_intervals() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(5, 15, "face", Value::symbol("italic"));

        // [0, 5) should still have "bold"
        let val = table.get_property(3, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "bold")
        );

        // [5, 15) should have "italic" (overwritten)
        let val = table.get_property(7, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "italic")
        );

        let val = table.get_property(12, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "italic")
        );
    }

    #[test]
    fn multiple_properties_on_same_range() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(0, 10, "mouse-face", Value::symbol("highlight"));

        let props = table.get_properties(5);
        assert_eq!(props.len(), 2);
    }

    #[test]
    fn put_property_inner_range() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 20, "face", Value::symbol("default"));
        table.put_property(5, 15, "face", Value::symbol("bold"));

        let val = table.get_property(3, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "default")
        );

        let val = table.get_property(10, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "bold")
        );

        let val = table.get_property(17, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "default")
        );
    }

    #[test]
    fn put_different_properties_on_overlapping_ranges() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(5, 15, "syntax-table", Value::fixnum(42));

        // Position 3: only "face"
        let props = table.get_properties(3);
        assert_eq!(props.len(), 1);
        assert!(props.contains_key("face"));

        // Position 7: both "face" and "syntax-table"
        let props = table.get_properties(7);
        assert_eq!(props.len(), 2);

        // Position 12: only "syntax-table"
        let props = table.get_properties(12);
        assert_eq!(props.len(), 1);
        assert!(props.contains_key("syntax-table"));
    }

    // -----------------------------------------------------------------------
    // Remove
    // -----------------------------------------------------------------------

    #[test]
    fn remove_property_basic() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(0, 10, "help-echo", Value::string("help"));

        table.remove_property(0, 10, "face");

        assert!(table.get_property(5, "face").is_none());
        assert!(table.get_property(5, "help-echo").is_some());
    }

    #[test]
    fn remove_property_partial_range() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));

        table.remove_property(3, 7, "face");

        // [0, 3) still has face
        assert!(table.get_property(2, "face").is_some());
        // [3, 7) no longer has face
        assert!(table.get_property(5, "face").is_none());
        // [7, 10) still has face
        assert!(table.get_property(8, "face").is_some());
    }

    #[test]
    fn remove_all_properties_basic() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(0, 10, "help-echo", Value::string("help"));

        table.remove_all_properties(0, 10);

        assert!(table.get_property(5, "face").is_none());
        assert!(table.get_property(5, "help-echo").is_none());
    }

    #[test]
    fn remove_all_properties_partial() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));

        table.remove_all_properties(3, 7);

        assert!(table.get_property(2, "face").is_some());
        assert!(table.get_property(5, "face").is_none());
        assert!(table.get_property(8, "face").is_some());
    }

    // -----------------------------------------------------------------------
    // next/previous property change
    // -----------------------------------------------------------------------

    #[test]
    fn next_property_change_basic() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));
        table.put_property(15, 20, "face", Value::symbol("italic"));

        // Before any interval
        assert_eq!(table.next_property_change(0), Some(5));
        // Inside first interval
        assert_eq!(table.next_property_change(7), Some(10));
        // Between intervals
        assert_eq!(table.next_property_change(12), Some(15));
        // Inside second interval
        assert_eq!(table.next_property_change(17), Some(20));
        // After all intervals
        assert_eq!(table.next_property_change(25), None);
    }

    #[test]
    fn next_property_change_at_boundary() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        // At start of interval
        assert_eq!(table.next_property_change(5), Some(10));
    }

    #[test]
    fn previous_property_change_basic() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));
        table.put_property(15, 20, "face", Value::symbol("italic"));

        // After second interval
        assert_eq!(table.previous_property_change(25), Some(20));
        // Inside second interval
        assert_eq!(table.previous_property_change(17), Some(15));
        // Between intervals
        assert_eq!(table.previous_property_change(12), Some(10));
        // Inside first interval
        assert_eq!(table.previous_property_change(7), Some(5));
        // Before any interval
        assert_eq!(table.previous_property_change(3), None);
        assert_eq!(table.previous_property_change(0), None);
    }

    #[test]
    fn previous_property_change_at_end() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        // At exclusive end of interval
        assert_eq!(table.previous_property_change(10), Some(10));
    }

    #[test]
    fn next_previous_empty_table() {
        crate::test_utils::init_test_tracing();
        let table = TextPropertyTable::new();
        assert_eq!(table.next_property_change(0), None);
        assert_eq!(table.previous_property_change(10), None);
    }

    // -----------------------------------------------------------------------
    // adjust_for_insert
    // -----------------------------------------------------------------------

    #[test]
    fn adjust_insert_shifts_intervals_after() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(10, 20, "face", Value::symbol("bold"));

        table.adjust_for_insert(5, 3);

        // Interval should now be [13, 23)
        assert!(table.get_property(12, "face").is_none());
        assert!(table.get_property(13, "face").is_some());
        assert!(table.get_property(22, "face").is_some());
        assert!(table.get_property(23, "face").is_none());
    }

    #[test]
    fn adjust_insert_splits_spanning_interval_around_plain_inserted_text() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 15, "face", Value::symbol("bold"));

        table.adjust_for_insert(10, 5);

        // Plain insert should leave the inserted range [10, 15) without properties.
        assert!(table.get_property(5, "face").is_some());
        assert!(table.get_property(9, "face").is_some());
        assert!(table.get_property(10, "face").is_none());
        assert!(table.get_property(12, "face").is_none());
        assert!(table.get_property(14, "face").is_none());
        assert!(table.get_property(15, "face").is_some());
        assert!(table.get_property(20, "face").is_none());
    }

    #[test]
    fn adjust_insert_at_interval_start() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        table.adjust_for_insert(5, 3);

        // Interval should shift to [8, 13)
        assert!(table.get_property(7, "face").is_none());
        assert!(table.get_property(8, "face").is_some());
        assert!(table.get_property(12, "face").is_some());
        assert!(table.get_property(13, "face").is_none());
    }

    #[test]
    fn adjust_insert_before_all() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        table.adjust_for_insert(0, 2);

        assert!(table.get_property(7, "face").is_some());
        assert!(table.get_property(6, "face").is_none());
    }

    #[test]
    fn adjust_insert_zero_length() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        table.adjust_for_insert(7, 0);

        // No change
        assert!(table.get_property(5, "face").is_some());
        assert!(table.get_property(9, "face").is_some());
        assert!(table.get_property(10, "face").is_none());
    }

    // -----------------------------------------------------------------------
    // adjust_for_delete
    // -----------------------------------------------------------------------

    #[test]
    fn adjust_delete_shifts_intervals_after() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(10, 20, "face", Value::symbol("bold"));

        table.adjust_for_delete(2, 5);

        // 3 bytes deleted before interval; interval becomes [7, 17)
        assert!(table.get_property(6, "face").is_none());
        assert!(table.get_property(7, "face").is_some());
        assert!(table.get_property(16, "face").is_some());
        assert!(table.get_property(17, "face").is_none());
    }

    #[test]
    fn adjust_delete_removes_contained_interval() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        table.adjust_for_delete(3, 12);

        // Entire interval was within deleted range
        assert!(table.get_property(5, "face").is_none());
        assert!(table.get_property(3, "face").is_none());
    }

    #[test]
    fn adjust_delete_truncates_start() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 15, "face", Value::symbol("bold"));

        table.adjust_for_delete(10, 20);

        // Deletion overlaps end of interval; truncated to [5, 10)
        assert!(table.get_property(5, "face").is_some());
        assert!(table.get_property(9, "face").is_some());
        assert!(table.get_property(10, "face").is_none());
    }

    #[test]
    fn adjust_delete_shrinks_spanning_interval() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 20, "face", Value::symbol("bold"));

        table.adjust_for_delete(10, 15);

        // Deletion within interval; shrinks to [5, 15)
        assert!(table.get_property(5, "face").is_some());
        assert!(table.get_property(14, "face").is_some());
        assert!(table.get_property(15, "face").is_none());
    }

    #[test]
    fn adjust_delete_overlaps_interval_start() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 15, "face", Value::symbol("bold"));

        table.adjust_for_delete(2, 10);

        // Deletion overlaps beginning of interval: [5,15) minus [2,10)
        // After: interval becomes [2, 7) (shifted: start=2, end=15-8=7)
        assert!(table.get_property(2, "face").is_some());
        assert!(table.get_property(6, "face").is_some());
        assert!(table.get_property(7, "face").is_none());
    }

    #[test]
    fn adjust_delete_empty_range() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 10, "face", Value::symbol("bold"));

        table.adjust_for_delete(7, 7);

        // No change
        assert!(table.get_property(5, "face").is_some());
        assert!(table.get_property(9, "face").is_some());
    }

    // -----------------------------------------------------------------------
    // Merge adjacent intervals
    // -----------------------------------------------------------------------

    #[test]
    fn merge_adjacent_same_properties() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 5, "face", Value::symbol("bold"));
        table.put_property(5, 10, "face", Value::symbol("bold"));

        // After put, adjacent intervals with same properties should merge.
        // We can verify by checking that only one interval exists.
        assert!(table.get_property(0, "face").is_some());
        assert!(table.get_property(7, "face").is_some());

        // next_property_change from 0 should go to 10 (not 5)
        assert_eq!(table.next_property_change(0), Some(10));
    }

    #[test]
    fn no_merge_different_properties() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 5, "face", Value::symbol("bold"));
        table.put_property(5, 10, "face", Value::symbol("italic"));

        // Should remain as two intervals.
        assert_eq!(table.next_property_change(0), Some(5));
        assert_eq!(table.next_property_change(5), Some(10));
    }

    // -----------------------------------------------------------------------
    // Edge cases
    // -----------------------------------------------------------------------

    #[test]
    fn put_property_empty_range() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(5, 5, "face", Value::symbol("bold"));
        assert!(table.get_property(5, "face").is_none());
    }

    #[test]
    fn put_property_overwrites_same_name() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 10, "face", Value::symbol("bold"));
        table.put_property(0, 10, "face", Value::symbol("italic"));

        let val = table.get_property(5, "face").unwrap();
        assert!(
            val.as_symbol_id()
                .map_or(false, |id| crate::emacs_core::intern::resolve_sym(id)
                    == "italic")
        );
    }

    #[test]
    fn multiple_non_contiguous_intervals() {
        crate::test_utils::init_test_tracing();
        let mut table = TextPropertyTable::new();
        table.put_property(0, 5, "face", Value::symbol("bold"));
        table.put_property(10, 15, "face", Value::symbol("italic"));
        table.put_property(20, 25, "face", Value::symbol("underline"));

        assert!(table.get_property(3, "face").is_some());
        assert!(table.get_property(7, "face").is_none());
        assert!(table.get_property(12, "face").is_some());
        assert!(table.get_property(17, "face").is_none());
        assert!(table.get_property(22, "face").is_some());
    }
}