Sources/OrgEditorAppKit/OrgEditor.swift

2cd54205f32212a32ac7cf2a011c7b019f3745c5
orgstar/Sources/OrgEditorAppKit/OrgEditor.swift

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