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