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