Sources/OrgPresentation/Presentation.swift

334 lines · 15734 bytes

  1import OrgCore
  2import os
  3
  4/// What a range of text is, for styling. Platform adapters map roles to attributes.
  5public enum StyleRole: Hashable, Sendable {
  6    /// A whole heading line.
  7    case heading(level: Int)
  8    /// All stars of a heading but the last, hidden as in `org-hide-leading-stars`.
  9    case leadingStars
 10    case todo, done, priority, tags
 11    case bold, italic, underline, strikeThrough, verbatim, code
 12    /// Emphasis markers.
 13    case markup
 14    case link
 15    /// Brackets and the target of a described link.
 16    case linkMarkup
 17    case timestamp, footnote, cookie, target, macro, latex, inlineSource
 18    case comment, keyword
 19    /// Planning lines, drawers, property drawers, clock lines.
 20    case metadata
 21    case block, blockDelimiter, table, rule
 22    /// Code in a src block, by what the language's grammar says it is.
 23    case syntax(SyntaxCategory)
 24}
 25
 26/// Kinds of code token, from tree-sitter highlight capture names.
 27public enum SyntaxCategory: String, Hashable, Sendable, CaseIterable {
 28    case keyword, string, comment, function, type, number, constant, variable, property, `operator`
 29    case punctuation, attribute, tag, escape, label
 30
 31    /// The category for a capture name such as `keyword.control` or `string.special`.
 32    public init?(capture name: String) {
 33        let head = name.split(separator: ".").first.map(String.init) ?? name
 34        switch head {
 35        case "keyword", "conditional", "repeat", "include", "exception", "storageclass": self = .keyword
 36        case "string", "character": self = name.hasPrefix("string.escape") ? .escape : .string
 37        case "comment": self = .comment
 38        case "function", "method": self = .function
 39        case "type", "constructor", "module", "namespace": self = .type
 40        case "number", "float": self = .number
 41        case "constant", "boolean": self = .constant
 42        case "variable", "parameter": self = .variable
 43        case "property", "field": self = .property
 44        case "operator": self = .operator
 45        case "punctuation": self = .punctuation
 46        case "attribute", "annotation", "decorator": self = .attribute
 47        case "tag": self = .tag
 48        case "escape": self = .escape
 49        case "label": self = .label
 50        default: return nil
 51        }
 52    }
 53}
 54
 55extension SyntaxCategory {
 56    /// The theme color for this kind of token; nil for those drawn in the text color.
 57    public var themeKey: String? {
 58        switch self {
 59        case .keyword: "syntax-keyword"
 60        case .string: "syntax-string"
 61        case .comment: "syntax-comment"
 62        case .function: "syntax-function"
 63        case .type: "syntax-type"
 64        case .number, .constant, .escape: "syntax-number"
 65        case .property, .attribute, .tag: "syntax-property"
 66        case .label: "syntax-label"
 67        case .variable, .operator, .punctuation: nil
 68        }
 69    }
 70}
 71
 72/// Highlights source code; the apps supply tree-sitter's (OrgHighlight).
 73public protocol CodeHighlighter: Sendable {
 74    /// Categories for ranges of `code`, in UTF-16 offsets; later runs win over earlier ones.
 75    /// Empty for languages it doesn't know.
 76    func highlights(language: String, code: String) -> [(range: Range<Int>, category: SyntaxCategory)]
 77}
 78
 79public struct StyleRun: Sendable, Equatable {
 80    public let range: Range<Int>
 81    public let role: StyleRole
 82}
 83
 84/// org-indent: how many columns a run of whole lines starts in.
 85public struct IndentRun: Sendable, Equatable {
 86    public let range: Range<Int>
 87    public let firstLine: Int
 88    /// Continuation lines of a wrapped paragraph.
 89    public let wrapped: Int
 90}
 91
 92public enum Presentation {
 93    /// Style runs for nodes and tokens overlapping `range`, outer before inner, so applying
 94    /// them in order lets inner roles win.
 95    public static func styles(_ tree: OrgTree, in range: Range<Int>, highlighter: (any CodeHighlighter)? = nil) -> [StyleRun] {
 96        var runs: [StyleRun] = []
 97        visit(tree.root, range, tree.settings, highlighter, &runs)
 98        return runs
 99    }
100
101    /// Runs for the code inside a src block, from `highlighter`.
102    static func sourceRuns(_ node: SyntaxNode, _ highlighter: any CodeHighlighter) -> [StyleRun] {
103        let lines = node.tokens.filter { $0.kind == .text }
104        guard lines.count >= 2, let first = lines.first, let last = lines.last,
105              let match = first.text.firstMatch(of: /^[ \t]*#\+(?i:begin_src)[ \t]+(\S+)/) else { return [] }
106        let language = String(match.1)
107        let start = first.range.upperBound + 1
108        let end = last.range.lowerBound
109        guard end > start else { return [] }
110        let utf16 = node.text.utf16
111        let lower = utf16.index(utf16.startIndex, offsetBy: start - node.range.lowerBound)
112        let upper = utf16.index(utf16.startIndex, offsetBy: end - node.range.lowerBound)
113        let code = String(node.text[lower..<upper])
114        return highlighter.highlights(language: language, code: code).map {
115            StyleRun(range: ($0.range.lowerBound + start)..<($0.range.upperBound + start), role: .syntax($0.category))
116        }
117    }
118
119    private static func visit(_ node: SyntaxNode, _ range: Range<Int>, _ settings: OrgSettings, _ highlighter: (any CodeHighlighter)?, _ runs: inout [StyleRun]) {
120        if let role = role(of: node) { runs.append(StyleRun(range: node.range, role: role)) }
121        switch node.kind {
122        case .heading:
123            for token in node.tokens {
124                switch token.kind {
125                case .stars where token.range.count > 1:
126                    runs.append(StyleRun(range: token.range.lowerBound..<(token.range.upperBound - 1), role: .leadingStars))
127                case .todoKeyword:
128                    runs.append(StyleRun(range: token.range, role: settings.isDone(token.text) ? .done : .todo))
129                case .priority:
130                    runs.append(StyleRun(range: token.range, role: .priority))
131                case .tags:
132                    runs.append(StyleRun(range: token.range, role: .tags))
133                default:
134                    break
135                }
136            }
137        case .link:
138            let described = node.children.contains { $0.kind == .linkDescription }
139            for token in node.tokens where token.kind == .marker || (described && token.kind == .linkPath) {
140                runs.append(StyleRun(range: token.range, role: .linkMarkup))
141            }
142        case .bold, .italic, .underline, .strikeThrough, .verbatim, .code:
143            for token in node.tokens where token.kind == .marker {
144                runs.append(StyleRun(range: token.range, role: .markup))
145            }
146        case .block, .dynamicBlock:
147            let lines = node.tokens.filter { $0.kind == .text }
148            for token in [lines.first, lines.count > 1 ? lines.last : nil].compactMap({ $0 }) {
149                runs.append(StyleRun(range: token.range, role: .blockDelimiter))
150            }
151            if let highlighter { runs += sourceRuns(node, highlighter) }
152        default:
153            break
154        }
155        for child in node.children(overlapping: range) {
156            visit(child, range, settings, highlighter, &runs)
157        }
158    }
159
160    static func role(of node: SyntaxNode) -> StyleRole? {
161        switch node.kind {
162        case .heading: .heading(level: node.tokens.first { $0.kind == .stars }?.text.count ?? 1)
163        case .bold: .bold
164        case .italic: .italic
165        case .underline: .underline
166        case .strikeThrough: .strikeThrough
167        case .verbatim: .verbatim
168        case .code: .code
169        case .link: .link
170        case .timestamp: .timestamp
171        case .footnoteReference, .footnoteDefinition: .footnote
172        case .statisticsCookie: .cookie
173        case .target, .radioTarget: .target
174        case .macro: .macro
175        case .latexFragment, .latexEnvironment: .latex
176        case .inlineSourceBlock, .inlineBabelCall, .exportSnippet: .inlineSource
177        case .citation: .link
178        case .itemTag: .bold
179        case .diarySexp: .timestamp
180        case .comment: .comment
181        case .keyword, .affiliatedKeyword: .keyword
182        case .planning, .propertyDrawer, .drawer, .clock: .metadata
183        case .block, .dynamicBlock, .fixedWidth: .block
184        case .table, .tableEl: .table
185        case .horizontalRule: .rule
186        default: nil
187        }
188    }
189
190    /// Heading lines start at column 0, with wrapped title lines under the title; a section's
191    /// own body starts one column past its stars.
192    public static func indents(_ tree: OrgTree, in range: Range<Int>) -> [IndentRun] {
193        var runs: [IndentRun] = []
194        collectIndents(tree.root, range, &runs)
195        return runs
196    }
197
198    private static func collectIndents(_ node: SyntaxNode, _ range: Range<Int>, _ runs: inout [IndentRun]) {
199        for section in node.children(overlapping: range) where section.kind == .section {
200            guard let heading = section.firstChild(.heading) else { continue }
201            let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
202            runs.append(IndentRun(range: heading.range, firstLine: 0, wrapped: level + 1))
203            let bodyEnd = section.firstChild(.section)?.range.lowerBound ?? section.range.upperBound
204            if heading.range.upperBound < bodyEnd {
205                runs.append(IndentRun(range: heading.range.upperBound..<bodyEnd, firstLine: level + 1, wrapped: level + 1))
206            }
207            collectIndents(section, range, &runs)
208        }
209    }
210
211    /// Blocks and fixed-width areas, drawn on a shaded band the width of the view. Sorted.
212    /// The last tree's are kept: the reader asks once per section.
213    public static func shadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
214        shadedBlocksCache.withLock { last in
215            if let last, last.green === tree.green { return last.ranges }
216            let ranges = computeShadedBlocks(tree)
217            last = (tree.green, ranges)
218            return ranges
219        }
220    }
221
222    private static let shadedBlocksCache = OSAllocatedUnfairLock<(green: GreenNode, ranges: [Range<Int>])?>(initialState: nil)
223
224    private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
225        var ranges: [Range<Int>] = []
226        func walk(_ node: SyntaxNode) {
227            for child in node.children {
228                switch child.kind {
229                case .block, .dynamicBlock, .fixedWidth:
230                    // Without the blank lines org counts as part of the element.
231                    let text = child.text
232                    let trimmed = text.utf16.count - String(text.reversed().prefix { $0.isWhitespace }).utf16.count
233                    ranges.append(child.range.lowerBound..<(child.range.lowerBound + trimmed))
234                case .paragraph, .table, .heading, .planning, .propertyDrawer, .drawer, .keyword, .comment: continue
235                default: walk(child)
236                }
237            }
238        }
239        walk(tree.root)
240        return ranges
241    }
242
243    /// Ranges to hide. A heading in `folds` hides everything after its line to the end of its
244    /// section; one in `bodyFolds` hides only its own body, up to its first child heading.
245    /// Sorted, without nested duplicates.
246    /// A drawer or block in `wrapperFolds` hides the lines after its opening line.
247    public static func hiddenRanges(_ tree: OrgTree, folds: Set<Int>, bodyFolds: Set<Int> = [], wrapperFolds: Set<Int> = []) -> [Range<Int>] {
248        hiddenRanges(tree, folds: folds, bodyFolds: bodyFolds, wrapperRanges: wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden })
249    }
250
251    /// The same, with the folded drawers' and blocks' hidden ranges already found.
252    public static func hiddenRanges(_ tree: OrgTree, folds: Set<Int>, bodyFolds: Set<Int>, wrapperRanges: [Range<Int>]) -> [Range<Int>] {
253        guard !folds.isEmpty || !bodyFolds.isEmpty || !wrapperRanges.isEmpty else { return [] }
254        var ranges: [Range<Int>] = []
255        if !folds.isEmpty || !bodyFolds.isEmpty { collectHidden(tree.root, folds, bodyFolds, &ranges) }
256        guard !wrapperRanges.isEmpty else { return ranges }
257        ranges += wrapperRanges
258        ranges.sort { $0.lowerBound != $1.lowerBound ? $0.lowerBound < $1.lowerBound : $0.upperBound > $1.upperBound }
259        var merged: [Range<Int>] = []
260        for range in ranges where !(merged.last.map { $0.upperBound >= range.upperBound } ?? false) { merged.append(range) }
261        return merged
262    }
263
264    private static func collectHidden(_ node: SyntaxNode, _ folds: Set<Int>, _ bodyFolds: Set<Int>, _ ranges: inout [Range<Int>]) {
265        for section in node.children where section.kind == .section {
266            guard let heading = section.firstChild(.heading) else { continue }
267            let start = heading.range.lowerBound
268            if folds.contains(start) {
269                if heading.range.upperBound < section.range.upperBound {
270                    ranges.append(heading.range.upperBound..<section.range.upperBound)
271                }
272                continue
273            }
274            if bodyFolds.contains(start) {
275                let bodyEnd = section.firstChild(.section)?.range.lowerBound ?? section.range.upperBound
276                if heading.range.upperBound < bodyEnd { ranges.append(heading.range.upperBound..<bodyEnd) }
277            }
278            collectHidden(section, folds, bodyFolds, &ranges)
279        }
280    }
281
282    /// Start offset of the heading whose line contains `offset`.
283    public static func heading(containing offset: Int, in tree: OrgTree) -> Int? {
284        var node = tree.root
285        while let child = node.child(containing: offset) {
286            if child.kind == .heading { return child.range.lowerBound }
287            guard child.kind == .section || child.kind == .zerothSection else { return nil }
288            node = child
289        }
290        return nil
291    }
292
293    /// Start offsets of every heading, for folding everything.
294    public static func headings(_ tree: OrgTree) -> [Int] {
295        tree.root.descendants().filter { $0.kind == .heading }.map(\.range.lowerBound)
296    }
297}
298
299extension SyntaxCategory {
300    /// The class htmlize gives the face Emacs uses for this kind of token.
301    public var htmlClass: String? {
302        switch self {
303        case .keyword: "org-keyword"
304        case .string: "org-string"
305        case .comment: "org-comment"
306        case .function: "org-function-name"
307        case .type: "org-type"
308        case .number, .constant, .escape: "org-constant"
309        case .property, .attribute, .tag: "org-property-name"
310        case .label: "org-label"
311        case .variable: "org-variable-name"
312        case .operator, .punctuation: nil
313        }
314    }
315}
316
317extension HTMLCodeStyle {
318    /// Source blocks colored by `highlighter` in `theme`'s colors, light and dark.
319    public init(highlighter: any CodeHighlighter, theme: ThemeSpec) {
320        var light: [String] = []
321        var dark: [String] = []
322        var seen = Set<String>()
323        for category in SyntaxCategory.allCases {
324            guard let cls = category.htmlClass, let key = category.themeKey, seen.insert(cls).inserted else { continue }
325            if let color = theme.color(key, dark: false) { light.append(".\(cls) { color: \(color.hex); }") }
326            if let color = theme.color(key, dark: true) { dark.append(".\(cls) { color: \(color.hex); }") }
327        }
328        var css = light.joined(separator: " ") + "\n"
329        if !dark.isEmpty { css += "@media (prefers-color-scheme: dark) { " + dark.joined(separator: " ") + " }\n" }
330        self.init(css: css) { language, code in
331            highlighter.highlights(language: language, code: code).compactMap { run in run.category.htmlClass.map { (run.range, $0) } }
332        }
333    }
334}