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