Sources/OrgEditorAppKit/OrgEditor+Styling.swift

161 lines · 8659 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 theme.mixedPitch {
 47            for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) {
 48                guard let clipped = clip(prefix, to: range) else { continue }
 49                storage.addAttribute(.font, value: theme.fixedPitch(storage, clipped), range: clipped)
 50            }
 51        }
 52        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
 53        applyShrunk(range, in: storage)
 54        applyHighlights(range, in: storage)
 55        applyImages(range, in: storage, revealed: revealed)
 56        applyLatex(range, in: storage, revealed: revealed)
 57    }
 58
 59    /// `org-pretty-entities`: entities drawn as their character over the entity's last
 60    /// character (the rest hidden), sub/superscripts raised without their markers.
 61    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
 62        let runs = Presentation.prettyRuns(
 63            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
 64            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
 65        )
 66        for (lineStart, run) in runs {
 67            switch run {
 68            case .entity(let r, let display):
 69                let start = lineStart + r.lowerBound
 70                let last = lineStart + r.upperBound - 1
 71                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
 72                storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
 73            case .script(let markers, let body, let superscript):
 74                for marker in markers {
 75                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
 76                }
 77                let size = theme.font.pointSize
 78                storage.addAttributes([
 79                    .font: theme.mixedPitch ? theme.body.withSize(size * 0.7) : NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
 80                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
 81                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
 82            }
 83        }
 84    }
 85
 86    /// Moving to another line shows its markup and hides the last one's.
 87    func revealCaretLine() {
 88        // LaTeX previews show their source on the caret's line whether or not markup shows.
 89        guard !showMarkup || showsLatex, isOrg else { return }
 90        let line = caretLine
 91        guard line != revealedLine else { return }
 92        let text = textView.string as NSString
 93        // The old line may have moved with edits since; restyle the line now at its start.
 94        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
 95        revealedLine = line
 96        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
 97            restyleOutsideEditing(range.location..<NSMaxRange(range))
 98        }
 99    }
100
101    /// Code highlights for the whole file in plain mode.
102    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
103        guard case .plain(let language?) = mode, let highlighter else { return [] }
104        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
105        let runs = highlighter.highlights(language: language, code: document.text)
106        codeRuns = (document.revision, runs)
107        return runs
108    }
109
110    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
111        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
112        if let style = paragraphStyles[key] { return style }
113        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
114        paragraphStyles[key] = style
115        return style
116    }
117
118    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
119        let clipped = run.clamped(to: range)
120        return clipped.isEmpty ? nil : NSRange(clipped)
121    }
122
123    /// The region an edit affects in one version of the tree: inside the innermost section
124    /// holding the edited lines (plus the line after), every element that overlaps them or the
125    /// line on either side. A changed heading line, or an added or removed heading, widens it
126    /// to that section's whole own body. Run on the old and the new tree, the union covers
127    /// elements that grew and elements that shrank.
128    static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
129        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
130        let lineRange = lines.location..<(lines.location + lines.length)
131        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
132        var container = tree.root
133        while let child = container.child(containing: lineRange.lowerBound),
134              child.kind == .section || child.kind == .zerothSection,
135              lineRange.upperBound <= child.range.upperBound {
136            container = child
137        }
138        var lower = lineRange.lowerBound
139        var upper = lineRange.upperBound
140        // Tables and lists carry no styling of their own, so inside them only the rows or
141        // items around the edit change, however large they are.
142        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
143            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
144                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
145                let inner = overlapping(node.children(overlapping: around))
146                return inner.isEmpty ? [node] : inner
147            }
148        }
149        for child in overlapping(container.children(overlapping: around)) {
150            lower = min(lower, child.range.lowerBound)
151            upper = max(upper, child.range.upperBound)
152        }
153        let heading = container.firstChild(.heading)
154        if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true {
155            lower = min(lower, container.range.lowerBound)
156            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
157        }
158        return lower..<min(upper, text.length)
159    }
160}
161#endif