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