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