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