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