Commit 2e0daf23dd

2e0daf23ddae974e49ddfb23e33bb2933bc00c4d

parent: fe955aa1d5

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 04:02 UTC

Split OrgEditor.swift

Layout: unified · split

Sources/OrgEditorAppKit/Fragments.swift added +145
@@ -0,0 +1,145 @@
1#if os(macOS)
2import AppKit
3
4/// A line of a block, on a band across the whole width of the view, as Emacs extends the
5/// `org-block` face.
6final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
7 private var band: CGRect {
8 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
9 // Not under the empty line TextKit adds after a final newline.
10 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
11 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
12 }
13
14 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
15
16 override func draw(at point: CGPoint, in context: CGContext) {
17 context.saveGState()
18 context.setFillColor(Theme.blockBackground.cgColor)
19 context.fill(band.offsetBy(dx: point.x, dy: point.y))
20 // The band covers the view's selection highlight, so the selected text is drawn on it,
21 // in the color the view uses: the theme's when focused, the system's muted one when not.
22 if let manager = textLayoutManager {
23 let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
24 context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
25 let single = textLineFragments.count == 1
26 for selection in manager.textSelections {
27 for range in selection.textRanges where !range.isEmpty {
28 guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
29 manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
30 var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
31 // A one-line fragment's selection covers its band, leaving no gap to the next line.
32 if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
33 context.fill(rect)
34 return true
35 }
36 }
37 }
38 }
39 context.restoreGState()
40 super.draw(at: point, in: context)
41 }
42}
43
44extension NSAttributedString.Key {
45 /// The character an entity shows as, on the entity's last character.
46 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
47 /// The image an image link's line shows under it.
48 static let orgImage = NSAttributedString.Key("OrgImage")
49}
50
51final class InlineImageBox: NSObject, @unchecked Sendable {
52 let image: NSImage
53 let size: CGSize
54 init(image: NSImage, size: CGSize) {
55 self.image = image
56 self.size = size
57 }
58}
59
60/// An image link's line drawn as the image, with the paragraph spacing making room for its
61/// height.
62final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
63 static func image(_ string: NSAttributedString) -> InlineImageBox? {
64 var found: InlineImageBox?
65 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
66 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
67 }
68 return found
69 }
70
71 private var frame: CGRect? {
72 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
73 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
74 }
75
76 override var renderingSurfaceBounds: CGRect {
77 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
78 }
79
80 override func draw(at point: CGPoint, in context: CGContext) {
81 super.draw(at: point, in: context)
82 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
83 NSGraphicsContext.saveGraphicsState()
84 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
85 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
86 NSGraphicsContext.restoreGraphicsState()
87 }
88}
89
90/// A paragraph with pretty entities: each is drawn as its character where the entity's last
91/// (now invisible) character sits, so it takes one column as in Emacs.
92final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
93 static func hasEntities(_ string: NSAttributedString) -> Bool {
94 var found = false
95 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
96 if value != nil { found = true; stop.pointee = true }
97 }
98 return found
99 }
100
101 override func draw(at point: CGPoint, in context: CGContext) {
102 super.draw(at: point, in: context)
103 Self.drawEntities(of: self, at: point, in: context)
104 }
105
106 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
107 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
108 NSGraphicsContext.saveGraphicsState()
109 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
110 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
111 guard let display = value as? String,
112 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
113 var attributes = string.attributes(at: range.location, effectiveRange: nil)
114 attributes[.foregroundColor] = NSColor.textColor
115 attributes[.orgEntityDisplay] = nil
116 let x = line.locationForCharacter(at: range.location).x
117 let bounds = line.typographicBounds
118 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
119 }
120 NSGraphicsContext.restoreGraphicsState()
121 }
122}
123
124/// A heading line drawn with an ellipsis after it, like org's folded headings.
125final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
126 override func draw(at point: CGPoint, in context: CGContext) {
127 super.draw(at: point, in: context)
128 EntityFragment.drawEntities(of: self, at: point, in: context)
129 guard let line = textLineFragments.first else { return }
130 let bounds = line.typographicBounds
131 let ellipsis = NSAttributedString(string: " …", attributes: [
132 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
133 .foregroundColor: NSColor.secondaryLabelColor,
134 ])
135 NSGraphicsContext.saveGraphicsState()
136 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
137 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
138 NSGraphicsContext.restoreGraphicsState()
139 }
140
141 override var renderingSurfaceBounds: CGRect {
142 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
143 }
144}
145#endif
Sources/OrgEditorAppKit/HiddenRanges.swift added +43
@@ -0,0 +1,43 @@
1#if os(macOS)
2import Foundation
3
4/// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread.
5final class HiddenRanges: @unchecked Sendable {
6 private let lock = NSLock()
7 private var ranges: [Range<Int>] = []
8
9 func set(_ new: [Range<Int>]) {
10 lock.withLock { ranges = new }
11 }
12
13 var all: [Range<Int>] {
14 lock.withLock { ranges }
15 }
16
17 func covers(_ start: Int, _ end: Int) -> Bool {
18 lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } }
19 }
20
21 func containing(_ offset: Int) -> Range<Int>? {
22 lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } }
23 }
24}
25
26/// Folded heading starts, read by the layout-fragment callback.
27final class FoldedHeadings: @unchecked Sendable {
28 private let lock = NSLock()
29 private var starts: Set<Int> = []
30
31 func set(_ new: Set<Int>) {
32 lock.withLock { starts = new }
33 }
34
35 func contains(_ offset: Int) -> Bool {
36 lock.withLock { starts.contains(offset) }
37 }
38
39 var all: Set<Int> {
40 lock.withLock { starts }
41 }
42}
43#endif
Sources/OrgEditorAppKit/OrgEditor+Folding.swift added +214
@@ -0,0 +1,214 @@
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgPresentation
5
6extension OrgEditor {
7 // MARK: - Folding
8
9 public var foldState: FoldState {
10 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
11 }
12
13
14 public func setFolds(_ state: FoldState) {
15 setFolds(state, wrappers: nil)
16 }
17
18 /// `wrappers`, when given, holds every folded drawer and block.
19 func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
20 sparseHidden = nil
21 view.folds = state.folds
22 view.bodyFolds = state.bodyFolds
23 view = view.pruned(to: document.tree, wrappers: false)
24 // Found one by one, or all at once when there are many.
25 let found = wrappers ?? (state.wrapperFolds.count > 32
26 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
27 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
28 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
29 view.wrapperFolds = Set(wrapperHidden.keys)
30 updateHiddenAndLayout()
31 orgTextView?.redrawLineNumbers()
32 textView.needsDisplay = true
33 let caret = textView.selectedRange().location
34 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
35 }
36
37
38 func updateHidden() {
39 if let sparseHidden {
40 let ns = textView.string as NSString
41 // Headings whose next line is hidden show the fold ellipsis.
42 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
43 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
44 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
45 }
46 folded.set(Set(headings).union(view.wrapperFolds))
47 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
48 return
49 }
50 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
51 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
52 }
53
54 /// `updateHidden`, laying out again only the text that changed between hidden and shown
55 /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit
56 /// estimate the height of everything above the window afresh, which moves the text under it.
57 private func updateHiddenAndLayout() {
58 let oldHidden = hidden.all
59 let oldFolded = folded.all
60 updateHidden()
61 invalidateLayout(from: oldHidden, to: hidden.all)
62 invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 })
63 }
64
65 /// Lays out again the ranges in `old` and not in `new`, and the other way round.
66 func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) {
67 invalidateLayout(lines: Array(Set(old).symmetricDifference(new)))
68 }
69
70 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
71 /// heading or opening line of a fold, whose fragment draws the fold mark.
72 func invalidateLayout(lines ranges: [Range<Int>]) {
73 guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return }
74 let text = textView.string as NSString
75 for range in ranges {
76 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
77 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
78 guard let start = content.location(content.documentRange.location, offsetBy: lower),
79 let end = content.location(start, offsetBy: upper - lower),
80 let textRange = NSTextRange(location: start, end: end) else { continue }
81 textLayoutManager.invalidateLayout(for: textRange)
82 }
83 }
84
85 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
86 /// top of the window back there. TextKit estimates the height of text it hasn't laid out,
87 /// so the same scroll position lands on different text after a fresh layout.
88 func keepingTopLine(_ change: () -> Void) {
89 guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() }
90 let visible = scroll.documentVisibleRect
91 let top = visible.minY - textView.textContainerOrigin.y
92 let start = content.documentRange.location
93 let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
94 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
95 }
96 change()
97 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
98 let above = NSTextRange(location: start, end: location) else { return }
99 // Styled now, not in the background passes, which would lay the text out again.
100 while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) }
101 textLayoutManager.ensureLayout(for: above)
102 guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return }
103 let frame = fragment.layoutFragmentFrame
104 let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height))
105 textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height))
106 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
107 let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height
108 if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) }
109 textView.scroll(NSPoint(x: visible.minX, y: y))
110 scroll.reflectScrolledClipView(scroll.contentView)
111 }
112
113 // MARK: - Sparse trees
114
115
116 func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
117 let text = textView.string
118 var state = foldState
119 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
120 state.wrapperFolds.remove(start)
121 }
122 sparseHidden = nil
123 setFolds(state)
124 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
125 self.highlights = highlights
126 keepingTopLine {
127 updateHiddenAndLayout()
128 restyleOutsideEditing(0..<utf16Length)
129 }
130 orgTextView?.redrawLineNumbers()
131 textView.needsDisplay = true
132 let caret = textView.selectedRange().location
133 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
134 }
135
136 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
137 /// open, the others folded.
138 func leaveSparseTree() {
139 guard let sparse = sparseHidden else { return }
140 sparseHidden = nil
141 let outline = Presentation.outline(document.tree)
142 let ns = textView.string as NSString
143 var open: Set<Int> = []
144 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
145 var parent = entry.parent
146 while let p = parent {
147 open.insert(outline[p].start)
148 parent = outline[p].parent
149 }
150 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
151 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
152 }
153 var state = foldState
154 state.folds = Set(outline.map(\.start)).subtracting(open)
155 state.bodyFolds = []
156 setFolds(state)
157 }
158
159 func clearHighlights() {
160 guard !highlights.isEmpty else { return }
161 let old = highlights
162 highlights = []
163 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
164 }
165
166 func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
167 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
168 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
169 }
170 }
171
172 // MARK: - Narrowing
173
174
175 func narrow(_ id: String) {
176 let caret = textView.selectedRange().location
177 do {
178 switch id {
179 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
180 // `org-toggle-narrow-to-subtree`.
181 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
182 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
183 default: narrowed = nil
184 }
185 } catch let failure as Narrowing.Failure {
186 onMessage?(failure.message)
187 return
188 } catch {
189 return
190 }
191 updateHiddenAndLayout()
192 orgTextView?.redrawLineNumbers()
193 textView.needsDisplay = true
194 if let narrowed {
195 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
196 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
197 } else {
198 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
199 }
200 }
201
202 /// What narrowing hides: the text before the region, and the lines after it.
203 private var narrowHidden: [Range<Int>] {
204 guard let narrowed else { return [] }
205 let length = utf16Length
206 var ranges: [Range<Int>] = []
207 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
208 let ns = textView.string as NSString
209 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
210 if tail < length { ranges.append(tail..<length) }
211 return ranges
212 }
213}
214#endif
Sources/OrgEditorAppKit/OrgEditor+Images.swift added +74
@@ -0,0 +1,74 @@
1#if os(macOS)
2import AppKit
3import OrgCore
4
5extension OrgEditor {
6 // MARK: - Inline images
7
8 private static let imageCache = NSCache<NSString, NSImage>()
9
10 func toggleImages() {
11 showsImages.toggle()
12 refreshImages()
13 if showsImages {
14 let ns = textView.string as NSString
15 var count = 0
16 var offset = 0
17 while offset < ns.length {
18 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
19 if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
20 offset = NSMaxRange(line)
21 }
22 onMessage?("\(count) images displayed inline")
23 } else {
24 onMessage?("Inline image display turned off")
25 }
26 }
27
28 func refreshImages() {
29 keepingTopLine {
30 restyleOutsideEditing(0..<utf16Length)
31 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
32 }
33 textView.needsDisplay = true
34 }
35
36 private func loadImage(_ path: String) -> NSImage? {
37 let expanded = (path as NSString).expandingTildeInPath
38 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
39 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
40 let key = "\(url.path)|\(modified)" as NSString
41 if let cached = Self.imageCache.object(forKey: key) { return cached }
42 guard let image = NSImage(contentsOf: url) else { return nil }
43 Self.imageCache.setObject(image, forKey: key)
44 return image
45 }
46
47 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
48 /// on the line.
49 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
50 guard showsImages, isOrg else { return }
51 let text = storage.string as NSString
52 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
53 var location = range.lowerBound
54 while location < range.upperBound, location < text.length {
55 let line = text.lineRange(for: NSRange(location: location, length: 0))
56 location = NSMaxRange(line)
57 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
58 var width = image.width.map(CGFloat.init) ?? picture.size.width
59 width = min(width, maxWidth)
60 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
61 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
62 // Invisible, keeping the line's height, so line numbers stay apart.
63 if line.location != revealed.location, content.length > 0 {
64 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
65 }
66 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
67 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
68 // The image sits where the line is; the spacing makes room for the rest of it.
69 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
70 storage.addAttribute(.paragraphStyle, value: style, range: line)
71 }
72 }
73}
74#endif
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift added +155
@@ -0,0 +1,155 @@
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5import OrgPresentation
6
7extension OrgEditor {
8 // MARK: - Shrunk table columns
9
10
11 /// Narrows `columns` of `table` and widens its others.
12 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
13 shrunk.set(columns, in: table, text: textView.string)
14 restyleOutsideEditing(table)
15 invalidateLayout(lines: [table])
16 textView.needsDisplay = true
17 }
18
19 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
20 /// `expand` for `org-table-expand`.
21 func tableColumnWidth(_ id: String) {
22 switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) {
23 case .notInTable: onMessage?("Not in a table")
24 case .set(let columns, let table): setShrunk(columns, in: table)
25 case .ask(let table, let current, let max):
26 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
27 guard let self, let answer else { return }
28 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
29 }
30 }
31 }
32
33 /// Hides each shrunk segment's text and draws its display where the text was.
34 func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
35 guard !shrunk.isEmpty else { return }
36 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
37 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
38 let r = segment.range
39 let shown = segment.display.count
40 let kept = min(shown, r.count)
41 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
42 guard kept > 0 else { continue }
43 let visible = NSRange(location: r.upperBound - kept, length: kept)
44 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
45 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
46 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
47 }
48 }
49
50 /// Moves drawer and block folds through `edit`, checking again only those near it.
51 func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
52 guard !wrapperHidden.isEmpty else { return }
53 var mapped: [Int: Range<Int>] = [:]
54 let entries = Array(wrapperHidden)
55 // One pass maps every start and range.
56 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
57 for i in entries.indices {
58 let newStart = moved[2 * i].lowerBound
59 let newRange = moved[2 * i + 1]
60 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
61 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
62 } else {
63 mapped[newStart] = newRange
64 }
65 }
66 wrapperHidden = mapped
67 view.wrapperFolds = Set(mapped.keys)
68 }
69
70 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
71 /// cycles folded, children, subtree. Returns false elsewhere.
72 @discardableResult
73 public func cycleAtCaret() -> Bool {
74 leaveSparseTree()
75 let caret = textView.selectedRange().location
76 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
77 setFolds(state)
78 // Off a closing line that folding hid, to the opening line, as org does.
79 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
80 return true
81 }
82
83 /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree).
84 func fold(_ id: String) {
85 leaveSparseTree()
86 let caret = textView.selectedRange().location
87 let tree = document.tree
88 let next: FoldState?
89 if id == "org.fold.close" {
90 next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) }
91 .map { Presentation.hideSubtree($0.start, foldState) }
92 } else {
93 next = Presentation.heading(containing: caret, in: tree).map {
94 id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState)
95 }
96 }
97 if let next, next != foldState { setFolds(next) }
98 }
99
100 /// Shift-TAB: overview, contents, show all.
101 public func cycleGlobal() {
102 leaveSparseTree()
103 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
104 globalVisibility = visibility
105 setFolds(state)
106 }
107
108 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
109 public func reveal(_ offset: Int) {
110 let target = max(0, min(offset, utf16Length))
111 if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
112 unfold(around: target)
113 setCaret(target)
114 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
115 }
116
117 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
118 func unfold(around offset: Int) {
119 leaveSparseTree()
120 var state = foldState
121 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
122 state.folds.remove(entry.start)
123 state.bodyFolds.remove(entry.start)
124 }
125 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
126 state.wrapperFolds.remove(start)
127 }
128 guard state != foldState else { return }
129 setFolds(state)
130 }
131
132 /// Applies edits through the text view as one undo step, not merged with typing around it.
133 func applyEdits(_ edits: [TextEdit]) {
134 guard !edits.isEmpty, let storage = textView.textStorage else { return }
135 textView.breakUndoCoalescing()
136 textView.undoManager?.beginUndoGrouping()
137 // By lines, so a fold between two changes stays.
138 let text = storage.string
139 for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
140 let range = NSRange(edit.range)
141 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
142 storage.replaceCharacters(in: range, with: edit.replacement)
143 textView.didChangeText()
144 }
145 textView.undoManager?.endUndoGrouping()
146 textView.breakUndoCoalescing()
147 }
148
149 func setCaret(_ offset: Int) {
150 let clamped = max(0, min(offset, utf16Length))
151 previousSelection = clamped
152 textView.setSelectedRange(NSRange(location: clamped, length: 0))
153 }
154}
155#endif
Sources/OrgEditorAppKit/OrgEditor+Styling.swift added +153
@@ -0,0 +1,153 @@
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
Sources/OrgEditorAppKit/OrgEditor.swift +17 −752
@@ -4,53 +4,13 @@ import OrgCore
44import OrgDocument
55import OrgPresentation
66
7/// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread.
8final class HiddenRanges: @unchecked Sendable {
9 private let lock = NSLock()
10 private var ranges: [Range<Int>] = []
11
12 func set(_ new: [Range<Int>]) {
13 lock.withLock { ranges = new }
14 }
15
16 var all: [Range<Int>] {
17 lock.withLock { ranges }
18 }
19
20 func covers(_ start: Int, _ end: Int) -> Bool {
21 lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } }
22 }
23
24 func containing(_ offset: Int) -> Range<Int>? {
25 lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } }
26 }
27}
28
29/// Folded heading starts, read by the layout-fragment callback.
30final class FoldedHeadings: @unchecked Sendable {
31 private let lock = NSLock()
32 private var starts: Set<Int> = []
33
34 func set(_ new: Set<Int>) {
35 lock.withLock { starts = new }
36 }
37
38 func contains(_ offset: Int) -> Bool {
39 lock.withLock { starts.contains(offset) }
40 }
41
42 var all: Set<Int> {
43 lock.withLock { starts }
44 }
45}
46
477/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
488/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
499@MainActor
5010public final class OrgEditor: NSObject {
5111 public let textView: NSTextView
5212 public private(set) var document: DocumentState
53 public private(set) var view = ViewState()
13 public internal(set) var view = ViewState()
5414 /// Called with the time from a character edit to restyled text.
5515 public var onEditTiming: ((Duration) -> Void)?
5616
@@ -74,7 +34,7 @@ public final class OrgEditor: NSObject {
7434 }
7535 }
7636 private var isLoading = false
77 private var previousSelection = 0
37 var previousSelection = 0
7838 /// The selection shaded block lines last drew.
7939 private var previousSelectionRange = NSRange(location: 0, length: 0)
8040 /// Text before this offset is styled; after it, only base attributes until the background
@@ -82,9 +42,9 @@ public final class OrgEditor: NSObject {
8242 private(set) var styledUpTo = 0
8343 private var stylingScheduled = false
8444 /// One paragraph style object per indent pair, shared by every line that uses it.
85 private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
45 var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
8646
87 private struct IndentKey: Hashable {
47 struct IndentKey: Hashable {
8848 let firstLine: Int
8949 let wrapped: Int
9050 }
@@ -115,7 +75,7 @@ public final class OrgEditor: NSObject {
11575 /// The spell checker's skipped ranges and the text they were found in.
11676 var spellSkipCache: (text: String, ranges: [Range<Int>])?
11777 /// Highlights of the whole file in plain mode, and the revision they were made for.
118 private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
78 var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
11979
12080 public init(
12181 document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
@@ -212,7 +172,7 @@ public final class OrgEditor: NSObject {
212172 // MARK: - Initial styling
213173
214174 /// Styles whole lines from the watermark onward, about `size` units.
215 private func styleNextChunk(_ size: Int) {
175 func styleNextChunk(_ size: Int) {
216176 let text = textView.textStorage!.string as NSString
217177 guard styledUpTo < text.length else { return }
218178 let target = min(text.length, styledUpTo + size)
@@ -247,7 +207,7 @@ public final class OrgEditor: NSObject {
247207 scheduleStyling()
248208 }
249209
250 private var caretLine: NSRange {
210 var caretLine: NSRange {
251211 let text = textView.string as NSString
252212 return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
253213 }
@@ -345,7 +305,7 @@ public final class OrgEditor: NSObject {
345305 var orgTextView: OrgTextView? { textView as? OrgTextView }
346306
347307 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
348 private var revealedLine: NSRange?
308 var revealedLine: NSRange?
349309 var dispatcher: KeyDispatcher
350310 /// Evil-style editing, for modal keymaps such as Doom's.
351311 public var modal = false {
@@ -578,600 +538,47 @@ public final class OrgEditor: NSObject {
578538
579539 // MARK: - Folding
580540
581 public var foldState: FoldState {
582 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
583 }
584
585 private var globalVisibility: GlobalVisibility?
586
587 public func setFolds(_ state: FoldState) {
588 setFolds(state, wrappers: nil)
589 }
590
591 /// `wrappers`, when given, holds every folded drawer and block.
592 private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
593 sparseHidden = nil
594 view.folds = state.folds
595 view.bodyFolds = state.bodyFolds
596 view = view.pruned(to: document.tree, wrappers: false)
597 // Found one by one, or all at once when there are many.
598 let found = wrappers ?? (state.wrapperFolds.count > 32
599 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
600 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
601 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
602 view.wrapperFolds = Set(wrapperHidden.keys)
603 updateHiddenAndLayout()
604 orgTextView?.redrawLineNumbers()
605 textView.needsDisplay = true
606 let caret = textView.selectedRange().location
607 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
608 }
609
541 var globalVisibility: GlobalVisibility?
610542 /// What each folded drawer and block hides, by opening-line start; kept in step with
611543 /// `view.wrapperFolds` and mapped through edits.
612 private var wrapperHidden: [Int: Range<Int>] = [:]
613
614 private func updateHidden() {
615 if let sparseHidden {
616 let ns = textView.string as NSString
617 // Headings whose next line is hidden show the fold ellipsis.
618 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
619 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
620 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
621 }
622 folded.set(Set(headings).union(view.wrapperFolds))
623 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
624 return
625 }
626 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
627 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
628 }
629
630 /// `updateHidden`, laying out again only the text that changed between hidden and shown
631 /// and the headings whose fold mark changed. Laying out the whole file again makes TextKit
632 /// estimate the height of everything above the window afresh, which moves the text under it.
633 private func updateHiddenAndLayout() {
634 let oldHidden = hidden.all
635 let oldFolded = folded.all
636 updateHidden()
637 invalidateLayout(from: oldHidden, to: hidden.all)
638 invalidateLayout(lines: oldFolded.symmetricDifference(folded.all).map { $0..<$0 })
639 }
640
641 /// Lays out again the ranges in `old` and not in `new`, and the other way round.
642 private func invalidateLayout(from old: [Range<Int>], to new: [Range<Int>]) {
643 invalidateLayout(lines: Array(Set(old).symmetricDifference(new)))
644 }
645
646 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
647 /// heading or opening line of a fold, whose fragment draws the fold mark.
648 private func invalidateLayout(lines ranges: [Range<Int>]) {
649 guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return }
650 let text = textView.string as NSString
651 for range in ranges {
652 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
653 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
654 guard let start = content.location(content.documentRange.location, offsetBy: lower),
655 let end = content.location(start, offsetBy: upper - lower),
656 let textRange = NSTextRange(location: start, end: end) else { continue }
657 textLayoutManager.invalidateLayout(for: textRange)
658 }
659 }
660
661 /// Runs `change`, which lays the whole file out again, and brings the line that was at the
662 /// top of the window back there. TextKit estimates the height of text it hasn't laid out,
663 /// so the same scroll position lands on different text after a fresh layout.
664 func keepingTopLine(_ change: () -> Void) {
665 guard let scroll = textView.enclosingScrollView, let content = textLayoutManager.textContentManager else { return change() }
666 let visible = scroll.documentVisibleRect
667 let top = visible.minY - textView.textContainerOrigin.y
668 let start = content.documentRange.location
669 let anchor = textLayoutManager.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top))).map {
670 (offset: content.offset(from: start, to: $0.rangeInElement.location), within: top - $0.layoutFragmentFrame.minY)
671 }
672 change()
673 guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset),
674 let above = NSTextRange(location: start, end: location) else { return }
675 // Styled now, not in the background passes, which would lay the text out again.
676 while styledUpTo < anchor.offset { styleNextChunk(Self.styleChunk) }
677 textLayoutManager.ensureLayout(for: above)
678 guard let fragment = textLayoutManager.textLayoutFragment(for: location) else { return }
679 let frame = fragment.layoutFragmentFrame
680 let y = frame.minY + textView.textContainerOrigin.y + max(0, min(anchor.within, frame.height))
681 textLayoutManager.ensureLayout(for: CGRect(x: 0, y: frame.minY, width: frame.width, height: 2 * visible.height))
682 // The view grows to the laid-out height on its next layout pass; the scroll needs it now.
683 let needed = textLayoutManager.usageBoundsForTextContainer.maxY + textView.textContainerOrigin.y + textView.textContainerInset.height
684 if textView.frame.height < needed { textView.setFrameSize(NSSize(width: textView.frame.width, height: needed)) }
685 textView.scroll(NSPoint(x: visible.minX, y: y))
686 scroll.reflectScrolledClipView(scroll.contentView)
687 }
544 var wrapperHidden: [Int: Range<Int>] = [:]
688545
689546 // MARK: - Sparse trees
690547
691548 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
692549 /// fold change. Mapped through edits.
693 private var sparseHidden: [Range<Int>]?
550 var sparseHidden: [Range<Int>]?
694551 /// Sparse tree matches, highlighted until the next edit or C-c C-c.
695 private var highlights: [Range<Int>] = []
696
697 private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
698 let text = textView.string
699 var state = foldState
700 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
701 state.wrapperFolds.remove(start)
702 }
703 sparseHidden = nil
704 setFolds(state)
705 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
706 self.highlights = highlights
707 keepingTopLine {
708 updateHiddenAndLayout()
709 restyleOutsideEditing(0..<utf16Length)
710 }
711 orgTextView?.redrawLineNumbers()
712 textView.needsDisplay = true
713 let caret = textView.selectedRange().location
714 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
715 }
716
717 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
718 /// open, the others folded.
719 private func leaveSparseTree() {
720 guard let sparse = sparseHidden else { return }
721 sparseHidden = nil
722 let outline = Presentation.outline(document.tree)
723 let ns = textView.string as NSString
724 var open: Set<Int> = []
725 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
726 var parent = entry.parent
727 while let p = parent {
728 open.insert(outline[p].start)
729 parent = outline[p].parent
730 }
731 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
732 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
733 }
734 var state = foldState
735 state.folds = Set(outline.map(\.start)).subtracting(open)
736 state.bodyFolds = []
737 setFolds(state)
738 }
739
740 private func clearHighlights() {
741 guard !highlights.isEmpty else { return }
742 let old = highlights
743 highlights = []
744 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
745 }
746
747 private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
748 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
749 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
750 }
751 }
552 var highlights: [Range<Int>] = []
752553
753554 // MARK: - STARTUP display
754555
755556 /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
756 private var indented = true
557 var indented = true
757558 /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
758 private var hideStars = false
559 var hideStars = false
759560
760561 // MARK: - Inline images
761562
762563 /// `org-toggle-inline-images`: lines that are only an image link show the image.
763 public private(set) var showsImages = false
564 public internal(set) var showsImages = false
764565 /// The file's folder, for relative image paths.
765566 public var baseDirectory: URL? {
766567 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
767568 }
768 private static let imageCache = NSCache<NSString, NSImage>()
769
770 private func toggleImages() {
771 showsImages.toggle()
772 refreshImages()
773 if showsImages {
774 let ns = textView.string as NSString
775 var count = 0
776 var offset = 0
777 while offset < ns.length {
778 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
779 if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
780 offset = NSMaxRange(line)
781 }
782 onMessage?("\(count) images displayed inline")
783 } else {
784 onMessage?("Inline image display turned off")
785 }
786 }
787
788 private func refreshImages() {
789 keepingTopLine {
790 restyleOutsideEditing(0..<utf16Length)
791 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
792 }
793 textView.needsDisplay = true
794 }
795
796 private func loadImage(_ path: String) -> NSImage? {
797 let expanded = (path as NSString).expandingTildeInPath
798 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
799 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
800 let key = "\(url.path)|\(modified)" as NSString
801 if let cached = Self.imageCache.object(forKey: key) { return cached }
802 guard let image = NSImage(contentsOf: url) else { return nil }
803 Self.imageCache.setObject(image, forKey: key)
804 return image
805 }
806
807 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
808 /// on the line.
809 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
810 guard showsImages, isOrg else { return }
811 let text = storage.string as NSString
812 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
813 var location = range.lowerBound
814 while location < range.upperBound, location < text.length {
815 let line = text.lineRange(for: NSRange(location: location, length: 0))
816 location = NSMaxRange(line)
817 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
818 var width = image.width.map(CGFloat.init) ?? picture.size.width
819 width = min(width, maxWidth)
820 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
821 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
822 // Invisible, keeping the line's height, so line numbers stay apart.
823 if line.location != revealed.location, content.length > 0 {
824 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
825 }
826 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
827 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
828 // The image sits where the line is; the spacing makes room for the rest of it.
829 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
830 storage.addAttribute(.paragraphStyle, value: style, range: line)
831 }
832 }
833569
834570 // MARK: - Narrowing
835571
836572 /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
837573 /// rest is hidden until `widen`. Mapped through edits.
838 public private(set) var narrowed: Range<Int>?
839
840 private func narrow(_ id: String) {
841 let caret = textView.selectedRange().location
842 do {
843 switch id {
844 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
845 // `org-toggle-narrow-to-subtree`.
846 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
847 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
848 default: narrowed = nil
849 }
850 } catch let failure as Narrowing.Failure {
851 onMessage?(failure.message)
852 return
853 } catch {
854 return
855 }
856 updateHiddenAndLayout()
857 orgTextView?.redrawLineNumbers()
858 textView.needsDisplay = true
859 if let narrowed {
860 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
861 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
862 } else {
863 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
864 }
865 }
866
867 /// What narrowing hides: the text before the region, and the lines after it.
868 private var narrowHidden: [Range<Int>] {
869 guard let narrowed else { return [] }
870 let length = utf16Length
871 var ranges: [Range<Int>] = []
872 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
873 let ns = textView.string as NSString
874 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
875 if tail < length { ranges.append(tail..<length) }
876 return ranges
877 }
574 public internal(set) var narrowed: Range<Int>?
878575
879576 // MARK: - Shrunk table columns
880577
881578 /// Narrowed table columns (`org-table-shrink`).
882 private var shrunk = ShrunkColumns()
579 var shrunk = ShrunkColumns()
883580 private var commandEditing = false
884581
885 /// Narrows `columns` of `table` and widens its others.
886 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
887 shrunk.set(columns, in: table, text: textView.string)
888 restyleOutsideEditing(table)
889 invalidateLayout(lines: [table])
890 textView.needsDisplay = true
891 }
892
893 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
894 /// `expand` for `org-table-expand`.
895 private func tableColumnWidth(_ id: String) {
896 switch shrunk.change(for: id, at: textView.selectedRange().location, in: textView.string) {
897 case .notInTable: onMessage?("Not in a table")
898 case .set(let columns, let table): setShrunk(columns, in: table)
899 case .ask(let table, let current, let max):
900 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
901 guard let self, let answer else { return }
902 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
903 }
904 }
905 }
906
907 /// Hides each shrunk segment's text and draws its display where the text was.
908 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
909 guard !shrunk.isEmpty else { return }
910 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
911 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
912 let r = segment.range
913 let shown = segment.display.count
914 let kept = min(shown, r.count)
915 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
916 guard kept > 0 else { continue }
917 let visible = NSRange(location: r.upperBound - kept, length: kept)
918 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
919 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
920 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
921 }
922 }
923
924 /// Moves drawer and block folds through `edit`, checking again only those near it.
925 private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
926 guard !wrapperHidden.isEmpty else { return }
927 var mapped: [Int: Range<Int>] = [:]
928 let entries = Array(wrapperHidden)
929 // One pass maps every start and range.
930 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
931 for i in entries.indices {
932 let newStart = moved[2 * i].lowerBound
933 let newRange = moved[2 * i + 1]
934 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
935 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
936 } else {
937 mapped[newStart] = newRange
938 }
939 }
940 wrapperHidden = mapped
941 view.wrapperFolds = Set(mapped.keys)
942 }
943
944 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
945 /// cycles folded, children, subtree. Returns false elsewhere.
946 @discardableResult
947 public func cycleAtCaret() -> Bool {
948 leaveSparseTree()
949 let caret = textView.selectedRange().location
950 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
951 setFolds(state)
952 // Off a closing line that folding hid, to the opening line, as org does.
953 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
954 return true
955 }
956
957 /// Doom's `za`, `zo` (on a heading line) and `zc` (anywhere in a subtree).
958 func fold(_ id: String) {
959 leaveSparseTree()
960 let caret = textView.selectedRange().location
961 let tree = document.tree
962 let next: FoldState?
963 if id == "org.fold.close" {
964 next = Presentation.outline(tree).last { $0.start <= caret && (caret < $0.end || $0.end == utf16Length) }
965 .map { Presentation.hideSubtree($0.start, foldState) }
966 } else {
967 next = Presentation.heading(containing: caret, in: tree).map {
968 id == "org.fold.open" ? Presentation.openFold($0, in: tree, foldState) : Presentation.toggleFold($0, in: tree, foldState)
969 }
970 }
971 if let next, next != foldState { setFolds(next) }
972 }
973
974 /// Shift-TAB: overview, contents, show all.
975 public func cycleGlobal() {
976 leaveSparseTree()
977 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
978 globalVisibility = visibility
979 setFolds(state)
980 }
981
982 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
983 public func reveal(_ offset: Int) {
984 let target = max(0, min(offset, utf16Length))
985 if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
986 unfold(around: target)
987 setCaret(target)
988 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
989 }
990
991 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
992 func unfold(around offset: Int) {
993 leaveSparseTree()
994 var state = foldState
995 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
996 state.folds.remove(entry.start)
997 state.bodyFolds.remove(entry.start)
998 }
999 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
1000 state.wrapperFolds.remove(start)
1001 }
1002 guard state != foldState else { return }
1003 setFolds(state)
1004 }
1005
1006 /// Applies edits through the text view as one undo step, not merged with typing around it.
1007 func applyEdits(_ edits: [TextEdit]) {
1008 guard !edits.isEmpty, let storage = textView.textStorage else { return }
1009 textView.breakUndoCoalescing()
1010 textView.undoManager?.beginUndoGrouping()
1011 // By lines, so a fold between two changes stays.
1012 let text = storage.string
1013 for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
1014 let range = NSRange(edit.range)
1015 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
1016 storage.replaceCharacters(in: range, with: edit.replacement)
1017 textView.didChangeText()
1018 }
1019 textView.undoManager?.endUndoGrouping()
1020 textView.breakUndoCoalescing()
1021 }
1022
1023 func setCaret(_ offset: Int) {
1024 let clamped = max(0, min(offset, utf16Length))
1025 previousSelection = clamped
1026 textView.setSelectedRange(NSRange(location: clamped, length: 0))
1027 }
1028
1029 // MARK: - Styling
1030
1031 private func restyleOutsideEditing(_ range: Range<Int>) {
1032 guard let storage = textView.textStorage else { return }
1033 storage.beginEditing()
1034 restyle(range, in: storage)
1035 storage.endEditing()
1036 }
1037
1038 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
1039 /// attribute changes are allowed and characters must not change.
1040 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
1041 guard !range.isEmpty else { return }
1042 let whole = NSRange(range)
1043 storage.setAttributes(theme.base, range: whole)
1044 guard isOrg else {
1045 for run in plainRuns() where run.range.overlaps(range) {
1046 guard let clipped = clip(run.range, to: range) else { continue }
1047 theme.apply(.syntax(run.category), to: storage, range: clipped)
1048 }
1049 return
1050 }
1051 if indented {
1052 for line in Presentation.lineIndents(document.tree, in: range) {
1053 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
1054 }
1055 }
1056 let revealed = caretLine
1057 var scriptExclusions: [Range<Int>] = []
1058 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
1059 guard let clipped = clip(run.range, to: range) else { continue }
1060 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
1061 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
1062 storage.addAttributes(theme.hidden, range: clipped)
1063 } else {
1064 theme.apply(run.role, to: storage, range: clipped)
1065 }
1066 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
1067 }
1068 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
1069 applyShrunk(range, in: storage)
1070 applyHighlights(range, in: storage)
1071 applyImages(range, in: storage, revealed: revealed)
1072 }
1073
1074 /// `org-pretty-entities`: entities drawn as their character over the entity's last
1075 /// character (the rest hidden), sub/superscripts raised without their markers.
1076 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
1077 let runs = Presentation.prettyRuns(
1078 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
1079 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
1080 )
1081 for (lineStart, run) in runs {
1082 switch run {
1083 case .entity(let r, let display):
1084 let start = lineStart + r.lowerBound
1085 let last = lineStart + r.upperBound - 1
1086 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
1087 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
1088 case .script(let markers, let body, let superscript):
1089 for marker in markers {
1090 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
1091 }
1092 let size = theme.font.pointSize
1093 storage.addAttributes([
1094 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
1095 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
1096 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
1097 }
1098 }
1099 }
1100
1101 /// Moving to another line shows its markup and hides the last one's.
1102 private func revealCaretLine() {
1103 guard !showMarkup, isOrg else { return }
1104 let line = caretLine
1105 guard line != revealedLine else { return }
1106 let text = textView.string as NSString
1107 // The old line may have moved with edits since; restyle the line now at its start.
1108 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
1109 revealedLine = line
1110 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
1111 restyleOutsideEditing(range.location..<NSMaxRange(range))
1112 }
1113 }
1114
1115 /// Code highlights for the whole file in plain mode.
1116 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
1117 guard case .plain(let language?) = mode, let highlighter else { return [] }
1118 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
1119 let runs = highlighter.highlights(language: language, code: document.text)
1120 codeRuns = (document.revision, runs)
1121 return runs
1122 }
1123
1124 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
1125 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
1126 if let style = paragraphStyles[key] { return style }
1127 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
1128 paragraphStyles[key] = style
1129 return style
1130 }
1131
1132 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
1133 let clipped = run.clamped(to: range)
1134 return clipped.isEmpty ? nil : NSRange(clipped)
1135 }
1136
1137 /// The region an edit affects in one version of the tree: inside the innermost section
1138 /// holding the edited lines (plus the line after), every element that overlaps them or the
1139 /// line on either side. A changed heading line, or an added or removed heading, widens it
1140 /// to that section's whole own body. Run on the old and the new tree, the union covers
1141 /// elements that grew and elements that shrank.
1142 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
1143 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
1144 let lineRange = lines.location..<(lines.location + lines.length)
1145 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
1146 var container = tree.root
1147 while let child = container.child(containing: lineRange.lowerBound),
1148 child.kind == .section || child.kind == .zerothSection,
1149 lineRange.upperBound <= child.range.upperBound {
1150 container = child
1151 }
1152 var lower = lineRange.lowerBound
1153 var upper = lineRange.upperBound
1154 // Tables and lists carry no styling of their own, so inside them only the rows or
1155 // items around the edit change, however large they are.
1156 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1157 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1158 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1159 let inner = overlapping(node.children(overlapping: around))
1160 return inner.isEmpty ? [node] : inner
1161 }
1162 }
1163 for child in overlapping(container.children(overlapping: around)) {
1164 lower = min(lower, child.range.lowerBound)
1165 upper = max(upper, child.range.upperBound)
1166 }
1167 let heading = container.firstChild(.heading)
1168 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1169 lower = min(lower, container.range.lowerBound)
1170 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1171 }
1172 return lower..<min(upper, text.length)
1173 }
1174
1175582 // MARK: - Editing
1176583
1177584 private var blockCheck: DispatchWorkItem?
@@ -1421,146 +828,4 @@ extension OrgEditor: NSTextLayoutManagerDelegate {
1421828 return NSTextLayoutFragment(textElement: textElement, range: range)
1422829 }
1423830}
1424
1425/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1426/// `org-block` face.
1427final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1428 private var band: CGRect {
1429 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1430 // Not under the empty line TextKit adds after a final newline.
1431 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1432 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1433 }
1434
1435 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1436
1437 override func draw(at point: CGPoint, in context: CGContext) {
1438 context.saveGState()
1439 context.setFillColor(Theme.blockBackground.cgColor)
1440 context.fill(band.offsetBy(dx: point.x, dy: point.y))
1441 // The band covers the view's selection highlight, so the selected text is drawn on it,
1442 // in the color the view uses: the theme's when focused, the system's muted one when not.
1443 if let manager = textLayoutManager {
1444 let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
1445 context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
1446 let single = textLineFragments.count == 1
1447 for selection in manager.textSelections {
1448 for range in selection.textRanges where !range.isEmpty {
1449 guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
1450 manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
1451 var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
1452 // A one-line fragment's selection covers its band, leaving no gap to the next line.
1453 if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
1454 context.fill(rect)
1455 return true
1456 }
1457 }
1458 }
1459 }
1460 context.restoreGState()
1461 super.draw(at: point, in: context)
1462 }
1463}
1464
1465extension NSAttributedString.Key {
1466 /// The character an entity shows as, on the entity's last character.
1467 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1468 /// The image an image link's line shows under it.
1469 static let orgImage = NSAttributedString.Key("OrgImage")
1470}
1471
1472final class InlineImageBox: NSObject, @unchecked Sendable {
1473 let image: NSImage
1474 let size: CGSize
1475 init(image: NSImage, size: CGSize) {
1476 self.image = image
1477 self.size = size
1478 }
1479}
1480
1481/// An image link's line drawn as the image, with the paragraph spacing making room for its
1482/// height.
1483final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
1484 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1485 var found: InlineImageBox?
1486 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1487 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1488 }
1489 return found
1490 }
1491
1492 private var frame: CGRect? {
1493 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
1494 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
1495 }
1496
1497 override var renderingSurfaceBounds: CGRect {
1498 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
1499 }
1500
1501 override func draw(at point: CGPoint, in context: CGContext) {
1502 super.draw(at: point, in: context)
1503 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
1504 NSGraphicsContext.saveGraphicsState()
1505 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1506 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
1507 NSGraphicsContext.restoreGraphicsState()
1508 }
1509}
1510
1511/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1512/// (now invisible) character sits, so it takes one column as in Emacs.
1513final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1514 static func hasEntities(_ string: NSAttributedString) -> Bool {
1515 var found = false
1516 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1517 if value != nil { found = true; stop.pointee = true }
1518 }
1519 return found
1520 }
1521
1522 override func draw(at point: CGPoint, in context: CGContext) {
1523 super.draw(at: point, in: context)
1524 Self.drawEntities(of: self, at: point, in: context)
1525 }
1526
1527 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1528 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1529 NSGraphicsContext.saveGraphicsState()
1530 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1531 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1532 guard let display = value as? String,
1533 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1534 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1535 attributes[.foregroundColor] = NSColor.textColor
1536 attributes[.orgEntityDisplay] = nil
1537 let x = line.locationForCharacter(at: range.location).x
1538 let bounds = line.typographicBounds
1539 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1540 }
1541 NSGraphicsContext.restoreGraphicsState()
1542 }
1543}
1544
1545/// A heading line drawn with an ellipsis after it, like org's folded headings.
1546final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1547 override func draw(at point: CGPoint, in context: CGContext) {
1548 super.draw(at: point, in: context)
1549 EntityFragment.drawEntities(of: self, at: point, in: context)
1550 guard let line = textLineFragments.first else { return }
1551 let bounds = line.typographicBounds
1552 let ellipsis = NSAttributedString(string: " …", attributes: [
1553 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1554 .foregroundColor: NSColor.secondaryLabelColor,
1555 ])
1556 NSGraphicsContext.saveGraphicsState()
1557 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1558 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1559 NSGraphicsContext.restoreGraphicsState()
1560 }
1561
1562 override var renderingSurfaceBounds: CGRect {
1563 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1564 }
1565}
1566831#endif