Sources/OrgEditorAppKit/OrgEditor.swift
1598 lines · 79300 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 /// The selection shaded block lines last drew.
73 private var previousSelectionRange = NSRange(location: 0, length: 0)
74 /// Text before this offset is styled; after it, only base attributes until the background
75 /// passes reach it. Always at a line start.
76 private(set) var styledUpTo = 0
77 private var stylingScheduled = false
78 /// One paragraph style object per indent pair, shared by every line that uses it.
79 private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
80
81 private struct IndentKey: Hashable {
82 let firstLine: Int
83 let wrapped: Int
84 }
85
86 /// Styled before the first render: more than a screenful.
87 static let firstStyleChunk = 30_000
88 /// Styled per run-loop turn afterwards.
89 static let styleChunk = 200_000
90
91 /// Highlights code in src blocks; nil leaves code plain.
92 public let highlighter: (any CodeHighlighter)?
93
94 /// What the file is: org, or plain text, highlighted as code when the language is known.
95 public enum Mode: Equatable, Sendable {
96 case org
97 case plain(language: String?)
98 }
99
100 public let mode: Mode
101 public var isOrg: Bool { mode == .org }
102 /// The text as shown for accessibility, and the storage generation it's for.
103 var accessibleCache: (storage: Int, text: AccessibleText)?
104 /// Bumped on every character or attribute change to the storage.
105 var storageGeneration = 0
106 /// The open completion list, and the pause before one opens by itself.
107 var completionPopup: CompletionPopup?
108 var completionTimer: DispatchWorkItem?
109 /// The spell checker's skipped ranges and the text they were found in.
110 var spellSkipCache: (text: String, ranges: [Range<Int>])?
111 /// Highlights of the whole file in plain mode, and the revision they were made for.
112 private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
113
114 public init(
115 document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
116 highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
117 ) {
118 self.document = document
119 self.options = options
120 self.highlighter = highlighter
121 self.mode = mode
122 let orgTextView = OrgTextView(usingTextLayoutManager: true)
123 textView = orgTextView
124 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
125 super.init()
126 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
127 orgTextView.onFocusChange = { [weak self] in
128 guard let self else { return }
129 let id = ObjectIdentifier(self.textLayoutManager)
130 if let window = self.textView.window, window.isKeyWindow, window.firstResponder === self.textView {
131 Theme.focusedLayouts.insert(id)
132 } else {
133 Theme.focusedLayouts.remove(id)
134 }
135 self.redrawShaded([self.textView.selectedRange()])
136 }
137 orgTextView.onCommandClick = { [weak self] offset in
138 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
139 || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
140 self.setCaret(offset)
141 self.run("org.link.open")
142 return true
143 }
144 orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false }
145 orgTextView.accessibleText = { [weak self] in
146 guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
147 if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
148 let text = AccessibleText(storage)
149 self.accessibleCache = (self.storageGeneration, text)
150 return text
151 }
152 orgTextView.onMouseDown = { [weak self] in
153 self?.markActive = false
154 self?.modalMouseDown()
155 }
156 textView.usesFindBar = true
157 textView.frame = frame
158 textView.isRichText = false
159 textView.isEditable = editable
160 textView.allowsUndo = true
161 textView.isAutomaticQuoteSubstitutionEnabled = false
162 textView.isAutomaticDashSubstitutionEnabled = false
163 textView.isAutomaticTextReplacementEnabled = false
164 textView.isAutomaticSpellingCorrectionEnabled = false
165 applyThemeToView()
166 textView.isVerticallyResizable = true
167 textView.autoresizingMask = [.width]
168 textView.textContainer?.widthTracksTextView = true
169 textView.delegate = self
170 textView.textStorage?.delegate = self
171 textLayoutManager.delegate = self
172 textContentStorage.delegate = self
173
174 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
175 load(document.text)
176 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
177 textView.setSelectedRange(NSRange(location: 0, length: 0))
178 if isOrg {
179 let words = Presentation.startupOptions(document.tree).map { $0.lowercased() }
180 indented = words.contains("indent") ? true : words.contains("noindent") ? false : options.startupIndented
181 hideStars = words.contains("hidestars") ? true : words.contains("showstars") ? false : options.hideLeadingStars
182 var startup = Presentation.startupFoldState(document.tree) ?? FoldState()
183 // VISIBILITY properties and archived trees, unless everything shows.
184 if Presentation.startupFoldState(document.tree) != nil, !words.contains("showeverything") {
185 startup = Presentation.applyVisibilityProperties(startup, in: document.tree)
186 }
187 let wrappers = Presentation.startupWrappers(document.tree, hideDrawers: options.hideDrawerStartup, hideBlocks: options.hideBlockStartup)
188 startup.wrapperFolds = Set(wrappers.map(\.start))
189 if startup != FoldState() { setFolds(startup, wrappers: wrappers) }
190 shrinkAtStartup()
191 if InlineImages.startup(document.tree) ?? options.startupWithInlineImages { showsImages = true }
192 if words.contains("align") || (options.startupAlignAllTables && !words.contains("noalign")) {
193 _ = perform(AlignAllTables())
194 }
195 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
196 }
197 spellChecking = options.spellCheck
198 truncatesLines = options.startupTruncated
199 }
200
201 /// Replaces the storage's text. Setting the attributed string directly is about 100x
202 /// faster than `NSTextView.string` for large files.
203 private func load(_ text: String) {
204 isLoading = true
205 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
206 isLoading = false
207 lines.reset(text as NSString)
208 orgTextView?.lineIndex = lines
209 orgTextView?.updateGutter()
210 styledUpTo = 0
211 styleNextChunk(Self.firstStyleChunk)
212 scheduleStyling()
213 }
214
215 // MARK: - Initial styling
216
217 /// Styles whole lines from the watermark onward, about `size` units.
218 private func styleNextChunk(_ size: Int) {
219 let text = textView.textStorage!.string as NSString
220 guard styledUpTo < text.length else { return }
221 let target = min(text.length, styledUpTo + size)
222 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
223 restyleOutsideEditing(styledUpTo..<end)
224 styledUpTo = end
225 }
226
227 /// The text view's own colors and font, and the line numbers'.
228 private func applyThemeToView() {
229 textView.font = theme.font
230 textView.typingAttributes = theme.base
231 textView.drawsBackground = true
232 textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
233 textView.insertionPointColor = theme.color("cursor") ?? .textColor
234 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
235 textView.selectedTextAttributes = [.backgroundColor: Theme.selection]
236 if let view = orgTextView {
237 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
238 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
239 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
240 view.updateGutter()
241 view.needsDisplay = true
242 }
243 }
244
245 /// Styles the whole file again, a screenful now and the rest in the background.
246 private func restyleEverything() {
247 styledUpTo = 0
248 revealedLine = caretLine
249 styleNextChunk(Self.firstStyleChunk)
250 scheduleStyling()
251 }
252
253 private var caretLine: NSRange {
254 let text = textView.string as NSString
255 return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
256 }
257
258 private func scheduleStyling() {
259 guard !stylingScheduled, styledUpTo < utf16Length else { return }
260 stylingScheduled = true
261 DispatchQueue.main.async { [weak self] in
262 guard let self else { return }
263 self.stylingScheduled = false
264 self.styleNextChunk(Self.styleChunk)
265 self.scheduleStyling()
266 }
267 }
268
269 /// Styles everything still waiting for a background pass.
270 public func finishStyling() {
271 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
272 }
273
274 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
275 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
276 var utf16Length: Int { (textView.string as NSString).length }
277
278 /// A scroll view holding the text view, ready for a window.
279 public func makeScrollView() -> NSScrollView {
280 let scroll = NSScrollView(frame: textView.frame)
281 scroll.hasVerticalScroller = true
282 scroll.documentView = textView
283 orgTextView?.showsLineNumbers = showLineNumbers
284 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
285 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
286 return scroll
287 }
288
289 // MARK: - Saving
290
291 /// Saves through `saver`. A merge that changes the buffer reloads the text view.
292 @discardableResult
293 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
294 try update { try saver.save(&$0, to: url) }
295 }
296
297 /// Called after every change to the document, typed or not.
298 public var onChange: (() -> Void)?
299
300 // MARK: - Commands
301
302 /// Called with messages commands report, such as why one couldn't run here.
303 public var onMessage: ((String) -> Void)?
304 /// Called with the pending prefix and what can follow it, and with nil when it ends.
305 /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
306 public var onModeChange: ((String?) -> Void)?
307 /// The selection moved.
308 public var onSelectionChange: ((NSRange) -> Void)?
309 var reportedMode: String?
310 public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
311 /// Called with `app.*` commands, which the app carries out.
312 public var onAppCommand: ((String) -> Void)?
313 /// `:e FILE`: the path as typed, for the app to open.
314 public var onOpenFile: ((String) -> Void)?
315 /// Called when a command asks a question; reply with the answer, or nil to cancel.
316 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
317 /// Runs work outside the text, such as a table recalculation in Emacs.
318 public var onExternal: ((ExternalRequest) -> Void)?
319 /// Tags used across the workspace, for tag completion.
320 public var knownTags: @Sendable () -> [String] = { [] }
321 /// Effects other than messages, for the app to carry out.
322 public var onEffect: ((Effect) -> Void)?
323
324 public var keymap: Keymap {
325 get { dispatcher.keymap }
326 set {
327 dispatcher.keymap = newValue
328 dispatcher.reset()
329 }
330 }
331
332 public var optionAsMeta: OptionAsMeta = [.left]
333 /// Org options commands follow.
334 public var options: EditingOptions = .org {
335 didSet {
336 if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
337 }
338 }
339 /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
340 /// `options`). Hidden markup shows on the caret's line, so it can be edited.
341 public var showMarkup = true {
342 didSet { if showMarkup != oldValue { restyleEverything() } }
343 }
344 /// Line numbers in a ruler beside the text.
345 public var showLineNumbers = true {
346 didSet { orgTextView?.showsLineNumbers = showLineNumbers }
347 }
348 var orgTextView: OrgTextView? { textView as? OrgTextView }
349
350 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
351 private var revealedLine: NSRange?
352 var dispatcher: KeyDispatcher
353 /// Evil-style editing, for modal keymaps such as Doom's.
354 public var modal = false {
355 didSet {
356 guard modal != oldValue else { return }
357 vim = Vim()
358 dispatcher.mode = modal ? vim.mode.keymapMode : nil
359 dispatcher.reset()
360 updateCursor()
361 }
362 }
363 var vim = Vim()
364 /// The text and caret when insert state began, to know what was typed for `.`.
365 var insertSnapshot: (text: String, caret: Int)?
366 /// The evil cursor in visual states, where the selection's start isn't it.
367 var visualCaret: Int?
368 /// Vim marks, mapped through edits.
369 var vimMarks: [Character: Int] = [:]
370 /// Jump positions, oldest first, mapped through edits; `jumpIndex` is where C-o and C-i are.
371 var jumpList: [Int] = []
372 var jumpIndex = 0
373 /// The register keys go into while `q` records, and its keys so far.
374 var recordingRegister: Character?
375 var recordedKeys: [KeyChord] = []
376 var macros: [Character: [KeyChord]] = [:]
377 var replayingMacro = 0
378 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
379 private(set) var markActive = false
380
381 public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
382 let selected = textView.selectedRange()
383 return EditContext(
384 revision: document.revision, text: document.text, tree: document.tree,
385 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
386 hidden: hidden.all, options: options, knownTags: knownTags,
387 lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
388 )
389 }
390
391 /// Offers a key press to the keymap. False lets the text system have it.
392 func handleKey(_ event: NSEvent) -> Bool {
393 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
394 if let handled = completionKey(chord) { return handled }
395 if modal { return handleModal(chord) }
396 switch dispatcher.feed(chord) {
397 case .pending(let keys):
398 let next = keymap.continuations(of: keys).map { item in
399 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
400 }
401 onKeysPending?(KeySequence.format(keys), next)
402 return true
403 case .cancelled:
404 onKeysPending?(nil, [])
405 onMessage?("Quit")
406 return true
407 case .undefined(let keys):
408 onKeysPending?(nil, [])
409 onMessage?("\(KeySequence.format(keys)) is undefined")
410 return true
411 case .unbound:
412 return electricPair(chord)
413 case .complete(let keys, let candidates):
414 if keys.count > 1 { onKeysPending?(nil, []) }
415 let context = context()
416 let runnable = candidates.first { binding in
417 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
418 }
419 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
420 run(binding.command)
421 return true
422 }
423 return keys.count == 1 && electricPair(chord)
424 }
425 }
426
427 /// `electric-pair-mode` for a key the keymap leaves to the text system: true when it
428 /// typed the key itself.
429 func electricPair(_ key: KeyChord) -> Bool {
430 guard isOrg, options.electricPair, key.modifiers.isEmpty, !textView.hasMarkedText(),
431 key.key == "DEL" || key.key == "RET" || ElectricPairKey.characters.contains(key.key) else { return false }
432 let command = ElectricPairKey(key: key.key)
433 guard command.applies(in: context()) else { return false }
434 _ = perform(command)
435 return true
436 }
437
438 private func applies(_ id: String, in context: EditContext) -> Bool {
439 if !isOrg, id.hasPrefix("org.") { return false }
440 return switch EditorCommands.command(id)?.action {
441 case .text(let command): command.applies(in: context)
442 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
443 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
444 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
445 case .edit, .mark, .app, .find: true
446 case nil: true
447 }
448 }
449
450 /// The last command run and the revision it left, for `last-command`.
451 private var lastCommand: (id: String, revision: Int)?
452
453 /// Runs a command by id, as a key, a menu item or the palette would.
454 public func run(_ id: String) {
455 defer { lastCommand = (id, document.revision) }
456 guard let command = EditorCommands.command(id) else {
457 onMessage?("Unknown command \(id)")
458 return
459 }
460 if !isOrg, id.hasPrefix("org.") {
461 onMessage?("Not an org file")
462 return
463 }
464 // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
465 if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
466 clearHighlights()
467 return
468 }
469 var keepMark = false
470 switch command.action {
471 case .text(let text):
472 perform(text)
473 case .view:
474 switch id {
475 case "org.cycle": cycleAtCaret()
476 case "org.cycle-global": cycleGlobal()
477 case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
478 case "org.toggle-inline-images": toggleImages()
479 case "editor.toggle-spell-check": toggleSpellCheck()
480 case "editor.complete": completeAtPoint()
481 case "editor.toggle-truncate-lines": toggleTruncateLines()
482 default: tableColumnWidth(id)
483 }
484 case .edit(let selector, let extending):
485 if markActive, let extending {
486 keepMark = true
487 textView.doCommand(by: NSSelectorFromString(extending))
488 } else {
489 textView.doCommand(by: NSSelectorFromString(selector))
490 }
491 case .find(let action):
492 let item = NSMenuItem()
493 item.tag = action.rawValue
494 textView.performTextFinderAction(item)
495 case .mark:
496 if id == "edit.set-mark" {
497 let caret = textView.selectedRange().location
498 textView.setSelectedRange(NSRange(location: caret, length: 0))
499 keepMark = true
500 onMessage?("Mark set")
501 } else {
502 let selected = textView.selectedRange()
503 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
504 onMessage?("Quit")
505 }
506 case .app:
507 onAppCommand?(id)
508 }
509 markActive = keepMark
510 }
511
512 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
513 /// they form one undo step and reach the document through the same path.
514 @discardableResult
515 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
516 let context = context(now: now, answers: answers)
517 let step = command.run(in: context)
518 switch step {
519 case .commit(let result):
520 guard textView.isEditable || result.edits.isEmpty else {
521 onMessage?("This file is read-only.")
522 return .failed("read-only")
523 }
524 commandEditing = true
525 applyEdits(result.edits)
526 commandEditing = false
527 if let selection = result.selection?.first {
528 if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
529 setCaret(selection.lowerBound)
530 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
531 }
532 for effect in result.effects {
533 switch effect {
534 case .message(let text): onMessage?(text)
535 case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
536 case .fold(let start):
537 var state = foldState
538 state.folds.insert(start)
539 setFolds(state)
540 default: onEffect?(effect)
541 }
542 }
543 case .failed(let message):
544 onMessage?(message)
545 case .external(let request):
546 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
547 case .prompt(let prompt):
548 onPrompt?(prompt) { [weak self] answer in
549 guard let self else { return }
550 guard let answer else {
551 self.onMessage?("Quit")
552 return
553 }
554 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
555 }
556 }
557 return step
558 }
559
560 // MARK: - Disk
561
562 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
563 /// its headings.
564 @discardableResult
565 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
566 update { $0.diskChanged(to: bytes) }
567 }
568
569 // MARK: - Folding
570
571 public var foldState: FoldState {
572 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
573 }
574
575 private var globalVisibility: GlobalVisibility?
576
577 public func setFolds(_ state: FoldState) {
578 setFolds(state, wrappers: nil)
579 }
580
581 /// `wrappers`, when given, holds every folded drawer and block.
582 private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
583 sparseHidden = nil
584 view.folds = state.folds
585 view.bodyFolds = state.bodyFolds
586 view = view.pruned(to: document.tree, wrappers: false)
587 // Found one by one, or all at once when there are many.
588 let found = wrappers ?? (state.wrapperFolds.count > 32
589 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
590 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
591 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
592 view.wrapperFolds = Set(wrapperHidden.keys)
593 updateHidden()
594 orgTextView?.redrawLineNumbers()
595 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
596 textView.needsDisplay = true
597 let caret = textView.selectedRange().location
598 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
599 }
600
601 /// What each folded drawer and block hides, by opening-line start; kept in step with
602 /// `view.wrapperFolds` and mapped through edits.
603 private var wrapperHidden: [Int: Range<Int>] = [:]
604
605 private func updateHidden() {
606 if let sparseHidden {
607 let ns = textView.string as NSString
608 // Headings whose next line is hidden show the fold ellipsis.
609 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
610 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
611 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
612 }
613 folded.set(Set(headings).union(view.wrapperFolds))
614 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
615 return
616 }
617 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
618 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
619 }
620
621 // MARK: - Sparse trees
622
623 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
624 /// fold change. Mapped through edits.
625 private var sparseHidden: [Range<Int>]?
626 /// Sparse tree matches, highlighted until the next edit or C-c C-c.
627 private var highlights: [Range<Int>] = []
628
629 private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
630 let text = textView.string
631 var state = foldState
632 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
633 state.wrapperFolds.remove(start)
634 }
635 sparseHidden = nil
636 setFolds(state)
637 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
638 self.highlights = highlights
639 updateHidden()
640 restyleOutsideEditing(0..<utf16Length)
641 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
642 orgTextView?.redrawLineNumbers()
643 textView.needsDisplay = true
644 let caret = textView.selectedRange().location
645 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
646 }
647
648 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
649 /// open, the others folded.
650 private func leaveSparseTree() {
651 guard let sparse = sparseHidden else { return }
652 sparseHidden = nil
653 let outline = Presentation.outline(document.tree)
654 let ns = textView.string as NSString
655 var open: Set<Int> = []
656 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
657 var parent = entry.parent
658 while let p = parent {
659 open.insert(outline[p].start)
660 parent = outline[p].parent
661 }
662 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
663 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
664 }
665 var state = foldState
666 state.folds = Set(outline.map(\.start)).subtracting(open)
667 state.bodyFolds = []
668 setFolds(state)
669 }
670
671 private func clearHighlights() {
672 guard !highlights.isEmpty else { return }
673 let old = highlights
674 highlights = []
675 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
676 }
677
678 private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
679 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
680 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
681 }
682 }
683
684 // MARK: - STARTUP display
685
686 /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
687 private var indented = true
688 /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
689 private var hideStars = false
690
691 // MARK: - Inline images
692
693 /// `org-toggle-inline-images`: lines that are only an image link show the image.
694 public private(set) var showsImages = false
695 /// The file's folder, for relative image paths.
696 public var baseDirectory: URL? {
697 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
698 }
699 private static let imageCache = NSCache<NSString, NSImage>()
700
701 private func toggleImages() {
702 showsImages.toggle()
703 refreshImages()
704 if showsImages {
705 let ns = textView.string as NSString
706 var count = 0
707 var offset = 0
708 while offset < ns.length {
709 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
710 if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
711 offset = NSMaxRange(line)
712 }
713 onMessage?("\(count) images displayed inline")
714 } else {
715 onMessage?("Inline image display turned off")
716 }
717 }
718
719 private func refreshImages() {
720 restyleOutsideEditing(0..<utf16Length)
721 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
722 textView.needsDisplay = true
723 }
724
725 private func loadImage(_ path: String) -> NSImage? {
726 let expanded = (path as NSString).expandingTildeInPath
727 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
728 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
729 let key = "\(url.path)|\(modified)" as NSString
730 if let cached = Self.imageCache.object(forKey: key) { return cached }
731 guard let image = NSImage(contentsOf: url) else { return nil }
732 Self.imageCache.setObject(image, forKey: key)
733 return image
734 }
735
736 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
737 /// on the line.
738 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
739 guard showsImages, isOrg else { return }
740 let text = storage.string as NSString
741 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
742 var location = range.lowerBound
743 while location < range.upperBound, location < text.length {
744 let line = text.lineRange(for: NSRange(location: location, length: 0))
745 location = NSMaxRange(line)
746 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
747 var width = image.width.map(CGFloat.init) ?? picture.size.width
748 width = min(width, maxWidth)
749 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
750 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
751 // Invisible, keeping the line's height, so line numbers stay apart.
752 if line.location != revealed.location, content.length > 0 {
753 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
754 }
755 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
756 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
757 // The image sits where the line is; the spacing makes room for the rest of it.
758 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
759 storage.addAttribute(.paragraphStyle, value: style, range: line)
760 }
761 }
762
763 // MARK: - Narrowing
764
765 /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
766 /// rest is hidden until `widen`. Mapped through edits.
767 public private(set) var narrowed: Range<Int>?
768
769 private func narrow(_ id: String) {
770 let caret = textView.selectedRange().location
771 do {
772 switch id {
773 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
774 // `org-toggle-narrow-to-subtree`.
775 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
776 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
777 default: narrowed = nil
778 }
779 } catch let failure as Narrowing.Failure {
780 onMessage?(failure.message)
781 return
782 } catch {
783 return
784 }
785 updateHidden()
786 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
787 orgTextView?.redrawLineNumbers()
788 textView.needsDisplay = true
789 if let narrowed {
790 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
791 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
792 } else {
793 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
794 }
795 }
796
797 /// What narrowing hides: the text before the region, and the lines after it.
798 private var narrowHidden: [Range<Int>] {
799 guard let narrowed else { return [] }
800 let length = utf16Length
801 var ranges: [Range<Int>] = []
802 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
803 let ns = textView.string as NSString
804 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
805 if tail < length { ranges.append(tail..<length) }
806 return ranges
807 }
808
809 // MARK: - Shrunk table columns
810
811 /// Narrowed table columns (`org-table-shrink`): by table start, each column's segments.
812 /// Recomputed as the text changes; typing into one widens its column again, as editing
813 /// org's overlays deletes them. Commands' edits keep columns narrow, as `org-table-align`
814 /// shrinks them again.
815 private var shrunk: [Int: [Int: [TableShrink.Segment]]] = [:]
816 private var commandEditing = false
817
818 /// Narrows `columns` of `table` and widens its others.
819 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
820 let text = textView.string
821 let segments = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
822 shrunk[table.lowerBound] = segments.isEmpty ? nil : segments
823 restyleOutsideEditing(table)
824 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
825 textView.needsDisplay = true
826 }
827
828 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
829 /// `expand` for `org-table-expand`.
830 private func tableColumnWidth(_ id: String) {
831 let caret = textView.selectedRange().location
832 let text = textView.string
833 guard let table = TableShrink.table(at: caret, in: text) else {
834 onMessage?("Not in a table")
835 return
836 }
837 let current = shrunk[table.lowerBound].map { Array($0.keys) } ?? []
838 switch id {
839 case "org.table.shrink": setShrunk(TableShrink.cookieColumns(table, in: text), in: table)
840 case "org.table.expand": setShrunk([], in: table)
841 default:
842 if let column = TableShrink.column(at: caret, in: text) {
843 setShrunk(Array(Set(current).symmetricDifference([column])), in: table)
844 return
845 }
846 let line = (text as NSString).lineRange(for: NSRange(location: caret, length: 0))
847 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
848 guard let self, let answer else { return }
849 self.setShrunk(Array(Set(current).symmetricDifference(TableShrink.columns(answer, max: line.length / 2))), in: table)
850 }
851 }
852 }
853
854 /// `#+STARTUP: shrink`: every table's columns with width cookies start narrow.
855 private func shrinkAtStartup() {
856 guard Presentation.startupOptions(document.tree).contains(where: { $0.lowercased() == "shrink" }) else { return }
857 let text = textView.string
858 var offset = 0
859 let ns = text as NSString
860 while offset < ns.length {
861 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
862 defer { offset = max(NSMaxRange(line), offset + 1) }
863 guard ns.substring(with: line).range(of: "^[ \\t]*\\|", options: .regularExpression) != nil,
864 let table = TableShrink.table(at: line.location, in: text) else { continue }
865 let columns = TableShrink.cookieColumns(table, in: text)
866 if !columns.isEmpty { shrunk[table.lowerBound] = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) }) }
867 offset = table.upperBound
868 }
869 }
870
871 /// Moves shrunk columns through `edit`; returns the tables to restyle.
872 private func mapShrunk(through edit: TextEdit) -> [Range<Int>] {
873 guard !shrunk.isEmpty else { return [] }
874 let text = textView.string
875 let delta = edit.replacement.utf16.count - edit.range.count
876 var mapped: [Int: [Int: [TableShrink.Segment]]] = [:]
877 var tables: [Range<Int>] = []
878 for (start, columns) in shrunk {
879 let kept = columns.filter { _, segments in
880 commandEditing || !segments.contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
881 }.keys
882 let touched = columns.values.joined().contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
883 let newStart = start < edit.range.lowerBound ? start : start >= edit.range.upperBound ? start + delta : edit.range.lowerBound
884 guard let table = TableShrink.table(at: min(newStart, max(0, text.utf16.count - 1)), in: text) else { continue }
885 if touched || kept.count != columns.count { tables.append(table) }
886 guard !kept.isEmpty else { continue }
887 mapped[table.lowerBound] = Dictionary(uniqueKeysWithValues: kept.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
888 }
889 shrunk = mapped
890 return tables
891 }
892
893 /// Hides each shrunk segment's text and draws its display where the text was.
894 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
895 guard !shrunk.isEmpty else { return }
896 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
897 for segment in shrunk.values.flatMap({ $0.values.joined() }) where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
898 let r = segment.range
899 let shown = segment.display.count
900 let kept = min(shown, r.count)
901 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
902 guard kept > 0 else { continue }
903 let visible = NSRange(location: r.upperBound - kept, length: kept)
904 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
905 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
906 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
907 }
908 }
909
910 /// Moves drawer and block folds through `edit`, checking again only those near it.
911 private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
912 guard !wrapperHidden.isEmpty else { return }
913 var mapped: [Int: Range<Int>] = [:]
914 let entries = Array(wrapperHidden)
915 // One pass maps every start and range.
916 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
917 for i in entries.indices {
918 let newStart = moved[2 * i].lowerBound
919 let newRange = moved[2 * i + 1]
920 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
921 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
922 } else {
923 mapped[newStart] = newRange
924 }
925 }
926 wrapperHidden = mapped
927 view.wrapperFolds = Set(mapped.keys)
928 }
929
930 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
931 /// cycles folded, children, subtree. Returns false elsewhere.
932 @discardableResult
933 public func cycleAtCaret() -> Bool {
934 leaveSparseTree()
935 let caret = textView.selectedRange().location
936 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
937 setFolds(state)
938 // Off a closing line that folding hid, to the opening line, as org does.
939 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
940 return true
941 }
942
943 /// Shift-TAB: overview, contents, show all.
944 public func cycleGlobal() {
945 leaveSparseTree()
946 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
947 globalVisibility = visibility
948 setFolds(state)
949 }
950
951 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
952 public func reveal(_ offset: Int) {
953 let target = max(0, min(offset, utf16Length))
954 if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
955 unfold(around: target)
956 setCaret(target)
957 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
958 }
959
960 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
961 func unfold(around offset: Int) {
962 leaveSparseTree()
963 var state = foldState
964 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
965 state.folds.remove(entry.start)
966 state.bodyFolds.remove(entry.start)
967 }
968 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
969 state.wrapperFolds.remove(start)
970 }
971 guard state != foldState else { return }
972 setFolds(state)
973 }
974
975 /// Applies edits through the text view as one undo step, not merged with typing around it.
976 func applyEdits(_ edits: [TextEdit]) {
977 guard !edits.isEmpty, let storage = textView.textStorage else { return }
978 textView.breakUndoCoalescing()
979 textView.undoManager?.beginUndoGrouping()
980 // By lines, so a fold between two changes stays.
981 let text = storage.string
982 for edit in edits.flatMap({ splitByLines($0, in: text) }).sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
983 let range = NSRange(edit.range)
984 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
985 storage.replaceCharacters(in: range, with: edit.replacement)
986 textView.didChangeText()
987 }
988 textView.undoManager?.endUndoGrouping()
989 textView.breakUndoCoalescing()
990 }
991
992 func setCaret(_ offset: Int) {
993 let clamped = max(0, min(offset, utf16Length))
994 previousSelection = clamped
995 textView.setSelectedRange(NSRange(location: clamped, length: 0))
996 }
997
998 // MARK: - Styling
999
1000 private func restyleOutsideEditing(_ range: Range<Int>) {
1001 guard let storage = textView.textStorage else { return }
1002 storage.beginEditing()
1003 restyle(range, in: storage)
1004 storage.endEditing()
1005 }
1006
1007 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
1008 /// attribute changes are allowed and characters must not change.
1009 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
1010 guard !range.isEmpty else { return }
1011 let whole = NSRange(range)
1012 storage.setAttributes(theme.base, range: whole)
1013 guard isOrg else {
1014 for run in plainRuns() where run.range.overlaps(range) {
1015 guard let clipped = clip(run.range, to: range) else { continue }
1016 theme.apply(.syntax(run.category), to: storage, range: clipped)
1017 }
1018 return
1019 }
1020 let text = storage.string as NSString
1021 for run in Presentation.indents(document.tree, in: range) where indented {
1022 guard let clipped = clip(run.range, to: range) else { continue }
1023 guard run.firstLine == run.wrapped else {
1024 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
1025 continue
1026 }
1027 // Body lines wrap under their own text: past leading blanks, and past a list bullet
1028 // and checkbox, as adaptive-wrap does in Emacs.
1029 var location = clipped.location
1030 while location < NSMaxRange(clipped) {
1031 let line = text.lineRange(for: NSRange(location: location, length: 0))
1032 let hanging = Self.hangingColumns(text.substring(with: line))
1033 let lineRange = NSIntersectionRange(line, clipped)
1034 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
1035 location = NSMaxRange(line)
1036 }
1037 }
1038 let revealed = caretLine
1039 var scriptExclusions: [Range<Int>] = []
1040 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
1041 guard let clipped = clip(run.range, to: range) else { continue }
1042 if run.role == .leadingStars, !indented, !hideStars { continue }
1043 if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
1044 storage.addAttributes(theme.hidden, range: clipped)
1045 } else {
1046 theme.apply(run.role, to: storage, range: clipped)
1047 }
1048 switch run.role {
1049 case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
1050 default: break
1051 }
1052 }
1053 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
1054 applyShrunk(range, in: storage)
1055 applyHighlights(range, in: storage)
1056 applyImages(range, in: storage, revealed: revealed)
1057 }
1058
1059 /// `org-pretty-entities`: entities drawn as their character over the entity's last
1060 /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
1061 /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
1062 /// keywords, as `org-raise-scripts` leaves them.
1063 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
1064 let text = storage.string as NSString
1065 var location = range.lowerBound
1066 while location < range.upperBound {
1067 let line = text.lineRange(for: NSRange(location: location, length: 0))
1068 guard line.length > 0 else { break }
1069 location = NSMaxRange(line)
1070 if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
1071 let content = text.substring(with: line)
1072 if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
1073 for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
1074 switch run {
1075 case .entity(let r, let display):
1076 let start = line.location + r.lowerBound
1077 let last = line.location + r.upperBound - 1
1078 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
1079 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
1080 case .script(let markers, let body, let superscript):
1081 let bodyStart = line.location + body.lowerBound
1082 if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
1083 for marker in markers {
1084 storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
1085 }
1086 let size = theme.font.pointSize
1087 storage.addAttributes([
1088 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
1089 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
1090 ], range: NSRange(location: bodyStart, length: body.count))
1091 }
1092 }
1093 }
1094 }
1095
1096 /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
1097 /// markers only when Emacs hides them too.
1098 private func hides(_ role: StyleRole) -> Bool {
1099 switch role {
1100 case .linkMarkup: true
1101 case .markup: options.hideEmphasisMarkers
1102 default: false
1103 }
1104 }
1105
1106 /// Moving to another line shows its markup and hides the last one's.
1107 private func revealCaretLine() {
1108 guard !showMarkup, isOrg else { return }
1109 let line = caretLine
1110 guard line != revealedLine else { return }
1111 let text = textView.string as NSString
1112 // The old line may have moved with edits since; restyle the line now at its start.
1113 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
1114 revealedLine = line
1115 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
1116 restyleOutsideEditing(range.location..<NSMaxRange(range))
1117 }
1118 }
1119
1120 /// Code highlights for the whole file in plain mode.
1121 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
1122 guard case .plain(let language?) = mode, let highlighter else { return [] }
1123 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
1124 let runs = highlighter.highlights(language: language, code: document.text)
1125 codeRuns = (document.revision, runs)
1126 return runs
1127 }
1128
1129 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
1130 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
1131 if let style = paragraphStyles[key] { return style }
1132 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
1133 paragraphStyles[key] = style
1134 return style
1135 }
1136
1137 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
1138 let clipped = run.clamped(to: range)
1139 return clipped.isEmpty ? nil : NSRange(clipped)
1140 }
1141
1142 /// The region an edit affects in one version of the tree: inside the innermost section
1143 /// holding the edited lines (plus the line after), every element that overlaps them or the
1144 /// line on either side. A changed heading line, or an added or removed heading, widens it
1145 /// to that section's whole own body. Run on the old and the new tree, the union covers
1146 /// elements that grew and elements that shrank.
1147 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
1148 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
1149 let lineRange = lines.location..<(lines.location + lines.length)
1150 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
1151 var container = tree.root
1152 while let child = container.child(containing: lineRange.lowerBound),
1153 child.kind == .section || child.kind == .zerothSection,
1154 lineRange.upperBound <= child.range.upperBound {
1155 container = child
1156 }
1157 var lower = lineRange.lowerBound
1158 var upper = lineRange.upperBound
1159 // Tables and lists carry no styling of their own, so inside them only the rows or
1160 // items around the edit change, however large they are.
1161 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1162 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1163 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1164 let inner = overlapping(node.children(overlapping: around))
1165 return inner.isEmpty ? [node] : inner
1166 }
1167 }
1168 for child in overlapping(container.children(overlapping: around)) {
1169 lower = min(lower, child.range.lowerBound)
1170 upper = max(upper, child.range.upperBound)
1171 }
1172 let heading = container.firstChild(.heading)
1173 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1174 lower = min(lower, container.range.lowerBound)
1175 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1176 }
1177 return lower..<min(upper, text.length)
1178 }
1179
1180 // MARK: - Editing
1181
1182 private var blockCheck: DispatchWorkItem?
1183
1184 /// Looks for blocks over the whole file once typing pauses, catching what moving the
1185 /// ranges can't see (a block's end found far away).
1186 private func scheduleBlockCheck() {
1187 blockCheck?.cancel()
1188 let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
1189 blockCheck = work
1190 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
1191 }
1192
1193 func settleBlocks() {
1194 blockCheck?.cancel()
1195 guard isOrg else { return }
1196 let blocks = Presentation.shadedBlocks(document.tree)
1197 guard blocks != shaded.all else { return }
1198 shaded.set(blocks)
1199 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1200 }
1201
1202 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
1203 /// them), hold a block delimiter or a fixed-width line.
1204 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
1205 let start = min(range.lowerBound, text.length)
1206 let end = min(range.upperBound + 1, text.length)
1207 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
1208 let content = text.substring(with: lines)
1209 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
1210 }
1211
1212 fileprivate func storageEdited(range: NSRange, delta: Int) {
1213 guard !isLoading, let storage = textView.textStorage else { return }
1214 markActive = false
1215 let clock = ContinuousClock()
1216 let start = clock.now
1217 let replacement = (storage.string as NSString).substring(with: range)
1218 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
1219 let oldText = document.text as NSString
1220 let newText = storage.string as NSString
1221 let newEnd = edit.range.lowerBound + replacement.utf16.count
1222 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
1223 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
1224 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
1225 do {
1226 try document.apply([edit], baseRevision: document.revision)
1227 } catch {
1228 assertionFailure("text view and document disagree: \(error)")
1229 return
1230 }
1231 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
1232 // edited line when the edit reaches into unstyled text.
1233 if styledUpTo >= edit.range.upperBound {
1234 styledUpTo += edit.replacement.utf16.count - edit.range.count
1235 } else if styledUpTo > edit.range.lowerBound {
1236 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
1237 }
1238 let oldHidden = hidden.all
1239 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
1240 let delta = edit.replacement.utf16.count - edit.range.count
1241 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
1242 view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
1243 mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
1244 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
1245 mapVimPositions(through: edit)
1246 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
1247 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
1248 highlights = []
1249 updateHidden()
1250 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
1251 for table in mapShrunk(through: edit) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
1252 for range in oldHighlights where range.upperBound <= newText.length {
1253 let lines = newText.lineRange(for: NSRange(range))
1254 restyle(lines.location..<NSMaxRange(lines), in: storage)
1255 }
1256 let oldShaded = shaded.all
1257 if isOrg {
1258 // Walking the tree for blocks costs more than typing; only an edit on a line that
1259 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
1260 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
1261 shaded.set(Presentation.shadedBlocks(document.tree))
1262 } else {
1263 shaded.set(oldShaded.map { mapRange($0, through: edit) })
1264 }
1265 scheduleBlockCheck()
1266 }
1267 if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
1268 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
1269 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1270 }
1271 onEditTiming?(clock.now - start)
1272 let lineCount = lines.lineCount
1273 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
1274 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
1275 orgTextView?.redrawLineNumbers()
1276 onChange?()
1277 }
1278
1279 /// Columns a wrapped continuation of `line` should start past the line's own start.
1280 nonisolated static func hangingColumns(_ line: String) -> Int {
1281 var columns = 0
1282 var rest = Substring(line)
1283 while let c = rest.first, c == " " || c == "\t" {
1284 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
1285 rest = rest.dropFirst()
1286 }
1287 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
1288 var bullet = 0
1289 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
1290 bullet = 1
1291 } else {
1292 let digits = rest.prefix { $0.isASCII && $0.isNumber }
1293 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
1294 bullet = digits.count + 1
1295 }
1296 }
1297 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
1298 columns += bullet + 1
1299 let afterBullet = rest.dropFirst(bullet + 1)
1300 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
1301 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
1302 columns += 4
1303 }
1304 return columns
1305 }
1306
1307 /// Whether a heading line touches `start..<end` or starts right after it, where joining
1308 /// lines could take it away.
1309 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1310 let length = min(end + 1, text.length) - start
1311 guard length >= 0 else { return false }
1312 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1313 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1314 let stars = line.prefix { $0 == "*" }
1315 let after = line.dropFirst(stars.count)
1316 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1317 }
1318 }
1319
1320 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1321 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1322 return mapped
1323 }
1324
1325 /// Shaded block lines the old or new selection covers are drawn again, as they draw the
1326 /// selection over their band.
1327 private func redrawShadedSelection(_ selection: NSRange) {
1328 defer { previousSelectionRange = selection }
1329 redrawShaded([previousSelectionRange, selection])
1330 }
1331
1332 private func redrawShaded(_ ranges: [NSRange]) {
1333 guard let manager = textLayoutManager.textContentManager else { return }
1334 for old in ranges where old.length > 0 {
1335 for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
1336 let lower = max(block.lowerBound, old.location)
1337 let upper = min(block.upperBound, NSMaxRange(old))
1338 guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
1339 let end = manager.location(start, offsetBy: upper - lower),
1340 let range = NSTextRange(location: start, end: end) else { continue }
1341 textLayoutManager.invalidateLayout(for: range)
1342 }
1343 }
1344 }
1345
1346 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1347 /// back jumps to the end of the heading line.
1348 func selectionChanged() {
1349 let selection = textView.selectedRange()
1350 defer { previousSelection = selection.location }
1351 redrawShadedSelection(selection)
1352 onSelectionChange?(selection)
1353 revealCaretLine()
1354 orgTextView?.redrawLineNumbers()
1355 // Narrowing keeps the caret in the region.
1356 if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
1357 setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
1358 return
1359 }
1360 // A selection reaching into folded text, as a find match does, unfolds it.
1361 if selection.length > 0 {
1362 if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1363 unfold(around: selection.location)
1364 unfold(around: NSMaxRange(selection) - 1)
1365 }
1366 return
1367 }
1368 guard let range = hidden.containing(selection.location) else { return }
1369 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1370 }
1371}
1372
1373extension OrgEditor: DocumentBuffer {
1374 /// The selected text, for capture's `%i`.
1375 public var selectedText: String {
1376 let range = textView.selectedRange()
1377 guard range.length > 0 else { return "" }
1378 return (textView.string as NSString).substring(with: range)
1379 }
1380
1381 public var selection: [Range<Int>] {
1382 let selected = textView.selectedRange()
1383 return [selected.location..<NSMaxRange(selected)]
1384 }
1385
1386 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1387 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1388 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1389 let before = document.text
1390 let defaultsBefore = document.defaults
1391 let selected = textView.selectedRange()
1392 let result = try change(&document)
1393 if document.text != before {
1394 let edits = lineEdits(from: before, to: document.text)
1395 var state = view
1396 state.selection = [selected.location..<NSMaxRange(selected)]
1397 let mapped = state.mapped(through: edits)
1398 load(document.text)
1399 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1400 let selection = mapped.selection[0]
1401 setCaret(selection.lowerBound)
1402 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1403 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1404 textView.undoManager?.removeAllActions(withTarget: textView)
1405 } else if document.defaults != defaultsBefore {
1406 // New settings for the same text: TODO keywords may color differently.
1407 restyleEverything()
1408 }
1409 onChange?()
1410 return result
1411 }
1412}
1413
1414extension OrgEditor: NSTextStorageDelegate {
1415 public nonisolated func textStorage(
1416 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1417 ) {
1418 MainActor.assumeIsolated { storageGeneration += 1 }
1419 guard editedMask.contains(.editedCharacters) else { return }
1420 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1421 }
1422}
1423
1424extension OrgEditor: NSTextContentStorageDelegate {
1425 /// Folded text isn't enumerated, so it isn't laid out or drawn.
1426 public nonisolated func textContentManager(
1427 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1428 ) -> Bool {
1429 guard let range = textElement.elementRange else { return true }
1430 let documentStart = textContentManager.documentRange.location
1431 let start = textContentManager.offset(from: documentStart, to: range.location)
1432 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1433 return !hidden.covers(start, end)
1434 }
1435}
1436
1437extension OrgEditor: NSTextLayoutManagerDelegate {
1438 public nonisolated func textLayoutManager(
1439 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1440 ) -> NSTextLayoutFragment {
1441 let range = textElement.elementRange
1442 if let range, let manager = textLayoutManager.textContentManager {
1443 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1444 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1445 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1446 if let paragraph = textElement as? NSTextParagraph, ImageFragment.image(paragraph.attributedString) != nil {
1447 return ImageFragment(textElement: textElement, range: range)
1448 }
1449 if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1450 return EntityFragment(textElement: textElement, range: range)
1451 }
1452 }
1453 return NSTextLayoutFragment(textElement: textElement, range: range)
1454 }
1455}
1456
1457/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1458/// `org-block` face.
1459final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1460 private var band: CGRect {
1461 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1462 // Not under the empty line TextKit adds after a final newline.
1463 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1464 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1465 }
1466
1467 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1468
1469 override func draw(at point: CGPoint, in context: CGContext) {
1470 context.saveGState()
1471 context.setFillColor(Theme.blockBackground.cgColor)
1472 context.fill(band.offsetBy(dx: point.x, dy: point.y))
1473 // The band covers the view's selection highlight, so the selected text is drawn on it,
1474 // in the color the view uses: the theme's when focused, the system's muted one when not.
1475 if let manager = textLayoutManager {
1476 let active = Theme.focusedLayouts.contains(ObjectIdentifier(manager))
1477 context.setFillColor((active ? Theme.selection : NSColor.unemphasizedSelectedTextBackgroundColor).cgColor)
1478 let single = textLineFragments.count == 1
1479 for selection in manager.textSelections {
1480 for range in selection.textRanges where !range.isEmpty {
1481 guard let part = range.intersection(rangeInElement), !part.isEmpty else { continue }
1482 manager.enumerateTextSegments(in: part, type: .selection, options: [.rangeNotRequired]) { _, frame, _, _ in
1483 var rect = frame.offsetBy(dx: point.x - self.layoutFragmentFrame.minX, dy: point.y - self.layoutFragmentFrame.minY)
1484 // A one-line fragment's selection covers its band, leaving no gap to the next line.
1485 if single { rect = CGRect(x: rect.minX, y: point.y, width: rect.width, height: self.band.height) }
1486 context.fill(rect)
1487 return true
1488 }
1489 }
1490 }
1491 }
1492 context.restoreGState()
1493 super.draw(at: point, in: context)
1494 }
1495}
1496
1497extension NSAttributedString.Key {
1498 /// The character an entity shows as, on the entity's last character.
1499 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1500 /// The image an image link's line shows under it.
1501 static let orgImage = NSAttributedString.Key("OrgImage")
1502}
1503
1504final class InlineImageBox: NSObject, @unchecked Sendable {
1505 let image: NSImage
1506 let size: CGSize
1507 init(image: NSImage, size: CGSize) {
1508 self.image = image
1509 self.size = size
1510 }
1511}
1512
1513/// An image link's line drawn as the image, with the paragraph spacing making room for its
1514/// height.
1515final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
1516 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1517 var found: InlineImageBox?
1518 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1519 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1520 }
1521 return found
1522 }
1523
1524 private var frame: CGRect? {
1525 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
1526 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
1527 }
1528
1529 override var renderingSurfaceBounds: CGRect {
1530 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
1531 }
1532
1533 override func draw(at point: CGPoint, in context: CGContext) {
1534 super.draw(at: point, in: context)
1535 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
1536 NSGraphicsContext.saveGraphicsState()
1537 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1538 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
1539 NSGraphicsContext.restoreGraphicsState()
1540 }
1541}
1542
1543/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1544/// (now invisible) character sits, so it takes one column as in Emacs.
1545final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1546 static func hasEntities(_ string: NSAttributedString) -> Bool {
1547 var found = false
1548 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1549 if value != nil { found = true; stop.pointee = true }
1550 }
1551 return found
1552 }
1553
1554 override func draw(at point: CGPoint, in context: CGContext) {
1555 super.draw(at: point, in: context)
1556 Self.drawEntities(of: self, at: point, in: context)
1557 }
1558
1559 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1560 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1561 NSGraphicsContext.saveGraphicsState()
1562 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1563 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1564 guard let display = value as? String,
1565 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1566 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1567 attributes[.foregroundColor] = NSColor.textColor
1568 attributes[.orgEntityDisplay] = nil
1569 let x = line.locationForCharacter(at: range.location).x
1570 let bounds = line.typographicBounds
1571 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1572 }
1573 NSGraphicsContext.restoreGraphicsState()
1574 }
1575}
1576
1577/// A heading line drawn with an ellipsis after it, like org's folded headings.
1578final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1579 override func draw(at point: CGPoint, in context: CGContext) {
1580 super.draw(at: point, in: context)
1581 EntityFragment.drawEntities(of: self, at: point, in: context)
1582 guard let line = textLineFragments.first else { return }
1583 let bounds = line.typographicBounds
1584 let ellipsis = NSAttributedString(string: " …", attributes: [
1585 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1586 .foregroundColor: NSColor.secondaryLabelColor,
1587 ])
1588 NSGraphicsContext.saveGraphicsState()
1589 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1590 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1591 NSGraphicsContext.restoreGraphicsState()
1592 }
1593
1594 override var renderingSurfaceBounds: CGRect {
1595 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1596 }
1597}
1598#endif