Sources/OrgEditorAppKit/OrgEditor.swift
1514 lines · 74386 bytes
1#if os(macOS)
2import AppKit
3import OrgCore
4import OrgDocument
5import OrgPresentation
6
7/// Hidden ranges, read by TextKit's enumeration callbacks, which may run off the main thread.
8final class HiddenRanges: @unchecked Sendable {
9 private let lock = NSLock()
10 private var ranges: [Range<Int>] = []
11
12 func set(_ new: [Range<Int>]) {
13 lock.withLock { ranges = new }
14 }
15
16 var all: [Range<Int>] {
17 lock.withLock { ranges }
18 }
19
20 func covers(_ start: Int, _ end: Int) -> Bool {
21 lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } }
22 }
23
24 func containing(_ offset: Int) -> Range<Int>? {
25 lock.withLock { ranges.first { $0.lowerBound <= offset && offset < $0.upperBound } }
26 }
27}
28
29/// Folded heading starts, read by the layout-fragment callback.
30final class FoldedHeadings: @unchecked Sendable {
31 private let lock = NSLock()
32 private var starts: Set<Int> = []
33
34 func set(_ new: Set<Int>) {
35 lock.withLock { starts = new }
36 }
37
38 func contains(_ offset: Int) -> Bool {
39 lock.withLock { starts.contains(offset) }
40 }
41}
42
43/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
44/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
45@MainActor
46public final class OrgEditor: NSObject {
47 public let textView: NSTextView
48 public private(set) var document: DocumentState
49 public private(set) var view = ViewState()
50 /// Called with the time from a character edit to restyled text.
51 public var onEditTiming: ((Duration) -> Void)?
52
53 let hidden = HiddenRanges()
54 let folded = FoldedHeadings()
55 /// Where lines start, for line numbers.
56 let lines = LineIndex()
57 /// Blocks drawn on a shaded band.
58 let shaded = HiddenRanges()
59 private(set) var theme = Theme()
60 /// Colors and type; a change restyles the file.
61 public var themeSpec: ThemeSpec = .default {
62 didSet {
63 guard themeSpec != oldValue else { return }
64 theme = Theme(themeSpec)
65 applyThemeToView()
66 restyleEverything()
67 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
68 }
69 }
70 private var isLoading = false
71 private var previousSelection = 0
72 /// Text before this offset is styled; after it, only base attributes until the background
73 /// passes reach it. Always at a line start.
74 private(set) var styledUpTo = 0
75 private var stylingScheduled = false
76 /// One paragraph style object per indent pair, shared by every line that uses it.
77 private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
78
79 private struct IndentKey: Hashable {
80 let firstLine: Int
81 let wrapped: Int
82 }
83
84 /// Styled before the first render: more than a screenful.
85 static let firstStyleChunk = 30_000
86 /// Styled per run-loop turn afterwards.
87 static let styleChunk = 200_000
88
89 /// Highlights code in src blocks; nil leaves code plain.
90 public let highlighter: (any CodeHighlighter)?
91
92 /// What the file is: org, or plain text, highlighted as code when the language is known.
93 public enum Mode: Equatable, Sendable {
94 case org
95 case plain(language: String?)
96 }
97
98 public let mode: Mode
99 public var isOrg: Bool { mode == .org }
100 /// The open completion list, and the pause before one opens by itself.
101 var completionPopup: CompletionPopup?
102 var completionTimer: DispatchWorkItem?
103 /// The spell checker's skipped ranges and the text they were found in.
104 var spellSkipCache: (text: String, ranges: [Range<Int>])?
105 /// Highlights of the whole file in plain mode, and the revision they were made for.
106 private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
107
108 public init(
109 document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
110 highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org, options: EditingOptions = .org
111 ) {
112 self.document = document
113 self.options = options
114 self.highlighter = highlighter
115 self.mode = mode
116 let orgTextView = OrgTextView(usingTextLayoutManager: true)
117 textView = orgTextView
118 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
119 super.init()
120 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
121 orgTextView.onCommandClick = { [weak self] offset in
122 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil else { return false }
123 self.setCaret(offset)
124 self.run("org.link.open")
125 return true
126 }
127 orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false }
128 orgTextView.onMouseDown = { [weak self] in
129 self?.markActive = false
130 self?.modalMouseDown()
131 }
132 textView.usesFindBar = true
133 textView.frame = frame
134 textView.isRichText = false
135 textView.isEditable = editable
136 textView.allowsUndo = true
137 textView.isAutomaticQuoteSubstitutionEnabled = false
138 textView.isAutomaticDashSubstitutionEnabled = false
139 textView.isAutomaticTextReplacementEnabled = false
140 textView.isAutomaticSpellingCorrectionEnabled = false
141 applyThemeToView()
142 textView.isVerticallyResizable = true
143 textView.autoresizingMask = [.width]
144 textView.textContainer?.widthTracksTextView = true
145 textView.delegate = self
146 textView.textStorage?.delegate = self
147 textLayoutManager.delegate = self
148 textContentStorage.delegate = self
149
150 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
151 load(document.text)
152 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
153 textView.setSelectedRange(NSRange(location: 0, length: 0))
154 if isOrg {
155 let words = Presentation.startupOptions(document.tree).map { $0.lowercased() }
156 indented = words.contains("indent") ? true : words.contains("noindent") ? false : options.startupIndented
157 hideStars = words.contains("hidestars") ? true : words.contains("showstars") ? false : options.hideLeadingStars
158 var startup = Presentation.startupFoldState(document.tree) ?? FoldState()
159 // VISIBILITY properties and archived trees, unless everything shows.
160 if Presentation.startupFoldState(document.tree) != nil, !words.contains("showeverything") {
161 startup = Presentation.applyVisibilityProperties(startup, in: document.tree)
162 }
163 let wrappers = Presentation.startupWrappers(document.tree, hideDrawers: options.hideDrawerStartup, hideBlocks: options.hideBlockStartup)
164 startup.wrapperFolds = Set(wrappers.map(\.start))
165 if startup != FoldState() { setFolds(startup, wrappers: wrappers) }
166 shrinkAtStartup()
167 if InlineImages.startup(document.tree) ?? options.startupWithInlineImages { showsImages = true }
168 if words.contains("align") || (options.startupAlignAllTables && !words.contains("noalign")) {
169 _ = perform(AlignAllTables())
170 }
171 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
172 }
173 spellChecking = options.spellCheck
174 truncatesLines = options.startupTruncated
175 }
176
177 /// Replaces the storage's text. Setting the attributed string directly is about 100x
178 /// faster than `NSTextView.string` for large files.
179 private func load(_ text: String) {
180 isLoading = true
181 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
182 isLoading = false
183 lines.reset(text as NSString)
184 orgTextView?.lineIndex = lines
185 orgTextView?.updateGutter()
186 styledUpTo = 0
187 styleNextChunk(Self.firstStyleChunk)
188 scheduleStyling()
189 }
190
191 // MARK: - Initial styling
192
193 /// Styles whole lines from the watermark onward, about `size` units.
194 private func styleNextChunk(_ size: Int) {
195 let text = textView.textStorage!.string as NSString
196 guard styledUpTo < text.length else { return }
197 let target = min(text.length, styledUpTo + size)
198 let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
199 restyleOutsideEditing(styledUpTo..<end)
200 styledUpTo = end
201 }
202
203 /// The text view's own colors and font, and the line numbers'.
204 private func applyThemeToView() {
205 textView.font = theme.font
206 textView.typingAttributes = theme.base
207 textView.drawsBackground = true
208 textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
209 textView.insertionPointColor = theme.color("cursor") ?? .textColor
210 textView.selectedTextAttributes = [.backgroundColor: theme.color("selection") ?? .selectedTextBackgroundColor]
211 if let view = orgTextView {
212 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
213 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
214 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
215 view.updateGutter()
216 view.needsDisplay = true
217 }
218 }
219
220 /// Styles the whole file again, a screenful now and the rest in the background.
221 private func restyleEverything() {
222 styledUpTo = 0
223 revealedLine = caretLine
224 styleNextChunk(Self.firstStyleChunk)
225 scheduleStyling()
226 }
227
228 private var caretLine: NSRange {
229 let text = textView.string as NSString
230 return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
231 }
232
233 private func scheduleStyling() {
234 guard !stylingScheduled, styledUpTo < utf16Length else { return }
235 stylingScheduled = true
236 DispatchQueue.main.async { [weak self] in
237 guard let self else { return }
238 self.stylingScheduled = false
239 self.styleNextChunk(Self.styleChunk)
240 self.scheduleStyling()
241 }
242 }
243
244 /// Styles everything still waiting for a background pass.
245 public func finishStyling() {
246 while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
247 }
248
249 public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
250 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
251 var utf16Length: Int { (textView.string as NSString).length }
252
253 /// A scroll view holding the text view, ready for a window.
254 public func makeScrollView() -> NSScrollView {
255 let scroll = NSScrollView(frame: textView.frame)
256 scroll.hasVerticalScroller = true
257 scroll.documentView = textView
258 orgTextView?.showsLineNumbers = showLineNumbers
259 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
260 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
261 return scroll
262 }
263
264 // MARK: - Saving
265
266 /// Saves through `saver`. A merge that changes the buffer reloads the text view.
267 @discardableResult
268 public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
269 try update { try saver.save(&$0, to: url) }
270 }
271
272 /// Called after every change to the document, typed or not.
273 public var onChange: (() -> Void)?
274
275 // MARK: - Commands
276
277 /// Called with messages commands report, such as why one couldn't run here.
278 public var onMessage: ((String) -> Void)?
279 /// Called with the pending prefix and what can follow it, and with nil when it ends.
280 /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
281 public var onModeChange: ((String?) -> Void)?
282 /// The selection moved.
283 public var onSelectionChange: ((NSRange) -> Void)?
284 var reportedMode: String?
285 public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
286 /// Called with `app.*` commands, which the app carries out.
287 public var onAppCommand: ((String) -> Void)?
288 /// `:e FILE`: the path as typed, for the app to open.
289 public var onOpenFile: ((String) -> Void)?
290 /// Called when a command asks a question; reply with the answer, or nil to cancel.
291 public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
292 /// Runs work outside the text, such as a table recalculation in Emacs.
293 public var onExternal: ((ExternalRequest) -> Void)?
294 /// Tags used across the workspace, for tag completion.
295 public var knownTags: @Sendable () -> [String] = { [] }
296 /// Effects other than messages, for the app to carry out.
297 public var onEffect: ((Effect) -> Void)?
298
299 public var keymap: Keymap {
300 get { dispatcher.keymap }
301 set {
302 dispatcher.keymap = newValue
303 dispatcher.reset()
304 }
305 }
306
307 public var optionAsMeta: OptionAsMeta = [.left]
308 /// Org options commands follow.
309 public var options: EditingOptions = .org {
310 didSet {
311 if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
312 }
313 }
314 /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
315 /// `options`). Hidden markup shows on the caret's line, so it can be edited.
316 public var showMarkup = true {
317 didSet { if showMarkup != oldValue { restyleEverything() } }
318 }
319 /// Line numbers in a ruler beside the text.
320 public var showLineNumbers = true {
321 didSet { orgTextView?.showsLineNumbers = showLineNumbers }
322 }
323 var orgTextView: OrgTextView? { textView as? OrgTextView }
324
325 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
326 private var revealedLine: NSRange?
327 var dispatcher: KeyDispatcher
328 /// Evil-style editing, for modal keymaps such as Doom's.
329 public var modal = false {
330 didSet {
331 guard modal != oldValue else { return }
332 vim = Vim()
333 dispatcher.mode = modal ? vim.mode.keymapMode : nil
334 dispatcher.reset()
335 updateCursor()
336 }
337 }
338 var vim = Vim()
339 /// The text and caret when insert state began, to know what was typed for `.`.
340 var insertSnapshot: (text: String, caret: Int)?
341 /// The evil cursor in visual states, where the selection's start isn't it.
342 var visualCaret: Int?
343 /// Vim marks, mapped through edits.
344 var vimMarks: [Character: Int] = [:]
345 /// Jump positions, oldest first, mapped through edits; `jumpIndex` is where C-o and C-i are.
346 var jumpList: [Int] = []
347 var jumpIndex = 0
348 /// The register keys go into while `q` records, and its keys so far.
349 var recordingRegister: Character?
350 var recordedKeys: [KeyChord] = []
351 var macros: [Character: [KeyChord]] = [:]
352 var replayingMacro = 0
353 /// A region is active: movement extends the selection, as after C-SPC in Emacs.
354 private(set) var markActive = false
355
356 public func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
357 let selected = textView.selectedRange()
358 return EditContext(
359 revision: document.revision, text: document.text, tree: document.tree,
360 selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
361 hidden: hidden.all, options: options, knownTags: knownTags,
362 lastCommand: lastCommand.flatMap { $0.revision == document.revision ? $0.id : nil }
363 )
364 }
365
366 /// Offers a key press to the keymap. False lets the text system have it.
367 func handleKey(_ event: NSEvent) -> Bool {
368 guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
369 if let handled = completionKey(chord) { return handled }
370 if modal { return handleModal(chord) }
371 switch dispatcher.feed(chord) {
372 case .pending(let keys):
373 let next = keymap.continuations(of: keys).map { item in
374 (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
375 }
376 onKeysPending?(KeySequence.format(keys), next)
377 return true
378 case .cancelled:
379 onKeysPending?(nil, [])
380 onMessage?("Quit")
381 return true
382 case .undefined(let keys):
383 onKeysPending?(nil, [])
384 onMessage?("\(KeySequence.format(keys)) is undefined")
385 return true
386 case .unbound:
387 return false
388 case .complete(let keys, let candidates):
389 if keys.count > 1 { onKeysPending?(nil, []) }
390 let context = context()
391 let runnable = candidates.first { binding in
392 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
393 }
394 if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
395 run(binding.command)
396 return true
397 }
398 return false
399 }
400 }
401
402 private func applies(_ id: String, in context: EditContext) -> Bool {
403 if !isOrg, id.hasPrefix("org.") { return false }
404 return switch EditorCommands.command(id)?.action {
405 case .text(let command): command.applies(in: context)
406 case .view where id.hasPrefix("org.table."): KeyContext.holds("table", in: context)
407 case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
408 || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
409 case .edit, .mark, .app, .find: true
410 case nil: true
411 }
412 }
413
414 /// The last command run and the revision it left, for `last-command`.
415 private var lastCommand: (id: String, revision: Int)?
416
417 /// Runs a command by id, as a key, a menu item or the palette would.
418 public func run(_ id: String) {
419 defer { lastCommand = (id, document.revision) }
420 guard let command = EditorCommands.command(id) else {
421 onMessage?("Unknown command \(id)")
422 return
423 }
424 if !isOrg, id.hasPrefix("org.") {
425 onMessage?("Not an org file")
426 return
427 }
428 // `org-ctrl-c-ctrl-c` first removes sparse tree highlights.
429 if id == "org.ctrl-c-ctrl-c", !highlights.isEmpty {
430 clearHighlights()
431 return
432 }
433 var keepMark = false
434 switch command.action {
435 case .text(let text):
436 perform(text)
437 case .view:
438 switch id {
439 case "org.cycle": cycleAtCaret()
440 case "org.cycle-global": cycleGlobal()
441 case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
442 case "org.toggle-inline-images": toggleImages()
443 case "editor.toggle-spell-check": toggleSpellCheck()
444 case "editor.complete": completeAtPoint()
445 case "editor.toggle-truncate-lines": toggleTruncateLines()
446 default: tableColumnWidth(id)
447 }
448 case .edit(let selector, let extending):
449 if markActive, let extending {
450 keepMark = true
451 textView.doCommand(by: NSSelectorFromString(extending))
452 } else {
453 textView.doCommand(by: NSSelectorFromString(selector))
454 }
455 case .find(let action):
456 let item = NSMenuItem()
457 item.tag = action.rawValue
458 textView.performTextFinderAction(item)
459 case .mark:
460 if id == "edit.set-mark" {
461 let caret = textView.selectedRange().location
462 textView.setSelectedRange(NSRange(location: caret, length: 0))
463 keepMark = true
464 onMessage?("Mark set")
465 } else {
466 let selected = textView.selectedRange()
467 if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
468 onMessage?("Quit")
469 }
470 case .app:
471 onAppCommand?(id)
472 }
473 markActive = keepMark
474 }
475
476 /// Runs `command` at the selection. Edits go through the text view, as typing does, so
477 /// they form one undo step and reach the document through the same path.
478 @discardableResult
479 public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
480 let context = context(now: now, answers: answers)
481 let step = command.run(in: context)
482 switch step {
483 case .commit(let result):
484 guard textView.isEditable || result.edits.isEmpty else {
485 onMessage?("This file is read-only.")
486 return .failed("read-only")
487 }
488 commandEditing = true
489 applyEdits(result.edits)
490 commandEditing = false
491 if let selection = result.selection?.first {
492 if hidden.containing(selection.lowerBound) != nil { unfold(around: selection.lowerBound) }
493 setCaret(selection.lowerBound)
494 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
495 }
496 for effect in result.effects {
497 switch effect {
498 case .message(let text): onMessage?(text)
499 case .sparseTree(let points, let highlights): showSparseTree(points, highlights: highlights)
500 case .fold(let start):
501 var state = foldState
502 state.folds.insert(start)
503 setFolds(state)
504 default: onEffect?(effect)
505 }
506 }
507 case .failed(let message):
508 onMessage?(message)
509 case .external(let request):
510 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
511 case .prompt(let prompt):
512 onPrompt?(prompt) { [weak self] answer in
513 guard let self else { return }
514 guard let answer else {
515 self.onMessage?("Quit")
516 return
517 }
518 self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
519 }
520 }
521 return step
522 }
523
524 // MARK: - Disk
525
526 /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
527 /// its headings.
528 @discardableResult
529 public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
530 update { $0.diskChanged(to: bytes) }
531 }
532
533 // MARK: - Folding
534
535 public var foldState: FoldState {
536 FoldState(folds: view.folds, bodyFolds: view.bodyFolds, wrapperFolds: view.wrapperFolds)
537 }
538
539 private var globalVisibility: GlobalVisibility?
540
541 public func setFolds(_ state: FoldState) {
542 setFolds(state, wrappers: nil)
543 }
544
545 /// `wrappers`, when given, holds every folded drawer and block.
546 private func setFolds(_ state: FoldState, wrappers: [Wrapper]?) {
547 sparseHidden = nil
548 view.folds = state.folds
549 view.bodyFolds = state.bodyFolds
550 view = view.pruned(to: document.tree, wrappers: false)
551 // Found one by one, or all at once when there are many.
552 let found = wrappers ?? (state.wrapperFolds.count > 32
553 ? Wrappers.all(document.tree).filter { state.wrapperFolds.contains($0.start) }
554 : state.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: document.tree) })
555 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
556 view.wrapperFolds = Set(wrapperHidden.keys)
557 updateHidden()
558 orgTextView?.redrawLineNumbers()
559 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
560 textView.needsDisplay = true
561 let caret = textView.selectedRange().location
562 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
563 }
564
565 /// What each folded drawer and block hides, by opening-line start; kept in step with
566 /// `view.wrapperFolds` and mapped through edits.
567 private var wrapperHidden: [Int: Range<Int>] = [:]
568
569 private func updateHidden() {
570 if let sparseHidden {
571 let ns = textView.string as NSString
572 // Headings whose next line is hidden show the fold ellipsis.
573 let headings = Presentation.outline(document.tree).map(\.start).filter { start in
574 let next = NSMaxRange(ns.lineRange(for: NSRange(location: start, length: 0)))
575 return sparseHidden.contains { $0.contains(next) } && !sparseHidden.contains { $0.contains(start) }
576 }
577 folded.set(Set(headings).union(view.wrapperFolds))
578 hidden.set(sparseHidden + Array(wrapperHidden.values) + narrowHidden)
579 return
580 }
581 folded.set(view.folds.union(view.bodyFolds).union(view.wrapperFolds))
582 hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds, wrapperRanges: Array(wrapperHidden.values)) + narrowHidden)
583 }
584
585 // MARK: - Sparse trees
586
587 /// What a sparse tree (`org-sparse-tree`) hides, replacing heading folds until the next
588 /// fold change. Mapped through edits.
589 private var sparseHidden: [Range<Int>]?
590 /// Sparse tree matches, highlighted until the next edit or C-c C-c.
591 private var highlights: [Range<Int>] = []
592
593 private func showSparseTree(_ points: [Int], highlights: [Range<Int>]) {
594 let text = textView.string
595 var state = foldState
596 for start in state.wrapperFolds where points.contains(where: { Wrappers.starting(at: start, in: document.tree)?.hidden.contains($0) == true }) {
597 state.wrapperFolds.remove(start)
598 }
599 sparseHidden = nil
600 setFolds(state)
601 sparseHidden = SparseTree.hidden(points, in: text, tree: document.tree)
602 self.highlights = highlights
603 updateHidden()
604 restyleOutsideEditing(0..<utf16Length)
605 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
606 orgTextView?.redrawLineNumbers()
607 textView.needsDisplay = true
608 let caret = textView.selectedRange().location
609 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
610 }
611
612 /// Leaves a sparse tree for ordinary folds: headings with something shown below them
613 /// open, the others folded.
614 private func leaveSparseTree() {
615 guard let sparse = sparseHidden else { return }
616 sparseHidden = nil
617 let outline = Presentation.outline(document.tree)
618 let ns = textView.string as NSString
619 var open: Set<Int> = []
620 for entry in outline where !sparse.contains(where: { $0.contains(entry.start) }) {
621 var parent = entry.parent
622 while let p = parent {
623 open.insert(outline[p].start)
624 parent = outline[p].parent
625 }
626 let next = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
627 if next < entry.end, !sparse.contains(where: { $0.contains(next) }) { open.insert(entry.start) }
628 }
629 var state = foldState
630 state.folds = Set(outline.map(\.start)).subtracting(open)
631 state.bodyFolds = []
632 setFolds(state)
633 }
634
635 private func clearHighlights() {
636 guard !highlights.isEmpty else { return }
637 let old = highlights
638 highlights = []
639 for range in old where range.upperBound <= utf16Length { restyleOutsideEditing(range) }
640 }
641
642 private func applyHighlights(_ range: Range<Int>, in storage: NSTextStorage) {
643 for highlight in highlights where highlight.overlaps(range) && highlight.upperBound <= storage.length {
644 storage.addAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.45), range: NSRange(highlight.clamped(to: range)))
645 }
646 }
647
648 // MARK: - STARTUP display
649
650 /// `org-indent-mode`: headings' bodies indented under their titles (`#+STARTUP: indent`).
651 private var indented = true
652 /// `org-hide-leading-stars` (`#+STARTUP: hidestars`); org-indent hides them as well.
653 private var hideStars = false
654
655 // MARK: - Inline images
656
657 /// `org-toggle-inline-images`: lines that are only an image link show the image.
658 public private(set) var showsImages = false
659 /// The file's folder, for relative image paths.
660 public var baseDirectory: URL? {
661 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
662 }
663 private static let imageCache = NSCache<NSString, NSImage>()
664
665 private func toggleImages() {
666 showsImages.toggle()
667 refreshImages()
668 if showsImages {
669 let ns = textView.string as NSString
670 var count = 0
671 var offset = 0
672 while offset < ns.length {
673 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
674 if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
675 offset = NSMaxRange(line)
676 }
677 onMessage?("\(count) images displayed inline")
678 } else {
679 onMessage?("Inline image display turned off")
680 }
681 }
682
683 private func refreshImages() {
684 restyleOutsideEditing(0..<utf16Length)
685 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
686 textView.needsDisplay = true
687 }
688
689 private func loadImage(_ path: String) -> NSImage? {
690 let expanded = (path as NSString).expandingTildeInPath
691 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
692 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
693 let key = "\(url.path)|\(modified)" as NSString
694 if let cached = Self.imageCache.object(forKey: key) { return cached }
695 guard let image = NSImage(contentsOf: url) else { return nil }
696 Self.imageCache.setObject(image, forKey: key)
697 return image
698 }
699
700 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
701 /// on the line.
702 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
703 guard showsImages, isOrg else { return }
704 let text = storage.string as NSString
705 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
706 var location = range.lowerBound
707 while location < range.upperBound, location < text.length {
708 let line = text.lineRange(for: NSRange(location: location, length: 0))
709 location = NSMaxRange(line)
710 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
711 var width = image.width.map(CGFloat.init) ?? picture.size.width
712 width = min(width, maxWidth)
713 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
714 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
715 // Invisible, keeping the line's height, so line numbers stay apart.
716 if line.location != revealed.location, content.length > 0 {
717 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
718 }
719 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
720 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
721 // The image sits where the line is; the spacing makes room for the rest of it.
722 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
723 storage.addAttribute(.paragraphStyle, value: style, range: line)
724 }
725 }
726
727 // MARK: - Narrowing
728
729 /// The text shown while narrowed (`org-narrow-to-subtree`, `org-narrow-to-block`); the
730 /// rest is hidden until `widen`. Mapped through edits.
731 public private(set) var narrowed: Range<Int>?
732
733 private func narrow(_ id: String) {
734 let caret = textView.selectedRange().location
735 do {
736 switch id {
737 case "org.narrow.subtree": narrowed = try Narrowing.subtree(at: caret, in: textView.string)
738 // `org-toggle-narrow-to-subtree`.
739 case "org.narrow.toggle": narrowed = narrowed == nil ? try Narrowing.subtree(at: caret, in: textView.string) : nil
740 case "org.narrow.block": narrowed = try Narrowing.block(at: caret, in: textView.string)
741 default: narrowed = nil
742 }
743 } catch let failure as Narrowing.Failure {
744 onMessage?(failure.message)
745 return
746 } catch {
747 return
748 }
749 updateHidden()
750 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
751 orgTextView?.redrawLineNumbers()
752 textView.needsDisplay = true
753 if let narrowed {
754 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
755 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
756 } else {
757 textView.scrollRangeToVisible(NSRange(location: caret, length: 0))
758 }
759 }
760
761 /// What narrowing hides: the text before the region, and the lines after it.
762 private var narrowHidden: [Range<Int>] {
763 guard let narrowed else { return [] }
764 let length = utf16Length
765 var ranges: [Range<Int>] = []
766 if narrowed.lowerBound > 0 { ranges.append(0..<narrowed.lowerBound) }
767 let ns = textView.string as NSString
768 let tail = narrowed.upperBound < length && ns.character(at: narrowed.upperBound) == 10 ? narrowed.upperBound + 1 : narrowed.upperBound
769 if tail < length { ranges.append(tail..<length) }
770 return ranges
771 }
772
773 // MARK: - Shrunk table columns
774
775 /// Narrowed table columns (`org-table-shrink`): by table start, each column's segments.
776 /// Recomputed as the text changes; typing into one widens its column again, as editing
777 /// org's overlays deletes them. Commands' edits keep columns narrow, as `org-table-align`
778 /// shrinks them again.
779 private var shrunk: [Int: [Int: [TableShrink.Segment]]] = [:]
780 private var commandEditing = false
781
782 /// Narrows `columns` of `table` and widens its others.
783 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
784 let text = textView.string
785 let segments = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
786 shrunk[table.lowerBound] = segments.isEmpty ? nil : segments
787 restyleOutsideEditing(table)
788 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
789 textView.needsDisplay = true
790 }
791
792 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
793 /// `expand` for `org-table-expand`.
794 private func tableColumnWidth(_ id: String) {
795 let caret = textView.selectedRange().location
796 let text = textView.string
797 guard let table = TableShrink.table(at: caret, in: text) else {
798 onMessage?("Not in a table")
799 return
800 }
801 let current = shrunk[table.lowerBound].map { Array($0.keys) } ?? []
802 switch id {
803 case "org.table.shrink": setShrunk(TableShrink.cookieColumns(table, in: text), in: table)
804 case "org.table.expand": setShrunk([], in: table)
805 default:
806 if let column = TableShrink.column(at: caret, in: text) {
807 setShrunk(Array(Set(current).symmetricDifference([column])), in: table)
808 return
809 }
810 let line = (text as NSString).lineRange(for: NSRange(location: caret, length: 0))
811 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
812 guard let self, let answer else { return }
813 self.setShrunk(Array(Set(current).symmetricDifference(TableShrink.columns(answer, max: line.length / 2))), in: table)
814 }
815 }
816 }
817
818 /// `#+STARTUP: shrink`: every table's columns with width cookies start narrow.
819 private func shrinkAtStartup() {
820 guard Presentation.startupOptions(document.tree).contains(where: { $0.lowercased() == "shrink" }) else { return }
821 let text = textView.string
822 var offset = 0
823 let ns = text as NSString
824 while offset < ns.length {
825 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
826 defer { offset = max(NSMaxRange(line), offset + 1) }
827 guard ns.substring(with: line).range(of: "^[ \\t]*\\|", options: .regularExpression) != nil,
828 let table = TableShrink.table(at: line.location, in: text) else { continue }
829 let columns = TableShrink.cookieColumns(table, in: text)
830 if !columns.isEmpty { shrunk[table.lowerBound] = Dictionary(uniqueKeysWithValues: columns.map { ($0, TableShrink.segments(table, column: $0, in: text)) }) }
831 offset = table.upperBound
832 }
833 }
834
835 /// Moves shrunk columns through `edit`; returns the tables to restyle.
836 private func mapShrunk(through edit: TextEdit) -> [Range<Int>] {
837 guard !shrunk.isEmpty else { return [] }
838 let text = textView.string
839 let delta = edit.replacement.utf16.count - edit.range.count
840 var mapped: [Int: [Int: [TableShrink.Segment]]] = [:]
841 var tables: [Range<Int>] = []
842 for (start, columns) in shrunk {
843 let kept = columns.filter { _, segments in
844 commandEditing || !segments.contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
845 }.keys
846 let touched = columns.values.joined().contains { $0.range.lowerBound <= edit.range.upperBound && edit.range.lowerBound <= $0.range.upperBound }
847 let newStart = start < edit.range.lowerBound ? start : start >= edit.range.upperBound ? start + delta : edit.range.lowerBound
848 guard let table = TableShrink.table(at: min(newStart, max(0, text.utf16.count - 1)), in: text) else { continue }
849 if touched || kept.count != columns.count { tables.append(table) }
850 guard !kept.isEmpty else { continue }
851 mapped[table.lowerBound] = Dictionary(uniqueKeysWithValues: kept.map { ($0, TableShrink.segments(table, column: $0, in: text)) })
852 }
853 shrunk = mapped
854 return tables
855 }
856
857 /// Hides each shrunk segment's text and draws its display where the text was.
858 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
859 guard !shrunk.isEmpty else { return }
860 let cell = ("0" as NSString).size(withAttributes: [.font: theme.font]).width
861 for segment in shrunk.values.flatMap({ $0.values.joined() }) where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
862 let r = segment.range
863 let shown = segment.display.count
864 let kept = min(shown, r.count)
865 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
866 guard kept > 0 else { continue }
867 let visible = NSRange(location: r.upperBound - kept, length: kept)
868 storage.addAttribute(.foregroundColor, value: NSColor.clear, range: visible)
869 storage.addAttribute(.orgEntityDisplay, value: segment.display, range: NSRange(location: visible.location, length: 1))
870 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
871 }
872 }
873
874 /// Moves drawer and block folds through `edit`, checking again only those near it.
875 private func mapWrapperFolds(through edit: TextEdit, near affected: Range<Int>) {
876 guard !wrapperHidden.isEmpty else { return }
877 var mapped: [Int: Range<Int>] = [:]
878 let entries = Array(wrapperHidden)
879 // One pass maps every start and range.
880 let moved = ViewState(selection: entries.flatMap { [$0.key..<$0.key, $0.value] }).mapped(through: [edit]).selection
881 for i in entries.indices {
882 let newStart = moved[2 * i].lowerBound
883 let newRange = moved[2 * i + 1]
884 if newStart <= affected.upperBound, newRange.upperBound >= affected.lowerBound {
885 if let wrapper = Wrappers.starting(at: newStart, in: document.tree) { mapped[newStart] = wrapper.hidden }
886 } else {
887 mapped[newStart] = newRange
888 }
889 }
890 wrapperHidden = mapped
891 view.wrapperFolds = Set(mapped.keys)
892 }
893
894 /// TAB on the first or last line of a drawer or block folds or unfolds it; on a heading,
895 /// cycles folded, children, subtree. Returns false elsewhere.
896 @discardableResult
897 public func cycleAtCaret() -> Bool {
898 leaveSparseTree()
899 let caret = textView.selectedRange().location
900 guard let state = Presentation.cycle(at: caret, in: document.tree, foldState) else { return false }
901 setFolds(state)
902 // Off a closing line that folding hid, to the opening line, as org does.
903 if let wrapper = Wrappers.toggleable(at: caret, in: document.tree), hidden.containing(caret) != nil { setCaret(wrapper.start) }
904 return true
905 }
906
907 /// Shift-TAB: overview, contents, show all.
908 public func cycleGlobal() {
909 leaveSparseTree()
910 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: view.wrapperFolds)
911 globalVisibility = visibility
912 setFolds(state)
913 }
914
915 /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
916 public func reveal(_ offset: Int) {
917 let target = max(0, min(offset, utf16Length))
918 if let narrowed, !(narrowed.lowerBound...narrowed.upperBound).contains(target) { narrow("org.widen") }
919 unfold(around: target)
920 setCaret(target)
921 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
922 }
923
924 /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
925 func unfold(around offset: Int) {
926 leaveSparseTree()
927 var state = foldState
928 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
929 state.folds.remove(entry.start)
930 state.bodyFolds.remove(entry.start)
931 }
932 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
933 state.wrapperFolds.remove(start)
934 }
935 guard state != foldState else { return }
936 setFolds(state)
937 }
938
939 /// Applies edits through the text view as one undo step, not merged with typing around it.
940 func applyEdits(_ edits: [TextEdit]) {
941 guard !edits.isEmpty, let storage = textView.textStorage else { return }
942 textView.breakUndoCoalescing()
943 textView.undoManager?.beginUndoGrouping()
944 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
945 let range = NSRange(edit.range)
946 guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
947 storage.replaceCharacters(in: range, with: edit.replacement)
948 textView.didChangeText()
949 }
950 textView.undoManager?.endUndoGrouping()
951 textView.breakUndoCoalescing()
952 }
953
954 func setCaret(_ offset: Int) {
955 let clamped = max(0, min(offset, utf16Length))
956 previousSelection = clamped
957 textView.setSelectedRange(NSRange(location: clamped, length: 0))
958 }
959
960 // MARK: - Styling
961
962 private func restyleOutsideEditing(_ range: Range<Int>) {
963 guard let storage = textView.textStorage else { return }
964 storage.beginEditing()
965 restyle(range, in: storage)
966 storage.endEditing()
967 }
968
969 /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
970 /// attribute changes are allowed and characters must not change.
971 private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
972 guard !range.isEmpty else { return }
973 let whole = NSRange(range)
974 storage.setAttributes(theme.base, range: whole)
975 guard isOrg else {
976 for run in plainRuns() where run.range.overlaps(range) {
977 guard let clipped = clip(run.range, to: range) else { continue }
978 theme.apply(.syntax(run.category), to: storage, range: clipped)
979 }
980 return
981 }
982 let text = storage.string as NSString
983 for run in Presentation.indents(document.tree, in: range) where indented {
984 guard let clipped = clip(run.range, to: range) else { continue }
985 guard run.firstLine == run.wrapped else {
986 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
987 continue
988 }
989 // Body lines wrap under their own text: past leading blanks, and past a list bullet
990 // and checkbox, as adaptive-wrap does in Emacs.
991 var location = clipped.location
992 while location < NSMaxRange(clipped) {
993 let line = text.lineRange(for: NSRange(location: location, length: 0))
994 let hanging = Self.hangingColumns(text.substring(with: line))
995 let lineRange = NSIntersectionRange(line, clipped)
996 storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
997 location = NSMaxRange(line)
998 }
999 }
1000 let revealed = caretLine
1001 var scriptExclusions: [Range<Int>] = []
1002 for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
1003 guard let clipped = clip(run.range, to: range) else { continue }
1004 if run.role == .leadingStars, !indented, !hideStars { continue }
1005 if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
1006 storage.addAttributes(theme.hidden, range: clipped)
1007 } else {
1008 theme.apply(run.role, to: storage, range: clipped)
1009 }
1010 switch run.role {
1011 case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: scriptExclusions.append(run.range)
1012 default: break
1013 }
1014 }
1015 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
1016 applyShrunk(range, in: storage)
1017 applyHighlights(range, in: storage)
1018 applyImages(range, in: storage, revealed: revealed)
1019 }
1020
1021 /// `org-pretty-entities`: entities drawn as their character over the entity's last
1022 /// character (the rest hidden), sub/superscripts raised without their markers. Not on the
1023 /// caret's line, in comments or in blocks; sub/superscripts not in emphasis, links or
1024 /// keywords, as `org-raise-scripts` leaves them.
1025 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
1026 let text = storage.string as NSString
1027 var location = range.lowerBound
1028 while location < range.upperBound {
1029 let line = text.lineRange(for: NSRange(location: location, length: 0))
1030 guard line.length > 0 else { break }
1031 location = NSMaxRange(line)
1032 if line.location == revealed.location || shaded.containing(line.location) != nil { continue }
1033 let content = text.substring(with: line)
1034 if content.range(of: "^[ \\t]*#([ +]|$)", options: .regularExpression) != nil { continue }
1035 for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces) {
1036 switch run {
1037 case .entity(let r, let display):
1038 let start = line.location + r.lowerBound
1039 let last = line.location + r.upperBound - 1
1040 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
1041 storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
1042 case .script(let markers, let body, let superscript):
1043 let bodyStart = line.location + body.lowerBound
1044 if scriptExclusions.contains(where: { $0.contains(bodyStart) }) || body.isEmpty { continue }
1045 for marker in markers {
1046 storage.addAttributes(theme.hidden, range: NSRange(location: line.location + marker.lowerBound, length: marker.count))
1047 }
1048 let size = theme.font.pointSize
1049 storage.addAttributes([
1050 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
1051 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
1052 ], range: NSRange(location: bodyStart, length: body.count))
1053 }
1054 }
1055 }
1056 }
1057
1058 /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
1059 /// markers only when Emacs hides them too.
1060 private func hides(_ role: StyleRole) -> Bool {
1061 switch role {
1062 case .linkMarkup: true
1063 case .markup: options.hideEmphasisMarkers
1064 default: false
1065 }
1066 }
1067
1068 /// Moving to another line shows its markup and hides the last one's.
1069 private func revealCaretLine() {
1070 guard !showMarkup, isOrg else { return }
1071 let line = caretLine
1072 guard line != revealedLine else { return }
1073 let text = textView.string as NSString
1074 // The old line may have moved with edits since; restyle the line now at its start.
1075 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
1076 revealedLine = line
1077 for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
1078 restyleOutsideEditing(range.location..<NSMaxRange(range))
1079 }
1080 }
1081
1082 /// Code highlights for the whole file in plain mode.
1083 private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
1084 guard case .plain(let language?) = mode, let highlighter else { return [] }
1085 if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
1086 let runs = highlighter.highlights(language: language, code: document.text)
1087 codeRuns = (document.revision, runs)
1088 return runs
1089 }
1090
1091 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
1092 let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
1093 if let style = paragraphStyles[key] { return style }
1094 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
1095 paragraphStyles[key] = style
1096 return style
1097 }
1098
1099 private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
1100 let clipped = run.clamped(to: range)
1101 return clipped.isEmpty ? nil : NSRange(clipped)
1102 }
1103
1104 /// The region an edit affects in one version of the tree: inside the innermost section
1105 /// holding the edited lines (plus the line after), every element that overlaps them or the
1106 /// line on either side. A changed heading line, or an added or removed heading, widens it
1107 /// to that section's whole own body. Run on the old and the new tree, the union covers
1108 /// elements that grew and elements that shrank.
1109 static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
1110 let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
1111 let lineRange = lines.location..<(lines.location + lines.length)
1112 let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
1113 var container = tree.root
1114 while let child = container.child(containing: lineRange.lowerBound),
1115 child.kind == .section || child.kind == .zerothSection,
1116 lineRange.upperBound <= child.range.upperBound {
1117 container = child
1118 }
1119 var lower = lineRange.lowerBound
1120 var upper = lineRange.upperBound
1121 // Tables and lists carry no styling of their own, so inside them only the rows or
1122 // items around the edit change, however large they are.
1123 func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
1124 nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
1125 guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
1126 let inner = overlapping(node.children(overlapping: around))
1127 return inner.isEmpty ? [node] : inner
1128 }
1129 }
1130 for child in overlapping(container.children(overlapping: around)) {
1131 lower = min(lower, child.range.lowerBound)
1132 upper = max(upper, child.range.upperBound)
1133 }
1134 let heading = container.firstChild(.heading)
1135 if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
1136 lower = min(lower, container.range.lowerBound)
1137 upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
1138 }
1139 return lower..<min(upper, text.length)
1140 }
1141
1142 // MARK: - Editing
1143
1144 private var blockCheck: DispatchWorkItem?
1145
1146 /// Looks for blocks over the whole file once typing pauses, catching what moving the
1147 /// ranges can't see (a block's end found far away).
1148 private func scheduleBlockCheck() {
1149 blockCheck?.cancel()
1150 let work = DispatchWorkItem { [weak self] in self?.settleBlocks() }
1151 blockCheck = work
1152 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
1153 }
1154
1155 func settleBlocks() {
1156 blockCheck?.cancel()
1157 guard isOrg else { return }
1158 let blocks = Presentation.shadedBlocks(document.tree)
1159 guard blocks != shaded.all else { return }
1160 shaded.set(blocks)
1161 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1162 }
1163
1164 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
1165 /// them), hold a block delimiter or a fixed-width line.
1166 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
1167 let start = min(range.lowerBound, text.length)
1168 let end = min(range.upperBound + 1, text.length)
1169 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
1170 let content = text.substring(with: lines)
1171 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
1172 }
1173
1174 fileprivate func storageEdited(range: NSRange, delta: Int) {
1175 guard !isLoading, let storage = textView.textStorage else { return }
1176 markActive = false
1177 let clock = ContinuousClock()
1178 let start = clock.now
1179 let replacement = (storage.string as NSString).substring(with: range)
1180 let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
1181 let oldText = document.text as NSString
1182 let newText = storage.string as NSString
1183 let newEnd = edit.range.lowerBound + replacement.utf16.count
1184 let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
1185 || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
1186 let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
1187 do {
1188 try document.apply([edit], baseRevision: document.revision)
1189 } catch {
1190 assertionFailure("text view and document disagree: \(error)")
1191 return
1192 }
1193 // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
1194 // edited line when the edit reaches into unstyled text.
1195 if styledUpTo >= edit.range.upperBound {
1196 styledUpTo += edit.replacement.utf16.count - edit.range.count
1197 } else if styledUpTo > edit.range.lowerBound {
1198 styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
1199 }
1200 let oldHidden = hidden.all
1201 let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
1202 let delta = edit.replacement.utf16.count - edit.range.count
1203 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
1204 view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false)
1205 mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound))
1206 if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] }
1207 mapVimPositions(through: edit)
1208 if let sparse = sparseHidden { sparseHidden = ViewState(selection: sparse).mapped(through: [edit]).selection.filter { !$0.isEmpty } }
1209 let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection
1210 highlights = []
1211 updateHidden()
1212 restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
1213 for table in mapShrunk(through: edit) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) }
1214 for range in oldHighlights where range.upperBound <= newText.length {
1215 let lines = newText.lineRange(for: NSRange(range))
1216 restyle(lines.location..<NSMaxRange(lines), in: storage)
1217 }
1218 let oldShaded = shaded.all
1219 if isOrg {
1220 // Walking the tree for blocks costs more than typing; only an edit on a line that
1221 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
1222 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
1223 shaded.set(Presentation.shadedBlocks(document.tree))
1224 } else {
1225 shaded.set(oldShaded.map { mapRange($0, through: edit) })
1226 }
1227 scheduleBlockCheck()
1228 }
1229 if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
1230 || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
1231 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
1232 }
1233 onEditTiming?(clock.now - start)
1234 let lineCount = lines.lineCount
1235 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
1236 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
1237 orgTextView?.redrawLineNumbers()
1238 onChange?()
1239 }
1240
1241 /// Columns a wrapped continuation of `line` should start past the line's own start.
1242 nonisolated static func hangingColumns(_ line: String) -> Int {
1243 var columns = 0
1244 var rest = Substring(line)
1245 while let c = rest.first, c == " " || c == "\t" {
1246 columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
1247 rest = rest.dropFirst()
1248 }
1249 // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
1250 var bullet = 0
1251 if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
1252 bullet = 1
1253 } else {
1254 let digits = rest.prefix { $0.isASCII && $0.isNumber }
1255 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
1256 bullet = digits.count + 1
1257 }
1258 }
1259 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
1260 columns += bullet + 1
1261 let afterBullet = rest.dropFirst(bullet + 1)
1262 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
1263 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
1264 columns += 4
1265 }
1266 return columns
1267 }
1268
1269 /// Whether a heading line touches `start..<end` or starts right after it, where joining
1270 /// lines could take it away.
1271 static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
1272 let length = min(end + 1, text.length) - start
1273 guard length >= 0 else { return false }
1274 let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
1275 return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
1276 let stars = line.prefix { $0 == "*" }
1277 let after = line.dropFirst(stars.count)
1278 return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
1279 }
1280 }
1281
1282 private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
1283 let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
1284 return mapped
1285 }
1286
1287 /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
1288 /// back jumps to the end of the heading line.
1289 func selectionChanged() {
1290 let selection = textView.selectedRange()
1291 defer { previousSelection = selection.location }
1292 onSelectionChange?(selection)
1293 revealCaretLine()
1294 orgTextView?.redrawLineNumbers()
1295 // Narrowing keeps the caret in the region.
1296 if let narrowed, selection.length == 0, !(narrowed.lowerBound...narrowed.upperBound).contains(selection.location) {
1297 setCaret(max(narrowed.lowerBound, min(selection.location, narrowed.upperBound)))
1298 return
1299 }
1300 // A selection reaching into folded text, as a find match does, unfolds it.
1301 if selection.length > 0 {
1302 if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
1303 unfold(around: selection.location)
1304 unfold(around: NSMaxRange(selection) - 1)
1305 }
1306 return
1307 }
1308 guard let range = hidden.containing(selection.location) else { return }
1309 setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
1310 }
1311}
1312
1313extension OrgEditor: DocumentBuffer {
1314 /// The selected text, for capture's `%i`.
1315 public var selectedText: String {
1316 let range = textView.selectedRange()
1317 guard range.length > 0 else { return "" }
1318 return (textView.string as NSString).substring(with: range)
1319 }
1320
1321 public var selection: [Range<Int>] {
1322 let selected = textView.selectedRange()
1323 return [selected.location..<NSMaxRange(selected)]
1324 }
1325
1326 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
1327 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
1328 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
1329 let before = document.text
1330 let selected = textView.selectedRange()
1331 let result = try change(&document)
1332 if document.text != before {
1333 let edits = lineEdits(from: before, to: document.text)
1334 var state = view
1335 state.selection = [selected.location..<NSMaxRange(selected)]
1336 let mapped = state.mapped(through: edits)
1337 load(document.text)
1338 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
1339 let selection = mapped.selection[0]
1340 setCaret(selection.lowerBound)
1341 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
1342 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
1343 textView.undoManager?.removeAllActions(withTarget: textView)
1344 }
1345 onChange?()
1346 return result
1347 }
1348}
1349
1350extension OrgEditor: NSTextStorageDelegate {
1351 public nonisolated func textStorage(
1352 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
1353 ) {
1354 guard editedMask.contains(.editedCharacters) else { return }
1355 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
1356 }
1357}
1358
1359extension OrgEditor: NSTextContentStorageDelegate {
1360 /// Folded text isn't enumerated, so it isn't laid out or drawn.
1361 public nonisolated func textContentManager(
1362 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
1363 ) -> Bool {
1364 guard let range = textElement.elementRange else { return true }
1365 let documentStart = textContentManager.documentRange.location
1366 let start = textContentManager.offset(from: documentStart, to: range.location)
1367 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
1368 return !hidden.covers(start, end)
1369 }
1370}
1371
1372extension OrgEditor: NSTextLayoutManagerDelegate {
1373 public nonisolated func textLayoutManager(
1374 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
1375 ) -> NSTextLayoutFragment {
1376 let range = textElement.elementRange
1377 if let range, let manager = textLayoutManager.textContentManager {
1378 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
1379 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
1380 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
1381 if let paragraph = textElement as? NSTextParagraph, ImageFragment.image(paragraph.attributedString) != nil {
1382 return ImageFragment(textElement: textElement, range: range)
1383 }
1384 if let paragraph = textElement as? NSTextParagraph, EntityFragment.hasEntities(paragraph.attributedString) {
1385 return EntityFragment(textElement: textElement, range: range)
1386 }
1387 }
1388 return NSTextLayoutFragment(textElement: textElement, range: range)
1389 }
1390}
1391
1392/// A line of a block, on a band across the whole width of the view, as Emacs extends the
1393/// `org-block` face.
1394final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
1395 private var band: CGRect {
1396 let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
1397 // Not under the empty line TextKit adds after a final newline.
1398 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1399 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: height)
1400 }
1401
1402 override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
1403
1404 override func draw(at point: CGPoint, in context: CGContext) {
1405 context.saveGState()
1406 context.setFillColor(Theme.blockBackground.cgColor)
1407 context.fill(band.offsetBy(dx: point.x, dy: point.y))
1408 context.restoreGState()
1409 super.draw(at: point, in: context)
1410 }
1411}
1412
1413extension NSAttributedString.Key {
1414 /// The character an entity shows as, on the entity's last character.
1415 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
1416 /// The image an image link's line shows under it.
1417 static let orgImage = NSAttributedString.Key("OrgImage")
1418}
1419
1420final class InlineImageBox: NSObject, @unchecked Sendable {
1421 let image: NSImage
1422 let size: CGSize
1423 init(image: NSImage, size: CGSize) {
1424 self.image = image
1425 self.size = size
1426 }
1427}
1428
1429/// An image link's line drawn as the image, with the paragraph spacing making room for its
1430/// height.
1431final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
1432 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1433 var found: InlineImageBox?
1434 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1435 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1436 }
1437 return found
1438 }
1439
1440 private var frame: CGRect? {
1441 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
1442 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
1443 }
1444
1445 override var renderingSurfaceBounds: CGRect {
1446 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
1447 }
1448
1449 override func draw(at point: CGPoint, in context: CGContext) {
1450 super.draw(at: point, in: context)
1451 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
1452 NSGraphicsContext.saveGraphicsState()
1453 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1454 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
1455 NSGraphicsContext.restoreGraphicsState()
1456 }
1457}
1458
1459/// A paragraph with pretty entities: each is drawn as its character where the entity's last
1460/// (now invisible) character sits, so it takes one column as in Emacs.
1461final class EntityFragment: NSTextLayoutFragment, @unchecked Sendable {
1462 static func hasEntities(_ string: NSAttributedString) -> Bool {
1463 var found = false
1464 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1465 if value != nil { found = true; stop.pointee = true }
1466 }
1467 return found
1468 }
1469
1470 override func draw(at point: CGPoint, in context: CGContext) {
1471 super.draw(at: point, in: context)
1472 Self.drawEntities(of: self, at: point, in: context)
1473 }
1474
1475 static func drawEntities(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
1476 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString else { return }
1477 NSGraphicsContext.saveGraphicsState()
1478 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1479 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1480 guard let display = value as? String,
1481 let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1482 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1483 attributes[.foregroundColor] = NSColor.textColor
1484 attributes[.orgEntityDisplay] = nil
1485 let x = line.locationForCharacter(at: range.location).x
1486 let bounds = line.typographicBounds
1487 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1488 }
1489 NSGraphicsContext.restoreGraphicsState()
1490 }
1491}
1492
1493/// A heading line drawn with an ellipsis after it, like org's folded headings.
1494final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
1495 override func draw(at point: CGPoint, in context: CGContext) {
1496 super.draw(at: point, in: context)
1497 EntityFragment.drawEntities(of: self, at: point, in: context)
1498 guard let line = textLineFragments.first else { return }
1499 let bounds = line.typographicBounds
1500 let ellipsis = NSAttributedString(string: " …", attributes: [
1501 .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
1502 .foregroundColor: NSColor.secondaryLabelColor,
1503 ])
1504 NSGraphicsContext.saveGraphicsState()
1505 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
1506 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1507 NSGraphicsContext.restoreGraphicsState()
1508 }
1509
1510 override var renderingSurfaceBounds: CGRect {
1511 super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
1512 }
1513}
1514#endif