-
Notifications
You must be signed in to change notification settings - Fork 2
/
AttributedRope.swift
1252 lines (997 loc) · 40.3 KB
/
AttributedRope.swift
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
863
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
//
// AttributedRope.swift
// Watt
//
// Created by David Albert on 8/27/23.
//
import AppKit
protocol AttributedRopeKey {
associatedtype Value: Equatable
static var name: String { get }
}
@dynamicMemberLookup
struct AttributedRope {
var text: Rope
var spans: Spans<Attributes>
init() {
self.init("")
}
init(_ string: String, attributes: Attributes = Attributes()) {
self.init(Rope(string), attributes: attributes)
}
init(_ text: Rope, attributes: Attributes = Attributes()) {
var b = SpansBuilder<Attributes>(totalCount: text.utf8.count)
if text.utf8.count > 0 {
b.add(attributes, covering: 0..<text.utf8.count)
}
self.init(text: text, spans: b.build())
}
init(_ subrope: AttributedSubrope) {
if Range(unvalidatedRange: subrope.bounds) == 0..<subrope.base.text.utf8.count {
self.init(text: subrope.base.text, spans: subrope.base.spans)
return
}
self.init(text: Rope(subrope.text), spans: Spans(subrope.spans))
}
// internal
fileprivate init(text: Rope, spans: Spans<Attributes>) {
assert(text.utf8.count == spans.upperBound)
self.text = text
self.spans = spans
}
}
@dynamicMemberLookup
struct AttributedSubrope {
var base: AttributedRope
var bounds: Range<AttributedRope.Index>
var text: Subrope {
base.text[bounds]
}
var spans: SpansSlice<AttributedRope.Attributes> {
base.spans[Range(bounds, in: base.spans)]
}
}
extension AttributedRope {
@dynamicMemberLookup
struct Attributes: Equatable {
static func == (lhs: Attributes, rhs: Attributes) -> Bool {
if lhs.contents.keys != rhs.contents.keys {
return false
}
for (key, value) in lhs.contents {
if !isEqual(value, rhs.contents[key]) {
return false
}
}
return true
}
var contents: [String: Any]
var count: Int {
contents.count
}
var isEmpty: Bool {
contents.isEmpty
}
init() {
contents = [:]
}
fileprivate init(_ contents: [String: Any]) {
self.contents = contents
}
mutating func merge(_ other: Attributes, mergePolicy: AttributeMergePolicy = .keepNew) {
contents.merge(other.contents, uniquingKeysWith: mergePolicy.combine)
}
func merging(_ other: Attributes, mergePolicy: AttributeMergePolicy = .keepNew) -> Attributes {
Attributes(contents.merging(other.contents, uniquingKeysWith: mergePolicy.combine))
}
func merging(_ dictionary: [NSAttributedString.Key: Any], mergePolicy: AttributeMergePolicy = .keepNew) -> Attributes {
merging(Attributes(dictionary), mergePolicy: mergePolicy)
}
}
struct AttributeBuilder<T: AttributedRopeKey> {
var attributes: Attributes
func callAsFunction(_ value: T.Value) -> Attributes {
var new = attributes
new[T.self] = value
return new
}
}
}
// MARK: - Runs
extension AttributedRope {
var runs: Runs {
Runs(base: self, bounds: startIndex..<endIndex)
}
struct Runs {
let base: AttributedRope
let bounds: Range<Index>
private var spans: SpansSlice<AttributedRope.Attributes> {
assert(bounds.lowerBound.position >= 0 && bounds.upperBound.position <= base.text.utf8.count, "Index out of bounds")
let start = base.spans.index(withBaseOffset: bounds.lowerBound.position)
let end = base.spans.index(withBaseOffset: bounds.upperBound.position)
return base.spans[Range(uncheckedBounds: (start, end))]
}
private func spansIndex(for i: Index) -> Spans<AttributedRope.Attributes>.Index {
i.assertValid(for: base.text)
return spans.index(withBaseOffset: i.position - bounds.lowerBound.position)
}
private func index(from i: Spans<AttributedRope.Attributes>.Index) -> Index {
i.assertValid(for: spans.base.root)
return base.text.utf8.index(at: i.position)
}
}
}
extension AttributedSubrope {
var runs: AttributedRope.Runs {
AttributedRope.Runs(base: base, bounds: bounds)
}
}
extension AttributedRope.Runs: BidirectionalCollection {
typealias Index = AttributedRope.Index
var count: Int {
base.spans[spansIndex(for: bounds.lowerBound)..<spansIndex(for: bounds.upperBound)].count
}
var startIndex: Index {
bounds.lowerBound
}
var endIndex: Index {
bounds.upperBound
}
struct Iterator: IteratorProtocol {
let base: AttributedRope
var spansIter: Spans<AttributedRope.Attributes>.Iterator
init(_ runs: AttributedRope.Runs) {
self.base = runs.base
spansIter = runs.spans.makeIterator()
}
mutating func next() -> AttributedRope.Runs.Run? {
guard let span = spansIter.next() else {
return nil
}
return AttributedRope.Runs.Run(base: base, span: span)
}
}
func makeIterator() -> Iterator {
Iterator(self)
}
func index(before i: Index) -> Index {
i.validate(for: base.text)
precondition(i.position > bounds.lowerBound.position && i.position <= bounds.upperBound.position, "Index out of bounds")
return index(from: spans.index(before: spansIndex(for: i)))
}
func index(after i: Index) -> Index {
i.validate(for: base.text)
precondition(i.position >= bounds.lowerBound.position && i.position < bounds.upperBound.position, "Index out of bounds")
return index(from: spans.index(after: spansIndex(for: i)))
}
subscript(position: Index) -> AttributedRope.Runs.Run {
position.validate(for: base.text)
precondition(position.position >= bounds.lowerBound.position && position.position < bounds.upperBound.position, "Index out of bounds")
return AttributedRope.Runs.Run(base: base, span: spans[spansIndex(for: position)])
}
func index(_ i: Index, offsetBy distance: Int) -> Index {
i.validate(for: base.text)
precondition(i.position >= bounds.lowerBound.position && i.position <= bounds.upperBound.position, "Index out of bounds")
return index(from: spans.index(spansIndex(for: i), offsetBy: distance))
}
func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
i.validate(for: base.text)
precondition(i.position >= bounds.lowerBound.position && i.position <= bounds.upperBound.position, "Index out of bounds")
guard let si = spans.index(spansIndex(for: i), offsetBy: distance, limitedBy: spansIndex(for: limit)) else {
return nil
}
return index(from: si)
}
func distance(from start: Index, to end: Index) -> Int {
start.validate(for: base.text)
end.validate(for: base.text)
precondition(start.position >= bounds.lowerBound.position && start.position <= bounds.upperBound.position, "Index out of bounds")
precondition(end.position >= bounds.lowerBound.position && end.position <= bounds.upperBound.position, "Index out of bounds")
return spans.distance(from: spansIndex(for: start), to: spansIndex(for: end))
}
}
extension AttributedRope.Runs {
@dynamicMemberLookup
struct Run {
let base: AttributedRope
let span: Span<AttributedRope.Attributes>
var range: Range<AttributedRope.Index> {
Range(span.range, in: base.text)
}
var attributes: AttributedRope.Attributes {
span.data
}
}
}
extension AttributedRope {
struct AttributesSlice<T> where T: AttributedRopeKey {
var runs: AttributedRope.Runs
var count: Int {
var c = 0
for run in runs {
if run.attributes[T.self] != nil {
c = 1
}
}
return c
}
}
}
extension AttributedRope.AttributesSlice: Sequence {
func makeIterator() -> Iterator {
Iterator(self)
}
struct Iterator: IteratorProtocol {
var runsIter: AttributedRope.Runs.Iterator
init(_ slice: AttributedRope.AttributesSlice<T>) {
self.runsIter = slice.runs.makeIterator()
}
mutating func next() -> AttributedRope.Runs.Run? {
while let run = runsIter.next() {
if run.attributes[T.self] != nil {
return run
}
}
return nil
}
}
}
// MARK: - Attributes
extension AttributedRope {
struct AttributeKeys {
// TODO: Make a macro for defining attributes that:
// 1. Creates the enum
// 2. Creates the property
// 3. If it maps to an NSAttributedString.Key, add the name to knownNSAttributedStringKeys
static var knownNSAttributedStringKeys: Set = [
NSAttributedString.Key.font.rawValue,
NSAttributedString.Key.foregroundColor.rawValue,
NSAttributedString.Key.backgroundColor.rawValue,
NSAttributedString.Key.underlineStyle.rawValue,
NSAttributedString.Key.underlineColor.rawValue,
NSAttributedString.Key.markedClauseSegment.rawValue,
NSAttributedString.Key.glyphInfo.rawValue,
NSAttributedString.Key.textAlternatives.rawValue,
NSAttributedString.Key.attachment.rawValue,
]
var font: FontAttribute
var foregroundColor: ForegroundColorAttribute
var backgroundColor: BackgroundColorAttribute
var underlineStyle: UnderlineStyleAttribute
var underlineColor: UnderlineColorAttribute
var markedClauseSegment: MarkedClauseSegmentAttribute
var glyphInfo: GlyphInfoAttribute
var textAlternatives: TextAlternativesAttribute
var attachment: AttachmentKey
enum FontAttribute: AttributedRopeKey {
typealias Value = NSFont
static let name = NSAttributedString.Key.font.rawValue
}
enum ForegroundColorAttribute: AttributedRopeKey {
typealias Value = NSColor
static let name = NSAttributedString.Key.foregroundColor.rawValue
}
enum BackgroundColorAttribute: AttributedRopeKey {
typealias Value = NSColor
static let name = NSAttributedString.Key.backgroundColor.rawValue
}
enum UnderlineStyleAttribute: AttributedRopeKey {
typealias Value = NSUnderlineStyle
static let name = NSAttributedString.Key.underlineStyle.rawValue
}
enum UnderlineColorAttribute: AttributedRopeKey {
typealias Value = NSColor
static let name = NSAttributedString.Key.underlineColor.rawValue
}
enum MarkedClauseSegmentAttribute: AttributedRopeKey {
typealias Value = NSNumber
static let name = NSAttributedString.Key.markedClauseSegment.rawValue
}
// We don't use these directly, but they're part of NSTextView's validAttributesForMarkedText
// which we're reproducing, so we want to have them supported.
//
// LanguageIdentifier is missing because I don't know its type.
enum GlyphInfoAttribute: AttributedRopeKey {
typealias Value = NSGlyphInfo
static let name = NSAttributedString.Key.glyphInfo.rawValue
}
enum TextAlternativesAttribute: AttributedRopeKey {
typealias Value = NSTextAlternatives
static let name = NSAttributedString.Key.textAlternatives.rawValue
}
enum AttachmentKey: AttributedRopeKey {
typealias Value = NSTextAttachment
static let name = NSAttributedString.Key.attachment.rawValue
}
// Watt-specific attributes
var token: TokenAttribute
var fontWeight: FontWeightAttribute
var symbolicTraits: SymbolicTraitsAttribute
// Store the whole token instead of just its type, because we want to
// make sure that two tokens aren't merged together. Each token has a
// unique range, which will prevent merging.
enum TokenAttribute: AttributedRopeKey {
typealias Value = Token
static let name = "is.dave.Watt.Token"
}
enum SymbolicTraitsAttribute: AttributedRopeKey {
typealias Value = NSFontDescriptor.SymbolicTraits
static let name = "is.dave.Watt.SymbolicTraits"
}
enum FontWeightAttribute: AttributedRopeKey {
typealias Value = NSFont.Weight
static let name = "is.dave.Watt.FontWeight"
}
}
}
extension AttributedRope.Attributes {
subscript<K>(_ attribute: K.Type) -> K.Value? where K: AttributedRopeKey {
get {
if let value = contents[K.name] {
// force cast so we panic if two different attribute keys
// have the same name but different types.
return (value as! K.Value)
} else {
return nil
}
}
set { contents[K.name] = newValue }
}
subscript<K>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> K.Value? where K: AttributedRopeKey {
get { self[K.self] }
set { self[K.self] = newValue }
}
}
extension AttributedRope.Attributes {
static subscript<K: AttributedRopeKey>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> AttributedRope.AttributeBuilder<K> {
return AttributedRope.AttributeBuilder(attributes: AttributedRope.Attributes())
}
subscript<K: AttributedRopeKey>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> AttributedRope.AttributeBuilder<K> {
return AttributedRope.AttributeBuilder(attributes: self)
}
func b<K: AttributedRopeKey>() -> AttributedRope.AttributeBuilder<K> {
return AttributedRope.AttributeBuilder(attributes: AttributedRope.Attributes())
}
}
extension AttributedRope {
enum AttributeMergePolicy: Equatable {
case keepCurrent
case keepNew
var combine: (Any, Any) -> Any {
switch self {
case .keepCurrent:
{ a, b in a }
case .keepNew:
{ a, b in b }
}
}
}
subscript<K>(_ attribute: K.Type) -> K.Value? where K: AttributedRopeKey {
get { self[startIndex..<endIndex][K.self] }
set { self[startIndex..<endIndex][K.self] = newValue }
}
subscript<K>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> K.Value? where K: AttributedRopeKey {
get { self[K.self] }
set { self[K.self] = newValue }
}
mutating func setAttributes(_ attributes: Attributes) {
self[...].setAttributes(attributes)
}
func setingAttributes(_ attributes: Attributes) -> AttributedRope {
self[...].settingAttributes(attributes)
}
mutating func mergeAttributes(_ attributes: Attributes, mergePolicy: AttributeMergePolicy = .keepNew) {
self[...].mergeAttributes(attributes, mergePolicy: mergePolicy)
}
func mergingAttributes(_ attributes: Attributes, mergePolicy: AttributeMergePolicy = .keepNew) -> AttributedRope {
self[...].mergingAttributes(attributes, mergePolicy: mergePolicy)
}
}
extension AttributedRope.Runs {
subscript<K>(attribute: K.Type) -> AttributedRope.AttributesSlice<K> where K: AttributedRopeKey {
AttributedRope.AttributesSlice(runs: self)
}
subscript<K>(keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> AttributedRope.AttributesSlice<K> where K: AttributedRopeKey {
self[K.self]
}
}
extension AttributedRope.Runs.Run {
subscript<K>(_ attribute: K.Type) -> K.Value? where K: AttributedRopeKey {
span.data[K.self]
}
subscript<K>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> K.Value? where K: AttributedRopeKey {
self[K.self]
}
}
extension AttributedSubrope {
subscript<K>(_ attribute: K.Type) -> K.Value? where K: AttributedRopeKey {
get {
if bounds.isEmpty {
return nil
}
var first = true
var v: K.Value?
let start = base.spans.index(withBaseOffset: bounds.lowerBound.position)
let end = base.spans.index(withBaseOffset: bounds.upperBound.position)
for span in base.spans[start..<end] {
if first {
v = span.data[K.self]
first = false
} else if span.data[K.self] != v {
return nil
}
}
return v
}
set {
if bounds.isEmpty {
return
}
var b = SpansBuilder<AttributedRope.Attributes>(totalCount: base.text.utf8.count)
var s = AttributedRope.Attributes()
s[K.self] = newValue
b.add(s, covering: Range(unvalidatedRange: bounds))
base.spans = base.spans.merging(b.build()) { a, b in
var a = a ?? AttributedRope.Attributes()
if let b {
a[K.self] = b[K.self]
}
return a
}
}
}
subscript<K>(dynamicMember keyPath: KeyPath<AttributedRope.AttributeKeys, K>) -> K.Value? where K: AttributedRopeKey {
get { self[K.self] }
set { self[K.self] = newValue }
}
mutating func setAttributes(_ attributes: AttributedRope.Attributes) {
if bounds.isEmpty {
return
}
let range = Range(unvalidatedRange: bounds)
var sb = SpansBuilder<AttributedRope.Attributes>(totalCount: range.count)
sb.add(attributes, covering: range)
var new = sb.build()
var dup = base.spans
var b = BTreeBuilder<Spans<AttributedRope.Attributes>>()
b.push(&dup.root, slicedBy: 0..<range.lowerBound)
b.push(&new.root)
b.push(&dup.root, slicedBy: range.upperBound..<dup.upperBound)
base.spans = b.build()
assert(base.spans.upperBound == base.text.utf8.count)
}
func settingAttributes(_ attributes: AttributedRope.Attributes) -> AttributedRope {
var dup = self
dup.setAttributes(attributes)
return AttributedRope(dup)
}
mutating func mergeAttributes(_ attributes: AttributedRope.Attributes, mergePolicy: AttributedRope.AttributeMergePolicy = .keepNew) {
if bounds.lowerBound.position == bounds.upperBound.position {
return
}
let intRange = Range(unvalidatedRange: bounds)
let spansRange = Range(bounds, in: base.spans)
let newSpans = Spans(base.spans[spansRange])
let newIntRange = 0..<newSpans.upperBound
var sb = SpansBuilder<AttributedRope.Attributes>(totalCount: newIntRange.count)
sb.add(attributes, covering: newIntRange)
var new = newSpans.merging(sb.build()) { a, b in
if let a, let b {
return a.merging(b, mergePolicy: mergePolicy)
} else {
return b ?? a
}
}
var dup = base.spans
var b = BTreeBuilder<Spans<AttributedRope.Attributes>>()
b.push(&dup.root, slicedBy: 0..<intRange.lowerBound)
b.push(&new.root)
b.push(&dup.root, slicedBy: intRange.upperBound..<dup.upperBound)
base.spans = b.build()
assert(base.spans.upperBound == base.text.utf8.count)
}
func mergingAttributes(_ attributes: AttributedRope.Attributes, mergePolicy: AttributedRope.AttributeMergePolicy = .keepNew) -> AttributedRope {
var dup = self
dup.mergeAttributes(attributes, mergePolicy: mergePolicy)
return AttributedRope(dup)
}
mutating func transformAttributes<K>(_ k: K.Type, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) where K: AttributedRopeKey {
var b = SpansBuilder<AttributedRope.Attributes>(totalCount: base.text.utf8.count)
for run in runs {
if run.attributes[K.self] != nil {
var t = AttributedRope.AttributeTransformer<K>(run: run, builder: b)
block(&t)
b = t.builder
}
}
let newSpans = base.spans.merging(b.build()) { a, b in
guard let b else {
return a
}
var a = a ?? AttributedRope.Attributes()
a[K.self] = nil
a.merge(b)
return a
}
base.spans = newSpans
}
mutating func transformAttributes<K>(_ k: KeyPath<AttributedRope.AttributeKeys, K>, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) where K: AttributedRopeKey {
transformAttributes(K.self, block)
}
func transformingAttributes<K>(_ k: K.Type, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) -> AttributedRope where K: AttributedRopeKey {
var dup = self
dup.transformAttributes(K.self, block)
return AttributedRope(dup)
}
func transformingAttributes<K>(_ k: KeyPath<AttributedRope.AttributeKeys, K>, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) -> AttributedRope where K: AttributedRopeKey {
var dup = self
dup.transformAttributes(K.self, block)
return AttributedRope(dup)
}
}
// MARK: - Attribute transformation
extension AttributedRope {
struct AttributeTransformer<T> where T: AttributedRopeKey {
let run: Runs.Run
var builder: SpansBuilder<Attributes>
var value: T.Value? {
get {
return run.attributes[T.self]
}
set {
if let newValue {
replace(with: T.self, value: newValue)
} else {
replace(with: Attributes())
}
}
}
mutating func replace(with attributes: Attributes) {
builder.add(attributes, covering: Range(unvalidatedRange: run.range))
}
mutating func replace<U>(with key: U.Type, value: U.Value) where U: AttributedRopeKey {
var attrs = Attributes()
attrs[key] = value
replace(with: attrs)
}
mutating func replace<U>(with keyPath: KeyPath<AttributeKeys, U>, value: U.Value) where U: AttributedRopeKey {
replace(with: U.self, value: value)
}
}
mutating func transformAttributes<K>(_ k: K.Type, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) where K: AttributedRopeKey {
self[...].transformAttributes(k, block)
}
mutating func transformAttributes<K>(_ k: KeyPath<AttributedRope.AttributeKeys, K>, _ block: (inout AttributedRope.AttributeTransformer<K>) -> Void) where K: AttributedRopeKey {
self[...].transformAttributes(k, block)
}
func transformingAttributes<K>(_ k: K.Type, _ block: (inout AttributeTransformer<K>) -> Void) -> AttributedRope where K: AttributedRopeKey {
self[...].transformingAttributes(k, block)
}
func transformingAttributes<K>(_ k: KeyPath<AttributeKeys, K>, _ block: (inout AttributeTransformer<K>) -> Void) -> AttributedRope where K: AttributedRopeKey {
self[...].transformingAttributes(k, block)
}
}
// MARK: - Collection
// AttributedRope is not actually a collection, but it acts like one.
extension AttributedRope {
typealias Index = Rope.Index
var startIndex: Index {
text.startIndex
}
var endIndex: Index {
text.endIndex
}
var count: Int {
text.count
}
var isEmpty: Bool {
text.isEmpty
}
func index(at offset: Int) -> Index {
text.index(at: offset)
}
func index(beforeCharacter i: Index) -> Index {
text.index(before: i)
}
func index(afterCharacter i: Index) -> Index {
text.index(after: i)
}
func index(_ i: Index, offsetByCharacters distance: Int) -> Index {
text.index(i, offsetBy: distance)
}
func index(_ i: Index, offsetByCharacters distance: Int, limitedBy limit: Index) -> Index? {
text.index(i, offsetBy: distance, limitedBy: limit)
}
mutating func replaceSubrange<R>(_ range: R, with s: AttributedSubrope) where R: RangeExpression<Index> {
replaceSubrange(range.relative(to: text), with: AttributedRope(s))
}
mutating func replaceSubrange<R>(_ range: R, with s: AttributedRope) where R: RangeExpression<Index> {
replaceSubrange(range.relative(to: text), with: s)
}
mutating func replaceSubrange(_ range: Range<Index>, with s: AttributedRope) {
if range == startIndex..<endIndex && s.isEmpty {
text = s.text // ""
spans = SpansBuilder<AttributedRope.Attributes>(totalCount: 0).build()
return
}
if isEmpty {
precondition(range.lowerBound == startIndex && range.upperBound == startIndex, "index out of bounds")
text = s.text
spans = s.spans
return
}
let start = text.unicodeScalars.index(roundingDown: range.lowerBound)
let end = text.unicodeScalars.index(roundingDown: range.upperBound)
let roundedRange = start..<end
text.replaceSubrange(roundedRange, with: s.text)
let replacementRange = Range(unvalidatedRange: roundedRange)
var dup = spans
var new = s.spans
var b = BTreeBuilder<Spans<AttributedRope.Attributes>>()
b.push(&dup.root, slicedBy: 0..<replacementRange.lowerBound)
b.push(&new.root)
b.push(&dup.root, slicedBy: replacementRange.upperBound..<spans.upperBound)
self.spans = b.build()
assert(spans.root.count == text.root.count)
}
mutating func insert(_ s: AttributedRope, at i: Index) {
replaceSubrange(i..<i, with: s)
}
mutating func insert(_ s: AttributedSubrope, at i: Index) {
replaceSubrange(i..<i, with: AttributedRope(s))
}
mutating func removeSubrange<R>(_ bounds: R) where R: RangeExpression<Index> {
replaceSubrange(bounds.relative(to: text), with: AttributedRope())
}
mutating func append(_ s: AttributedRope) {
replaceSubrange(endIndex..<endIndex, with: s)
}
mutating func append(_ s: AttributedSubrope) {
replaceSubrange(endIndex..<endIndex, with: AttributedRope(s))
}
subscript<R>(bounds: R) -> AttributedSubrope where R: RangeExpression<Index> {
_read {
let bounds = bounds.relative(to: text)
bounds.lowerBound.validate(for: text)
bounds.upperBound.validate(for: text)
yield AttributedSubrope(base: self, bounds: bounds)
}
// TODO: it's possible to for the caller to totally replace c.base rather
// than modifying the one we give it. We should prevent this. AttributedString
// sets an ID and then verifies that it remians the same after the yield.
_modify {
let bounds = bounds.relative(to: text)
bounds.lowerBound.validate(for: text)
bounds.upperBound.validate(for: text)
var r = AttributedSubrope(base: self, bounds: bounds)
self = AttributedRope()
yield &r
self = r.base
}
}
subscript(x: (UnboundedRange_) -> ()) -> AttributedSubrope {
_read {
yield self[startIndex..<endIndex]
}
_modify {
yield &self[startIndex..<endIndex]
}
}
}
extension AttributedSubrope {
var startIndex: AttributedRope.Index {
bounds.lowerBound
}
var endIndex: AttributedRope.Index {
bounds.upperBound
}
subscript<R>(bounds: R) -> AttributedSubrope where R: RangeExpression<AttributedRope.Index> {
let bounds = bounds.relative(to: base.text)
bounds.lowerBound.validate(for: base.text)
bounds.upperBound.validate(for: base.text)
return AttributedSubrope(base: base, bounds: bounds)
}
}
// MARK: - Characters
extension AttributedRope {
struct CharacterView {
var base: AttributedRope
var bounds: Range<AttributedRope.Index>
}
var characters: CharacterView {
_read {
yield CharacterView(base: self, bounds: startIndex..<endIndex)
}
// TODO: it's possible to for the caller to totally replace c.base rather
// than modifying the one we give it. We should prevent this. AttributedString
// sets an ID and then verifies that it remians the same after the yield.
_modify {
var c = CharacterView(base: self, bounds: startIndex..<endIndex)
self = AttributedRope()
yield &c
self = c.base
}
}
}
extension AttributedSubrope {
var characters: AttributedRope.CharacterView {
AttributedRope.CharacterView(base: base, bounds: bounds)
}
}
extension AttributedRope.CharacterView: BidirectionalCollection {
typealias Index = AttributedRope.Index
var startIndex: Index {
bounds.lowerBound
}
var endIndex: Index {
bounds.upperBound
}
func index(after i: Index) -> Index {
precondition(bounds.lowerBound <= i && i < bounds.upperBound, "out of bounds")
return base.text.index(after: i)
}
func index(before i: Index) -> Index {
precondition(bounds.lowerBound < i && i <= bounds.upperBound, "out of bounds")
return base.text.index(before: i)
}
subscript(position: Index) -> Character {
precondition(bounds.lowerBound <= position && position < bounds.upperBound, "out of bounds")
return base.text[position]
}
// Delegate to Rope's more efficient implementations of these methods.
func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(bounds.lowerBound <= i && i <= bounds.upperBound, "out of bounds")
let res = base.text.index(i, offsetBy: distance)
precondition(bounds.lowerBound <= res && res <= bounds.upperBound, "out of bounds")
return res
}
func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
precondition(bounds.lowerBound <= i && i <= bounds.upperBound, "out of bounds")
guard let res = base.text.index(i, offsetBy: distance, limitedBy: limit) else { return nil }
precondition(bounds.lowerBound <= res && res <= bounds.upperBound, "out of bounds")
return res
}
func distance(from start: Index, to end: Index) -> Int {
precondition(bounds.lowerBound <= start && start <= bounds.upperBound)
precondition(bounds.lowerBound <= end && end <= bounds.upperBound)
return base.text.distance(from: start, to: end)
}
}
extension AttributedRope.CharacterView: RangeReplaceableCollection {
init() {
let r = AttributedRope()
self.init(base: r, bounds: r.startIndex..<r.endIndex)
}
mutating func replaceSubrange<C>(_ subrange: Range<Index>, with newElements: C) where C: Collection, C.Element == Character {
precondition(subrange.lowerBound >= startIndex && subrange.upperBound <= endIndex, "index out of bounds")
let s = AttributedRope(Rope(newElements), attributes: attributes(forReplacementRange: subrange, in: base))
base.replaceSubrange(subrange, with: s)
}
// The default implementation calls append(_:) in a loop.
mutating func append<S>(contentsOf newElements: S) where S: Sequence, Self.Element == S.Element {
replaceSubrange(endIndex..<endIndex, with: Rope(newElements))
}
}
fileprivate func attributes(forReplacementRange range: Range<AttributedRope.Index>, in attrRope: AttributedRope) -> AttributedRope.Attributes {
range.lowerBound.assertValid(for: attrRope.text)
range.upperBound.assertValid(for: attrRope.text)
if attrRope.isEmpty {
return AttributedRope.Attributes()
}
let location = range.lowerBound.position == attrRope.text.utf8.count ? attrRope.index(beforeCharacter: attrRope.endIndex) : range.lowerBound
var run = attrRope.runs[location]
if range.isEmpty && range.lowerBound.position == run.range.lowerBound.position && run.range.lowerBound.position != 0 {
run = attrRope.runs[attrRope.index(beforeCharacter: range.lowerBound)]
}
return run.attributes
}
// MARK: - Builder
extension AttributedRope {
struct Builder {
var rb: RopeBuilder