Sources/OrgEditorAppKit/OrgEditor+Styling.swift

155 lines · 8272 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4import OrgPresentation
  5
  6extension OrgEditor {
  7    // MARK: - Styling
  8
  9    func restyleOutsideEditing(_ range: Range<Int>) {
 10        guard let storage = textView.textStorage else { return }
 11        storage.beginEditing()
 12        restyle(range, in: storage)
 13        storage.endEditing()
 14    }
 15
 16    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
 17    /// attribute changes are allowed and characters must not change.
 18    func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
 19        guard !range.isEmpty else { return }
 20        let whole = NSRange(range)
 21        storage.setAttributes(theme.base, range: whole)
 22        guard isOrg else {
 23            for run in plainRuns() where run.range.overlaps(range) {
 24                guard let clipped = clip(run.range, to: range) else { continue }
 25                theme.apply(.syntax(run.category), to: storage, range: clipped)
 26            }
 27            return
 28        }
 29        if indented {
 30            for line in Presentation.lineIndents(document.tree, in: range) {
 31                storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
 32            }
 33        }
 34        let revealed = caretLine
 35        var scriptExclusions: [Range<Int>] = []
 36        for run in Presentation.styles(document.tree, in: range, highlighter: highlighter) {
 37            guard let clipped = clip(run.range, to: range) else { continue }
 38            if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
 39            if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
 40                storage.addAttributes(theme.hidden, range: clipped)
 41            } else {
 42                theme.apply(run.role, to: storage, range: clipped)
 43            }
 44            if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
 45        }
 46        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
 47        applyShrunk(range, in: storage)
 48        applyHighlights(range, in: storage)
 49        applyImages(range, in: storage, revealed: revealed)
 50        applyLatex(range, in: storage, revealed: revealed)
 51    }
 52
 53    /// `org-pretty-entities`: entities drawn as their character over the entity's last
 54    /// character (the rest hidden), sub/superscripts raised without their markers.
 55    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
 56        let runs = Presentation.prettyRuns(
 57            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
 58            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
 59        )
 60        for (lineStart, run) in runs {
 61            switch run {
 62            case .entity(let r, let display):
 63                let start = lineStart + r.lowerBound
 64                let last = lineStart + r.upperBound - 1
 65                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
 66                storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
 67            case .script(let markers, let body, let superscript):
 68                for marker in markers {
 69                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
 70                }
 71                let size = theme.font.pointSize
 72                storage.addAttributes([
 73                    .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
 74                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
 75                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
 76            }
 77        }
 78    }
 79
 80    /// Moving to another line shows its markup and hides the last one's.
 81    func revealCaretLine() {
 82        // LaTeX previews show their source on the caret's line whether or not markup shows.
 83        guard !showMarkup || showsLatex, isOrg else { return }
 84        let line = caretLine
 85        guard line != revealedLine else { return }
 86        let text = textView.string as NSString
 87        // The old line may have moved with edits since; restyle the line now at its start.
 88        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
 89        revealedLine = line
 90        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
 91            restyleOutsideEditing(range.location..<NSMaxRange(range))
 92        }
 93    }
 94
 95    /// Code highlights for the whole file in plain mode.
 96    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
 97        guard case .plain(let language?) = mode, let highlighter else { return [] }
 98        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
 99        let runs = highlighter.highlights(language: language, code: document.text)
100        codeRuns = (document.revision, runs)
101        return runs
102    }
103
104    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
105        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
106        if let style = paragraphStyles[key] { return style }
107        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
108        paragraphStyles[key] = style
109        return style
110    }
111
112    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
113        let clipped = run.clamped(to: range)
114        return clipped.isEmpty ? nil : NSRange(clipped)
115    }
116
117    /// The region an edit affects in one version of the tree: inside the innermost section
118    /// holding the edited lines (plus the line after), every element that overlaps them or the
119    /// line on either side. A changed heading line, or an added or removed heading, widens it
120    /// to that section's whole own body. Run on the old and the new tree, the union covers
121    /// elements that grew and elements that shrank.
122    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
123        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
124        let lineRange = lines.location..<(lines.location + lines.length)
125        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
126        var container = tree.root
127        while let child = container.child(containing: lineRange.lowerBound),
128              child.kind == .section || child.kind == .zerothSection,
129              lineRange.upperBound <= child.range.upperBound {
130            container = child
131        }
132        var lower = lineRange.lowerBound
133        var upper = lineRange.upperBound
134        // Tables and lists carry no styling of their own, so inside them only the rows or
135        // items around the edit change, however large they are.
136        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
137            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
138                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
139                let inner = overlapping(node.children(overlapping: around))
140                return inner.isEmpty ? [node] : inner
141            }
142        }
143        for child in overlapping(container.children(overlapping: around)) {
144            lower = min(lower, child.range.lowerBound)
145            upper = max(upper, child.range.upperBound)
146        }
147        let heading = container.firstChild(.heading)
148        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
149            lower = min(lower, container.range.lowerBound)
150            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
151        }
152        return lower..<min(upper, text.length)
153    }
154}
155#endif