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