Sources/OrgEditorAppKit/OrgEditor+Styling.swift
177 lines · 9550 bytes
10 symbols in this file
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 let revealed = caretLine
30 let (changes, scriptExclusions) = Presentation.styleChanges(
31 document.tree, in: range, highlighter: highlighter, indented: indented, hideStars: hideStars,
32 showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed)
33 )
34 var tags: [Range<Int>] = []
35 for change in changes {
36 switch change {
37 case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
38 case .role(let role, let range):
39 theme.apply(role, to: storage, range: NSRange(range))
40 if role == .tags { tags.append(range) }
41 case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range))
42 }
43 }
44 if theme.mixedPitch {
45 for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) {
46 guard let clipped = clip(prefix, to: range) else { continue }
47 storage.addAttribute(.font, value: theme.fixedPitch(storage, clipped), range: clipped)
48 }
49 }
50 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
51 applyShrunk(range, in: storage)
52 applyHighlights(range, in: storage)
53 applyImages(range, in: storage, revealed: revealed)
54 applyLatex(range, in: storage, revealed: revealed)
55 fitTagGaps(tags, in: storage)
56 }
57
58 /// The text container's width, for tag gaps: the narrowest view's, as images are sized.
59 var tagGapAvailableWidth: CGFloat {
60 let widths = textViews.compactMap { view in view.textContainer.map { $0.size.width - 2 * $0.lineFragmentPadding } }
61 return widths.filter { $0 > 0 }.min() ?? 0
62 }
63
64 /// Draws the spaces before each heading's tags in `tags` as one gap that fits the view
65 /// (`Presentation.tagGapWidth`): all but the last space hidden, the last widened.
66 func fitTagGaps(_ tags: [Range<Int>], in storage: NSTextStorage) {
67 guard !tags.isEmpty else { return }
68 let available = tagGapAvailableWidth
69 guard available > 0 else { return }
70 // The storage's own string: `string` copies the whole text.
71 let text = storage.mutableString
72 for range in tags where range.upperBound <= text.length {
73 guard let gap = Presentation.tagGap(tags: range, in: text) else { continue }
74 let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
75 let indent = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.firstLineHeadIndent ?? 0
76 // Without the paragraph style, whose indent is taken from the width apart.
77 func width(_ range: Range<Int>) -> CGFloat {
78 let part = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: NSRange(range)))
79 part.removeAttribute(.paragraphStyle, range: NSRange(location: 0, length: part.length))
80 return part.size().width
81 }
82 // Spaces measured before the tags: trailing spaces may not count.
83 let last = gap.gap.upperBound - 1
84 let title = width(line.location..<gap.gap.lowerBound), tagsWidth = width(gap.tags)
85 let space = width(last..<gap.tags.upperBound) - tagsWidth
86 // A point to spare, so rounding doesn't wrap the tags.
87 guard let shown = Presentation.tagGapWidth(
88 title: title, gap: width(line.location..<gap.tags.upperBound) - title - tagsWidth, space: space, tags: tagsWidth,
89 available: available - indent - 1
90 ) else { continue }
91 storage.addAttributes(theme.hidden, range: NSRange(gap.gap.lowerBound..<last))
92 storage.addAttribute(.kern, value: max(0, shown - space), range: NSRange(location: last, length: 1))
93 }
94 }
95
96 /// Draws tag gaps again once the view's width has changed, after the layout pass that changed it.
97 func refitTagGaps() {
98 guard isOrg, !fittingTagGaps else { return }
99 fittingTagGaps = true
100 DispatchQueue.main.async { [weak self] in
101 guard let self else { return }
102 self.fittingTagGaps = false
103 guard self.tagGapWidth != self.tagGapAvailableWidth else { return }
104 let text = self.document.text as NSString
105 for gap in Presentation.tagGaps(self.document.tree) where gap.tags.upperBound <= text.length {
106 let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
107 self.restyleOutsideEditing(line.location..<NSMaxRange(line))
108 }
109 self.tagGapWidth = self.tagGapAvailableWidth
110 }
111 }
112
113 /// `org-pretty-entities`: entities drawn as their character over the entity's last
114 /// character (the rest hidden), sub/superscripts raised without their markers.
115 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
116 let runs = Presentation.prettyRuns(
117 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
118 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
119 )
120 for (lineStart, run) in runs {
121 switch run {
122 case .entity(let r, let display):
123 let start = lineStart + r.lowerBound
124 let last = lineStart + r.upperBound - 1
125 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
126 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
127 case .script(let markers, let body, let superscript):
128 for marker in markers {
129 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
130 }
131 let size = theme.font.pointSize
132 storage.addAttributes([
133 .font: theme.mixedPitch ? theme.body.withSize(size * 0.7) : NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
134 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
135 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
136 }
137 }
138 }
139
140 /// Moving to another line shows its markup and hides the last one's.
141 func revealCaretLine() {
142 // LaTeX previews and images show their source on the caret's line whether or not markup shows.
143 guard !showMarkup || showsLatex || showsImages, isOrg else { return }
144 let line = caretLine
145 guard line != revealedLine else { return }
146 let text = textView.string as NSString
147 // The old line may have moved with edits since; restyle the line now at its start.
148 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
149 revealedLine = line
150 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
151 restyleOutsideEditing(range.location..<NSMaxRange(range))
152 }
153 }
154
155 /// Code highlights for the whole file in plain mode.
156 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
157 guard case .plain(let language?) = mode, let highlighter else { return [] }
158 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
159 let runs = highlighter.highlights(language: language, code: document.text)
160 codeRuns = (document.revision, runs)
161 return runs
162 }
163
164 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
165 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
166 if let style = paragraphStyles[key] { return style }
167 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
168 paragraphStyles[key] = style
169 return style
170 }
171
172 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
173 let clipped = run.clamped(to: range)
174 return clipped.isEmpty ? nil : NSRange(clipped)
175 }
176}
177#endif