Sources/OrgEditorAppKit/OrgEditor.swift

cfb37bd8ac1997e58fa785317197bbb0959d1d0b
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

853 lines · 38245 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    /// Blocks drawn on a shaded band.
 56    let shaded = HiddenRanges()
 57    let theme = Theme()
 58    private var isLoading = false
 59    private var previousSelection = 0
 60    /// Text before this offset is styled; after it, only base attributes until the background
 61    /// passes reach it. Always at a line start.
 62    private(set) var styledUpTo = 0
 63    private var stylingScheduled = false
 64    /// One paragraph style object per indent pair, shared by every line that uses it.
 65    private var paragraphStyles: [IndentKey: NSParagraphStyle] = [:]
 66
 67    private struct IndentKey: Hashable {
 68        let firstLine: Int
 69        let wrapped: Int
 70    }
 71
 72    /// Styled before the first render: more than a screenful.
 73    static let firstStyleChunk = 30_000
 74    /// Styled per run-loop turn afterwards.
 75    static let styleChunk = 200_000
 76
 77    /// Highlights code in src blocks; nil leaves code plain.
 78    public let highlighter: (any CodeHighlighter)?
 79
 80    /// What the file is: org, or plain text, highlighted as code when the language is known.
 81    public enum Mode: Equatable, Sendable {
 82        case org
 83        case plain(language: String?)
 84    }
 85
 86    public let mode: Mode
 87    public var isOrg: Bool { mode == .org }
 88    /// Highlights of the whole file in plain mode, and the revision they were made for.
 89    private var codeRuns: (revision: Int, runs: [(range: Range<Int>, category: SyntaxCategory)])?
 90
 91    public init(
 92        document: DocumentState, frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800), editable: Bool = true,
 93        highlighter: (any CodeHighlighter)? = nil, mode: Mode = .org
 94    ) {
 95        self.document = document
 96        self.highlighter = highlighter
 97        self.mode = mode
 98        let orgTextView = OrgTextView(usingTextLayoutManager: true)
 99        textView = orgTextView
100        dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
101        super.init()
102        orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
103        orgTextView.onMouseDown = { [weak self] in
104            self?.markActive = false
105            self?.modalMouseDown()
106        }
107        textView.usesFindBar = true
108        textView.frame = frame
109        textView.isRichText = false
110        textView.isEditable = editable
111        textView.allowsUndo = true
112        textView.isAutomaticQuoteSubstitutionEnabled = false
113        textView.isAutomaticDashSubstitutionEnabled = false
114        textView.isAutomaticTextReplacementEnabled = false
115        textView.isAutomaticSpellingCorrectionEnabled = false
116        textView.font = theme.font
117        textView.typingAttributes = theme.base
118        textView.isVerticallyResizable = true
119        textView.autoresizingMask = [.width]
120        textView.textContainer?.widthTracksTextView = true
121        textView.delegate = self
122        textView.textStorage?.delegate = self
123        textLayoutManager.delegate = self
124        textContentStorage.delegate = self
125
126        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
127        load(document.text)
128        if isOrg, let startup = Presentation.startupFoldState(document.tree) { setFolds(startup) }
129    }
130
131    /// Replaces the storage's text. Setting the attributed string directly is about 100x
132    /// faster than `NSTextView.string` for large files.
133    private func load(_ text: String) {
134        isLoading = true
135        textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
136        isLoading = false
137        styledUpTo = 0
138        styleNextChunk(Self.firstStyleChunk)
139        scheduleStyling()
140    }
141
142    // MARK: - Initial styling
143
144    /// Styles whole lines from the watermark onward, about `size` units.
145    private func styleNextChunk(_ size: Int) {
146        let text = textView.textStorage!.string as NSString
147        guard styledUpTo < text.length else { return }
148        let target = min(text.length, styledUpTo + size)
149        let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
150        restyleOutsideEditing(styledUpTo..<end)
151        styledUpTo = end
152    }
153
154    /// Styles the whole file again, a screenful now and the rest in the background.
155    private func restyleEverything() {
156        styledUpTo = 0
157        revealedLine = caretLine
158        styleNextChunk(Self.firstStyleChunk)
159        scheduleStyling()
160    }
161
162    private var caretLine: NSRange {
163        let text = textView.string as NSString
164        return text.lineRange(for: NSRange(location: min(textView.selectedRange().location, text.length), length: 0))
165    }
166
167    private func scheduleStyling() {
168        guard !stylingScheduled, styledUpTo < utf16Length else { return }
169        stylingScheduled = true
170        DispatchQueue.main.async { [weak self] in
171            guard let self else { return }
172            self.stylingScheduled = false
173            self.styleNextChunk(Self.styleChunk)
174            self.scheduleStyling()
175        }
176    }
177
178    /// Styles everything still waiting for a background pass.
179    public func finishStyling() {
180        while styledUpTo < utf16Length { styleNextChunk(Self.styleChunk) }
181    }
182
183    public var textLayoutManager: NSTextLayoutManager { textView.textLayoutManager! }
184    var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
185    var utf16Length: Int { (textView.string as NSString).length }
186
187    /// A scroll view holding the text view, ready for a window.
188    public func makeScrollView() -> NSScrollView {
189        let scroll = NSScrollView(frame: textView.frame)
190        scroll.hasVerticalScroller = true
191        scroll.documentView = textView
192        textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
193        textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
194        return scroll
195    }
196
197    // MARK: - Saving
198
199    /// Saves through `saver`. A merge that changes the buffer reloads the text view.
200    @discardableResult
201    public func save(using saver: Saver, to url: URL) throws -> SaveOutcome {
202        try update { try saver.save(&$0, to: url) }
203    }
204
205    /// Called after every change to the document, typed or not.
206    public var onChange: (() -> Void)?
207
208    // MARK: - Commands
209
210    /// Called with messages commands report, such as why one couldn't run here.
211    public var onMessage: ((String) -> Void)?
212    /// Called with the pending prefix and what can follow it, and with nil when it ends.
213    /// The evil state when editing modally (`normal`, `insert`, `visual`, `visual-line`), nil otherwise.
214    public var onModeChange: ((String?) -> Void)?
215    /// The selection moved.
216    public var onSelectionChange: ((NSRange) -> Void)?
217    var reportedMode: String?
218    public var onKeysPending: ((_ keys: String?, _ next: [(key: String, title: String)]) -> Void)?
219    /// Called with `app.*` commands, which the app carries out.
220    public var onAppCommand: ((String) -> Void)?
221    /// Called when a command asks a question; reply with the answer, or nil to cancel.
222    public var onPrompt: ((Prompt, _ reply: @escaping (String?) -> Void) -> Void)?
223    /// Runs work outside the text, such as a table recalculation in Emacs.
224    public var onExternal: ((ExternalRequest) -> Void)?
225
226    public var keymap: Keymap {
227        get { dispatcher.keymap }
228        set {
229            dispatcher.keymap = newValue
230            dispatcher.reset()
231        }
232    }
233
234    public var optionAsMeta: OptionAsMeta = [.left]
235    /// Org options commands follow.
236    public var options: EditingOptions = .org {
237        didSet {
238            if options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers, !showMarkup { restyleEverything() }
239        }
240    }
241    /// Show link brackets and targets, and emphasis markers (when Emacs hides them, per
242    /// `options`). Hidden markup shows on the caret's line, so it can be edited.
243    public var showMarkup = true {
244        didSet { if showMarkup != oldValue { restyleEverything() } }
245    }
246    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
247    private var revealedLine: NSRange?
248    var dispatcher: KeyDispatcher
249    /// Evil-style editing, for modal keymaps such as Doom's.
250    public var modal = false {
251        didSet {
252            guard modal != oldValue else { return }
253            vim = Vim()
254            dispatcher.mode = modal ? vim.mode.keymapMode : nil
255            dispatcher.reset()
256            updateCursor()
257        }
258    }
259    var vim = Vim()
260    /// The text and caret when insert state began, to know what was typed for `.`.
261    var insertSnapshot: (text: String, caret: Int)?
262    /// The evil cursor in visual states, where the selection's start isn't it.
263    var visualCaret: Int?
264    /// A region is active: movement extends the selection, as after C-SPC in Emacs.
265    private(set) var markActive = false
266
267    private func context(now: Date = Date(), answers: [String: String] = [:]) -> EditContext {
268        let selected = textView.selectedRange()
269        return EditContext(
270            revision: document.revision, text: document.text, tree: document.tree,
271            selection: [selected.location..<NSMaxRange(selected)], now: now, calendar: .current, answers: answers,
272            hidden: hidden.all, options: options
273        )
274    }
275
276    /// Offers a key press to the keymap. False lets the text system have it.
277    func handleKey(_ event: NSEvent) -> Bool {
278        guard let chord = KeyEvents.chord(for: event, optionAsMeta: optionAsMeta) else { return modal && vim.mode != .insert }
279        if modal { return handleModal(chord) }
280        switch dispatcher.feed(chord) {
281        case .pending(let keys):
282            let next = keymap.continuations(of: keys).map { item in
283                (key: item.key.description, title: item.command.map { EditorCommands.command($0)?.title ?? $0 } ?? "+prefix")
284            }
285            onKeysPending?(KeySequence.format(keys), next)
286            return true
287        case .cancelled:
288            onKeysPending?(nil, [])
289            onMessage?("Quit")
290            return true
291        case .undefined(let keys):
292            onKeysPending?(nil, [])
293            onMessage?("\(KeySequence.format(keys)) is undefined")
294            return true
295        case .unbound:
296            return false
297        case .complete(let keys, let candidates):
298            if keys.count > 1 { onKeysPending?(nil, []) }
299            let context = context()
300            let runnable = candidates.first { binding in
301                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
302            }
303            if let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) {
304                run(binding.command)
305                return true
306            }
307            return false
308        }
309    }
310
311    private func applies(_ id: String, in context: EditContext) -> Bool {
312        if !isOrg, id.hasPrefix("org.") { return false }
313        return switch EditorCommands.command(id)?.action {
314        case .text(let command): command.applies(in: context)
315        case .view: id != "org.cycle" || Presentation.heading(containing: context.caret, in: context.tree) != nil
316        case .edit, .mark, .app, .find: true
317        case nil: true
318        }
319    }
320
321    /// Runs a command by id, as a key, a menu item or the palette would.
322    public func run(_ id: String) {
323        guard let command = EditorCommands.command(id) else {
324            onMessage?("Unknown command \(id)")
325            return
326        }
327        if !isOrg, id.hasPrefix("org.") {
328            onMessage?("Not an org file")
329            return
330        }
331        var keepMark = false
332        switch command.action {
333        case .text(let text):
334            perform(text)
335        case .view:
336            if id == "org.cycle" { cycleAtCaret() } else { cycleGlobal() }
337        case .edit(let selector, let extending):
338            if markActive, let extending {
339                keepMark = true
340                textView.doCommand(by: NSSelectorFromString(extending))
341            } else {
342                textView.doCommand(by: NSSelectorFromString(selector))
343            }
344        case .find(let action):
345            let item = NSMenuItem()
346            item.tag = action.rawValue
347            textView.performTextFinderAction(item)
348        case .mark:
349            if id == "edit.set-mark" {
350                let caret = textView.selectedRange().location
351                textView.setSelectedRange(NSRange(location: caret, length: 0))
352                keepMark = true
353                onMessage?("Mark set")
354            } else {
355                let selected = textView.selectedRange()
356                if markActive || selected.length > 0 { textView.setSelectedRange(NSRange(location: NSMaxRange(selected), length: 0)) }
357                onMessage?("Quit")
358            }
359        case .app:
360            onAppCommand?(id)
361        }
362        markActive = keepMark
363    }
364
365    /// Runs `command` at the selection. Edits go through the text view, as typing does, so
366    /// they form one undo step and reach the document through the same path.
367    @discardableResult
368    public func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
369        let context = context(now: now, answers: answers)
370        let step = command.run(in: context)
371        switch step {
372        case .commit(let result):
373            guard textView.isEditable || result.edits.isEmpty else {
374                onMessage?("This file is read-only.")
375                return .failed("read-only")
376            }
377            applyEdits(result.edits)
378            if let selection = result.selection?.first {
379                setCaret(selection.lowerBound)
380                if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
381            }
382            for case .message(let text) in result.effects { onMessage?(text) }
383        case .failed(let message):
384            onMessage?(message)
385        case .external(let request):
386            if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") }
387        case .prompt(let prompt):
388            onPrompt?(prompt) { [weak self] answer in
389                guard let self else { return }
390                guard let answer else {
391                    self.onMessage?("Quit")
392                    return
393                }
394                self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
395            }
396        }
397        return step
398    }
399
400    // MARK: - Disk
401
402    /// The file on disk now holds `bytes`: reload or merge, keeping folds where the text kept
403    /// its headings.
404    @discardableResult
405    public func diskChanged(to bytes: [UInt8]) -> DocumentState.ExternalChange {
406        update { $0.diskChanged(to: bytes) }
407    }
408
409    // MARK: - Folding
410
411    public var foldState: FoldState {
412        FoldState(folds: view.folds, bodyFolds: view.bodyFolds)
413    }
414
415    private var globalVisibility: GlobalVisibility?
416
417    public func setFolds(_ state: FoldState) {
418        view.folds = state.folds
419        view.bodyFolds = state.bodyFolds
420        view = view.pruned(to: document.tree)
421        updateHidden()
422        textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
423        textView.needsDisplay = true
424        let caret = textView.selectedRange().location
425        if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
426    }
427
428    private func updateHidden() {
429        folded.set(view.folds.union(view.bodyFolds))
430        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds, bodyFolds: view.bodyFolds))
431    }
432
433    /// TAB on a heading: folded, children, subtree. Returns false off a heading.
434    @discardableResult
435    public func cycleAtCaret() -> Bool {
436        guard let heading = Presentation.heading(containing: textView.selectedRange().location, in: document.tree) else { return false }
437        setFolds(Presentation.cycle(heading, in: document.tree, foldState))
438        return true
439    }
440
441    /// Shift-TAB: overview, contents, show all.
442    public func cycleGlobal() {
443        let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree)
444        globalVisibility = visibility
445        setFolds(state)
446    }
447
448    /// Unfolds whatever hides `offset`, puts the caret there and scrolls to it.
449    public func reveal(_ offset: Int) {
450        let target = max(0, min(offset, utf16Length))
451        unfold(around: target)
452        setCaret(target)
453        textView.scrollRangeToVisible(NSRange(location: target, length: 0))
454    }
455
456    /// Unfolds the headings whose folds hide `offset`, leaving the selection alone.
457    func unfold(around offset: Int) {
458        var state = foldState
459        for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
460            state.folds.remove(entry.start)
461            state.bodyFolds.remove(entry.start)
462        }
463        guard state != foldState else { return }
464        setFolds(state)
465    }
466
467    /// Applies edits through the text view as one undo step, not merged with typing around it.
468    func applyEdits(_ edits: [TextEdit]) {
469        guard !edits.isEmpty, let storage = textView.textStorage else { return }
470        textView.breakUndoCoalescing()
471        textView.undoManager?.beginUndoGrouping()
472        for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
473            let range = NSRange(edit.range)
474            guard textView.shouldChangeText(in: range, replacementString: edit.replacement) else { continue }
475            storage.replaceCharacters(in: range, with: edit.replacement)
476            textView.didChangeText()
477        }
478        textView.undoManager?.endUndoGrouping()
479        textView.breakUndoCoalescing()
480    }
481
482    func setCaret(_ offset: Int) {
483        let clamped = max(0, min(offset, utf16Length))
484        previousSelection = clamped
485        textView.setSelectedRange(NSRange(location: clamped, length: 0))
486    }
487
488    // MARK: - Styling
489
490    private func restyleOutsideEditing(_ range: Range<Int>) {
491        guard let storage = textView.textStorage else { return }
492        storage.beginEditing()
493        restyle(range, in: storage)
494        storage.endEditing()
495    }
496
497    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
498    /// attribute changes are allowed and characters must not change.
499    private func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
500        guard !range.isEmpty else { return }
501        let whole = NSRange(range)
502        storage.setAttributes(theme.base, range: whole)
503        guard isOrg else {
504            for run in plainRuns() where run.range.overlaps(range) {
505                guard let clipped = clip(run.range, to: range) else { continue }
506                theme.apply(.syntax(run.category), to: storage, range: clipped)
507            }
508            return
509        }
510        let text = storage.string as NSString
511        for run in Presentation.indents(document.tree, in: range) {
512            guard let clipped = clip(run.range, to: range) else { continue }
513            guard run.firstLine == run.wrapped else {
514                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped), range: clipped)
515                continue
516            }
517            // Body lines wrap under their own text: past leading blanks, and past a list bullet
518            // and checkbox, as adaptive-wrap does in Emacs.
519            var location = clipped.location
520            while location < NSMaxRange(clipped) {
521                let line = text.lineRange(for: NSRange(location: location, length: 0))
522                let hanging = Self.hangingColumns(text.substring(with: line))
523                let lineRange = NSIntersectionRange(line, clipped)
524                storage.addAttribute(.paragraphStyle, value: paragraphStyle(run.firstLine, run.wrapped + hanging), range: lineRange)
525                location = NSMaxRange(line)
526            }
527        }
528        let revealed = caretLine
529        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
530            guard let clipped = clip(run.range, to: range) else { continue }
531            if !showMarkup, hides(run.role), NSIntersectionRange(clipped, revealed).length == 0 {
532                storage.addAttributes(theme.hidden, range: clipped)
533            } else {
534                theme.apply(run.role, to: storage, range: clipped)
535            }
536        }
537    }
538
539    /// Link brackets and targets are hidden as with `org-link-descriptive`; emphasis
540    /// markers only when Emacs hides them too.
541    private func hides(_ role: StyleRole) -> Bool {
542        switch role {
543        case .linkMarkup: true
544        case .markup: options.hideEmphasisMarkers
545        default: false
546        }
547    }
548
549    /// Moving to another line shows its markup and hides the last one's.
550    private func revealCaretLine() {
551        guard !showMarkup, isOrg else { return }
552        let line = caretLine
553        guard line != revealedLine else { return }
554        let text = textView.string as NSString
555        // The old line may have moved with edits since; restyle the line now at its start.
556        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
557        revealedLine = line
558        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
559            restyleOutsideEditing(range.location..<NSMaxRange(range))
560        }
561    }
562
563    /// Code highlights for the whole file in plain mode.
564    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
565        guard case .plain(let language?) = mode, let highlighter else { return [] }
566        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
567        let runs = highlighter.highlights(language: language, code: document.text)
568        codeRuns = (document.revision, runs)
569        return runs
570    }
571
572    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
573        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
574        if let style = paragraphStyles[key] { return style }
575        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
576        paragraphStyles[key] = style
577        return style
578    }
579
580    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
581        let clipped = run.clamped(to: range)
582        return clipped.isEmpty ? nil : NSRange(clipped)
583    }
584
585    /// The region an edit affects in one version of the tree: inside the innermost section
586    /// holding the edited lines (plus the line after), every element that overlaps them or the
587    /// line on either side. A changed heading line, or an added or removed heading, widens it
588    /// to that section's whole own body. Run on the old and the new tree, the union covers
589    /// elements that grew and elements that shrank.
590    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
591        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
592        let lineRange = lines.location..<(lines.location + lines.length)
593        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
594        var container = tree.root
595        while let child = container.child(containing: lineRange.lowerBound),
596              child.kind == .section || child.kind == .zerothSection,
597              lineRange.upperBound <= child.range.upperBound {
598            container = child
599        }
600        var lower = lineRange.lowerBound
601        var upper = lineRange.upperBound
602        // Tables and lists carry no styling of their own, so inside them only the rows or
603        // items around the edit change, however large they are.
604        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
605            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
606                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
607                let inner = overlapping(node.children(overlapping: around))
608                return inner.isEmpty ? [node] : inner
609            }
610        }
611        for child in overlapping(container.children(overlapping: around)) {
612            lower = min(lower, child.range.lowerBound)
613            upper = max(upper, child.range.upperBound)
614        }
615        let heading = container.firstChild(.heading)
616        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
617            lower = min(lower, container.range.lowerBound)
618            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
619        }
620        return lower..<min(upper, text.length)
621    }
622
623    // MARK: - Editing
624
625    fileprivate func storageEdited(range: NSRange, delta: Int) {
626        guard !isLoading, let storage = textView.textStorage else { return }
627        markActive = false
628        let clock = ContinuousClock()
629        let start = clock.now
630        let replacement = (storage.string as NSString).substring(with: range)
631        let edit = TextEdit(range: range.location..<(range.location + range.length - delta), replacement: replacement)
632        let oldText = document.text as NSString
633        let newText = storage.string as NSString
634        let newEnd = edit.range.lowerBound + replacement.utf16.count
635        let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText)
636            || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText)
637        let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
638        do {
639            try document.apply([edit], baseRevision: document.revision)
640        } catch {
641            assertionFailure("text view and document disagree: \(error)")
642            return
643        }
644        // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the
645        // edited line when the edit reaches into unstyled text.
646        if styledUpTo >= edit.range.upperBound {
647            styledUpTo += edit.replacement.utf16.count - edit.range.count
648        } else if styledUpTo > edit.range.lowerBound {
649            styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
650        }
651        let oldHidden = hidden.all
652        view = view.mapped(through: [edit]).pruned(to: document.tree)
653        folded.set(view.folds)
654        hidden.set(Presentation.hiddenRanges(document.tree, folds: view.folds))
655        let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
656        let delta = edit.replacement.utf16.count - edit.range.count
657        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
658        restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage)
659        let oldShaded = shaded.all
660        if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
661        if hidden.all != oldHidden.map({ mapRange($0, through: edit) })
662            || shaded.all != oldShaded.map({ mapRange($0, through: edit) }) {
663            textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
664        }
665        onEditTiming?(clock.now - start)
666        onChange?()
667    }
668
669    /// Columns a wrapped continuation of `line` should start past the line's own start.
670    nonisolated static func hangingColumns(_ line: String) -> Int {
671        var columns = 0
672        var rest = Substring(line)
673        while let c = rest.first, c == " " || c == "\t" {
674            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
675            rest = rest.dropFirst()
676        }
677        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
678        var bullet = 0
679        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
680            bullet = 1
681        } else {
682            let digits = rest.prefix { $0.isASCII && $0.isNumber }
683            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
684                bullet = digits.count + 1
685            }
686        }
687        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
688        columns += bullet + 1
689        let afterBullet = rest.dropFirst(bullet + 1)
690        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
691           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
692            columns += 4
693        }
694        return columns
695    }
696
697    /// Whether a heading line touches `start..<end` or starts right after it, where joining
698    /// lines could take it away.
699    static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
700        let length = min(end + 1, text.length) - start
701        guard length >= 0 else { return false }
702        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
703        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
704            let stars = line.prefix { $0 == "*" }
705            let after = line.dropFirst(stars.count)
706            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
707        }
708    }
709
710    private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> {
711        let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0]
712        return mapped
713    }
714
715    /// Keeps the caret out of folded text: moving forward into a fold jumps past it, moving
716    /// back jumps to the end of the heading line.
717    fileprivate func selectionChanged() {
718        let selection = textView.selectedRange()
719        defer { previousSelection = selection.location }
720        onSelectionChange?(selection)
721        revealCaretLine()
722        // A selection reaching into folded text, as a find match does, unfolds it.
723        if selection.length > 0 {
724            if hidden.containing(selection.location) != nil || hidden.containing(NSMaxRange(selection) - 1) != nil {
725                unfold(around: selection.location)
726                unfold(around: NSMaxRange(selection) - 1)
727            }
728            return
729        }
730        guard let range = hidden.containing(selection.location) else { return }
731        setCaret(selection.location >= previousSelection ? range.upperBound : range.lowerBound - 1)
732    }
733}
734
735extension OrgEditor: DocumentBuffer {
736    /// The selected text, for capture's `%i`.
737    public var selectedText: String {
738        let range = textView.selectedRange()
739        guard range.length > 0 else { return "" }
740        return (textView.string as NSString).substring(with: range)
741    }
742
743    public var selection: [Range<Int>] {
744        let selected = textView.selectedRange()
745        return [selected.location..<NSMaxRange(selected)]
746    }
747
748    /// Runs `change`; if it changed the text, reloads the view with folds and the selection
749    /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
750    public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
751        let before = document.text
752        let selected = textView.selectedRange()
753        let result = try change(&document)
754        if document.text != before {
755            let edits = lineEdits(from: before, to: document.text)
756            var state = view
757            state.selection = [selected.location..<NSMaxRange(selected)]
758            let mapped = state.mapped(through: edits)
759            load(document.text)
760            setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds))
761            let selection = mapped.selection[0]
762            setCaret(selection.lowerBound)
763            if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
764            textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
765            textView.undoManager?.removeAllActions(withTarget: textView)
766        }
767        onChange?()
768        return result
769    }
770}
771
772extension OrgEditor: NSTextViewDelegate {
773    public func textViewDidChangeSelection(_ notification: Notification) {
774        selectionChanged()
775    }
776}
777
778extension OrgEditor: NSTextStorageDelegate {
779    public nonisolated func textStorage(
780        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int
781    ) {
782        guard editedMask.contains(.editedCharacters) else { return }
783        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
784    }
785}
786
787extension OrgEditor: NSTextContentStorageDelegate {
788    /// Folded text isn't enumerated, so it isn't laid out or drawn.
789    public nonisolated func textContentManager(
790        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
791    ) -> Bool {
792        guard let range = textElement.elementRange else { return true }
793        let documentStart = textContentManager.documentRange.location
794        let start = textContentManager.offset(from: documentStart, to: range.location)
795        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
796        return !hidden.covers(start, end)
797    }
798}
799
800extension OrgEditor: NSTextLayoutManagerDelegate {
801    public nonisolated func textLayoutManager(
802        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
803    ) -> NSTextLayoutFragment {
804        let range = textElement.elementRange
805        if let range, let manager = textLayoutManager.textContentManager {
806            let offset = manager.offset(from: manager.documentRange.location, to: range.location)
807            if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
808            if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
809        }
810        return NSTextLayoutFragment(textElement: textElement, range: range)
811    }
812}
813
814/// A line of a block, on a band across the whole width of the view, as Emacs extends the
815/// `org-block` face.
816final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
817    private var band: CGRect {
818        let width = textLayoutManager?.textContainer?.size.width ?? layoutFragmentFrame.width
819        return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: width, height: layoutFragmentFrame.height)
820    }
821
822    override var renderingSurfaceBounds: CGRect { super.renderingSurfaceBounds.union(band) }
823
824    override func draw(at point: CGPoint, in context: CGContext) {
825        context.saveGState()
826        context.setFillColor(Theme.blockBackground.cgColor)
827        context.fill(band.offsetBy(dx: point.x, dy: point.y))
828        context.restoreGState()
829        super.draw(at: point, in: context)
830    }
831}
832
833/// A heading line drawn with an ellipsis after it, like org's folded headings.
834final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
835    override func draw(at point: CGPoint, in context: CGContext) {
836        super.draw(at: point, in: context)
837        guard let line = textLineFragments.first else { return }
838        let bounds = line.typographicBounds
839        let ellipsis = NSAttributedString(string: " …", attributes: [
840            .font: NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular),
841            .foregroundColor: NSColor.secondaryLabelColor,
842        ])
843        NSGraphicsContext.saveGraphicsState()
844        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
845        ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
846        NSGraphicsContext.restoreGraphicsState()
847    }
848
849    override var renderingSurfaceBounds: CGRect {
850        super.renderingSurfaceBounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0)
851    }
852}
853#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form