Sources/OrgEditorAppKit/OrgEditor.swift
502 lines · 22839 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5import OrgPresentation
6
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
43/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
44/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
45@MainActor
46public final class OrgEditor: NSObject {
47 public let textView: NSTextView
48 public private(set) var document: DocumentState
49 public private(set) var view = ViewState()
50 /// Called with the time from a character edit to restyled text.
51 public var onEditTiming: ((Duration) -> Void)?
52
53 let hidden = HiddenRanges()
54 let folded = FoldedHeadings()
55 let theme = Theme()
56 private var isLoading = false
57 private var previousSelection = 0
58 /// Text before this offset is styled; after it, only base attributes until the background
59 /// passes reach it. Always at a line start.
60 private(set) var styledUpTo = 0
61 private var stylingScheduled = false
62 /// One paragraph style object per indent pair, shared by every line that uses it.
63 private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
64
65 private struct IndentKey: Hashable {
66 let firstLine: Int
67 let wrapped: Int
68 }
69
70 /// Styled before the first render: more than a screenful.
71 static let firstStyleChunk = 30_000
72 /// Styled per run-loop turn afterwards.
73 static let styleChunk = 200_000
74
75 public init(document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true) {
76 self.document = document
77 textView = NSTextView(usingTextLayoutManager: true)
78 super.init()
79 textView.frame = frame
80 textView.isRichText = false
81 textView.isEditable = editable
82 textView.allowsUndo = true
83 textView.isAutomaticQuoteSubstitutionEnabled = false
84 textView.isAutomaticDashSubstitutionEnabled = false
85 textView.isAutomaticTextReplacementEnabled = false
86 textView.isAutomaticSpellingCorrectionEnabled = false
87 textView.font = theme.font
88 textView.typingAttributes = theme.base
89 textView.isVerticallyResizable = true
90 textView.autoresizingMask = [.width]
91 textView.textContainer?.widthTracksTextView = true
92 textView.delegate = self
93 textView.textStorage?.delegate = self
94 textLayoutManager.delegate = self
95 textContentStorage.delegate = self
96
97 load(document.text)
98 if let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
99 }
100
101 /// Replaces the storage's text. Setting the attributed string directly is about 100x
102 /// faster than `NSTextView.string` for large files.
103 private func load(_ text: String) {
104 isLoading = true
105 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
106 isLoading = false
107 styledUpTo = 0
108 styleNextChunk(Self.firstStyleChunk)
109 scheduleStyling()
110 }
111
112 // MARK: - Initial styling
113
114 /// Styles whole lines from the watermark onward, about `size` units.
115 private func styleNextChunk(_ size: Int) {
116 let text = textView.textStorage!.string as NSString
117 guard styledUpTo < text.length else { return }
118 let target = min(text.length, styledUpTo + size)
119 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
120 restyleOutsideEditing(styledUpTo..<end)
121 styledUpTo = end
122 }
123
124 private func scheduleStyling() {
125 guard !stylingScheduled, styledUpTo < utf16Length else { return }
126 stylingScheduled = true
127 DispatchQueue.main.async { [weak self] in
128 guard let self else { return }
129 self.stylingScheduled = false
130 self.styleNextChunk(Self.styleChunk)
131 self.scheduleStyling()
132 }
133 }
134
135 /// Styles everything still waiting for a background pass.
136 public func finishStyling() {
137 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
138 }
139
140 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
141 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
142 var utf16Length: Int { (textView.string as NSString).length }
143
144 /// A scroll view holding the text view, ready for a window.
145 public func makeScrollView() -> NSScrollView {
146 let scroll = NSScrollView(frame: textView.frame)
147 scroll.hasVerticalScroller = true
148 scroll.documentView = textView
149 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
150 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
151 return scroll
152 }
153
154 // MARK: - Saving
155
156 /// Saves through `saver`. When a merge changes the buffer, the text view is reloaded and
157 /// folds are mapped through the change.
158 @discardableResult
159 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
160 let before = document.text
161 let outcome = try saver.save(&document, to: url)
162 if document.text != before {
163 let edits = lineEdits(from: before, to: document.text)
164 load(document.text)
165 let mapped = view.mapped(through: edits)
166 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
167 }
168 return outcome
169 }
170
171 // MARK: - Disk
172
173 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
174 /// its headings.
175 public func diskChanged(to bytes: [UInt8]) {
176 let edits: [TextEdit]
177 switch document.diskChanged(to: bytes) {
178 case .reloaded(let changes), .merged(let changes): edits = changes
179 case .unchanged, .conflict: return
180 }
181 let mapped = view.mapped(through: edits)
182 load(document.text)
183 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
184 }
185
186 // MARK: - Folding
187
188 public var foldState: FoldState {
189 FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
190 }
191
192 private var globalVisibility: GlobalVisibility?
193
194 public func setFolds(_ state: FoldState) {
195 view.folds = state.folds
196 view.bodyFolds = state.bodyFolds
197 view = view.pruned(to: document.tree)
198 updateHidden()
199 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
200 textView.needsDisplay = true
201 let caret = textView.selectedRange().location
202 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
203 }
204
205 private func updateHidden() {
206 folded.set(view.folds.union(view.bodyFolds))
207 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
208 }
209
210 /// TAB on a heading: folded, children, subtree. Returns false off a heading.
211 @discardableResult
212 public func cycleAtCaret() -> Bool {
213 guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
214 setFolds(Presentation.cycle(heading, in: document.tree, foldState))
215 return true
216 }
217
218 /// Shift-TAB: overview, contents, show all.
219 public func cycleGlobal() {
220 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
221 globalVisibility = visibility
222 setFolds(state)
223 }
224
225 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
226 public func reveal(_ offset: Int) {
227 let target = max(0, min(offset, utf16Length))
228 var state = foldState
229 for entry in Presentation.outline(document.tree) where entry.start < target && target < entry.end {
230 state.folds.remove(entry.start)
231 state.bodyFolds.remove(entry.start)
232 }
233 setFolds(state)
234 setCaret(target)
235 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
236 }
237
238 private func setCaret(_ offset: Int) {
239 let clamped = max(0, min(offset, utf16Length))
240 previousSelection = clamped
241 textView.setSelectedRange(NSRange(location: clamped, length: 0))
242 }
243
244 // MARK: - Styling
245
246 private func restyleOutsideEditing(_ range: Range<Int>) {
247 guard let storage = textView.textStorage else { return }
248 storage.beginEditing()
249 restyle(range, in: storage)
250 storage.endEditing()
251 }
252
253 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
254 /// attribute changes are allowed and characters must not change.
255 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
256 guard !range.isEmpty else { return }
257 let whole = NSRange(range)
258 storage.setAttributes(theme.base, range: whole)
259 let text = storage.string as NSString
260 for run in Presentation.indents(document.tree, in: range) {
261 guard let clipped = clip(run.range, to: range) else { continue }
262 guard run.firstLine == run.wrapped else {
263 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
264 continue
265 }
266 // Body lines wrap under their own text: past leading blanks, and past a list bullet
267 // and checkbox, as adaptive-wrap does in Emacs.
268 var location = clipped.location
269 while location < NSMaxRange(clipped) {
270 let line = text.lineRange(for: NSRange(location: location, length: 0))
271 let hanging = Self.hangingColumns(text.substring(with: line))
272 let lineRange = NSIntersectionRange(line, clipped)
273 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
274 location = NSMaxRange(line)
275 }
276 }
277 for run in Presentation.styles(document.tree, in: range) {
278 guard let clipped = clip(run.range, to: range) else { continue }
279 theme.apply(run.role, to: storage, range: clipped)
280 }
281 }
282
283 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
284 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
285 if let style = paragraphStyles[key] { return style }
286 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
287 paragraphStyles[key] = style
288 return style
289 }
290
291 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
292 let clipped = run.clamped(to: range)
293 return clipped.isEmpty ? nil : NSRange(clipped)
294 }
295
296 /// The region an edit affects in one version of the tree: inside the innermost section
297 /// holding the edited lines (plus the line after), every element that overlaps them or the
298 /// line on either side. A changed heading line, or an added or removed heading, widens it
299 /// to that section's whole own body. Run on the old and the new tree, the union covers
300 /// elements that grew and elements that shrank.
301 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
302 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
303 let lineRange = lines.location..<(lines.location + lines.length)
304 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
305 var container = tree.root
306 while let child = container.child(containing: lineRange.lowerBound),
307 child.kind == .section || child.kind == .zerothSection,
308 lineRange.upperBound <= child.range.upperBound {
309 container = child
310 }
311 var lower = lineRange.lowerBound
312 var upper = lineRange.upperBound
313 // Tables and lists carry no styling of their own, so inside them only the rows or
314 // items around the edit change, however large they are.
315 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
316 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
317 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
318 let inner = overlapping(node.children(overlapping: around))
319 return inner.isEmpty ? [node] : inner
320 }
321 }
322 for child in overlapping(container.children(overlapping: around)) {
323 lower = min(lower, child.range.lowerBound)
324 upper = max(upper, child.range.upperBound)
325 }
326 let heading = container.firstChild(.heading)
327 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
328 lower = min(lower, container.range.lowerBound)
329 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
330 }
331 return lower..<min(upper, text.length)
332 }
333
334 // MARK: - Editing
335
336 fileprivate func storageEdited(range: NSRange, delta: Int) {
337 guard !isLoading, let storage = textView.textStorage else { return }
338 let clock = ContinuousClock()
339 let start = clock.now
340 let replacement = (storage.string as NSString).substring(with: range)
341 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
342 let oldText = document.text as NSString
343 let newText = storage.string as NSString
344 let newEnd = edit.range.lowerBound + replacement.utf16.count
345 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
346 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
347 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
348 do {
349 try document.apply([edit], baseRevision: document.revision)
350 } catch {
351 assertionFailure("text view and document disagree: \(error)")
352 return
353 }
354 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
355 // edited line when the edit reaches into unstyled text.
356 if styledUpTo >= edit.range.upperBound {
357 styledUpTo += edit.replacement.utf16.count - edit.range.count
358 } else if styledUpTo > edit.range.lowerBound {
359 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
360 }
361 let oldHidden = hidden.all
362 view = view.mapped(through: [edit]).pruned(to: document.tree)
363 folded.set(view.folds)
364 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
365 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
366 let delta = edit.replacement.utf16.count - edit.range.count
367 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
368 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
369 if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
370 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
371 }
372 onEditTiming?(clock.now - start)
373 }
374
375 /// Columns a wrapped continuation of `line` should start past the line's own start.
376 nonisolated static func hangingColumns(_ line: String) -> Int {
377 var columns = 0
378 var rest = Substring(line)
379 while let c = rest.first, c == " " || c == "\t" {
380 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
381 rest = rest.dropFirst()
382 }
383 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
384 var bullet = 0
385 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
386 bullet = 1
387 } else {
388 let digits = rest.prefix { $0.isASCII && $0.isNumber }
389 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
390 bullet = digits.count + 1
391 }
392 }
393 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
394 columns += bullet + 1
395 let afterBullet = rest.dropFirst(bullet + 1)
396 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
397 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
398 columns += 4
399 }
400 return columns
401 }
402
403 /// Whether a heading line touches `start..<end` or starts right after it, where joining
404 /// lines could take it away.
405 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
406 let length = min(end + 1, text.length) - start
407 guard length >= 0 else { return false }
408 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
409 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
410 let stars = line.prefix { $0 == "*" }
411 let after = line.dropFirst(stars.count)
412 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
413 }
414 }
415
416 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
417 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
418 return mapped
419 }
420
421 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
422 /// back jumps to the end of the heading line.
423 fileprivate func selectionChanged() {
424 let selection = textView.selectedRange()
425 defer { previousSelection = selection.location }
426 guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
427 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
428 }
429}
430
431extension OrgEditor: NSTextViewDelegate {
432 public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
433 switch selector {
434 case #selector(NSResponder.insertTab(_:)): return cycleAtCaret()
435 case #selector(NSResponder.insertBacktab(_:)):
436 cycleGlobal()
437 return true
438 default: return false
439 }
440 }
441
442 public func textViewDidChangeSelection(_ notification: Notification) {
443 selectionChanged()
444 }
445}
446
447extension OrgEditor: NSTextStorageDelegate {
448 public nonisolated func textStorage(
449 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
450 ) {
451 guard editedMask.contains(.editedCharacters) else { return }
452 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
453 }
454}
455
456extension OrgEditor: NSTextContentStorageDelegate {
457 /// Folded text isn't enumerated, so it isn't laid out or drawn.
458 public nonisolated func textContentManager(
459 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
460 ) -> Bool {
461 guard let range = textElement.elementRange else { return true }
462 let documentStart = textContentManager.documentRange.location
463 let start = textContentManager.offset(from: documentStart, to: range.location)
464 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
465 return !hidden.covers(start, end)
466 }
467}
468
469extension OrgEditor: NSTextLayoutManagerDelegate {
470 public nonisolated func textLayoutManager(
471 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
472 ) -> NSTextLayoutFragment {
473 let range = textElement.elementRange
474 if let range, let manager = textLayoutManager.textContentManager {
475 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
476 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
477 }
478 return NSTextLayoutFragment(textElement: textElement, range: range)
479 }
480}
481
482/// A heading line drawn with an ellipsis after it, like org's folded headings.
483final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
484 override func draw(at point: CGPoint, in context: CGContext) {
485 super.draw(at: point, in: context)
486 guard let line = textLineFragments.first else { return }
487 let bounds = line.typographicBounds
488 let ellipsis = NSAttributedString(string: " …", attributes: [
489 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
490 .foregroundColor: NSColor.secondaryLabelColor,
491 ])
492 NSGraphicsContext.saveGraphicsState()
493 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
494 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
495 NSGraphicsContext.restoreGraphicsState()
496 }
497
498 override var renderingSurfaceBounds: CGRect {
499 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
500 }
501}
502#endif