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