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