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