krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Sources/OrgPresentation/ThemeSpec.swift

15f6b0709d88971fb62ed432c3e5b8032643670a
orgstar/Sources/OrgPresentation/ThemeSpec.swift history · blame · raw

240 lines · 12786 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        ("sidebar-background", "the folder sidebar and the outline; unset: the system's"),
 99        ("sidebar-foreground", "file and heading names there; unset: the system's"),
100        ("sidebar-header", "folder names there; unset: the system's"),
101        ("modeline-background", "the modeline and message line; unset: the system's"),
102        ("modeline-foreground", "modeline text; unset: the system's"),
103        ("modeline-highlight", "the outline path and the clock in the modeline"),
104        ("state-normal", "the NORMAL tag"),
105        ("state-insert", "the INSERT tag"),
106        ("state-visual", "the VISUAL and V-LINE tags"),
107        ("agenda-background", "the agenda and board; unset: the system's"),
108        ("agenda-date", "agenda day headers"),
109        ("agenda-today", "today's header and the current time"),
110        ("agenda-time", "times and the time grid"),
111        ("agenda-category", "categories"),
112        ("agenda-deadline", "deadlines due"),
113        ("agenda-upcoming", "deadlines coming up"),
114        ("agenda-scheduled", "scheduled items"),
115        ("agenda-scheduled-past", "items scheduled on an earlier day"),
116        ("habit-clear", "habit graph: not due yet"),
117        ("habit-ready", "habit graph: due"),
118        ("habit-alert", "habit graph: due today, last chance"),
119        ("habit-overdue", "habit graph: overdue"),
120    ]
121
122    /// Keys the default theme leaves to the system, so windows keep the macOS look.
123    public static let systemDefaults: Set<String> = [
124        "sidebar-background", "sidebar-foreground", "sidebar-header", "modeline-background", "modeline-foreground", "agenda-background",
125    ]
126
127    // MARK: - The default theme
128
129    private static func palette(_ pairs: [String: String]) -> [String: RGBA] {
130        pairs.compactMapValues { RGBA(hex: $0) }
131    }
132
133    /// Calm colors after GitHub's light and dark themes: headings colored by level, keywords
134    /// clear without shouting, code in the colors developers know.
135    public static let `default` = ThemeSpec(
136        light: palette([
137            "background": "#ffffff", "foreground": "#1f2328", "cursor": "#0969da", "selection": "#0969da33",
138            "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
139            "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
140            "todo": "#cf222e", "done": "#1a7f37", "priority": "#bc4c00", "tags": "#6e7781",
141            "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
142            "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
143            "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
144            "line-number": "#8c959f", "line-number-current": "#1f2328",
145            "syntax-keyword": "#cf222e", "syntax-string": "#0a3069", "syntax-comment": "#6e7781", "syntax-function": "#8250df",
146            "syntax-type": "#953800", "syntax-number": "#1b7c83", "syntax-property": "#0550ae", "syntax-label": "#8250df",
147            "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00",
148            "agenda-date": "#1f2328", "agenda-today": "#0969da", "agenda-time": "#6e7781", "agenda-category": "#6e7781",
149            "agenda-deadline": "#cf222e", "agenda-upcoming": "#bc4c00", "agenda-scheduled": "#6e7781", "agenda-scheduled-past": "#953800",
150            "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182",
151        ]),
152        dark: palette([
153            "background": "#0d1117", "foreground": "#e6edf3", "cursor": "#58a6ff", "selection": "#388bfd66",
154            "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
155            "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
156            "todo": "#ff7b72", "done": "#3fb950", "priority": "#ffa657", "tags": "#8b949e",
157            "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
158            "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
159            "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
160            "line-number": "#6e7681", "line-number-current": "#e6edf3",
161            "syntax-keyword": "#ff7b72", "syntax-string": "#a5d6ff", "syntax-comment": "#8b949e", "syntax-function": "#d2a8ff",
162            "syntax-type": "#ffa657", "syntax-number": "#56d4dd", "syntax-property": "#79c0ff", "syntax-label": "#d2a8ff",
163            "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03",
164            "agenda-date": "#e6edf3", "agenda-today": "#58a6ff", "agenda-time": "#8b949e", "agenda-category": "#8b949e",
165            "agenda-deadline": "#ff7b72", "agenda-upcoming": "#ffa657", "agenda-scheduled": "#8b949e", "agenda-scheduled-past": "#d29922",
166            "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633",
167        ])
168    )
169
170    // MARK: - Reading
171
172    /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
173    public static let typeKeys: Set<String> = ["font", "font-size", "line-spacing", "heading-size-step", "theme-file"]
174
175    /// Whether a table holds theme colors.
176    public static func isThemeTable(_ name: String) -> Bool {
177        name == "theme" || name.hasPrefix("theme.")
178    }
179
180    /// `base` with the colors of `tables` laid over it, in order; problems for keys and
181    /// values it can't use.
182    public static func reading(_ tables: [TOML.Table], over base: ThemeSpec = .default, file: String = "config.toml") -> (ThemeSpec, [String]) {
183        var spec = base
184        var problems: [String] = []
185        let known = Set(slots.map(\.key))
186        for table in tables where isThemeTable(table.name) {
187            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
188                if table.name == "theme", typeKeys.contains(key) { continue }
189                guard let text = value.string, let color = RGBA(hex: text) else {
190                    problems.append("\(file): \(table.name).\(key) must be a color such as \"#1f2328\"")
191                    continue
192                }
193                switch table.name {
194                case "theme.todo":
195                    spec.todo[key] = color
196                case "theme", "theme.light", "theme.dark":
197                    guard known.contains(key) else {
198                        problems.append("\(file): unknown theme color \(key)")
199                        continue
200                    }
201                    if table.name != "theme.dark" { spec.light[key] = color }
202                    if table.name != "theme.light" { spec.dark[key] = color }
203                default:
204                    problems.append("\(file): unknown table [\(table.name)]")
205                }
206            }
207        }
208        return (spec, problems)
209    }
210
211    /// The default theme written out, to copy colors from.
212    public static func defaultThemeFile() -> String {
213        var out = """
214            # Orgstar's default theme, for reference: Orgstar writes this file again each time it
215            # starts, so change colors in config.toml. A key set under [theme] colors both
216            # appearances; [theme.light] and [theme.dark] set one. Colors are "#rrggbb" or
217            # "#rrggbbaa". [theme.todo] colors TODO keywords by name, as org-todo-keyword-faces:
218            #
219            #   [theme.todo]
220            #   WAIT = "#bf8700"
221            #
222            # A theme kept in its own file (with the same tables) is used with
223            # `theme-file = "name.toml"` under [theme] in config.toml.
224
225            """
226        for (name, colors) in [("theme.light", ThemeSpec.default.light), ("theme.dark", ThemeSpec.default.dark)] {
227            out += "\n[\(name)]\n"
228            for slot in slots {
229                guard let color = colors[slot.key] else {
230                    let line = "# \(slot.key) = \"#rrggbb\""
231                    out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
232                    continue
233                }
234                let line = "\(slot.key) = \"\(color.hex)\""
235                out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
236            }
237        }
238        return out
239    }
240}