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