Sources/OrgEditorAppKit/OrgEditor.swift
549 lines · 25106 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: - Commands
172
173 /// Called with messages commands report, such as why one couldn't run here.
174 public var onMessage: ((String) -> Void)?
175
176 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
177 /// they form one undo step and reach the document through the same path.
178 @discardableResult
179 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
180 let selected = textView.selectedRange()
181 let context = EditContext(
182 revision: document.revision, text: document.text, tree: document.tree,
183 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers
184 )
185 let step = command.run(in: context)
186 switch step {
187 case .commit(let result):
188 guard textView.isEditable || result.edits.isEmpty else {
189 onMessage?("This file is read-only.")
190 return .failed("read-only")
191 }
192 if !result.edits.isEmpty, let storage = textView.textStorage {
193 // Each command is its own undo step, not merged with typing around it.
194 textView.breakUndoCoalescing()
195 textView.undoManager?.beginUndoGrouping()
196 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
197 let range = NSRange(edit.range)
198 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
199 storage.replaceCharacters(in: range, with: edit.replacement)
200 textView.didChangeText()
201 }
202 textView.undoManager?.endUndoGrouping()
203 textView.breakUndoCoalescing()
204 }
205 if let selection = result.selection?.first {
206 setCaret(selection.lowerBound)
207 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
208 }
209 for case .message(let text) in result.effects { onMessage?(text) }
210 case .failed(let message):
211 onMessage?(message)
212 case .prompt:
213 break
214 }
215 return step
216 }
217
218 // MARK: - Disk
219
220 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
221 /// its headings.
222 public func diskChanged(to bytes: [UInt8]) {
223 let edits: [TextEdit]
224 switch document.diskChanged(to: bytes) {
225 case .reloaded(let changes), .merged(let changes): edits = changes
226 case .unchanged, .conflict: return
227 }
228 let mapped = view.mapped(through: edits)
229 load(document.text)
230 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
231 }
232
233 // MARK: - Folding
234
235 public var foldState: FoldState {
236 FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
237 }
238
239 private var globalVisibility: GlobalVisibility?
240
241 public func setFolds(_ state: FoldState) {
242 view.folds = state.folds
243 view.bodyFolds = state.bodyFolds
244 view = view.pruned(to: document.tree)
245 updateHidden()
246 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
247 textView.needsDisplay = true
248 let caret = textView.selectedRange().location
249 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
250 }
251
252 private func updateHidden() {
253 folded.set(view.folds.union(view.bodyFolds))
254 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
255 }
256
257 /// TAB on a heading: folded, children, subtree. Returns false off a heading.
258 @discardableResult
259 public func cycleAtCaret() -> Bool {
260 guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
261 setFolds(Presentation.cycle(heading, in: document.tree, foldState))
262 return true
263 }
264
265 /// Shift-TAB: overview, contents, show all.
266 public func cycleGlobal() {
267 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
268 globalVisibility = visibility
269 setFolds(state)
270 }
271
272 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
273 public func reveal(_ offset: Int) {
274 let target = max(0, min(offset, utf16Length))
275 var state = foldState
276 for entry in Presentation.outline(document.tree) where entry.start < target && target < entry.end {
277 state.folds.remove(entry.start)
278 state.bodyFolds.remove(entry.start)
279 }
280 setFolds(state)
281 setCaret(target)
282 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
283 }
284
285 private func setCaret(_ offset: Int) {
286 let clamped = max(0, min(offset, utf16Length))
287 previousSelection = clamped
288 textView.setSelectedRange(NSRange(location: clamped, length: 0))
289 }
290
291 // MARK: - Styling
292
293 private func restyleOutsideEditing(_ range: Range<Int>) {
294 guard let storage = textView.textStorage else { return }
295 storage.beginEditing()
296 restyle(range, in: storage)
297 storage.endEditing()
298 }
299
300 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
301 /// attribute changes are allowed and characters must not change.
302 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
303 guard !range.isEmpty else { return }
304 let whole = NSRange(range)
305 storage.setAttributes(theme.base, range: whole)
306 let text = storage.string as NSString
307 for run in Presentation.indents(document.tree, in: range) {
308 guard let clipped = clip(run.range, to: range) else { continue }
309 guard run.firstLine == run.wrapped else {
310 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
311 continue
312 }
313 // Body lines wrap under their own text: past leading blanks, and past a list bullet
314 // and checkbox, as adaptive-wrap does in Emacs.
315 var location = clipped.location
316 while location < NSMaxRange(clipped) {
317 let line = text.lineRange(for: NSRange(location: location, length: 0))
318 let hanging = Self.hangingColumns(text.substring(with: line))
319 let lineRange = NSIntersectionRange(line, clipped)
320 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
321 location = NSMaxRange(line)
322 }
323 }
324 for run in Presentation.styles(document.tree, in: range) {
325 guard let clipped = clip(run.range, to: range) else { continue }
326 theme.apply(run.role, to: storage, range: clipped)
327 }
328 }
329
330 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
331 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
332 if let style = paragraphStyles[key] { return style }
333 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
334 paragraphStyles[key] = style
335 return style
336 }
337
338 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
339 let clipped = run.clamped(to: range)
340 return clipped.isEmpty ? nil : NSRange(clipped)
341 }
342
343 /// The region an edit affects in one version of the tree: inside the innermost section
344 /// holding the edited lines (plus the line after), every element that overlaps them or the
345 /// line on either side. A changed heading line, or an added or removed heading, widens it
346 /// to that section's whole own body. Run on the old and the new tree, the union covers
347 /// elements that grew and elements that shrank.
348 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
349 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
350 let lineRange = lines.location..<(lines.location + lines.length)
351 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
352 var container = tree.root
353 while let child = container.child(containing: lineRange.lowerBound),
354 child.kind == .section || child.kind == .zerothSection,
355 lineRange.upperBound <= child.range.upperBound {
356 container = child
357 }
358 var lower = lineRange.lowerBound
359 var upper = lineRange.upperBound
360 // Tables and lists carry no styling of their own, so inside them only the rows or
361 // items around the edit change, however large they are.
362 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
363 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
364 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
365 let inner = overlapping(node.children(overlapping: around))
366 return inner.isEmpty ? [node] : inner
367 }
368 }
369 for child in overlapping(container.children(overlapping: around)) {
370 lower = min(lower, child.range.lowerBound)
371 upper = max(upper, child.range.upperBound)
372 }
373 let heading = container.firstChild(.heading)
374 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
375 lower = min(lower, container.range.lowerBound)
376 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
377 }
378 return lower..<min(upper, text.length)
379 }
380
381 // MARK: - Editing
382
383 fileprivate func storageEdited(range: NSRange, delta: Int) {
384 guard !isLoading, let storage = textView.textStorage else { return }
385 let clock = ContinuousClock()
386 let start = clock.now
387 let replacement = (storage.string as NSString).substring(with: range)
388 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
389 let oldText = document.text as NSString
390 let newText = storage.string as NSString
391 let newEnd = edit.range.lowerBound + replacement.utf16.count
392 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
393 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
394 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
395 do {
396 try document.apply([edit], baseRevision: document.revision)
397 } catch {
398 assertionFailure("text view and document disagree: \(error)")
399 return
400 }
401 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
402 // edited line when the edit reaches into unstyled text.
403 if styledUpTo >= edit.range.upperBound {
404 styledUpTo += edit.replacement.utf16.count - edit.range.count
405 } else if styledUpTo > edit.range.lowerBound {
406 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
407 }
408 let oldHidden = hidden.all
409 view = view.mapped(through: [edit]).pruned(to: document.tree)
410 folded.set(view.folds)
411 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
412 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
413 let delta = edit.replacement.utf16.count - edit.range.count
414 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
415 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
416 if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
417 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
418 }
419 onEditTiming?(clock.now - start)
420 }
421
422 /// Columns a wrapped continuation of `line` should start past the line's own start.
423 nonisolated static func hangingColumns(_ line: String) -> Int {
424 var columns = 0
425 var rest = Substring(line)
426 while let c = rest.first, c == " " || c == "\t" {
427 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
428 rest = rest.dropFirst()
429 }
430 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
431 var bullet = 0
432 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
433 bullet = 1
434 } else {
435 let digits = rest.prefix { $0.isASCII && $0.isNumber }
436 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
437 bullet = digits.count + 1
438 }
439 }
440 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
441 columns += bullet + 1
442 let afterBullet = rest.dropFirst(bullet + 1)
443 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
444 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
445 columns += 4
446 }
447 return columns
448 }
449
450 /// Whether a heading line touches `start..<end` or starts right after it, where joining
451 /// lines could take it away.
452 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
453 let length = min(end + 1, text.length) - start
454 guard length >= 0 else { return false }
455 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
456 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
457 let stars = line.prefix { $0 == "*" }
458 let after = line.dropFirst(stars.count)
459 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
460 }
461 }
462
463 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
464 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
465 return mapped
466 }
467
468 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
469 /// back jumps to the end of the heading line.
470 fileprivate func selectionChanged() {
471 let selection = textView.selectedRange()
472 defer { previousSelection = selection.location }
473 guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
474 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
475 }
476}
477
478extension OrgEditor: NSTextViewDelegate {
479 public func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
480 switch selector {
481 case #selector(NSResponder.insertTab(_:)): return cycleAtCaret()
482 case #selector(NSResponder.insertBacktab(_:)):
483 cycleGlobal()
484 return true
485 default: return false
486 }
487 }
488
489 public func textViewDidChangeSelection(_ notification: Notification) {
490 selectionChanged()
491 }
492}
493
494extension OrgEditor: NSTextStorageDelegate {
495 public nonisolated func textStorage(
496 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
497 ) {
498 guard editedMask.contains(.editedCharacters) else { return }
499 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
500 }
501}
502
503extension OrgEditor: NSTextContentStorageDelegate {
504 /// Folded text isn't enumerated, so it isn't laid out or drawn.
505 public nonisolated func textContentManager(
506 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
507 ) -> Bool {
508 guard let range = textElement.elementRange else { return true }
509 let documentStart = textContentManager.documentRange.location
510 let start = textContentManager.offset(from: documentStart, to: range.location)
511 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
512 return !hidden.covers(start, end)
513 }
514}
515
516extension OrgEditor: NSTextLayoutManagerDelegate {
517 public nonisolated func textLayoutManager(
518 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
519 ) -> NSTextLayoutFragment {
520 let range = textElement.elementRange
521 if let range, let manager = textLayoutManager.textContentManager {
522 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
523 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
524 }
525 return NSTextLayoutFragment(textElement: textElement, range: range)
526 }
527}
528
529/// A heading line drawn with an ellipsis after it, like org's folded headings.
530final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
531 override func draw(at point: CGPoint, in context: CGContext) {
532 super.draw(at: point, in: context)
533 guard let line = textLineFragments.first else { return }
534 let bounds = line.typographicBounds
535 let ellipsis = NSAttributedString(string: " …", attributes: [
536 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
537 .foregroundColor: NSColor.secondaryLabelColor,
538 ])
539 NSGraphicsContext.saveGraphicsState()
540 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
541 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
542 NSGraphicsContext.restoreGraphicsState()
543 }
544
545 override var renderingSurfaceBounds: CGRect {
546 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
547 }
548}
549#endif