Sources/OrgEditorAppKit/OrgEditor.swift
1357 lines · 65517 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 // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
396 if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
397 clearHighlights()
398 return
399 }
400 var keepMark = false
401 switch command.action {
402 case .text(let text):
403 perform(text)
404 case .view:
405 switch id {
406 case "org.cycle": cycleAtCaret()
407 case "org.cycle-global": cycleGlobal()
408 case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
409 default: tableColumnWidth(id)
410 }
411 case .edit(let selector, let extending):
412 if markActive, let extending {
413 keepMark = true
414 textView.doCommand(by: NSSelectorFromString(extending))
415 } else {
416 textView.doCommand(by: NSSelectorFromString(selector))
417 }
418 case .find(let action):
419 let item = NSMenuItem()
420 item.tag = action.rawValue
421 textView.performTextFinderAction(item)
422 case .mark:
423 if id == "edit.set-mark" {
424 let caret = textView.selectedRange().location
425 textView.setSelectedRange(NSRange(location: caret, length: 0))
426 keepMark = true
427 onMessage?("Mark set")
428 } else {
429 let selected = textView.selectedRange()
430 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
431 onMessage?("Quit")
432 }
433 case .app:
434 onAppCommand?(id)
435 }
436 markActive = keepMark
437 }
438
439 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
440 /// they form one undo step and reach the document through the same path.
441 @discardableResult
442 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
443 let context = context(now: now, answers: answers)
444 let step = command.run(in: context)
445 switch step {
446 case .commit(let result):
447 guard textView.isEditable || result.edits.isEmpty else {
448 onMessage?("This file is read-only.")
449 return .failed("read-only")
450 }
451 commandEditing = true
452 applyEdits(result.edits)
453 commandEditing = false
454 if let selection = result.selection?.first {
455 if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
456 setCaret(selection.lowerBound)
457 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
458 }
459 for effect in result.effects {
460 switch effect {
461 case .message(let text): onMessage?(text)
462 case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
463 case .fold(let start):
464 var state = foldState
465 state.folds.insert(start)
466 setFolds(state)
467 default: onEffect?(effect)
468 }
469 }
470 case .failed(let message):
471 onMessage?(message)
472 case .external(let request):
473 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
474 case .prompt(let prompt):
475 onPrompt?(prompt) { [weak self] answer in
476 guard let self else { return }
477 guard let answer else {
478 self.onMessage?("Quit")
479 return
480 }
481 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
482 }
483 }
484 return step
485 }
486
487 // MARK: - Disk
488
489 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
490 /// its headings.
491 @discardableResult
492 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
493 update { $0.diskChanged(to: bytes) }
494 }
495
496 // MARK: - Folding
497
498 public var foldState: FoldState {
499 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
500 }
501
502 private var globalVisibility: GlobalVisibility?
503
504 public func setFolds(_ state: FoldState) {
505 setFolds(state, wrappers: nil)
506 }
507
508 /// `wrappers`, when given, holds every folded drawer and block.
509 private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
510 sparseHidden = nil
511 view.folds = state.folds
512 view.bodyFolds = state.bodyFolds
513 view = view.pruned(to: document.tree, wrappers: false)
514 // Found one by one, or all at once when there are many.
515 let found = wrappers ?? (state.wrapperFolds.count > 32
516 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
517 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
518 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
519 view.wrapperFolds = Set(wrapperHidden.keys)
520 updateHidden()
521 orgTextView?.redrawLineNumbers()
522 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
523 textView.needsDisplay = true
524 let caret = textView.selectedRange().location
525 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
526 }
527
528 /// What each folded drawer and block hides, by opening-line start; kept in step with
529 /// `view.wrapperFolds` and mapped through edits.
530 private var wrapperHidden: [Int: Range<Int>] = [:]
531
532 private func updateHidden() {
533 if let sparseHidden {
534 let ns = textView.string as NSString
535 // Headings whose next line is hidden show the fold ellipsis.
536 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
537 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
538 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
539 }
540 folded.set(Set(headings).union(view.wrapperFolds))
541 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
542 return
543 }
544 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
545 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
546 }
547
548 // MARK: - Sparse trees
549
550 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
551 /// fold change. Mapped through edits.
552 private var sparseHidden: [Range<Int>]?
553 /// Sparse tree matches, highlighted until the next edit or C-c C-c.
554 private var highlights: [Range<Int>] = []
555
556 private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
557 let text = textView.string
558 var state = foldState
559 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
560 state.wrapperFolds.remove(start)
561 }
562 sparseHidden = nil
563 setFolds(state)
564 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
565 self.highlights = highlights
566 updateHidden()
567 restyleOutsideEditing(0..<utf16Length)
568 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
569 orgTextView?.redrawLineNumbers()
570 textView.needsDisplay = true
571 let caret = textView.selectedRange().location
572 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
573 }
574
575 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
576 /// open, the others folded.
577 private func leaveSparseTree() {
578 guard let sparse = sparseHidden else { return }
579 sparseHidden = nil
580 let outline = Presentation.outline(document.tree)
581 let ns = textView.string as NSString
582 var open: Set<Int> = []
583 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
584 var parent = entry.parent
585 while let p = parent {
586 open.insert(outline[p].start)
587 parent = outline[p].parent
588 }
589 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
590 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
591 }
592 var state = foldState
593 state.folds = Set(outline.map(\.start)).subtracting(open)
594 state.bodyFolds = []
595 setFolds(state)
596 }
597
598 private func clearHighlights() {
599 guard !highlights.isEmpty else { return }
600 let old = highlights
601 highlights = []
602 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
603 }
604
605 private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
606 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
607 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
608 }
609 }
610
611 // MARK: - Narrowing
612
613 /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
614 /// rest is hidden until `widen`. Mapped through edits.
615 public private(set) var narrowed: Range<Int>?
616
617 private func narrow(_ id: String) {
618 let caret = textView.selectedRange().location
619 do {
620 switch id {
621 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
622 // `org-toggle-narrow-to-subtree`.
623 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
624 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
625 default: narrowed = nil
626 }
627 } catch let failure as Narrowing.Failure {
628 onMessage?(failure.message)
629 return
630 } catch {
631 return
632 }
633 updateHidden()
634 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
635 orgTextView?.redrawLineNumbers()
636 textView.needsDisplay = true
637 if let narrowed {
638 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
639 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
640 } else {
641 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
642 }
643 }
644
645 /// What narrowing hides: the text before the region, and the lines after it.
646 private var narrowHidden: [Range<Int>] {
647 guard let narrowed else { return [] }
648 let length = utf16Length
649 var ranges: [Range<Int>] = []
650 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
651 let ns = textView.string as NSString
652 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
653 if tail < length { ranges.append(tail..<length) }
654 return ranges
655 }
656
657 // MARK: - Shrunk table columns
658
659 /// Narrowed table columns (`org-table-shrink`): by table start, each column's segments.
660 /// Recomputed as the text changes; typing into one widens its column again, as editing
661 /// org's overlays deletes them. Commands' edits keep columns narrow, as `org-table-align`
662 /// shrinks them again.
663 private var shrunk: [Int: [Int: [TableShrink.Segment]]] = [:]
664 private var commandEditing = false
665
666 /// Narrows `columns` of `table` and widens its others.
667 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
668 let text = textView.string
669 let segments = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
670 shrunk[table.lowerBound] = segments.isEmpty ? nil : segments
671 restyleOutsideEditing(table)
672 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
673 textView.needsDisplay = true
674 }
675
676 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
677 /// `expand` for `org-table-expand`.
678 private func tableColumnWidth(_ id: String) {
679 let caret = textView.selectedRange().location
680 let text = textView.string
681 guard let table = TableShrink.table(at: caret, in: text) else {
682 onMessage?("Not in a table")
683 return
684 }
685 let current = shrunk[table.lowerBound].map { Array($0.keys) } ?? []
686 switch id {
687 case "org.table.shrink": setShrunk(TableShrink.cookieColumns(table, in: text), in: table)
688 case "org.table.expand": setShrunk([], in: table)
689 default:
690 if let column = TableShrink.column(at: caret, in: text) {
691 setShrunk(Array(Set(current).symmetricDifference([column])), in: table)
692 return
693 }
694 let line = (text as NSString).lineRange(for: NSRange(location: caret, length: 0))
695 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
696 guard let self, let answer else { return }
697 self.setShrunk(Array(Set(current).symmetricDifference(TableShrink.columns(answer, max: line.length / 2))), in: table)
698 }
699 }
700 }
701
702 /// `#+STARTUP: shrink`: every table's columns with width cookies start narrow.
703 private func shrinkAtStartup() {
704 guard Presentation.startupOptions(document.tree).contains(where: { $0.lowercased() == "shrink" }) else { return }
705 let text = textView.string
706 var offset = 0
707 let ns = text as NSString
708 while offset < ns.length {
709 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
710 defer { offset = max(NSMaxRange(line), offset + 1) }
711 guard ns.substring(with: line).range(of: "^[ \\t]*\\|", options: .regularExpression) != nil,
712 let table = TableShrink.table(at: line.location, in: text) else { continue }
713 let columns = TableShrink.cookieColumns(table, in: text)
714 if !columns.isEmpty { shrunk[table.lowerBound] = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) }) }
715 offset = table.upperBound
716 }
717 }
718
719 /// Moves shrunk columns through `edit`; returns the tables to restyle.
720 private func mapShrunk(through edit: TextEdit) -> [Range<Int>] {
721 guard !shrunk.isEmpty else { return [] }
722 let text = textView.string
723 let delta = edit.replacement.utf16.count - edit.range.count
724 var mapped: [Int: [Int: [TableShrink.Segment]]] = [:]
725 var tables: [Range<Int>] = []
726 for (start, columns) in shrunk {
727 let kept = columns.filter { _, segments in
728 commandEditing || !segments.contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
729 }.keys
730 let touched = columns.values.joined().contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
731 let newStart = start < edit.range.lowerBound ? start : start >= edit.range.upperBound ? start + delta : edit.range.lowerBound
732 guard let table = TableShrink.table(at: min(newStart, max(0, text.utf16.count - 1)), in: text) else { continue }
733 if touched || kept.count != columns.count { tables.append(table) }
734 guard !kept.isEmpty else { continue }
735 mapped[table.lowerBound] = Dictionary(uniqueKeysWithValues: kept.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
736 }
737 shrunk = mapped
738 return tables
739 }
740
741 /// Hides each shrunk segment's text and draws its display where the text was.
742 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
743 guard !shrunk.isEmpty else { return }
744 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
745 for segment in shrunk.values.flatMap({ $0.values.joined() }) where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
746 let r = segment.range
747 let shown = segment.display.count
748 let kept = min(shown, r.count)
749 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
750 guard kept > 0 else { continue }
751 let visible = NSRange(location: r.upperBound - kept, length: kept)
752 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
753 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
754 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
755 }
756 }
757
758 /// Moves drawer and block folds through `edit`, checking again only those near it.
759 private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
760 guard !wrapperHidden.isEmpty else { return }
761 var mapped: [Int: Range<Int>] = [:]
762 let entries = Array(wrapperHidden)
763 // One pass maps every start and range.
764 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
765 for i in entries.indices {
766 let newStart = moved[2 * i].lowerBound
767 let newRange = moved[2 * i + 1]
768 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
769 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
770 } else {
771 mapped[newStart] = newRange
772 }
773 }
774 wrapperHidden = mapped
775 view.wrapperFolds = Set(mapped.keys)
776 }
777
778 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
779 /// cycles folded, children, subtree. Returns false elsewhere.
780 @discardableResult
781 public func cycleAtCaret() -> Bool {
782 leaveSparseTree()
783 let caret = textView.selectedRange().location
784 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
785 setFolds(state)
786 // Off a closing line that folding hid, to the opening line, as org does.
787 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
788 return true
789 }
790
791 /// Shift-TAB: overview, contents, show all.
792 public func cycleGlobal() {
793 leaveSparseTree()
794 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
795 globalVisibility = visibility
796 setFolds(state)
797 }
798
799 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
800 public func reveal(_ offset: Int) {
801 let target = max(0, min(offset, utf16Length))
802 if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
803 unfold(around: target)
804 setCaret(target)
805 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
806 }
807
808 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
809 func unfold(around offset: Int) {
810 leaveSparseTree()
811 var state = foldState
812 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
813 state.folds.remove(entry.start)
814 state.bodyFolds.remove(entry.start)
815 }
816 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
817 state.wrapperFolds.remove(start)
818 }
819 guard state != foldState else { return }
820 setFolds(state)
821 }
822
823 /// Applies edits through the text view as one undo step, not merged with typing around it.
824 func applyEdits(_ edits: [TextEdit]) {
825 guard !edits.isEmpty, let storage = textView.textStorage else { return }
826 textView.breakUndoCoalescing()
827 textView.undoManager?.beginUndoGrouping()
828 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
829 let range = NSRange(edit.range)
830 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
831 storage.replaceCharacters(in: range, with: edit.replacement)
832 textView.didChangeText()
833 }
834 textView.undoManager?.endUndoGrouping()
835 textView.breakUndoCoalescing()
836 }
837
838 func setCaret(_ offset: Int) {
839 let clamped = max(0, min(offset, utf16Length))
840 previousSelection = clamped
841 textView.setSelectedRange(NSRange(location: clamped, length: 0))
842 }
843
844 // MARK: - Styling
845
846 private func restyleOutsideEditing(_ range: Range<Int>) {
847 guard let storage = textView.textStorage else { return }
848 storage.beginEditing()
849 restyle(range, in: storage)
850 storage.endEditing()
851 }
852
853 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
854 /// attribute changes are allowed and characters must not change.
855 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
856 guard !range.isEmpty else { return }
857 let whole = NSRange(range)
858 storage.setAttributes(theme.base, range: whole)
859 guard isOrg else {
860 for run in plainRuns() where run.range.overlaps(range) {
861 guard let clipped = clip(run.range, to: range) else { continue }
862 theme.apply(.syntax(run.category), to: storage, range: clipped)
863 }
864 return
865 }
866 let text = storage.string as NSString
867 for run in Presentation.indents(document.tree, in: range) {
868 guard let clipped = clip(run.range, to: range) else { continue }
869 guard run.firstLine == run.wrapped else {
870 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
871 continue
872 }
873 // Body lines wrap under their own text: past leading blanks, and past a list bullet
874 // and checkbox, as adaptive-wrap does in Emacs.
875 var location = clipped.location
876 while location < NSMaxRange(clipped) {
877 let line = text.lineRange(for: NSRange(location: location, length: 0))
878 let hanging = Self.hangingColumns(text.substring(with: line))
879 let lineRange = NSIntersectionRange(line, clipped)
880 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
881 location = NSMaxRange(line)
882 }
883 }
884 let revealed = caretLine
885 var scriptExclusions: [Range<Int>] = []
886 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
887 guard let clipped = clip(run.range, to: range) else { continue }
888 if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
889 storage.addAttributes(theme.hidden, range: clipped)
890 } else {
891 theme.apply(run.role, to: storage, range: clipped)
892 }
893 switch run.role {
894 case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
895 default: break
896 }
897 }
898 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
899 applyShrunk(range, in: storage)
900 applyHighlights(range, in: storage)
901 }
902
903 /// `org-pretty-entities`: entities drawn as their character over the entity's last
904 /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
905 /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
906 /// keywords, as `org-raise-scripts` leaves them.
907 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
908 let text = storage.string as NSString
909 var location = range.lowerBound
910 while location < range.upperBound {
911 let line = text.lineRange(for: NSRange(location: location, length: 0))
912 guard line.length > 0 else { break }
913 location = NSMaxRange(line)
914 if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
915 let content = text.substring(with: line)
916 if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
917 for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
918 switch run {
919 case .entity(let r, let display):
920 let start = line.location + r.lowerBound
921 let last = line.location + r.upperBound - 1
922 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
923 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
924 case .script(let markers, let body, let superscript):
925 let bodyStart = line.location + body.lowerBound
926 if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
927 for marker in markers {
928 storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
929 }
930 let size = theme.font.pointSize
931 storage.addAttributes([
932 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
933 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
934 ], range: NSRange(location: bodyStart, length: body.count))
935 }
936 }
937 }
938 }
939
940 /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
941 /// markers only when Emacs hides them too.
942 private func hides(_ role: StyleRole) -> Bool {
943 switch role {
944 case .linkMarkup: true
945 case .markup: options.hideEmphasisMarkers
946 default: false
947 }
948 }
949
950 /// Moving to another line shows its markup and hides the last one's.
951 private func revealCaretLine() {
952 guard !showMarkup, isOrg else { return }
953 let line = caretLine
954 guard line != revealedLine else { return }
955 let text = textView.string as NSString
956 // The old line may have moved with edits since; restyle the line now at its start.
957 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
958 revealedLine = line
959 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
960 restyleOutsideEditing(range.location..<NSMaxRange(range))
961 }
962 }
963
964 /// Code highlights for the whole file in plain mode.
965 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
966 guard case .plain(let language?) = mode, let highlighter else { return [] }
967 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
968 let runs = highlighter.highlights(language: language, code: document.text)
969 codeRuns = (document.revision, runs)
970 return runs
971 }
972
973 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
974 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
975 if let style = paragraphStyles[key] { return style }
976 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
977 paragraphStyles[key] = style
978 return style
979 }
980
981 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
982 let clipped = run.clamped(to: range)
983 return clipped.isEmpty ? nil : NSRange(clipped)
984 }
985
986 /// The region an edit affects in one version of the tree: inside the innermost section
987 /// holding the edited lines (plus the line after), every element that overlaps them or the
988 /// line on either side. A changed heading line, or an added or removed heading, widens it
989 /// to that section's whole own body. Run on the old and the new tree, the union covers
990 /// elements that grew and elements that shrank.
991 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
992 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
993 let lineRange = lines.location..<(lines.location + lines.length)
994 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
995 var container = tree.root
996 while let child = container.child(containing: lineRange.lowerBound),
997 child.kind == .section || child.kind == .zerothSection,
998 lineRange.upperBound <= child.range.upperBound {
999 container = child
1000 }
1001 var lower = lineRange.lowerBound
1002 var upper = lineRange.upperBound
1003 // Tables and lists carry no styling of their own, so inside them only the rows or
1004 // items around the edit change, however large they are.
1005 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1006 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1007 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1008 let inner = overlapping(node.children(overlapping: around))
1009 return inner.isEmpty ? [node] : inner
1010 }
1011 }
1012 for child in overlapping(container.children(overlapping: around)) {
1013 lower = min(lower, child.range.lowerBound)
1014 upper = max(upper, child.range.upperBound)
1015 }
1016 let heading = container.firstChild(.heading)
1017 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1018 lower = min(lower, container.range.lowerBound)
1019 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1020 }
1021 return lower..<min(upper, text.length)
1022 }
1023
1024 // MARK: - Editing
1025
1026 private var blockCheck: DispatchWorkItem?
1027
1028 /// Looks for blocks over the whole file once typing pauses, catching what moving the
1029 /// ranges can't see (a block's end found far away).
1030 private func scheduleBlockCheck() {
1031 blockCheck?.cancel()
1032 let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
1033 blockCheck = work
1034 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
1035 }
1036
1037 func settleBlocks() {
1038 blockCheck?.cancel()
1039 guard isOrg else { return }
1040 let blocks = Presentation.shadedBlocks(document.tree)
1041 guard blocks != shaded.all else { return }
1042 shaded.set(blocks)
1043 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1044 }
1045
1046 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
1047 /// them), hold a block delimiter or a fixed-width line.
1048 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
1049 let start = min(range.lowerBound, text.length)
1050 let end = min(range.upperBound + 1, text.length)
1051 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
1052 let content = text.substring(with: lines)
1053 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
1054 }
1055
1056 fileprivate func storageEdited(range: NSRange, delta: Int) {
1057 guard !isLoading, let storage = textView.textStorage else { return }
1058 markActive = false
1059 let clock = ContinuousClock()
1060 let start = clock.now
1061 let replacement = (storage.string as NSString).substring(with: range)
1062 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
1063 let oldText = document.text as NSString
1064 let newText = storage.string as NSString
1065 let newEnd = edit.range.lowerBound + replacement.utf16.count
1066 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
1067 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
1068 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
1069 do {
1070 try document.apply([edit], baseRevision: document.revision)
1071 } catch {
1072 assertionFailure("text view and document disagree: \(error)")
1073 return
1074 }
1075 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
1076 // edited line when the edit reaches into unstyled text.
1077 if styledUpTo >= edit.range.upperBound {
1078 styledUpTo += edit.replacement.utf16.count - edit.range.count
1079 } else if styledUpTo > edit.range.lowerBound {
1080 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
1081 }
1082 let oldHidden = hidden.all
1083 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
1084 let delta = edit.replacement.utf16.count - edit.range.count
1085 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
1086 view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
1087 mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
1088 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
1089 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
1090 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
1091 highlights = []
1092 updateHidden()
1093 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
1094 for table in mapShrunk(through: edit) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
1095 for range in oldHighlights where range.upperBound <= newText.length {
1096 let lines = newText.lineRange(for: NSRange(range))
1097 restyle(lines.location..<NSMaxRange(lines), in: storage)
1098 }
1099 let oldShaded = shaded.all
1100 if isOrg {
1101 // Walking the tree for blocks costs more than typing; only an edit on a line that
1102 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
1103 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
1104 shaded.set(Presentation.shadedBlocks(document.tree))
1105 } else {
1106 shaded.set(oldShaded.map { mapRange($0, through: edit) })
1107 }
1108 scheduleBlockCheck()
1109 }
1110 if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
1111 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
1112 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1113 }
1114 onEditTiming?(clock.now - start)
1115 let lineCount = lines.lineCount
1116 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
1117 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
1118 orgTextView?.redrawLineNumbers()
1119 onChange?()
1120 }
1121
1122 /// Columns a wrapped continuation of `line` should start past the line's own start.
1123 nonisolated static func hangingColumns(_ line: String) -> Int {
1124 var columns = 0
1125 var rest = Substring(line)
1126 while let c = rest.first, c == " " || c == "\t" {
1127 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
1128 rest = rest.dropFirst()
1129 }
1130 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
1131 var bullet = 0
1132 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
1133 bullet = 1
1134 } else {
1135 let digits = rest.prefix { $0.isASCII && $0.isNumber }
1136 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
1137 bullet = digits.count + 1
1138 }
1139 }
1140 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
1141 columns += bullet + 1
1142 let afterBullet = rest.dropFirst(bullet + 1)
1143 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
1144 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
1145 columns += 4
1146 }
1147 return columns
1148 }
1149
1150 /// Whether a heading line touches `start..<end` or starts right after it, where joining
1151 /// lines could take it away.
1152 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1153 let length = min(end + 1, text.length) - start
1154 guard length >= 0 else { return false }
1155 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1156 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1157 let stars = line.prefix { $0 == "*" }
1158 let after = line.dropFirst(stars.count)
1159 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1160 }
1161 }
1162
1163 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1164 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1165 return mapped
1166 }
1167
1168 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1169 /// back jumps to the end of the heading line.
1170 fileprivate func selectionChanged() {
1171 let selection = textView.selectedRange()
1172 defer { previousSelection = selection.location }
1173 onSelectionChange?(selection)
1174 revealCaretLine()
1175 orgTextView?.redrawLineNumbers()
1176 // Narrowing keeps the caret in the region.
1177 if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
1178 setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
1179 return
1180 }
1181 // A selection reaching into folded text, as a find match does, unfolds it.
1182 if selection.length > 0 {
1183 if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1184 unfold(around: selection.location)
1185 unfold(around: NSMaxRange(selection) - 1)
1186 }
1187 return
1188 }
1189 guard let range = hidden.containing(selection.location) else { return }
1190 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1191 }
1192}
1193
1194extension OrgEditor: DocumentBuffer {
1195 /// The selected text, for capture's `%i`.
1196 public var selectedText: String {
1197 let range = textView.selectedRange()
1198 guard range.length > 0 else { return "" }
1199 return (textView.string as NSString).substring(with: range)
1200 }
1201
1202 public var selection: [Range<Int>] {
1203 let selected = textView.selectedRange()
1204 return [selected.location..<NSMaxRange(selected)]
1205 }
1206
1207 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1208 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1209 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1210 let before = document.text
1211 let selected = textView.selectedRange()
1212 let result = try change(&document)
1213 if document.text != before {
1214 let edits = lineEdits(from: before, to: document.text)
1215 var state = view
1216 state.selection = [selected.location..<NSMaxRange(selected)]
1217 let mapped = state.mapped(through: edits)
1218 load(document.text)
1219 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1220 let selection = mapped.selection[0]
1221 setCaret(selection.lowerBound)
1222 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1223 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1224 textView.undoManager?.removeAllActions(withTarget: textView)
1225 }
1226 onChange?()
1227 return result
1228 }
1229}
1230
1231extension OrgEditor: NSTextViewDelegate {
1232 public func textViewDidChangeSelection(_ notification: Notification) {
1233 selectionChanged()
1234 }
1235}
1236
1237extension OrgEditor: NSTextStorageDelegate {
1238 public nonisolated func textStorage(
1239 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1240 ) {
1241 guard editedMask.contains(.editedCharacters) else { return }
1242 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1243 }
1244}
1245
1246extension OrgEditor: NSTextContentStorageDelegate {
1247 /// Folded text isn't enumerated, so it isn't laid out or drawn.
1248 public nonisolated func textContentManager(
1249 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1250 ) -> Bool {
1251 guard let range = textElement.elementRange else { return true }
1252 let documentStart = textContentManager.documentRange.location
1253 let start = textContentManager.offset(from: documentStart, to: range.location)
1254 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1255 return !hidden.covers(start, end)
1256 }
1257}
1258
1259extension OrgEditor: NSTextLayoutManagerDelegate {
1260 public nonisolated func textLayoutManager(
1261 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1262 ) -> NSTextLayoutFragment {
1263 let range = textElement.elementRange
1264 if let range, let manager = textLayoutManager.textContentManager {
1265 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1266 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1267 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1268 if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1269 return EntityFragment(textElement: textElement, range: range)
1270 }
1271 }
1272 return NSTextLayoutFragment(textElement: textElement, range: range)
1273 }
1274}
1275
1276/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1277/// `org-block` face.
1278final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1279 private var band: CGRect {
1280 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1281 // Not under the empty line TextKit adds after a final newline.
1282 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1283 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1284 }
1285
1286 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1287
1288 override func draw(at point: CGPoint, in context: CGContext) {
1289 context.saveGState()
1290 context.setFillColor(Theme.blockBackground.cgColor)
1291 context.fill(band.offsetBy(dx: point.x, dy: point.y))
1292 context.restoreGState()
1293 super.draw(at: point, in: context)
1294 }
1295}
1296
1297extension NSAttributedString.Key {
1298 /// The character an entity shows as, on the entity's last character.
1299 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1300}
1301
1302/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1303/// (now invisible) character sits, so it takes one column as in Emacs.
1304final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1305 static func hasEntities(_ string: NSAttributedString) -> Bool {
1306 var found = false
1307 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1308 if value != nil { found = true; stop.pointee = true }
1309 }
1310 return found
1311 }
1312
1313 override func draw(at point: CGPoint, in context: CGContext) {
1314 super.draw(at: point, in: context)
1315 Self.drawEntities(of: self, at: point, in: context)
1316 }
1317
1318 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1319 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1320 NSGraphicsContext.saveGraphicsState()
1321 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1322 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1323 guard let display = value as? String,
1324 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1325 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1326 attributes[.foregroundColor] = NSColor.textColor
1327 attributes[.orgEntityDisplay] = nil
1328 let x = line.locationForCharacter(at: range.location).x
1329 let bounds = line.typographicBounds
1330 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1331 }
1332 NSGraphicsContext.restoreGraphicsState()
1333 }
1334}
1335
1336/// A heading line drawn with an ellipsis after it, like org's folded headings.
1337final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1338 override func draw(at point: CGPoint, in context: CGContext) {
1339 super.draw(at: point, in: context)
1340 EntityFragment.drawEntities(of: self, at: point, in: context)
1341 guard let line = textLineFragments.first else { return }
1342 let bounds = line.typographicBounds
1343 let ellipsis = NSAttributedString(string: " …", attributes: [
1344 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1345 .foregroundColor: NSColor.secondaryLabelColor,
1346 ])
1347 NSGraphicsContext.saveGraphicsState()
1348 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1349 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1350 NSGraphicsContext.restoreGraphicsState()
1351 }
1352
1353 override var renderingSurfaceBounds: CGRect {
1354 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1355 }
1356}
1357#endif