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