Sources/OrgPresentation/ThemeSpec.swift

bd76bdbef02dcaa96435b05ce2586c024c56b478
orgstar/Sources/OrgPresentation/ThemeSpec.swift history · blame · raw

201 lines · 9935 bytes

  1import OrgCore
  2
  3/// A color as `#rrggbb` or `#rrggbbaa`.
  4public struct RGBA: Hashable, Sendable {
  5    public var red, green, blue, alpha: Double
  6
  7    public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {
  8        self.red = red
  9        self.green = green
 10        self.blue = blue
 11        self.alpha = alpha
 12    }
 13
 14    public init?(hex: String) {
 15        var digits = Substring(hex.trimmingCharacters(in: .whitespaces))
 16        guard digits.first == "#" else { return nil }
 17        digits = digits.dropFirst()
 18        guard digits.count == 6 || digits.count == 8, let value = UInt64(digits, radix: 16) else { return nil }
 19        let full = digits.count == 6 ? value << 8 | 0xFF : value
 20        red = Double(full >> 24 & 0xFF) / 255
 21        green = Double(full >> 16 & 0xFF) / 255
 22        blue = Double(full >> 8 & 0xFF) / 255
 23        alpha = Double(full & 0xFF) / 255
 24    }
 25
 26    public var hex: String {
 27        func byte(_ d: Double) -> String {
 28            let s = String(Int((d * 255).rounded()), radix: 16)
 29            return s.count == 1 ? "0" + s : s
 30        }
 31        return "#" + byte(red) + byte(green) + byte(blue) + (alpha < 1 ? byte(alpha) : "")
 32    }
 33}
 34
 35/// The editor's look: colors for each kind of text in light and dark appearance, colors for
 36/// TODO keywords, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]` and
 37/// `[theme.todo]` in config.toml, on top of the default theme.
 38public struct ThemeSpec: Equatable, Sendable {
 39    /// A font family; empty for the system's monospaced font.
 40    public var font = ""
 41    public var fontSize = 13
 42    /// Points between lines.
 43    public var lineSpacing = 2
 44    /// Points a heading is larger than the next level down (level 4 and deeper are body size).
 45    public var headingSizeStep = 1
 46    public var light: [String: RGBA]
 47    public var dark: [String: RGBA]
 48    /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances.
 49    public var todo: [String: RGBA] = [:]
 50
 51    public init(light: [String: RGBA], dark: [String: RGBA]) {
 52        self.light = light
 53        self.dark = dark
 54    }
 55
 56    public func color(_ key: String, dark isDark: Bool) -> RGBA? {
 57        (isDark ? dark : light)[key]
 58    }
 59
 60    // MARK: - Slots
 61
 62    /// Every color key, with what it colors.
 63    public static let slots: [(key: String, description: String)] = [
 64        ("background", "the editor's background"),
 65        ("foreground", "body text"),
 66        ("cursor", "the caret"),
 67        ("selection", "selected text's background"),
 68        ("heading-1", "level 1 headings"), ("heading-2", "level 2 headings"), ("heading-3", "level 3 headings"),
 69        ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"),
 70        ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"),
 71        ("todo", "TODO keywords not yet done"),
 72        ("done", "DONE keywords"),
 73        ("priority", "[#A] cookies"),
 74        ("tags", ":tags:"),
 75        ("link", "links"),
 76        ("timestamp", "timestamps"),
 77        ("code", "~code~ and inline source"),
 78        ("verbatim", "=verbatim="),
 79        ("inline-background", "behind ~code~ and =verbatim="),
 80        ("markup", "link brackets and emphasis markers"),
 81        ("comment", "comments"),
 82        ("keyword", "#+KEYWORD lines"),
 83        ("metadata", "planning lines, drawers, properties and clocks"),
 84        ("special", "footnotes, statistics cookies, targets, macros and LaTeX"),
 85        ("block-background", "the band behind blocks"),
 86        ("block-delimiter", "#+begin_ and #+end_ lines"),
 87        ("table", "tables"),
 88        ("line-number", "line numbers"),
 89        ("line-number-current", "the caret's line number"),
 90        ("syntax-keyword", "code: keywords"),
 91        ("syntax-string", "code: strings"),
 92        ("syntax-comment", "code: comments"),
 93        ("syntax-function", "code: functions"),
 94        ("syntax-type", "code: types and modules"),
 95        ("syntax-number", "code: numbers, constants and escapes"),
 96        ("syntax-property", "code: properties, attributes and tags"),
 97        ("syntax-label", "code: labels"),
 98    ]
 99
100    // MARK: - The default theme
101
102    private static func palette(_ pairs: [String: String]) -> [String: RGBA] {
103        pairs.compactMapValues { RGBA(hex: $0) }
104    }
105
106    /// Calm colors after GitHub's light and dark themes: headings colored by level, keywords
107    /// clear without shouting, code in the colors developers know.
108    public static let `default` = ThemeSpec(
109        light: palette([
110            "background": "#ffffff", "foreground": "#1f2328", "cursor": "#0969da", "selection": "#0969da33",
111            "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
112            "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
113            "todo": "#cf222e", "done": "#1a7f37", "priority": "#bc4c00", "tags": "#6e7781",
114            "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
115            "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
116            "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
117            "line-number": "#8c959f", "line-number-current": "#1f2328",
118            "syntax-keyword": "#cf222e", "syntax-string": "#0a3069", "syntax-comment": "#6e7781", "syntax-function": "#8250df",
119            "syntax-type": "#953800", "syntax-number": "#0550ae", "syntax-property": "#0550ae", "syntax-label": "#8250df",
120        ]),
121        dark: palette([
122            "background": "#0d1117", "foreground": "#e6edf3", "cursor": "#58a6ff", "selection": "#388bfd66",
123            "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
124            "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
125            "todo": "#ff7b72", "done": "#3fb950", "priority": "#ffa657", "tags": "#8b949e",
126            "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
127            "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
128            "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
129            "line-number": "#6e7681", "line-number-current": "#e6edf3",
130            "syntax-keyword": "#ff7b72", "syntax-string": "#a5d6ff", "syntax-comment": "#8b949e", "syntax-function": "#d2a8ff",
131            "syntax-type": "#ffa657", "syntax-number": "#79c0ff", "syntax-property": "#79c0ff", "syntax-label": "#d2a8ff",
132        ])
133    )
134
135    // MARK: - Reading
136
137    /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
138    public static let typeKeys: Set<String> = ["font", "font-size", "line-spacing", "heading-size-step", "theme-file"]
139
140    /// Whether a table holds theme colors.
141    public static func isThemeTable(_ name: String) -> Bool {
142        name == "theme" || name.hasPrefix("theme.")
143    }
144
145    /// `base` with the colors of `tables` laid over it, in order; problems for keys and
146    /// values it can't use.
147    public static func reading(_ tables: [TOML.Table], over base: ThemeSpec = .default, file: String = "config.toml") -> (ThemeSpec, [String]) {
148        var spec = base
149        var problems: [String] = []
150        let known = Set(slots.map(\.key))
151        for table in tables where isThemeTable(table.name) {
152            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
153                if table.name == "theme", typeKeys.contains(key) { continue }
154                guard let text = value.string, let color = RGBA(hex: text) else {
155                    problems.append("\(file): \(table.name).\(key) must be a color such as \"#1f2328\"")
156                    continue
157                }
158                switch table.name {
159                case "theme.todo":
160                    spec.todo[key] = color
161                case "theme", "theme.light", "theme.dark":
162                    guard known.contains(key) else {
163                        problems.append("\(file): unknown theme color \(key)")
164                        continue
165                    }
166                    if table.name != "theme.dark" { spec.light[key] = color }
167                    if table.name != "theme.light" { spec.dark[key] = color }
168                default:
169                    problems.append("\(file): unknown table [\(table.name)]")
170                }
171            }
172        }
173        return (spec, problems)
174    }
175
176    /// The default theme written out, to copy colors from.
177    public static func defaultThemeFile() -> String {
178        var out = """
179            # Orgstar's default theme, for reference: Orgstar writes this file again each time it
180            # starts, so change colors in config.toml. A key set under [theme] colors both
181            # appearances; [theme.light] and [theme.dark] set one. Colors are "#rrggbb" or
182            # "#rrggbbaa". [theme.todo] colors TODO keywords by name, as org-todo-keyword-faces:
183            #
184            #   [theme.todo]
185            #   WAIT = "#bf8700"
186            #
187            # A theme kept in its own file (with the same tables) is used with
188            # `theme-file = "name.toml"` under [theme] in config.toml.
189
190            """
191        for (name, colors) in [("theme.light", ThemeSpec.default.light), ("theme.dark", ThemeSpec.default.dark)] {
192            out += "\n[\(name)]\n"
193            for slot in slots {
194                guard let color = colors[slot.key] else { continue }
195                let line = "\(slot.key) = \"\(color.hex)\""
196                out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
197            }
198        }
199        return out
200    }
201}