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