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