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