Sources/OrgEditorAppKit/OrgEditor.swift
1203 lines · 58090 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 /// Where lines start, for line numbers.
56 let lines = LineIndex()
57 /// Blocks drawn on a shaded band.
58 let shaded = HiddenRanges()
59 private(set) var theme = Theme()
60 /// Colors and type; a change restyles the file.
61 public var themeSpec: ThemeSpec = .default {
62 didSet {
63 guard themeSpec != oldValue else { return }
64 theme = Theme(themeSpec)
65 applyThemeToView()
66 restyleEverything()
67 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
68 }
69 }
70 private var isLoading = false
71 private var previousSelection = 0
72 /// Text before this offset is styled; after it, only base attributes until the background
73 /// passes reach it. Always at a line start.
74 private(set) var styledUpTo = 0
75 private var stylingScheduled = false
76 /// One paragraph style object per indent pair, shared by every line that uses it.
77 private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
78
79 private struct IndentKey: Hashable {
80 let firstLine: Int
81 let wrapped: Int
82 }
83
84 /// Styled before the first render: more than a screenful.
85 static let firstStyleChunk = 30_000
86 /// Styled per run-loop turn afterwards.
87 static let styleChunk = 200_000
88
89 /// Highlights code in src blocks; nil leaves code plain.
90 public let highlighter: (any CodeHighlighter)?
91
92 /// What the file is: org, or plain text, highlighted as code when the language is known.
93 public enum Mode: Equatable, Sendable {
94 case org
95 case plain(language: String?)
96 }
97
98 public let mode: Mode
99 public var isOrg: Bool { mode == .org }
100 /// Highlights of the whole file in plain mode, and the revision they were made for.
101 private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
102
103 public init(
104 document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
105 highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
106 ) {
107 self.document = document
108 self.options = options
109 self.highlighter = highlighter
110 self.mode = mode
111 let orgTextView = OrgTextView(usingTextLayoutManager: true)
112 textView = orgTextView
113 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
114 super.init()
115 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
116 orgTextView.onCommandClick = { [weak self] offset in
117 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil else { return false }
118 self.setCaret(offset)
119 self.run("org.link.open")
120 return true
121 }
122 orgTextView.onMouseDown = { [weak self] in
123 self?.markActive = false
124 self?.modalMouseDown()
125 }
126 textView.usesFindBar = true
127 textView.frame = frame
128 textView.isRichText = false
129 textView.isEditable = editable
130 textView.allowsUndo = true
131 textView.isAutomaticQuoteSubstitutionEnabled = false
132 textView.isAutomaticDashSubstitutionEnabled = false
133 textView.isAutomaticTextReplacementEnabled = false
134 textView.isAutomaticSpellingCorrectionEnabled = false
135 applyThemeToView()
136 textView.isVerticallyResizable = true
137 textView.autoresizingMask = [.width]
138 textView.textContainer?.widthTracksTextView = true
139 textView.delegate = self
140 textView.textStorage?.delegate = self
141 textLayoutManager.delegate = self
142 textContentStorage.delegate = self
143
144 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
145 load(document.text)
146 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
147 textView.setSelectedRange(NSRange(location: 0, length: 0))
148 if isOrg {
149 var startup = Presentation.startupFoldState(document.tree) ?? FoldState()
150 let wrappers = Presentation.startupWrappers(document.tree, hideDrawers: options.hideDrawerStartup, hideBlocks: options.hideBlockStartup)
151 startup.wrapperFolds = Set(wrappers.map(\.start))
152 if startup != FoldState() { setFolds(startup, wrappers: wrappers) }
153 shrinkAtStartup()
154 }
155 }
156
157 /// Replaces the storage's text. Setting the attributed string directly is about 100x
158 /// faster than `NSTextView.string` for large files.
159 private func load(_ text: String) {
160 isLoading = true
161 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
162 isLoading = false
163 lines.reset(text as NSString)
164 orgTextView?.lineIndex = lines
165 orgTextView?.updateGutter()
166 styledUpTo = 0
167 styleNextChunk(Self.firstStyleChunk)
168 scheduleStyling()
169 }
170
171 // MARK: - Initial styling
172
173 /// Styles whole lines from the watermark onward, about `size` units.
174 private func styleNextChunk(_ size: Int) {
175 let text = textView.textStorage!.string as NSString
176 guard styledUpTo < text.length else { return }
177 let target = min(text.length, styledUpTo + size)
178 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
179 restyleOutsideEditing(styledUpTo..<end)
180 styledUpTo = end
181 }
182
183 /// The text view's own colors and font, and the line numbers'.
184 private func applyThemeToView() {
185 textView.font = theme.font
186 textView.typingAttributes = theme.base
187 textView.drawsBackground = true
188 textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
189 textView.insertionPointColor = theme.color("cursor") ?? .textColor
190 textView.selectedTextAttributes = [.backgroundColor: theme.color("selection") ?? .selectedTextBackgroundColor]
191 if let view = orgTextView {
192 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
193 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
194 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
195 view.updateGutter()
196 view.needsDisplay = true
197 }
198 }
199
200 /// Styles the whole file again, a screenful now and the rest in the background.
201 private func restyleEverything() {
202 styledUpTo = 0
203 revealedLine = caretLine
204 styleNextChunk(Self.firstStyleChunk)
205 scheduleStyling()
206 }
207
208 private var caretLine: NSRange {
209 let text = textView.string as NSString
210 return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
211 }
212
213 private func scheduleStyling() {
214 guard !stylingScheduled, styledUpTo < utf16Length else { return }
215 stylingScheduled = true
216 DispatchQueue.main.async { [weak self] in
217 guard let self else { return }
218 self.stylingScheduled = false
219 self.styleNextChunk(Self.styleChunk)
220 self.scheduleStyling()
221 }
222 }
223
224 /// Styles everything still waiting for a background pass.
225 public func finishStyling() {
226 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
227 }
228
229 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
230 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
231 var utf16Length: Int { (textView.string as NSString).length }
232
233 /// A scroll view holding the text view, ready for a window.
234 public func makeScrollView() -> NSScrollView {
235 let scroll = NSScrollView(frame: textView.frame)
236 scroll.hasVerticalScroller = true
237 scroll.documentView = textView
238 orgTextView?.showsLineNumbers = showLineNumbers
239 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
240 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
241 return scroll
242 }
243
244 // MARK: - Saving
245
246 /// Saves through `saver`. A merge that changes the buffer reloads the text view.
247 @discardableResult
248 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
249 try update { try saver.save(&$0, to: url) }
250 }
251
252 /// Called after every change to the document, typed or not.
253 public var onChange: (() -> Void)?
254
255 // MARK: - Commands
256
257 /// Called with messages commands report, such as why one couldn't run here.
258 public var onMessage: ((String) -> Void)?
259 /// Called with the pending prefix and what can follow it, and with nil when it ends.
260 /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
261 public var onModeChange: ((String?) -> Void)?
262 /// The selection moved.
263 public var onSelectionChange: ((NSRange) -> Void)?
264 var reportedMode: String?
265 public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
266 /// Called with `app.*` commands, which the app carries out.
267 public var onAppCommand: ((String) -> Void)?
268 /// Called when a command asks a question; reply with the answer, or nil to cancel.
269 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
270 /// Runs work outside the text, such as a table recalculation in Emacs.
271 public var onExternal: ((ExternalRequest) -> Void)?
272 /// Tags used across the workspace, for tag completion.
273 public var knownTags: @Sendable () -> [String] = { [] }
274 /// Effects other than messages, for the app to carry out.
275 public var onEffect: ((Effect) -> Void)?
276
277 public var keymap: Keymap {
278 get { dispatcher.keymap }
279 set {
280 dispatcher.keymap = newValue
281 dispatcher.reset()
282 }
283 }
284
285 public var optionAsMeta: OptionAsMeta = [.left]
286 /// Org options commands follow.
287 public var options: EditingOptions = .org {
288 didSet {
289 if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
290 }
291 }
292 /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
293 /// `options`). Hidden markup shows on the caret's line, so it can be edited.
294 public var showMarkup = true {
295 didSet { if showMarkup != oldValue { restyleEverything() } }
296 }
297 /// Line numbers in a ruler beside the text.
298 public var showLineNumbers = true {
299 didSet { orgTextView?.showsLineNumbers = showLineNumbers }
300 }
301 var orgTextView: OrgTextView? { textView as? OrgTextView }
302
303 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
304 private var revealedLine: NSRange?
305 var dispatcher: KeyDispatcher
306 /// Evil-style editing, for modal keymaps such as Doom's.
307 public var modal = false {
308 didSet {
309 guard modal != oldValue else { return }
310 vim = Vim()
311 dispatcher.mode = modal ? vim.mode.keymapMode : nil
312 dispatcher.reset()
313 updateCursor()
314 }
315 }
316 var vim = Vim()
317 /// The text and caret when insert state began, to know what was typed for `.`.
318 var insertSnapshot: (text: String, caret: Int)?
319 /// The evil cursor in visual states, where the selection's start isn't it.
320 var visualCaret: Int?
321 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
322 private(set) var markActive = false
323
324 public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
325 let selected = textView.selectedRange()
326 return EditContext(
327 revision: document.revision, text: document.text, tree: document.tree,
328 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
329 hidden: hidden.all, options: options, knownTags: knownTags,
330 lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
331 )
332 }
333
334 /// Offers a key press to the keymap. False lets the text system have it.
335 func handleKey(_ event: NSEvent) -> Bool {
336 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
337 if modal { return handleModal(chord) }
338 switch dispatcher.feed(chord) {
339 case .pending(let keys):
340 let next = keymap.continuations(of: keys).map { item in
341 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
342 }
343 onKeysPending?(KeySequence.format(keys), next)
344 return true
345 case .cancelled:
346 onKeysPending?(nil, [])
347 onMessage?("Quit")
348 return true
349 case .undefined(let keys):
350 onKeysPending?(nil, [])
351 onMessage?("\(KeySequence.format(keys)) is undefined")
352 return true
353 case .unbound:
354 return false
355 case .complete(let keys, let candidates):
356 if keys.count > 1 { onKeysPending?(nil, []) }
357 let context = context()
358 let runnable = candidates.first { binding in
359 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
360 }
361 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
362 run(binding.command)
363 return true
364 }
365 return false
366 }
367 }
368
369 private func applies(_ id: String, in context: EditContext) -> Bool {
370 if !isOrg, id.hasPrefix("org.") { return false }
371 return switch EditorCommands.command(id)?.action {
372 case .text(let command): command.applies(in: context)
373 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
374 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
375 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
376 case .edit, .mark, .app, .find: true
377 case nil: true
378 }
379 }
380
381 /// The last command run and the revision it left, for `last-command`.
382 private var lastCommand: (id: String, revision: Int)?
383
384 /// Runs a command by id, as a key, a menu item or the palette would.
385 public func run(_ id: String) {
386 defer { lastCommand = (id, document.revision) }
387 guard let command = EditorCommands.command(id) else {
388 onMessage?("Unknown command \(id)")
389 return
390 }
391 if !isOrg, id.hasPrefix("org.") {
392 onMessage?("Not an org file")
393 return
394 }
395 var keepMark = false
396 switch command.action {
397 case .text(let text):
398 perform(text)
399 case .view:
400 switch id {
401 case "org.cycle": cycleAtCaret()
402 case "org.cycle-global": cycleGlobal()
403 default: tableColumnWidth(id)
404 }
405 case .edit(let selector, let extending):
406 if markActive, let extending {
407 keepMark = true
408 textView.doCommand(by: NSSelectorFromString(extending))
409 } else {
410 textView.doCommand(by: NSSelectorFromString(selector))
411 }
412 case .find(let action):
413 let item = NSMenuItem()
414 item.tag = action.rawValue
415 textView.performTextFinderAction(item)
416 case .mark:
417 if id == "edit.set-mark" {
418 let caret = textView.selectedRange().location
419 textView.setSelectedRange(NSRange(location: caret, length: 0))
420 keepMark = true
421 onMessage?("Mark set")
422 } else {
423 let selected = textView.selectedRange()
424 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
425 onMessage?("Quit")
426 }
427 case .app:
428 onAppCommand?(id)
429 }
430 markActive = keepMark
431 }
432
433 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
434 /// they form one undo step and reach the document through the same path.
435 @discardableResult
436 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
437 let context = context(now: now, answers: answers)
438 let step = command.run(in: context)
439 switch step {
440 case .commit(let result):
441 guard textView.isEditable || result.edits.isEmpty else {
442 onMessage?("This file is read-only.")
443 return .failed("read-only")
444 }
445 commandEditing = true
446 applyEdits(result.edits)
447 commandEditing = false
448 if let selection = result.selection?.first {
449 setCaret(selection.lowerBound)
450 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
451 }
452 for effect in result.effects {
453 if case .message(let text) = effect { onMessage?(text) } else { onEffect?(effect) }
454 }
455 case .failed(let message):
456 onMessage?(message)
457 case .external(let request):
458 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
459 case .prompt(let prompt):
460 onPrompt?(prompt) { [weak self] answer in
461 guard let self else { return }
462 guard let answer else {
463 self.onMessage?("Quit")
464 return
465 }
466 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
467 }
468 }
469 return step
470 }
471
472 // MARK: - Disk
473
474 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
475 /// its headings.
476 @discardableResult
477 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
478 update { $0.diskChanged(to: bytes) }
479 }
480
481 // MARK: - Folding
482
483 public var foldState: FoldState {
484 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
485 }
486
487 private var globalVisibility: GlobalVisibility?
488
489 public func setFolds(_ state: FoldState) {
490 setFolds(state, wrappers: nil)
491 }
492
493 /// `wrappers`, when given, holds every folded drawer and block.
494 private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
495 view.folds = state.folds
496 view.bodyFolds = state.bodyFolds
497 view = view.pruned(to: document.tree, wrappers: false)
498 // Found one by one, or all at once when there are many.
499 let found = wrappers ?? (state.wrapperFolds.count > 32
500 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
501 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
502 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
503 view.wrapperFolds = Set(wrapperHidden.keys)
504 updateHidden()
505 orgTextView?.redrawLineNumbers()
506 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
507 textView.needsDisplay = true
508 let caret = textView.selectedRange().location
509 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
510 }
511
512 /// What each folded drawer and block hides, by opening-line start; kept in step with
513 /// `view.wrapperFolds` and mapped through edits.
514 private var wrapperHidden: [Int: Range<Int>] = [:]
515
516 private func updateHidden() {
517 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
518 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)))
519 }
520
521 // MARK: - Shrunk table columns
522
523 /// Narrowed table columns (`org-table-shrink`): by table start, each column's segments.
524 /// Recomputed as the text changes; typing into one widens its column again, as editing
525 /// org's overlays deletes them. Commands' edits keep columns narrow, as `org-table-align`
526 /// shrinks them again.
527 private var shrunk: [Int: [Int: [TableShrink.Segment]]] = [:]
528 private var commandEditing = false
529
530 /// Narrows `columns` of `table` and widens its others.
531 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
532 let text = textView.string
533 let segments = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
534 shrunk[table.lowerBound] = segments.isEmpty ? nil : segments
535 restyleOutsideEditing(table)
536 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
537 textView.needsDisplay = true
538 }
539
540 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
541 /// `expand` for `org-table-expand`.
542 private func tableColumnWidth(_ id: String) {
543 let caret = textView.selectedRange().location
544 let text = textView.string
545 guard let table = TableShrink.table(at: caret, in: text) else {
546 onMessage?("Not in a table")
547 return
548 }
549 let current = shrunk[table.lowerBound].map { Array($0.keys) } ?? []
550 switch id {
551 case "org.table.shrink": setShrunk(TableShrink.cookieColumns(table, in: text), in: table)
552 case "org.table.expand": setShrunk([], in: table)
553 default:
554 if let column = TableShrink.column(at: caret, in: text) {
555 setShrunk(Array(Set(current).symmetricDifference([column])), in: table)
556 return
557 }
558 let line = (text as NSString).lineRange(for: NSRange(location: caret, length: 0))
559 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
560 guard let self, let answer else { return }
561 self.setShrunk(Array(Set(current).symmetricDifference(TableShrink.columns(answer, max: line.length / 2))), in: table)
562 }
563 }
564 }
565
566 /// `#+STARTUP: shrink`: every table's columns with width cookies start narrow.
567 private func shrinkAtStartup() {
568 guard Presentation.startupOptions(document.tree).contains(where: { $0.lowercased() == "shrink" }) else { return }
569 let text = textView.string
570 var offset = 0
571 let ns = text as NSString
572 while offset < ns.length {
573 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
574 defer { offset = max(NSMaxRange(line), offset + 1) }
575 guard ns.substring(with: line).range(of: "^[ \\t]*\\|", options: .regularExpression) != nil,
576 let table = TableShrink.table(at: line.location, in: text) else { continue }
577 let columns = TableShrink.cookieColumns(table, in: text)
578 if !columns.isEmpty { shrunk[table.lowerBound] = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) }) }
579 offset = table.upperBound
580 }
581 }
582
583 /// Moves shrunk columns through `edit`; returns the tables to restyle.
584 private func mapShrunk(through edit: TextEdit) -> [Range<Int>] {
585 guard !shrunk.isEmpty else { return [] }
586 let text = textView.string
587 let delta = edit.replacement.utf16.count - edit.range.count
588 var mapped: [Int: [Int: [TableShrink.Segment]]] = [:]
589 var tables: [Range<Int>] = []
590 for (start, columns) in shrunk {
591 let kept = columns.filter { _, segments in
592 commandEditing || !segments.contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
593 }.keys
594 let touched = columns.values.joined().contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
595 let newStart = start < edit.range.lowerBound ? start : start >= edit.range.upperBound ? start + delta : edit.range.lowerBound
596 guard let table = TableShrink.table(at: min(newStart, max(0, text.utf16.count - 1)), in: text) else { continue }
597 if touched || kept.count != columns.count { tables.append(table) }
598 guard !kept.isEmpty else { continue }
599 mapped[table.lowerBound] = Dictionary(uniqueKeysWithValues: kept.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
600 }
601 shrunk = mapped
602 return tables
603 }
604
605 /// Hides each shrunk segment's text and draws its display where the text was.
606 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
607 guard !shrunk.isEmpty else { return }
608 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
609 for segment in shrunk.values.flatMap({ $0.values.joined() }) where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
610 let r = segment.range
611 let shown = segment.display.count
612 let kept = min(shown, r.count)
613 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
614 guard kept > 0 else { continue }
615 let visible = NSRange(location: r.upperBound - kept, length: kept)
616 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
617 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
618 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
619 }
620 }
621
622 /// Moves drawer and block folds through `edit`, checking again only those near it.
623 private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
624 guard !wrapperHidden.isEmpty else { return }
625 var mapped: [Int: Range<Int>] = [:]
626 let entries = Array(wrapperHidden)
627 // One pass maps every start and range.
628 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
629 for i in entries.indices {
630 let newStart = moved[2 * i].lowerBound
631 let newRange = moved[2 * i + 1]
632 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
633 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
634 } else {
635 mapped[newStart] = newRange
636 }
637 }
638 wrapperHidden = mapped
639 view.wrapperFolds = Set(mapped.keys)
640 }
641
642 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
643 /// cycles folded, children, subtree. Returns false elsewhere.
644 @discardableResult
645 public func cycleAtCaret() -> Bool {
646 let caret = textView.selectedRange().location
647 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
648 setFolds(state)
649 // Off a closing line that folding hid, to the opening line, as org does.
650 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
651 return true
652 }
653
654 /// Shift-TAB: overview, contents, show all.
655 public func cycleGlobal() {
656 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
657 globalVisibility = visibility
658 setFolds(state)
659 }
660
661 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
662 public func reveal(_ offset: Int) {
663 let target = max(0, min(offset, utf16Length))
664 unfold(around: target)
665 setCaret(target)
666 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
667 }
668
669 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
670 func unfold(around offset: Int) {
671 var state = foldState
672 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
673 state.folds.remove(entry.start)
674 state.bodyFolds.remove(entry.start)
675 }
676 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
677 state.wrapperFolds.remove(start)
678 }
679 guard state != foldState else { return }
680 setFolds(state)
681 }
682
683 /// Applies edits through the text view as one undo step, not merged with typing around it.
684 func applyEdits(_ edits: [TextEdit]) {
685 guard !edits.isEmpty, let storage = textView.textStorage else { return }
686 textView.breakUndoCoalescing()
687 textView.undoManager?.beginUndoGrouping()
688 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
689 let range = NSRange(edit.range)
690 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
691 storage.replaceCharacters(in: range, with: edit.replacement)
692 textView.didChangeText()
693 }
694 textView.undoManager?.endUndoGrouping()
695 textView.breakUndoCoalescing()
696 }
697
698 func setCaret(_ offset: Int) {
699 let clamped = max(0, min(offset, utf16Length))
700 previousSelection = clamped
701 textView.setSelectedRange(NSRange(location: clamped, length: 0))
702 }
703
704 // MARK: - Styling
705
706 private func restyleOutsideEditing(_ range: Range<Int>) {
707 guard let storage = textView.textStorage else { return }
708 storage.beginEditing()
709 restyle(range, in: storage)
710 storage.endEditing()
711 }
712
713 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
714 /// attribute changes are allowed and characters must not change.
715 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
716 guard !range.isEmpty else { return }
717 let whole = NSRange(range)
718 storage.setAttributes(theme.base, range: whole)
719 guard isOrg else {
720 for run in plainRuns() where run.range.overlaps(range) {
721 guard let clipped = clip(run.range, to: range) else { continue }
722 theme.apply(.syntax(run.category), to: storage, range: clipped)
723 }
724 return
725 }
726 let text = storage.string as NSString
727 for run in Presentation.indents(document.tree, in: range) {
728 guard let clipped = clip(run.range, to: range) else { continue }
729 guard run.firstLine == run.wrapped else {
730 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
731 continue
732 }
733 // Body lines wrap under their own text: past leading blanks, and past a list bullet
734 // and checkbox, as adaptive-wrap does in Emacs.
735 var location = clipped.location
736 while location < NSMaxRange(clipped) {
737 let line = text.lineRange(for: NSRange(location: location, length: 0))
738 let hanging = Self.hangingColumns(text.substring(with: line))
739 let lineRange = NSIntersectionRange(line, clipped)
740 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
741 location = NSMaxRange(line)
742 }
743 }
744 let revealed = caretLine
745 var scriptExclusions: [Range<Int>] = []
746 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
747 guard let clipped = clip(run.range, to: range) else { continue }
748 if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
749 storage.addAttributes(theme.hidden, range: clipped)
750 } else {
751 theme.apply(run.role, to: storage, range: clipped)
752 }
753 switch run.role {
754 case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
755 default: break
756 }
757 }
758 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
759 applyShrunk(range, in: storage)
760 }
761
762 /// `org-pretty-entities`: entities drawn as their character over the entity's last
763 /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
764 /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
765 /// keywords, as `org-raise-scripts` leaves them.
766 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
767 let text = storage.string as NSString
768 var location = range.lowerBound
769 while location < range.upperBound {
770 let line = text.lineRange(for: NSRange(location: location, length: 0))
771 guard line.length > 0 else { break }
772 location = NSMaxRange(line)
773 if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
774 let content = text.substring(with: line)
775 if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
776 for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
777 switch run {
778 case .entity(let r, let display):
779 let start = line.location + r.lowerBound
780 let last = line.location + r.upperBound - 1
781 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
782 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
783 case .script(let markers, let body, let superscript):
784 let bodyStart = line.location + body.lowerBound
785 if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
786 for marker in markers {
787 storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
788 }
789 let size = theme.font.pointSize
790 storage.addAttributes([
791 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
792 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
793 ], range: NSRange(location: bodyStart, length: body.count))
794 }
795 }
796 }
797 }
798
799 /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
800 /// markers only when Emacs hides them too.
801 private func hides(_ role: StyleRole) -> Bool {
802 switch role {
803 case .linkMarkup: true
804 case .markup: options.hideEmphasisMarkers
805 default: false
806 }
807 }
808
809 /// Moving to another line shows its markup and hides the last one's.
810 private func revealCaretLine() {
811 guard !showMarkup, isOrg else { return }
812 let line = caretLine
813 guard line != revealedLine else { return }
814 let text = textView.string as NSString
815 // The old line may have moved with edits since; restyle the line now at its start.
816 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
817 revealedLine = line
818 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
819 restyleOutsideEditing(range.location..<NSMaxRange(range))
820 }
821 }
822
823 /// Code highlights for the whole file in plain mode.
824 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
825 guard case .plain(let language?) = mode, let highlighter else { return [] }
826 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
827 let runs = highlighter.highlights(language: language, code: document.text)
828 codeRuns = (document.revision, runs)
829 return runs
830 }
831
832 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
833 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
834 if let style = paragraphStyles[key] { return style }
835 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
836 paragraphStyles[key] = style
837 return style
838 }
839
840 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
841 let clipped = run.clamped(to: range)
842 return clipped.isEmpty ? nil : NSRange(clipped)
843 }
844
845 /// The region an edit affects in one version of the tree: inside the innermost section
846 /// holding the edited lines (plus the line after), every element that overlaps them or the
847 /// line on either side. A changed heading line, or an added or removed heading, widens it
848 /// to that section's whole own body. Run on the old and the new tree, the union covers
849 /// elements that grew and elements that shrank.
850 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
851 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
852 let lineRange = lines.location..<(lines.location + lines.length)
853 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
854 var container = tree.root
855 while let child = container.child(containing: lineRange.lowerBound),
856 child.kind == .section || child.kind == .zerothSection,
857 lineRange.upperBound <= child.range.upperBound {
858 container = child
859 }
860 var lower = lineRange.lowerBound
861 var upper = lineRange.upperBound
862 // Tables and lists carry no styling of their own, so inside them only the rows or
863 // items around the edit change, however large they are.
864 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
865 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
866 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
867 let inner = overlapping(node.children(overlapping: around))
868 return inner.isEmpty ? [node] : inner
869 }
870 }
871 for child in overlapping(container.children(overlapping: around)) {
872 lower = min(lower, child.range.lowerBound)
873 upper = max(upper, child.range.upperBound)
874 }
875 let heading = container.firstChild(.heading)
876 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
877 lower = min(lower, container.range.lowerBound)
878 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
879 }
880 return lower..<min(upper, text.length)
881 }
882
883 // MARK: - Editing
884
885 private var blockCheck: DispatchWorkItem?
886
887 /// Looks for blocks over the whole file once typing pauses, catching what moving the
888 /// ranges can't see (a block's end found far away).
889 private func scheduleBlockCheck() {
890 blockCheck?.cancel()
891 let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
892 blockCheck = work
893 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
894 }
895
896 func settleBlocks() {
897 blockCheck?.cancel()
898 guard isOrg else { return }
899 let blocks = Presentation.shadedBlocks(document.tree)
900 guard blocks != shaded.all else { return }
901 shaded.set(blocks)
902 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
903 }
904
905 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
906 /// them), hold a block delimiter or a fixed-width line.
907 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
908 let start = min(range.lowerBound, text.length)
909 let end = min(range.upperBound + 1, text.length)
910 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
911 let content = text.substring(with: lines)
912 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
913 }
914
915 fileprivate func storageEdited(range: NSRange, delta: Int) {
916 guard !isLoading, let storage = textView.textStorage else { return }
917 markActive = false
918 let clock = ContinuousClock()
919 let start = clock.now
920 let replacement = (storage.string as NSString).substring(with: range)
921 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
922 let oldText = document.text as NSString
923 let newText = storage.string as NSString
924 let newEnd = edit.range.lowerBound + replacement.utf16.count
925 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
926 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
927 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
928 do {
929 try document.apply([edit], baseRevision: document.revision)
930 } catch {
931 assertionFailure("text view and document disagree: \(error)")
932 return
933 }
934 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
935 // edited line when the edit reaches into unstyled text.
936 if styledUpTo >= edit.range.upperBound {
937 styledUpTo += edit.replacement.utf16.count - edit.range.count
938 } else if styledUpTo > edit.range.lowerBound {
939 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
940 }
941 let oldHidden = hidden.all
942 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
943 let delta = edit.replacement.utf16.count - edit.range.count
944 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
945 view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
946 mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
947 updateHidden()
948 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
949 for table in mapShrunk(through: edit) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
950 let oldShaded = shaded.all
951 if isOrg {
952 // Walking the tree for blocks costs more than typing; only an edit on a line that
953 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
954 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
955 shaded.set(Presentation.shadedBlocks(document.tree))
956 } else {
957 shaded.set(oldShaded.map { mapRange($0, through: edit) })
958 }
959 scheduleBlockCheck()
960 }
961 if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
962 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
963 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
964 }
965 onEditTiming?(clock.now - start)
966 let lineCount = lines.lineCount
967 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
968 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
969 orgTextView?.redrawLineNumbers()
970 onChange?()
971 }
972
973 /// Columns a wrapped continuation of `line` should start past the line's own start.
974 nonisolated static func hangingColumns(_ line: String) -> Int {
975 var columns = 0
976 var rest = Substring(line)
977 while let c = rest.first, c == " " || c == "\t" {
978 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
979 rest = rest.dropFirst()
980 }
981 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
982 var bullet = 0
983 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
984 bullet = 1
985 } else {
986 let digits = rest.prefix { $0.isASCII && $0.isNumber }
987 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
988 bullet = digits.count + 1
989 }
990 }
991 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
992 columns += bullet + 1
993 let afterBullet = rest.dropFirst(bullet + 1)
994 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
995 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
996 columns += 4
997 }
998 return columns
999 }
1000
1001 /// Whether a heading line touches `start..<end` or starts right after it, where joining
1002 /// lines could take it away.
1003 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1004 let length = min(end + 1, text.length) - start
1005 guard length >= 0 else { return false }
1006 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1007 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1008 let stars = line.prefix { $0 == "*" }
1009 let after = line.dropFirst(stars.count)
1010 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1011 }
1012 }
1013
1014 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1015 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1016 return mapped
1017 }
1018
1019 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1020 /// back jumps to the end of the heading line.
1021 fileprivate func selectionChanged() {
1022 let selection = textView.selectedRange()
1023 defer { previousSelection = selection.location }
1024 onSelectionChange?(selection)
1025 revealCaretLine()
1026 orgTextView?.redrawLineNumbers()
1027 // A selection reaching into folded text, as a find match does, unfolds it.
1028 if selection.length > 0 {
1029 if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1030 unfold(around: selection.location)
1031 unfold(around: NSMaxRange(selection) - 1)
1032 }
1033 return
1034 }
1035 guard let range = hidden.containing(selection.location) else { return }
1036 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1037 }
1038}
1039
1040extension OrgEditor: DocumentBuffer {
1041 /// The selected text, for capture's `%i`.
1042 public var selectedText: String {
1043 let range = textView.selectedRange()
1044 guard range.length > 0 else { return "" }
1045 return (textView.string as NSString).substring(with: range)
1046 }
1047
1048 public var selection: [Range<Int>] {
1049 let selected = textView.selectedRange()
1050 return [selected.location..<NSMaxRange(selected)]
1051 }
1052
1053 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1054 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1055 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1056 let before = document.text
1057 let selected = textView.selectedRange()
1058 let result = try change(&document)
1059 if document.text != before {
1060 let edits = lineEdits(from: before, to: document.text)
1061 var state = view
1062 state.selection = [selected.location..<NSMaxRange(selected)]
1063 let mapped = state.mapped(through: edits)
1064 load(document.text)
1065 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1066 let selection = mapped.selection[0]
1067 setCaret(selection.lowerBound)
1068 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1069 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1070 textView.undoManager?.removeAllActions(withTarget: textView)
1071 }
1072 onChange?()
1073 return result
1074 }
1075}
1076
1077extension OrgEditor: NSTextViewDelegate {
1078 public func textViewDidChangeSelection(_ notification: Notification) {
1079 selectionChanged()
1080 }
1081}
1082
1083extension OrgEditor: NSTextStorageDelegate {
1084 public nonisolated func textStorage(
1085 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1086 ) {
1087 guard editedMask.contains(.editedCharacters) else { return }
1088 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1089 }
1090}
1091
1092extension OrgEditor: NSTextContentStorageDelegate {
1093 /// Folded text isn't enumerated, so it isn't laid out or drawn.
1094 public nonisolated func textContentManager(
1095 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1096 ) -> Bool {
1097 guard let range = textElement.elementRange else { return true }
1098 let documentStart = textContentManager.documentRange.location
1099 let start = textContentManager.offset(from: documentStart, to: range.location)
1100 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1101 return !hidden.covers(start, end)
1102 }
1103}
1104
1105extension OrgEditor: NSTextLayoutManagerDelegate {
1106 public nonisolated func textLayoutManager(
1107 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1108 ) -> NSTextLayoutFragment {
1109 let range = textElement.elementRange
1110 if let range, let manager = textLayoutManager.textContentManager {
1111 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1112 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1113 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1114 if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1115 return EntityFragment(textElement: textElement, range: range)
1116 }
1117 }
1118 return NSTextLayoutFragment(textElement: textElement, range: range)
1119 }
1120}
1121
1122/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1123/// `org-block` face.
1124final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1125 private var band: CGRect {
1126 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1127 // Not under the empty line TextKit adds after a final newline.
1128 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1129 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1130 }
1131
1132 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1133
1134 override func draw(at point: CGPoint, in context: CGContext) {
1135 context.saveGState()
1136 context.setFillColor(Theme.blockBackground.cgColor)
1137 context.fill(band.offsetBy(dx: point.x, dy: point.y))
1138 context.restoreGState()
1139 super.draw(at: point, in: context)
1140 }
1141}
1142
1143extension NSAttributedString.Key {
1144 /// The character an entity shows as, on the entity's last character.
1145 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1146}
1147
1148/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1149/// (now invisible) character sits, so it takes one column as in Emacs.
1150final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1151 static func hasEntities(_ string: NSAttributedString) -> Bool {
1152 var found = false
1153 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1154 if value != nil { found = true; stop.pointee = true }
1155 }
1156 return found
1157 }
1158
1159 override func draw(at point: CGPoint, in context: CGContext) {
1160 super.draw(at: point, in: context)
1161 Self.drawEntities(of: self, at: point, in: context)
1162 }
1163
1164 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1165 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1166 NSGraphicsContext.saveGraphicsState()
1167 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1168 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1169 guard let display = value as? String,
1170 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1171 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1172 attributes[.foregroundColor] = NSColor.textColor
1173 attributes[.orgEntityDisplay] = nil
1174 let x = line.locationForCharacter(at: range.location).x
1175 let bounds = line.typographicBounds
1176 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1177 }
1178 NSGraphicsContext.restoreGraphicsState()
1179 }
1180}
1181
1182/// A heading line drawn with an ellipsis after it, like org's folded headings.
1183final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1184 override func draw(at point: CGPoint, in context: CGContext) {
1185 super.draw(at: point, in: context)
1186 EntityFragment.drawEntities(of: self, at: point, in: context)
1187 guard let line = textLineFragments.first else { return }
1188 let bounds = line.typographicBounds
1189 let ellipsis = NSAttributedString(string: " …", attributes: [
1190 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1191 .foregroundColor: NSColor.secondaryLabelColor,
1192 ])
1193 NSGraphicsContext.saveGraphicsState()
1194 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1195 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1196 NSGraphicsContext.restoreGraphicsState()
1197 }
1198
1199 override var renderingSurfaceBounds: CGRect {
1200 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1201 }
1202}
1203#endif