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