Sources/OrgEditorAppKit/OrgEditor.swift
831 lines · 39202 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5import OrgPresentation
6
7/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
8/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
9@MainActor
10public final class OrgEditor: NSObject {
11 public let textView: NSTextView
12 public private(set) var document: DocumentState
13 public internal(set) var view = ViewState()
14 /// Called with the time from a character edit to restyled text.
15 public var onEditTiming: ((Duration) -> Void)?
16
17 let hidden = HiddenRanges()
18 let folded = FoldedHeadings()
19 /// Where lines start, for line numbers.
20 let lines = LineIndex()
21 /// Blocks drawn on a shaded band.
22 let shaded = HiddenRanges()
23 private(set) var theme = Theme()
24 /// Colors and type; a change restyles the file.
25 public var themeSpec: ThemeSpec = .default {
26 didSet {
27 guard themeSpec != oldValue else { return }
28 theme = Theme(themeSpec)
29 keepingTopLine {
30 applyThemeToView()
31 restyleEverything()
32 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
33 }
34 }
35 }
36 private var isLoading = false
37 var previousSelection = 0
38 /// The selection shaded block lines last drew.
39 private var previousSelectionRange = NSRange(location: 0, length: 0)
40 /// Text before this offset is styled; after it, only base attributes until the background
41 /// passes reach it. Always at a line start.
42 private(set) var styledUpTo = 0
43 private var stylingScheduled = false
44 /// One paragraph style object per indent pair, shared by every line that uses it.
45 var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
46
47 struct IndentKey: Hashable {
48 let firstLine: Int
49 let wrapped: Int
50 }
51
52 /// Styled before the first render: more than a screenful.
53 static let firstStyleChunk = 30_000
54 /// Styled per run-loop turn afterwards.
55 static let styleChunk = 200_000
56
57 /// Highlights code in src blocks; nil leaves code plain.
58 public let highlighter: (any CodeHighlighter)?
59
60 /// What the file is: org, or plain text, highlighted as code when the language is known.
61 public enum Mode: Equatable, Sendable {
62 case org
63 case plain(language: String?)
64 }
65
66 public let mode: Mode
67 public var isOrg: Bool { mode == .org }
68 /// The text as shown for accessibility, and the storage generation it's for.
69 var accessibleCache: (storage: Int, text: AccessibleText)?
70 /// Bumped on every character or attribute change to the storage.
71 var storageGeneration = 0
72 /// The open completion list, and the pause before one opens by itself.
73 var completionPopup: CompletionPopup?
74 var completionTimer: DispatchWorkItem?
75 /// The spell checker's skipped ranges and the text they were found in.
76 var spellSkipCache: (text: String, ranges: [Range<Int>])?
77 /// Highlights of the whole file in plain mode, and the revision they were made for.
78 var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
79
80 public init(
81 document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
82 highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
83 ) {
84 self.document = document
85 self.options = options
86 self.highlighter = highlighter
87 self.mode = mode
88 let orgTextView = OrgTextView(usingTextLayoutManager: true)
89 textView = orgTextView
90 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
91 super.init()
92 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
93 orgTextView.onFocusChange = { [weak self] in
94 guard let self else { return }
95 let id = ObjectIdentifier(self.textLayoutManager)
96 if let window = self.textView.window, window.isKeyWindow, window.firstResponder === self.textView {
97 Theme.focusedLayouts.insert(id)
98 } else {
99 Theme.focusedLayouts.remove(id)
100 }
101 self.redrawShaded([self.textView.selectedRange()])
102 }
103 orgTextView.onCommandClick = { [weak self] offset in
104 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
105 || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
106 self.setCaret(offset)
107 self.run("org.link.open")
108 return true
109 }
110 orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false }
111 orgTextView.accessibleText = { [weak self] in
112 guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
113 if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
114 let text = AccessibleText(storage)
115 self.accessibleCache = (self.storageGeneration, text)
116 return text
117 }
118 orgTextView.onMouseDown = { [weak self] in
119 self?.markActive = false
120 self?.modalMouseDown()
121 }
122 textView.usesFindBar = true
123 textView.frame = frame
124 textView.isRichText = false
125 textView.isEditable = editable
126 textView.allowsUndo = true
127 textView.isAutomaticQuoteSubstitutionEnabled = false
128 textView.isAutomaticDashSubstitutionEnabled = false
129 textView.isAutomaticTextReplacementEnabled = false
130 textView.isAutomaticSpellingCorrectionEnabled = false
131 applyThemeToView()
132 textView.isVerticallyResizable = true
133 textView.autoresizingMask = [.width]
134 textView.textContainer?.widthTracksTextView = true
135 textView.delegate = self
136 textView.textStorage?.delegate = self
137 textLayoutManager.delegate = self
138 textContentStorage.delegate = self
139
140 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
141 load(document.text)
142 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
143 textView.setSelectedRange(NSRange(location: 0, length: 0))
144 if isOrg {
145 let startup = Presentation.startupDisplay(document.tree, options: options)
146 indented = startup.indented
147 hideStars = startup.hideStars
148 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) }
149 shrunk = ShrunkColumns.startup(document.tree)
150 if startup.inlineImages { showsImages = true }
151 if startup.alignTables { _ = perform(AlignAllTables()) }
152 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
153 }
154 spellChecking = options.spellCheck
155 truncatesLines = options.startupTruncated
156 }
157
158 /// Replaces the storage's text. Setting the attributed string directly is about 100x
159 /// faster than `NSTextView.string` for large files.
160 private func load(_ text: String) {
161 isLoading = true
162 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
163 isLoading = false
164 lines.reset(text as NSString)
165 orgTextView?.lineIndex = lines
166 orgTextView?.updateGutter()
167 styledUpTo = 0
168 styleNextChunk(Self.firstStyleChunk)
169 scheduleStyling()
170 }
171
172 // MARK: - Initial styling
173
174 /// Styles whole lines from the watermark onward, about `size` units.
175 func styleNextChunk(_ size: Int) {
176 let text = textView.textStorage!.string as NSString
177 guard styledUpTo < text.length else { return }
178 let target = min(text.length, styledUpTo + size)
179 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
180 restyleOutsideEditing(styledUpTo..<end)
181 styledUpTo = end
182 }
183
184 /// The text view's own colors and font, and the line numbers'.
185 private func applyThemeToView() {
186 textView.font = theme.font
187 textView.typingAttributes = theme.base
188 textView.drawsBackground = true
189 textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
190 textView.insertionPointColor = theme.color("cursor") ?? .textColor
191 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
192 textView.selectedTextAttributes = [.backgroundColor: Theme.selection]
193 if let view = orgTextView {
194 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
195 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
196 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
197 view.updateGutter()
198 view.needsDisplay = true
199 }
200 }
201
202 /// Styles the whole file again, a screenful now and the rest in the background.
203 private func restyleEverything() {
204 styledUpTo = 0
205 revealedLine = caretLine
206 styleNextChunk(Self.firstStyleChunk)
207 scheduleStyling()
208 }
209
210 var caretLine: NSRange {
211 let text = textView.string as NSString
212 return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
213 }
214
215 private func scheduleStyling() {
216 guard !stylingScheduled, styledUpTo < utf16Length else { return }
217 stylingScheduled = true
218 DispatchQueue.main.async { [weak self] in
219 guard let self else { return }
220 self.stylingScheduled = false
221 self.styleNextChunk(Self.styleChunk)
222 self.scheduleStyling()
223 }
224 }
225
226 /// Styles everything still waiting for a background pass.
227 public func finishStyling() {
228 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
229 }
230
231 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
232 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
233 var utf16Length: Int { (textView.string as NSString).length }
234
235 /// A scroll view holding the text view, ready for a window.
236 public func makeScrollView() -> NSScrollView {
237 let scroll = NSScrollView(frame: textView.frame)
238 scroll.hasVerticalScroller = true
239 scroll.documentView = textView
240 orgTextView?.showsLineNumbers = showLineNumbers
241 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
242 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
243 return scroll
244 }
245
246 // MARK: - Saving
247
248 /// Saves through `saver`. A merge that changes the buffer reloads the text view.
249 @discardableResult
250 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
251 try update { try saver.save(&$0, to: url) }
252 }
253
254 /// Called after every change to the document, typed or not.
255 public var onChange: (() -> Void)?
256
257 // MARK: - Commands
258
259 /// Called with messages commands report, such as why one couldn't run here.
260 public var onMessage: ((String) -> Void)?
261 /// Called with the pending prefix and what can follow it, and with nil when it ends.
262 /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
263 public var onModeChange: ((String?) -> Void)?
264 /// The selection moved.
265 public var onSelectionChange: ((NSRange) -> Void)?
266 var reportedMode: String?
267 public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
268 /// Called with `app.*` commands, which the app carries out.
269 public var onAppCommand: ((String) -> Void)?
270 /// `:e FILE`: the path as typed, for the app to open.
271 public var onOpenFile: ((String) -> Void)?
272 /// Called when a command asks a question; reply with the answer, or nil to cancel.
273 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
274 /// Runs work outside the text, such as a table recalculation in Emacs.
275 public var onExternal: ((ExternalRequest) -> Void)?
276 /// Tags used across the workspace, for tag completion.
277 public var knownTags: @Sendable () -> [String] = { [] }
278 /// Effects other than messages, for the app to carry out.
279 public var onEffect: ((Effect) -> Void)?
280
281 public var keymap: Keymap {
282 get { dispatcher.keymap }
283 set {
284 dispatcher.keymap = newValue
285 dispatcher.reset()
286 }
287 }
288
289 public var optionAsMeta: OptionAsMeta = [.left]
290 /// Org options commands follow.
291 public var options: EditingOptions = .org {
292 didSet {
293 if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
294 }
295 }
296 /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
297 /// `options`). Hidden markup shows on the caret's line, so it can be edited.
298 public var showMarkup = true {
299 didSet { if showMarkup != oldValue { restyleEverything() } }
300 }
301 /// Line numbers in a ruler beside the text.
302 public var showLineNumbers = true {
303 didSet { orgTextView?.showsLineNumbers = showLineNumbers }
304 }
305 var orgTextView: OrgTextView? { textView as? OrgTextView }
306
307 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
308 var revealedLine: NSRange?
309 var dispatcher: KeyDispatcher
310 /// Evil-style editing, for modal keymaps such as Doom's.
311 public var modal = false {
312 didSet {
313 guard modal != oldValue else { return }
314 vim = Vim()
315 dispatcher.mode = modal ? vim.mode.keymapMode : nil
316 dispatcher.reset()
317 updateCursor()
318 }
319 }
320 var vim = Vim()
321 /// The text and caret when insert state began, to know what was typed for `.`.
322 var insertSnapshot: (text: String, caret: Int)?
323 /// The evil cursor in visual states, where the selection's start isn't it.
324 var visualCaret: Int?
325 /// Vim's lowercase marks, mapped through edits.
326 var vimMarks: [Character: Int] = [:]
327 /// Uppercase marks, with the editor each is in: global, as evil's file marks are.
328 static var fileMarks: [Character: (owner: WeakEditor, offset: Int)] = [:]
329 /// Registers and keyboard macros, shared by every editor as evil's are global.
330 static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
331 static var vimClipboardRecord: (text: String, linewise: Bool)?
332 static var macros: [Character: [KeyChord]] = [:]
333 /// Shows `editor`'s buffer with the caret at the offset, for a jump to a file mark set
334 /// there.
335 public var onJumpToEditor: ((OrgEditor, Int) -> Void)?
336 /// Jump positions, oldest first, mapped through edits; `jumpIndex` is where C-o and C-i are.
337 var jumpList: [Int] = []
338 var jumpIndex = 0
339 /// The register keys go into while `q` records, and its keys so far.
340 var recordingRegister: Character?
341 var recordedKeys: [KeyChord] = []
342 var replayingMacro = 0
343 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
344 private(set) var markActive = false
345
346 public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
347 let selected = textView.selectedRange()
348 return EditContext(
349 revision: document.revision, text: document.text, tree: document.tree,
350 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
351 hidden: hidden.all, options: options, knownTags: knownTags,
352 lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
353 )
354 }
355
356 /// Offers a key press to the keymap. False lets the text system have it.
357 func handleKey(_ event: NSEvent) -> Bool {
358 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
359 if let handled = completionKey(chord) { return handled }
360 if modal { return handleModal(chord) }
361 switch dispatcher.feed(chord) {
362 case .pending(let keys):
363 let context = context()
364 let next = keymap.continuations(of: keys) { runs($0, in: context) }.map { item in
365 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
366 }
367 onKeysPending?(KeySequence.format(keys), next)
368 return true
369 case .cancelled:
370 onKeysPending?(nil, [])
371 onMessage?("Quit")
372 return true
373 case .undefined(let keys):
374 onKeysPending?(nil, [])
375 onMessage?("\(KeySequence.format(keys)) is undefined")
376 return true
377 case .unbound:
378 return electricPair(chord)
379 case .complete(let keys, let candidates):
380 if keys.count > 1 { onKeysPending?(nil, []) }
381 let context = context()
382 let runnable = candidates.first { runs($0, in: context) }
383 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
384 run(binding.command)
385 return true
386 }
387 return keys.count == 1 && electricPair(chord)
388 }
389 }
390
391 /// `electric-pair-mode` for a key the keymap leaves to the text system: true when it
392 /// typed the key itself.
393 func electricPair(_ key: KeyChord) -> Bool {
394 guard isOrg, options.electricPair, key.modifiers.isEmpty, !textView.hasMarkedText(),
395 key.key == "DEL" || key.key == "RET" || ElectricPairKey.characters.contains(key.key) else { return false }
396 let command = ElectricPairKey(key: key.key)
397 guard command.applies(in: context()) else { return false }
398 _ = perform(command)
399 return true
400 }
401
402 /// Whether a key's `binding` runs in `context`: its context holds and its command applies.
403 private func runs(_ binding: KeyBinding, in context: EditContext) -> Bool {
404 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
405 }
406
407 private func applies(_ id: String, in context: EditContext) -> Bool {
408 if !isOrg, id.hasPrefix("org.") { return false }
409 return switch EditorCommands.command(id)?.action {
410 case .text(let command): command.applies(in: context)
411 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
412 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
413 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
414 case .edit, .mark, .app, .find: true
415 case nil: true
416 }
417 }
418
419 /// The last command run and the revision it left, for `last-command`.
420 private var lastCommand: (id: String, revision: Int)?
421
422 /// Runs a command by id, as a key, a menu item or the palette would.
423 public func run(_ id: String) {
424 defer { lastCommand = (id, document.revision) }
425 guard let command = EditorCommands.command(id) else {
426 onMessage?("Unknown command \(id)")
427 return
428 }
429 if !isOrg, id.hasPrefix("org.") {
430 onMessage?("Not an org file")
431 return
432 }
433 // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
434 if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
435 clearHighlights()
436 return
437 }
438 var keepMark = false
439 switch command.action {
440 case .text(let text):
441 perform(text)
442 case .view:
443 switch id {
444 case "org.cycle": cycleAtCaret()
445 case "org.cycle-global": cycleGlobal()
446 case "org.fold.toggle", "org.fold.open", "org.fold.close": fold(id)
447 case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
448 case "org.toggle-inline-images": toggleImages()
449 case "editor.toggle-spell-check": toggleSpellCheck()
450 case "editor.complete": completeAtPoint()
451 case "editor.toggle-truncate-lines": toggleTruncateLines()
452 default: tableColumnWidth(id)
453 }
454 case .edit(let selector, let extending):
455 if markActive, let extending {
456 keepMark = true
457 textView.doCommand(by: NSSelectorFromString(extending))
458 } else {
459 textView.doCommand(by: NSSelectorFromString(selector))
460 }
461 case .find(let action):
462 let item = NSMenuItem()
463 item.tag = action.rawValue
464 textView.performTextFinderAction(item)
465 case .mark:
466 if id == "edit.set-mark" {
467 let caret = textView.selectedRange().location
468 textView.setSelectedRange(NSRange(location: caret, length: 0))
469 keepMark = true
470 onMessage?("Mark set")
471 } else {
472 let selected = textView.selectedRange()
473 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
474 onMessage?("Quit")
475 }
476 case .app:
477 onAppCommand?(id)
478 }
479 markActive = keepMark
480 }
481
482 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
483 /// they form one undo step and reach the document through the same path.
484 @discardableResult
485 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
486 let context = context(now: now, answers: answers)
487 let step = command.run(in: context)
488 switch step {
489 case .commit(let result):
490 guard textView.isEditable || result.edits.isEmpty else {
491 onMessage?("This file is read-only.")
492 return .failed("read-only")
493 }
494 commandEditing = true
495 applyEdits(result.edits)
496 commandEditing = false
497 if let selection = result.selection?.first {
498 if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
499 setCaret(selection.lowerBound)
500 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
501 }
502 for effect in result.effects {
503 switch effect {
504 case .message(let text): onMessage?(text)
505 case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
506 case .fold(let start):
507 var state = foldState
508 state.folds.insert(start)
509 setFolds(state)
510 default: onEffect?(effect)
511 }
512 }
513 case .failed(let message):
514 onMessage?(message)
515 case .external(let request):
516 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
517 case .prompt(let prompt):
518 onPrompt?(prompt) { [weak self] answer in
519 guard let self else { return }
520 guard let answer else {
521 self.onMessage?("Quit")
522 return
523 }
524 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
525 }
526 }
527 return step
528 }
529
530 // MARK: - Disk
531
532 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
533 /// its headings.
534 @discardableResult
535 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
536 update { $0.diskChanged(to: bytes) }
537 }
538
539 // MARK: - Folding
540
541 var globalVisibility: GlobalVisibility?
542 /// What each folded drawer and block hides, by opening-line start; kept in step with
543 /// `view.wrapperFolds` and mapped through edits.
544 var wrapperHidden: [Int: Range<Int>] = [:]
545
546 // MARK: - Sparse trees
547
548 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
549 /// fold change. Mapped through edits.
550 var sparseHidden: [Range<Int>]?
551 /// Sparse tree matches, highlighted until the next edit or C-c C-c.
552 var highlights: [Range<Int>] = []
553
554 // MARK: - STARTUP display
555
556 /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
557 var indented = true
558 /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
559 var hideStars = false
560
561 // MARK: - Inline images
562
563 /// `org-toggle-inline-images`: lines that are only an image link show the image.
564 public internal(set) var showsImages = false
565 /// The file's folder, for relative image paths.
566 public var baseDirectory: URL? {
567 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
568 }
569
570 // MARK: - Narrowing
571
572 /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
573 /// rest is hidden until `widen`. Mapped through edits.
574 public internal(set) var narrowed: Range<Int>?
575
576 // MARK: - Shrunk table columns
577
578 /// Narrowed table columns (`org-table-shrink`).
579 var shrunk = ShrunkColumns()
580 private var commandEditing = false
581
582 // MARK: - Editing
583
584 private var blockCheck: DispatchWorkItem?
585
586 /// Looks for blocks over the whole file once typing pauses, catching what moving the
587 /// ranges can't see (a block's end found far away).
588 private func scheduleBlockCheck() {
589 blockCheck?.cancel()
590 let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
591 blockCheck = work
592 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
593 }
594
595 func settleBlocks() {
596 blockCheck?.cancel()
597 guard isOrg else { return }
598 let blocks = Presentation.shadedBlocks(document.tree)
599 guard blocks != shaded.all else { return }
600 let old = shaded.all
601 shaded.set(blocks)
602 invalidateLayout(from: old, to: blocks)
603 }
604
605 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
606 /// them), hold a block delimiter or a fixed-width line.
607 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
608 let start = min(range.lowerBound, text.length)
609 let end = min(range.upperBound + 1, text.length)
610 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
611 let content = text.substring(with: lines)
612 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
613 }
614
615 fileprivate func storageEdited(range: NSRange, delta: Int) {
616 guard !isLoading, let storage = textView.textStorage else { return }
617 markActive = false
618 let clock = ContinuousClock()
619 let start = clock.now
620 let replacement = (storage.string as NSString).substring(with: range)
621 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
622 let oldText = document.text as NSString
623 let newText = storage.string as NSString
624 let newEnd = edit.range.lowerBound + replacement.utf16.count
625 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
626 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
627 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
628 do {
629 try document.apply([edit], baseRevision: document.revision)
630 } catch {
631 assertionFailure("text view and document disagree: \(error)")
632 return
633 }
634 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
635 // edited line when the edit reaches into unstyled text.
636 if styledUpTo >= edit.range.upperBound {
637 styledUpTo += edit.replacement.utf16.count - edit.range.count
638 } else if styledUpTo > edit.range.lowerBound {
639 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
640 }
641 let oldHidden = hidden.all
642 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
643 let delta = edit.replacement.utf16.count - edit.range.count
644 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
645 view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
646 mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
647 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
648 mapVimPositions(through: edit)
649 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
650 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
651 highlights = []
652 updateHidden()
653 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
654 for table in shrunk.map(through: edit, in: storage.string, command: commandEditing) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
655 for range in oldHighlights where range.upperBound <= newText.length {
656 let lines = newText.lineRange(for: NSRange(range))
657 restyle(lines.location..<NSMaxRange(lines), in: storage)
658 }
659 let oldShaded = shaded.all
660 if isOrg {
661 // Walking the tree for blocks costs more than typing; only an edit on a line that
662 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
663 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
664 shaded.set(Presentation.shadedBlocks(document.tree))
665 } else {
666 shaded.set(oldShaded.map { mapRange($0, through: edit) })
667 }
668 scheduleBlockCheck()
669 }
670 invalidateLayout(from: oldHidden.map { mapRange($0, through: edit) }, to: hidden.all)
671 invalidateLayout(from: oldShaded.map { mapRange($0, through: edit) }, to: shaded.all)
672 onEditTiming?(clock.now - start)
673 let lineCount = lines.lineCount
674 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
675 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
676 orgTextView?.redrawLineNumbers()
677 onChange?()
678 }
679
680 /// Whether a heading line touches `start..<end` or starts right after it, where joining
681 /// lines could take it away.
682 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
683 let length = min(end + 1, text.length) - start
684 guard length >= 0 else { return false }
685 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
686 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
687 let stars = line.prefix { $0 == "*" }
688 let after = line.dropFirst(stars.count)
689 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
690 }
691 }
692
693 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
694 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
695 return mapped
696 }
697
698 /// Shaded block lines the old or new selection covers are drawn again, as they draw the
699 /// selection over their band.
700 private func redrawShadedSelection(_ selection: NSRange) {
701 defer { previousSelectionRange = selection }
702 redrawShaded([previousSelectionRange, selection])
703 }
704
705 private func redrawShaded(_ ranges: [NSRange]) {
706 guard let manager = textLayoutManager.textContentManager else { return }
707 for old in ranges where old.length > 0 {
708 for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
709 let lower = max(block.lowerBound, old.location)
710 let upper = min(block.upperBound, NSMaxRange(old))
711 guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
712 let end = manager.location(start, offsetBy: upper - lower),
713 let range = NSTextRange(location: start, end: end) else { continue }
714 textLayoutManager.invalidateLayout(for: range)
715 }
716 }
717 }
718
719 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
720 /// back jumps to the end of the heading line.
721 func selectionChanged() {
722 let selection = textView.selectedRange()
723 defer { previousSelection = selection.location }
724 redrawShadedSelection(selection)
725 onSelectionChange?(selection)
726 revealCaretLine()
727 orgTextView?.redrawLineNumbers()
728 // Narrowing keeps the caret in the region.
729 if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
730 setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
731 return
732 }
733 // A selection reaching into folded text, as a find match does, unfolds it.
734 if selection.length > 0 {
735 if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
736 unfold(around: selection.location)
737 unfold(around: NSMaxRange(selection) - 1)
738 }
739 return
740 }
741 guard let range = hidden.containing(selection.location) else { return }
742 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
743 }
744}
745
746extension OrgEditor: DocumentBuffer {
747 /// The selected text, for capture's `%i`.
748 public var selectedText: String {
749 let range = textView.selectedRange()
750 guard range.length > 0 else { return "" }
751 return (textView.string as NSString).substring(with: range)
752 }
753
754 public var selection: [Range<Int>] {
755 let selected = textView.selectedRange()
756 return [selected.location..<NSMaxRange(selected)]
757 }
758
759 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
760 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
761 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
762 let before = document.text
763 let defaultsBefore = document.defaults
764 let selected = textView.selectedRange()
765 let result = try change(&document)
766 if document.text != before {
767 let edits = lineEdits(from: before, to: document.text)
768 var state = view
769 state.selection = [selected.location..<NSMaxRange(selected)]
770 let mapped = state.mapped(through: edits)
771 // Shrunk columns were measured on the old text.
772 shrunk = ShrunkColumns()
773 load(document.text)
774 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
775 let selection = mapped.selection[0]
776 setCaret(selection.lowerBound)
777 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
778 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
779 textView.undoManager?.removeAllActions(withTarget: textView)
780 } else if document.defaults != defaultsBefore {
781 // New settings for the same text: TODO keywords may color differently.
782 restyleEverything()
783 }
784 onChange?()
785 return result
786 }
787}
788
789extension OrgEditor: NSTextStorageDelegate {
790 public nonisolated func textStorage(
791 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
792 ) {
793 MainActor.assumeIsolated { storageGeneration += 1 }
794 guard editedMask.contains(.editedCharacters) else { return }
795 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
796 }
797}
798
799extension OrgEditor: NSTextContentStorageDelegate {
800 /// Folded text isn't enumerated, so it isn't laid out or drawn.
801 public nonisolated func textContentManager(
802 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
803 ) -> Bool {
804 guard let range = textElement.elementRange else { return true }
805 let documentStart = textContentManager.documentRange.location
806 let start = textContentManager.offset(from: documentStart, to: range.location)
807 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
808 return !hidden.covers(start, end)
809 }
810}
811
812extension OrgEditor: NSTextLayoutManagerDelegate {
813 public nonisolated func textLayoutManager(
814 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
815 ) -> NSTextLayoutFragment {
816 let range = textElement.elementRange
817 if let range, let manager = textLayoutManager.textContentManager {
818 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
819 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
820 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
821 if let paragraph = textElement as? NSTextParagraph, ImageFragment.image(paragraph.attributedString) != nil {
822 return ImageFragment(textElement: textElement, range: range)
823 }
824 if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
825 return EntityFragment(textElement: textElement, range: range)
826 }
827 }
828 return NSTextLayoutFragment(textElement: textElement, range: range)
829 }
830}
831#endif