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