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