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