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