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