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