Sources/OrgEditorAppKit/OrgEditor+Styling.swift
153 lines · 8106 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgPresentation
5
6extension OrgEditor {
7 // MARK: - Styling
8
9 func restyleOutsideEditing(_ range: Range<Int>) {
10 guard let storage = textView.textStorage else { return }
11 storage.beginEditing()
12 restyle(range, in: storage)
13 storage.endEditing()
14 }
15
16 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
17 /// attribute changes are allowed and characters must not change.
18 func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
19 guard !range.isEmpty else { return }
20 let whole = NSRange(range)
21 storage.setAttributes(theme.base, range: whole)
22 guard isOrg else {
23 for run in plainRuns() where run.range.overlaps(range) {
24 guard let clipped = clip(run.range, to: range) else { continue }
25 theme.apply(.syntax(run.category), to: storage, range: clipped)
26 }
27 return
28 }
29 if indented {
30 for line in Presentation.lineIndents(document.tree, in: range) {
31 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
32 }
33 }
34 let revealed = caretLine
35 var scriptExclusions: [Range<Int>] = []
36 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
37 guard let clipped = clip(run.range, to: range) else { continue }
38 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
39 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
40 storage.addAttributes(theme.hidden, range: clipped)
41 } else {
42 theme.apply(run.role, to: storage, range: clipped)
43 }
44 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
45 }
46 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
47 applyShrunk(range, in: storage)
48 applyHighlights(range, in: storage)
49 applyImages(range, in: storage, revealed: revealed)
50 }
51
52 /// `org-pretty-entities`: entities drawn as their character over the entity's last
53 /// character (the rest hidden), sub/superscripts raised without their markers.
54 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
55 let runs = Presentation.prettyRuns(
56 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
57 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
58 )
59 for (lineStart, run) in runs {
60 switch run {
61 case .entity(let r, let display):
62 let start = lineStart + r.lowerBound
63 let last = lineStart + r.upperBound - 1
64 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
65 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
66 case .script(let markers, let body, let superscript):
67 for marker in markers {
68 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
69 }
70 let size = theme.font.pointSize
71 storage.addAttributes([
72 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
73 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
74 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
75 }
76 }
77 }
78
79 /// Moving to another line shows its markup and hides the last one's.
80 func revealCaretLine() {
81 guard !showMarkup, isOrg else { return }
82 let line = caretLine
83 guard line != revealedLine else { return }
84 let text = textView.string as NSString
85 // The old line may have moved with edits since; restyle the line now at its start.
86 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
87 revealedLine = line
88 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
89 restyleOutsideEditing(range.location..<NSMaxRange(range))
90 }
91 }
92
93 /// Code highlights for the whole file in plain mode.
94 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
95 guard case .plain(let language?) = mode, let highlighter else { return [] }
96 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
97 let runs = highlighter.highlights(language: language, code: document.text)
98 codeRuns = (document.revision, runs)
99 return runs
100 }
101
102 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
103 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
104 if let style = paragraphStyles[key] { return style }
105 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
106 paragraphStyles[key] = style
107 return style
108 }
109
110 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
111 let clipped = run.clamped(to: range)
112 return clipped.isEmpty ? nil : NSRange(clipped)
113 }
114
115 /// The region an edit affects in one version of the tree: inside the innermost section
116 /// holding the edited lines (plus the line after), every element that overlaps them or the
117 /// line on either side. A changed heading line, or an added or removed heading, widens it
118 /// to that section's whole own body. Run on the old and the new tree, the union covers
119 /// elements that grew and elements that shrank.
120 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
121 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
122 let lineRange = lines.location..<(lines.location + lines.length)
123 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
124 var container = tree.root
125 while let child = container.child(containing: lineRange.lowerBound),
126 child.kind == .section || child.kind == .zerothSection,
127 lineRange.upperBound <= child.range.upperBound {
128 container = child
129 }
130 var lower = lineRange.lowerBound
131 var upper = lineRange.upperBound
132 // Tables and lists carry no styling of their own, so inside them only the rows or
133 // items around the edit change, however large they are.
134 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
135 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
136 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
137 let inner = overlapping(node.children(overlapping: around))
138 return inner.isEmpty ? [node] : inner
139 }
140 }
141 for child in overlapping(container.children(overlapping: around)) {
142 lower = min(lower, child.range.lowerBound)
143 upper = max(upper, child.range.upperBound)
144 }
145 let heading = container.firstChild(.heading)
146 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
147 lower = min(lower, container.range.lowerBound)
148 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
149 }
150 return lower..<min(upper, text.length)
151 }
152}
153#endif