Skip to content

Commit 2e8358d

Browse files
authored
Preserve syntax styles across editor settings changes (#479)
* Preserve syntax highlighting during layout changes * Retain syntax styles during spacing and theme updates
1 parent 2638895 commit 2e8358d

6 files changed

Lines changed: 552 additions & 52 deletions

File tree

‎Sources/Runestone/Library/DefaultStringAttributes.swift‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,25 @@ struct DefaultStringAttributes {
88
let tabWidth: CGFloat
99

1010
func apply(to attributedString: NSMutableAttributedString) {
11+
let range = NSRange(location: 0, length: attributedString.length)
12+
attributedString.setAttributes([.foregroundColor: textColor, .font: font], range: range)
13+
applyLayout(to: attributedString)
14+
}
15+
16+
/// Layout settings do not replace the fonts and colors supplied by syntax captures.
17+
func applyLayout(to attributedString: NSMutableAttributedString) {
1118
let paragraphStyle = NSMutableParagraphStyle()
1219
paragraphStyle.tabStops = (0 ..< 20).map { index in
1320
NSTextTab(textAlignment: .natural, location: CGFloat(index) * tabWidth)
1421
}
1522
paragraphStyle.defaultTabInterval = tabWidth
1623
let range = NSRange(location: 0, length: attributedString.length)
1724
let attributes: [NSAttributedString.Key: Any] = [
18-
.foregroundColor: textColor,
19-
.font: font,
2025
.kern: kern as NSNumber,
2126
.paragraphStyle: paragraphStyle
2227
]
2328
attributedString.beginEditing()
24-
attributedString.setAttributes(attributes, range: range)
29+
attributedString.addAttributes(attributes, range: range)
2530
attributedString.endEditing()
2631
}
2732
}

‎Sources/Runestone/TextView/Core/TextInputView.swift‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,8 @@ final class TextInputView: UIView, UITextInput {
573573
didSet {
574574
if indentStrategy != oldValue {
575575
indentController.indentStrategy = indentStrategy
576+
invalidateLines()
577+
contentSizeService.invalidateContentSize()
576578
layoutManager.setNeedsLayout()
577579
setNeedsLayout()
578580
layoutIfNeeded()
@@ -1165,7 +1167,7 @@ final class TextInputView: UIView, UITextInput {
11651167
internalLanguageMode.parse(string) { [weak self] finished in
11661168
if let self = self, finished {
11671169
self.refreshCodeFolding()
1168-
self.invalidateLines()
1170+
self.invalidateLines(includingSyntaxHighlighting: true)
11691171
self.layoutManager.setNeedsLayout()
11701172
self.layoutManager.layoutIfNeeded()
11711173
self.invalidateSpellChecking()
@@ -1236,7 +1238,7 @@ final class TextInputView: UIView, UITextInput {
12361238
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
12371239
super.traitCollectionDidChange(previousTraitCollection)
12381240
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
1239-
invalidateLines()
1241+
invalidateLines(includingSyntaxHighlighting: true)
12401242
layoutManager.setNeedsLayout()
12411243
}
12421244
}
@@ -1331,13 +1333,16 @@ private extension TextInputView {
13311333
layoutManager.layoutIfNeeded()
13321334
}
13331335

1334-
private func invalidateLines() {
1336+
private func invalidateLines(includingSyntaxHighlighting: Bool = false) {
13351337
for lineController in lineControllerStorage {
13361338
lineController.lineFragmentHeightMultiplier = lineHeightMultiplier
13371339
lineController.tabWidth = indentController.tabWidth
13381340
lineController.kern = kern
13391341
lineController.lineBreakMode = lineBreakMode
1340-
lineController.invalidateSyntaxHighlighting()
1342+
lineController.invalidateLayout()
1343+
if includingSyntaxHighlighting {
1344+
lineController.invalidateSyntaxHighlighting()
1345+
}
13411346
}
13421347
}
13431348

@@ -2088,6 +2093,7 @@ extension TextInputView: LineControllerStorageDelegate {
20882093
lineController.estimatedLineFragmentHeight = theme.font.totalLineHeight
20892094
lineController.lineFragmentHeightMultiplier = lineHeightMultiplier
20902095
lineController.tabWidth = indentController.tabWidth
2096+
lineController.kern = kern
20912097
lineController.theme = theme
20922098
lineController.lineBreakMode = lineBreakMode
20932099
}

‎Sources/Runestone/TextView/LineController/LineController.swift‎

Lines changed: 89 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ final class LineController {
2222
var lineFragmentHeightMultiplier: CGFloat = 1 {
2323
didSet {
2424
if lineFragmentHeightMultiplier != oldValue {
25-
invalidatePrefixReuse()
25+
invalidateLayout()
2626
typesetter.lineFragmentHeightMultiplier = lineFragmentHeightMultiplier
2727
}
2828
}
@@ -37,15 +37,18 @@ final class LineController {
3737
var estimatedLineFragmentHeight: CGFloat = 15
3838
var tabWidth: CGFloat = 10 {
3939
didSet {
40-
if tabWidth != oldValue { invalidatePrefixReuse() }
40+
if tabWidth != oldValue {
41+
invalidateLayout()
42+
isLayoutAttributesInvalid = true
43+
}
4144
}
4245
}
4346
var constrainingWidth: CGFloat {
4447
get {
4548
typesetter.constrainingWidth
4649
}
4750
set {
48-
if typesetter.constrainingWidth != newValue { invalidatePrefixReuse() }
51+
if typesetter.constrainingWidth != newValue { invalidateLayout() }
4952
typesetter.constrainingWidth = newValue
5053
}
5154
}
@@ -73,8 +76,8 @@ final class LineController {
7376
var kern: CGFloat = 0 {
7477
didSet {
7578
if kern != oldValue {
76-
invalidatePrefixReuse()
77-
isDefaultAttributesInvalid = true
79+
invalidateLayout()
80+
isLayoutAttributesInvalid = true
7881
}
7982
}
8083
}
@@ -83,7 +86,7 @@ final class LineController {
8386
typesetter.lineBreakMode
8487
}
8588
set {
86-
if typesetter.lineBreakMode != newValue { invalidatePrefixReuse() }
89+
if typesetter.lineBreakMode != newValue { invalidateLayout() }
8790
typesetter.lineBreakMode = newValue
8891
}
8992
}
@@ -105,6 +108,8 @@ final class LineController {
105108
private var isLineFragmentCacheInvalid = true
106109
private var isStringInvalid = true
107110
private var isDefaultAttributesInvalid = true
111+
private var isLayoutAttributesInvalid = true
112+
private var hasAppliedSyntaxHighlighting = false
108113
private var isSyntaxHighlightingInvalid = true
109114
private var isTypesetterInvalid = true
110115
private var allowsPrefixReuse = false
@@ -153,6 +158,11 @@ final class LineController {
153158
}
154159

155160
func cancelSyntaxHighlighting() {
161+
// A staged appearance has not reached the displayed string yet. Rebuild
162+
// its defaults if this request is cancelled and the line is revisited.
163+
if let input = pendingHighlightInput, input.attributedString !== attributedString {
164+
isDefaultAttributesInvalid = true
165+
}
156166
pendingHighlightInput = nil
157167
cachedSyntaxHighlighter?.cancel()
158168
}
@@ -173,6 +183,15 @@ final class LineController {
173183
_lineHeight = nil
174184
}
175185

186+
/// Reflow the existing styled string without discarding attributes or restarting
187+
/// a pending highlight request. Geometry changes do not change syntax captures.
188+
func invalidateLayout() {
189+
invalidatePrefixReuse()
190+
isLineFragmentCacheInvalid = true
191+
isTypesetterInvalid = true
192+
_lineHeight = nil
193+
}
194+
176195
func invalidateSyntaxHighlighter() {
177196
invalidatePrefixReuse()
178197
cancelSyntaxHighlighting()
@@ -240,14 +259,15 @@ private extension LineController {
240259
// new object. Never retain an additional snapshot after this preparation.
241260
let previous = allowsPrefixReuse && isStringInvalid && !syntaxHighlightAsynchronously ? attributedString : nil
242261
allowsPrefixReuse = false
243-
if isStringInvalid || isDefaultAttributesInvalid
262+
if !syntaxHighlightAsynchronously || isStringInvalid || isDefaultAttributesInvalid
244263
|| pendingHighlightInput.map({ $0.byteRange != line.data.totalByteRange }) == true {
245264
cancelSyntaxHighlighting()
246265
}
247266
clearLineFragmentControllersIfNecessary()
248267
updateStringIfNecessary()
249-
updateDefaultAttributesIfNecessary()
250-
updateSyntaxHighlightingIfNecessary(async: syntaxHighlightAsynchronously)
268+
let stagedInput = updateDefaultAttributesIfNecessary(async: syntaxHighlightAsynchronously)
269+
updateLayoutAttributesIfNecessary()
270+
updateSyntaxHighlightingIfNecessary(async: syntaxHighlightAsynchronously, stagedInput: stagedInput)
251271
updateTypesetterIfNecessary(previous: previous, prefixLimit: previous == nil ? 0 : prefixLimit(for: amount))
252272
}
253273

@@ -295,27 +315,49 @@ private extension LineController {
295315
attributedString = nil
296316
}
297317
isStringInvalid = false
318+
hasAppliedSyntaxHighlighting = false
298319
isDefaultAttributesInvalid = true
299320
isSyntaxHighlightingInvalid = true
300321
isTypesetterInvalid = true
301322
}
302323
}
303324

304-
private func updateDefaultAttributesIfNecessary() {
305-
if isDefaultAttributesInvalid {
306-
if let input = createLineSyntaxHighlightInput() {
307-
let defaultStringAttributes = DefaultStringAttributes(
308-
textColor: theme.textColor,
309-
font: theme.font,
310-
kern: kern,
311-
tabWidth: tabWidth
312-
)
313-
defaultStringAttributes.apply(to: input.attributedString)
314-
}
315-
isDefaultAttributesInvalid = false
316-
isSyntaxHighlightingInvalid = true
317-
isTypesetterInvalid = true
325+
private var defaultStringAttributes: DefaultStringAttributes {
326+
DefaultStringAttributes(textColor: theme.textColor, font: theme.font, kern: kern, tabWidth: tabWidth)
327+
}
328+
329+
private func updateDefaultAttributesIfNecessary(async: Bool) -> LineSyntaxHighlighterInput? {
330+
guard isDefaultAttributesInvalid, let attributedString else {
331+
return nil
332+
}
333+
// Keep already styled text visible while a replacement appearance is
334+
// highlighted. The pending request owns the temporary string, so it is
335+
// released on completion or cancellation rather than cached per line.
336+
let shouldStage = async && hasAppliedSyntaxHighlighting && syntaxHighlighter?.canHighlight == true
337+
let target = shouldStage ? NSMutableAttributedString(string: attributedString.string) : attributedString
338+
defaultStringAttributes.apply(to: target)
339+
isDefaultAttributesInvalid = false
340+
isSyntaxHighlightingInvalid = true
341+
if shouldStage {
342+
return LineSyntaxHighlighterInput(attributedString: target, byteRange: line.data.totalByteRange)
318343
}
344+
isLayoutAttributesInvalid = false
345+
isTypesetterInvalid = true
346+
return nil
347+
}
348+
349+
private func updateLayoutAttributesIfNecessary() {
350+
guard isLayoutAttributesInvalid else {
351+
return
352+
}
353+
if let attributedString {
354+
defaultStringAttributes.applyLayout(to: attributedString)
355+
}
356+
if let input = pendingHighlightInput, input.attributedString !== attributedString {
357+
defaultStringAttributes.applyLayout(to: input.attributedString)
358+
}
359+
isLayoutAttributesInvalid = false
360+
isTypesetterInvalid = true
319361
}
320362

321363
private func updateTypesetterIfNecessary(previous: NSAttributedString? = nil, prefixLimit: Int = 0) {
@@ -334,7 +376,7 @@ private extension LineController {
334376
}
335377
}
336378

337-
private func updateSyntaxHighlightingIfNecessary(async: Bool) {
379+
private func updateSyntaxHighlightingIfNecessary(async: Bool, stagedInput: LineSyntaxHighlighterInput?) {
338380
guard isSyntaxHighlightingInvalid else {
339381
return
340382
}
@@ -345,7 +387,7 @@ private extension LineController {
345387
isSyntaxHighlightingInvalid = false
346388
return
347389
}
348-
guard let input = createLineSyntaxHighlightInput() else {
390+
guard let input = stagedInput ?? createLineSyntaxHighlightInput() else {
349391
isSyntaxHighlightingInvalid = false
350392
return
351393
}
@@ -362,24 +404,38 @@ private extension LineController {
362404
&& self.line.data.totalByteRange == input.byteRange
363405
}
364406
syntaxHighlighter.syntaxHighlight(input) { [weak self] result in
365-
guard let self = self, self.pendingHighlightInput === input else {
366-
return
367-
}
368-
self.pendingHighlightInput = nil
369-
if case .success(let attributesResult) = result {
370-
self.didApplyHighlightAttributes(attributesResult)
371-
}
407+
self?.completeSyntaxHighlighting(input, result: result)
372408
}
373409
} else {
374410
cancelSyntaxHighlighting()
375411
syntaxHighlighter.syntaxHighlight(input)
412+
hasAppliedSyntaxHighlighting = true
376413
isSyntaxHighlightingInvalid = false
377414
isTypesetterInvalid = true
378415
}
379416
}
380417

418+
private func completeSyntaxHighlighting(_ input: LineSyntaxHighlighterInput,
419+
result: Result<LineSyntaxHiglighterSetAttributesResult, Error>) {
420+
guard pendingHighlightInput === input, line.data.totalByteRange == input.byteRange else {
421+
return
422+
}
423+
pendingHighlightInput = nil
424+
if case .success(let attributesResult) = result {
425+
if attributedString !== input.attributedString {
426+
attributedString = input.attributedString
427+
isTypesetterInvalid = true
428+
}
429+
hasAppliedSyntaxHighlighting = true
430+
didApplyHighlightAttributes(attributesResult)
431+
} else if attributedString !== input.attributedString {
432+
isDefaultAttributesInvalid = true
433+
}
434+
}
435+
381436
private func didApplyHighlightAttributes(_ result: LineSyntaxHiglighterSetAttributesResult) {
382437
let oldWidth = lineWidth
438+
let oldHeight = lineHeight
383439
isSyntaxHighlightingInvalid = false
384440
if result.isSizingInvalid || isTypesetterInvalid {
385441
isTypesetterInvalid = true
@@ -392,7 +448,7 @@ private extension LineController {
392448
reapplyLineFragmentToLineFragmentControllers()
393449
setNeedsDisplayOnLineFragmentViews()
394450
}
395-
if abs(lineWidth - oldWidth) > CGFloat.ulpOfOne {
451+
if abs(lineWidth - oldWidth) > CGFloat.ulpOfOne || abs(lineHeight - oldHeight) > CGFloat.ulpOfOne {
396452
delegate?.lineControllerDidInvalidateLineWidthDuringAsyncSyntaxHighlight(self)
397453
}
398454
}

0 commit comments

Comments
 (0)