Sources/OrgEditorAppKit/OrgEditor.swift
680 lines · 30884 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 let orgTextView = OrgTextView(usingTextLayoutManager: true)
78 textView = orgTextView
79 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
80 super.init()
81 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
82 orgTextView.onMouseDown = { [weak self] in self?.markActive = false }
83 textView.usesFindBar = true
84 textView.frame = frame
85 textView.isRichText = false
86 textView.isEditable = editable
87 textView.allowsUndo = true
88 textView.isAutomaticQuoteSubstitutionEnabled = false
89 textView.isAutomaticDashSubstitutionEnabled = false
90 textView.isAutomaticTextReplacementEnabled = false
91 textView.isAutomaticSpellingCorrectionEnabled = false
92 textView.font = theme.font
93 textView.typingAttributes = theme.base
94 textView.isVerticallyResizable = true
95 textView.autoresizingMask = [.width]
96 textView.textContainer?.widthTracksTextView = true
97 textView.delegate = self
98 textView.textStorage?.delegate = self
99 textLayoutManager.delegate = self
100 textContentStorage.delegate = self
101
102 load(document.text)
103 if let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
104 }
105
106 /// Replaces the storage's text. Setting the attributed string directly is about 100x
107 /// faster than `NSTextView.string` for large files.
108 private func load(_ text: String) {
109 isLoading = true
110 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
111 isLoading = false
112 styledUpTo = 0
113 styleNextChunk(Self.firstStyleChunk)
114 scheduleStyling()
115 }
116
117 // MARK: - Initial styling
118
119 /// Styles whole lines from the watermark onward, about `size` units.
120 private func styleNextChunk(_ size: Int) {
121 let text = textView.textStorage!.string as NSString
122 guard styledUpTo < text.length else { return }
123 let target = min(text.length, styledUpTo + size)
124 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
125 restyleOutsideEditing(styledUpTo..<end)
126 styledUpTo = end
127 }
128
129 private func scheduleStyling() {
130 guard !stylingScheduled, styledUpTo < utf16Length else { return }
131 stylingScheduled = true
132 DispatchQueue.main.async { [weak self] in
133 guard let self else { return }
134 self.stylingScheduled = false
135 self.styleNextChunk(Self.styleChunk)
136 self.scheduleStyling()
137 }
138 }
139
140 /// Styles everything still waiting for a background pass.
141 public func finishStyling() {
142 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
143 }
144
145 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
146 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
147 var utf16Length: Int { (textView.string as NSString).length }
148
149 /// A scroll view holding the text view, ready for a window.
150 public func makeScrollView() -> NSScrollView {
151 let scroll = NSScrollView(frame: textView.frame)
152 scroll.hasVerticalScroller = true
153 scroll.documentView = textView
154 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
155 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
156 return scroll
157 }
158
159 // MARK: - Saving
160
161 /// Saves through `saver`. A merge that changes the buffer reloads the text view.
162 @discardableResult
163 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
164 try update { try saver.save(&$0, to: url) }
165 }
166
167 /// Called after every change to the document, typed or not.
168 public var onChange: (() -> Void)?
169
170 // MARK: - Commands
171
172 /// Called with messages commands report, such as why one couldn't run here.
173 public var onMessage: ((String) -> Void)?
174 /// Called with the pending prefix and what can follow it, and with nil when it ends.
175 public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
176 /// Called with `app.*` commands, which the app carries out.
177 public var onAppCommand: ((String) -> Void)?
178 /// Called when a command asks a question; reply with the answer, or nil to cancel.
179 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
180
181 public var keymap: Keymap {
182 get { dispatcher.keymap }
183 set {
184 dispatcher.keymap = newValue
185 dispatcher.reset()
186 }
187 }
188
189 public var optionAsMeta: OptionAsMeta = [.left]
190 /// Org options commands follow.
191 public var options: EditingOptions = .org
192 private var dispatcher: KeyDispatcher
193 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
194 private(set) var markActive = false
195
196 private func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
197 let selected = textView.selectedRange()
198 return EditContext(
199 revision: document.revision, text: document.text, tree: document.tree,
200 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
201 hidden: hidden.all, options: options
202 )
203 }
204
205 /// Offers a key press to the keymap. False lets the text system have it.
206 func handleKey(_ event: NSEvent) -> Bool {
207 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return false }
208 switch dispatcher.feed(chord) {
209 case .pending(let keys):
210 let next = keymap.continuations(of: keys).map { item in
211 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
212 }
213 onKeysPending?(KeySequence.format(keys), next)
214 return true
215 case .cancelled:
216 onKeysPending?(nil, [])
217 onMessage?("Quit")
218 return true
219 case .undefined(let keys):
220 onKeysPending?(nil, [])
221 onMessage?("\(KeySequence.format(keys)) is undefined")
222 return true
223 case .unbound:
224 return false
225 case .complete(let keys, let candidates):
226 if keys.count > 1 { onKeysPending?(nil, []) }
227 let context = context()
228 let runnable = candidates.first { binding in
229 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
230 }
231 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
232 run(binding.command)
233 return true
234 }
235 return false
236 }
237 }
238
239 private func applies(_ id: String, in context: EditContext) -> Bool {
240 switch EditorCommands.command(id)?.action {
241 case .text(let command): command.applies(in: context)
242 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
243 case .edit, .mark, .app: true
244 case nil: true
245 }
246 }
247
248 /// Runs a command by id, as a key, a menu item or the palette would.
249 public func run(_ id: String) {
250 guard let command = EditorCommands.command(id) else {
251 onMessage?("Unknown command \(id)")
252 return
253 }
254 var keepMark = false
255 switch command.action {
256 case .text(let text):
257 perform(text)
258 case .view:
259 if id == "org.cycle" { cycleAtCaret() } else { cycleGlobal() }
260 case .edit(let selector, let extending):
261 if markActive, let extending {
262 keepMark = true
263 textView.doCommand(by: NSSelectorFromString(extending))
264 } else if selector == "performTextFinderAction:" {
265 let item = NSMenuItem()
266 item.tag = NSTextFinder.Action.showFindInterface.rawValue
267 textView.performTextFinderAction(item)
268 } else {
269 textView.doCommand(by: NSSelectorFromString(selector))
270 }
271 case .mark:
272 if id == "edit.set-mark" {
273 let caret = textView.selectedRange().location
274 textView.setSelectedRange(NSRange(location: caret, length: 0))
275 keepMark = true
276 onMessage?("Mark set")
277 } else {
278 let selected = textView.selectedRange()
279 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
280 onMessage?("Quit")
281 }
282 case .app:
283 onAppCommand?(id)
284 }
285 markActive = keepMark
286 }
287
288 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
289 /// they form one undo step and reach the document through the same path.
290 @discardableResult
291 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
292 let context = context(now: now, answers: answers)
293 let step = command.run(in: context)
294 switch step {
295 case .commit(let result):
296 guard textView.isEditable || result.edits.isEmpty else {
297 onMessage?("This file is read-only.")
298 return .failed("read-only")
299 }
300 if !result.edits.isEmpty, let storage = textView.textStorage {
301 // Each command is its own undo step, not merged with typing around it.
302 textView.breakUndoCoalescing()
303 textView.undoManager?.beginUndoGrouping()
304 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
305 let range = NSRange(edit.range)
306 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
307 storage.replaceCharacters(in: range, with: edit.replacement)
308 textView.didChangeText()
309 }
310 textView.undoManager?.endUndoGrouping()
311 textView.breakUndoCoalescing()
312 }
313 if let selection = result.selection?.first {
314 setCaret(selection.lowerBound)
315 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
316 }
317 for case .message(let text) in result.effects { onMessage?(text) }
318 case .failed(let message):
319 onMessage?(message)
320 case .prompt(let prompt):
321 onPrompt?(prompt) { [weak self] answer in
322 guard let self else { return }
323 guard let answer else {
324 self.onMessage?("Quit")
325 return
326 }
327 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
328 }
329 }
330 return step
331 }
332
333 // MARK: - Disk
334
335 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
336 /// its headings.
337 @discardableResult
338 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
339 update { $0.diskChanged(to: bytes) }
340 }
341
342 // MARK: - Folding
343
344 public var foldState: FoldState {
345 FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
346 }
347
348 private var globalVisibility: GlobalVisibility?
349
350 public func setFolds(_ state: FoldState) {
351 view.folds = state.folds
352 view.bodyFolds = state.bodyFolds
353 view = view.pruned(to: document.tree)
354 updateHidden()
355 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
356 textView.needsDisplay = true
357 let caret = textView.selectedRange().location
358 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
359 }
360
361 private func updateHidden() {
362 folded.set(view.folds.union(view.bodyFolds))
363 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
364 }
365
366 /// TAB on a heading: folded, children, subtree. Returns false off a heading.
367 @discardableResult
368 public func cycleAtCaret() -> Bool {
369 guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
370 setFolds(Presentation.cycle(heading, in: document.tree, foldState))
371 return true
372 }
373
374 /// Shift-TAB: overview, contents, show all.
375 public func cycleGlobal() {
376 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
377 globalVisibility = visibility
378 setFolds(state)
379 }
380
381 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
382 public func reveal(_ offset: Int) {
383 let target = max(0, min(offset, utf16Length))
384 var state = foldState
385 for entry in Presentation.outline(document.tree) where entry.start < target && target < entry.end {
386 state.folds.remove(entry.start)
387 state.bodyFolds.remove(entry.start)
388 }
389 setFolds(state)
390 setCaret(target)
391 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
392 }
393
394 private func setCaret(_ offset: Int) {
395 let clamped = max(0, min(offset, utf16Length))
396 previousSelection = clamped
397 textView.setSelectedRange(NSRange(location: clamped, length: 0))
398 }
399
400 // MARK: - Styling
401
402 private func restyleOutsideEditing(_ range: Range<Int>) {
403 guard let storage = textView.textStorage else { return }
404 storage.beginEditing()
405 restyle(range, in: storage)
406 storage.endEditing()
407 }
408
409 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
410 /// attribute changes are allowed and characters must not change.
411 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
412 guard !range.isEmpty else { return }
413 let whole = NSRange(range)
414 storage.setAttributes(theme.base, range: whole)
415 let text = storage.string as NSString
416 for run in Presentation.indents(document.tree, in: range) {
417 guard let clipped = clip(run.range, to: range) else { continue }
418 guard run.firstLine == run.wrapped else {
419 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
420 continue
421 }
422 // Body lines wrap under their own text: past leading blanks, and past a list bullet
423 // and checkbox, as adaptive-wrap does in Emacs.
424 var location = clipped.location
425 while location < NSMaxRange(clipped) {
426 let line = text.lineRange(for: NSRange(location: location, length: 0))
427 let hanging = Self.hangingColumns(text.substring(with: line))
428 let lineRange = NSIntersectionRange(line, clipped)
429 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
430 location = NSMaxRange(line)
431 }
432 }
433 for run in Presentation.styles(document.tree, in: range) {
434 guard let clipped = clip(run.range, to: range) else { continue }
435 theme.apply(run.role, to: storage, range: clipped)
436 }
437 }
438
439 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
440 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
441 if let style = paragraphStyles[key] { return style }
442 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
443 paragraphStyles[key] = style
444 return style
445 }
446
447 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
448 let clipped = run.clamped(to: range)
449 return clipped.isEmpty ? nil : NSRange(clipped)
450 }
451
452 /// The region an edit affects in one version of the tree: inside the innermost section
453 /// holding the edited lines (plus the line after), every element that overlaps them or the
454 /// line on either side. A changed heading line, or an added or removed heading, widens it
455 /// to that section's whole own body. Run on the old and the new tree, the union covers
456 /// elements that grew and elements that shrank.
457 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
458 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
459 let lineRange = lines.location..<(lines.location + lines.length)
460 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
461 var container = tree.root
462 while let child = container.child(containing: lineRange.lowerBound),
463 child.kind == .section || child.kind == .zerothSection,
464 lineRange.upperBound <= child.range.upperBound {
465 container = child
466 }
467 var lower = lineRange.lowerBound
468 var upper = lineRange.upperBound
469 // Tables and lists carry no styling of their own, so inside them only the rows or
470 // items around the edit change, however large they are.
471 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
472 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
473 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
474 let inner = overlapping(node.children(overlapping: around))
475 return inner.isEmpty ? [node] : inner
476 }
477 }
478 for child in overlapping(container.children(overlapping: around)) {
479 lower = min(lower, child.range.lowerBound)
480 upper = max(upper, child.range.upperBound)
481 }
482 let heading = container.firstChild(.heading)
483 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
484 lower = min(lower, container.range.lowerBound)
485 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
486 }
487 return lower..<min(upper, text.length)
488 }
489
490 // MARK: - Editing
491
492 fileprivate func storageEdited(range: NSRange, delta: Int) {
493 guard !isLoading, let storage = textView.textStorage else { return }
494 markActive = false
495 let clock = ContinuousClock()
496 let start = clock.now
497 let replacement = (storage.string as NSString).substring(with: range)
498 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
499 let oldText = document.text as NSString
500 let newText = storage.string as NSString
501 let newEnd = edit.range.lowerBound + replacement.utf16.count
502 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
503 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
504 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
505 do {
506 try document.apply([edit], baseRevision: document.revision)
507 } catch {
508 assertionFailure("text view and document disagree: \(error)")
509 return
510 }
511 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
512 // edited line when the edit reaches into unstyled text.
513 if styledUpTo >= edit.range.upperBound {
514 styledUpTo += edit.replacement.utf16.count - edit.range.count
515 } else if styledUpTo > edit.range.lowerBound {
516 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
517 }
518 let oldHidden = hidden.all
519 view = view.mapped(through: [edit]).pruned(to: document.tree)
520 folded.set(view.folds)
521 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
522 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
523 let delta = edit.replacement.utf16.count - edit.range.count
524 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
525 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
526 if hidden.all != oldHidden.map({ mapRange($0, through: edit) }) {
527 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
528 }
529 onEditTiming?(clock.now - start)
530 onChange?()
531 }
532
533 /// Columns a wrapped continuation of `line` should start past the line's own start.
534 nonisolated static func hangingColumns(_ line: String) -> Int {
535 var columns = 0
536 var rest = Substring(line)
537 while let c = rest.first, c == " " || c == "\t" {
538 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
539 rest = rest.dropFirst()
540 }
541 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
542 var bullet = 0
543 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
544 bullet = 1
545 } else {
546 let digits = rest.prefix { $0.isASCII && $0.isNumber }
547 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
548 bullet = digits.count + 1
549 }
550 }
551 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
552 columns += bullet + 1
553 let afterBullet = rest.dropFirst(bullet + 1)
554 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
555 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
556 columns += 4
557 }
558 return columns
559 }
560
561 /// Whether a heading line touches `start..<end` or starts right after it, where joining
562 /// lines could take it away.
563 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
564 let length = min(end + 1, text.length) - start
565 guard length >= 0 else { return false }
566 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
567 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
568 let stars = line.prefix { $0 == "*" }
569 let after = line.dropFirst(stars.count)
570 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
571 }
572 }
573
574 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
575 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
576 return mapped
577 }
578
579 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
580 /// back jumps to the end of the heading line.
581 fileprivate func selectionChanged() {
582 let selection = textView.selectedRange()
583 defer { previousSelection = selection.location }
584 guard selection.length == 0, let range = hidden.containing(selection.location) else { return }
585 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
586 }
587}
588
589extension OrgEditor: DocumentBuffer {
590 public var selection: [Range<Int>] {
591 let selected = textView.selectedRange()
592 return [selected.location..<NSMaxRange(selected)]
593 }
594
595 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
596 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
597 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
598 let before = document.text
599 let selected = textView.selectedRange()
600 let result = try change(&document)
601 if document.text != before {
602 let edits = lineEdits(from: before, to: document.text)
603 var state = view
604 state.selection = [selected.location..<NSMaxRange(selected)]
605 let mapped = state.mapped(through: edits)
606 load(document.text)
607 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
608 let selection = mapped.selection[0]
609 setCaret(selection.lowerBound)
610 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
611 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
612 textView.undoManager?.removeAllActions(withTarget: textView)
613 }
614 onChange?()
615 return result
616 }
617}
618
619extension OrgEditor: NSTextViewDelegate {
620 public func textViewDidChangeSelection(_ notification: Notification) {
621 selectionChanged()
622 }
623}
624
625extension OrgEditor: NSTextStorageDelegate {
626 public nonisolated func textStorage(
627 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
628 ) {
629 guard editedMask.contains(.editedCharacters) else { return }
630 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
631 }
632}
633
634extension OrgEditor: NSTextContentStorageDelegate {
635 /// Folded text isn't enumerated, so it isn't laid out or drawn.
636 public nonisolated func textContentManager(
637 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
638 ) -> Bool {
639 guard let range = textElement.elementRange else { return true }
640 let documentStart = textContentManager.documentRange.location
641 let start = textContentManager.offset(from: documentStart, to: range.location)
642 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
643 return !hidden.covers(start, end)
644 }
645}
646
647extension OrgEditor: NSTextLayoutManagerDelegate {
648 public nonisolated func textLayoutManager(
649 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
650 ) -> NSTextLayoutFragment {
651 let range = textElement.elementRange
652 if let range, let manager = textLayoutManager.textContentManager {
653 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
654 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
655 }
656 return NSTextLayoutFragment(textElement: textElement, range: range)
657 }
658}
659
660/// A heading line drawn with an ellipsis after it, like org's folded headings.
661final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
662 override func draw(at point: CGPoint, in context: CGContext) {
663 super.draw(at: point, in: context)
664 guard let line = textLineFragments.first else { return }
665 let bounds = line.typographicBounds
666 let ellipsis = NSAttributedString(string: " …", attributes: [
667 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
668 .foregroundColor: NSColor.secondaryLabelColor,
669 ])
670 NSGraphicsContext.saveGraphicsState()
671 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
672 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
673 NSGraphicsContext.restoreGraphicsState()
674 }
675
676 override var renderingSurfaceBounds: CGRect {
677 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
678 }
679}
680#endif