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