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