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