Sources/OrgPresentation/ThemeSpec.swift

8f8f9a8c12170a956eedc8c5db4f319a9e7f7518
orgstar/Sources/OrgPresentation/ThemeSpec.swift

358 lines · 18656 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 categories, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]`,
 37/// `[theme.todo]` and `[theme.category]` 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    /// The font for prose: a family, `system` for the system's proportional font, or empty for
 42    /// `font` throughout. Tables, code and other `Presentation.isFixedPitch` text keep `font`.
 43    public var bodyFont = ""
 44    public var fontSize = 13
 45    /// Points between lines.
 46    public var lineSpacing = 2
 47    /// Points a heading is larger than the next level down (level 4 and deeper are body size).
 48    public var headingSizeStep = 1
 49    public var light: [String: RGBA]
 50    public var dark: [String: RGBA]
 51    /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances.
 52    public var todo: [String: RGBA] = [:]
 53    /// A color per agenda category, the same in both appearances, over `categoryColor`'s hue.
 54    public var category: [String: RGBA] = [:]
 55
 56    public init(light: [String: RGBA], dark: [String: RGBA]) {
 57        self.light = light
 58        self.dark = dark
 59    }
 60
 61    public func color(_ key: String, dark isDark: Bool) -> RGBA? {
 62        (isDark ? dark : light)[key]
 63    }
 64
 65    // MARK: - Slots
 66
 67    /// Every color key, with what it colors.
 68    public static let slots: [(key: String, description: String)] = [
 69        ("background", "the editor's background"),
 70        ("foreground", "body text"),
 71        ("cursor", "the caret"),
 72        ("selection", "selected text's background"),
 73        ("heading-1", "level 1 headings"), ("heading-2", "level 2 headings"), ("heading-3", "level 3 headings"),
 74        ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"),
 75        ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"),
 76        ("todo", "TODO keywords not yet done"),
 77        ("todo-next", "keywords of work under way: NEXT, STRT, STARTED, DOING, ACTIVE"),
 78        ("todo-waiting", "keywords of work on hold: WAIT, WAITING, HOLD, BLOCKED, DEFERRED, SOMEDAY, MAYBE"),
 79        ("done", "DONE keywords"),
 80        ("todo-cancelled", "done keywords that cancel: KILL, CANCELLED, CANCELED, CANCEL, SKIPPED, SKIP, ABORTED, NO, WONTFIX"),
 81        ("priority", "[#A] cookies"),
 82        ("priority-a", "agenda: priority A"),
 83        ("priority-b", "agenda: priority B"),
 84        ("priority-c", "agenda: priority C"),
 85        ("tags", ":tags:"),
 86        ("link", "links"),
 87        ("timestamp", "timestamps"),
 88        ("code", "~code~ and inline source"),
 89        ("verbatim", "=verbatim="),
 90        ("inline-background", "behind ~code~ and =verbatim="),
 91        ("markup", "link brackets and emphasis markers"),
 92        ("comment", "comments"),
 93        ("keyword", "#+KEYWORD lines"),
 94        ("metadata", "planning lines, drawers, properties and clocks"),
 95        ("special", "footnotes, statistics cookies, targets, macros and LaTeX"),
 96        ("block-background", "the band behind blocks"),
 97        ("block-delimiter", "#+begin_ and #+end_ lines"),
 98        ("table", "tables"),
 99        ("line-number", "line numbers"),
100        ("line-number-current", "the caret's line number"),
101        ("syntax-keyword", "code: keywords"),
102        ("syntax-string", "code: strings"),
103        ("syntax-comment", "code: comments"),
104        ("syntax-function", "code: functions"),
105        ("syntax-type", "code: types and modules"),
106        ("syntax-number", "code: numbers, constants and escapes"),
107        ("syntax-property", "code: properties, attributes and tags"),
108        ("syntax-label", "code: labels"),
109        ("sidebar-background", "the folder sidebar and the outline; unset: the system's"),
110        ("sidebar-foreground", "file and heading names there; unset: the system's"),
111        ("sidebar-header", "folder names there; unset: the system's"),
112        ("modeline-background", "the modeline and message line; unset: the system's"),
113        ("modeline-foreground", "modeline text; unset: the system's"),
114        ("modeline-highlight", "the outline path and the clock in the modeline"),
115        ("state-normal", "the NORMAL tag"),
116        ("state-insert", "the INSERT tag"),
117        ("state-visual", "the VISUAL and V-LINE tags"),
118        ("agenda-background", "the agenda and board; unset: the system's"),
119        ("agenda-date", "agenda day headers"),
120        ("agenda-today", "today's header and the current time"),
121        ("agenda-time", "times and the time grid"),
122        ("agenda-category", "categories"),
123        ("agenda-overdue", "agenda: the status of entries past their deadline or scheduled date"),
124        ("agenda-due-soon", "agenda: the status of deadlines due today or coming up"),
125        ("agenda-event", "agenda: calendar events whose calendar has no color"),
126        ("habit-clear", "habit graph: not due yet"),
127        ("habit-ready", "habit graph: due"),
128        ("habit-alert", "habit graph: due today, last chance"),
129        ("habit-overdue", "habit graph: overdue"),
130    ]
131
132    /// Keys the default theme leaves to the system, so windows keep the macOS look.
133    public static let systemDefaults: Set<String> = [
134        "sidebar-background", "sidebar-foreground", "sidebar-header", "modeline-background", "modeline-foreground", "agenda-background",
135    ]
136
137    // MARK: - The default theme
138
139    private static func palette(_ pairs: [String: String]) -> [String: RGBA] {
140        pairs.compactMapValues { RGBA(hex: $0) }
141    }
142
143    /// Calm colors after GitHub's light and dark themes for text and code: headings colored by
144    /// level, code in the colors developers know. Keywords, priorities and the agenda's states
145    /// use the system's accessible reds, oranges, blues and greens, so they match iOS and macOS.
146    public static let `default` = ThemeSpec(
147        light: palette([
148            "background": "#ffffff", "foreground": "#1f2328", "cursor": "#0969da", "selection": "#0969da33",
149            "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
150            "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
151            "todo": "#d70015", "done": "#248a3d", "priority": "#c93400", "tags": "#6e7781",
152            "todo-next": "#0a66d8", "todo-waiting": "#b25000", "todo-cancelled": "#8e8e93",
153            "priority-a": "#d70015", "priority-b": "#c93400", "priority-c": "#6c7a8c",
154            "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
155            "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
156            "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
157            "line-number": "#8c959f", "line-number-current": "#1f2328",
158            "syntax-keyword": "#cf222e", "syntax-string": "#0a3069", "syntax-comment": "#6e7781", "syntax-function": "#8250df",
159            "syntax-type": "#953800", "syntax-number": "#1b7c83", "syntax-property": "#0550ae", "syntax-label": "#8250df",
160            "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00",
161            "agenda-date": "#1f2328", "agenda-today": "#007aff", "agenda-time": "#6c6c70", "agenda-category": "#6c6c70",
162            "agenda-overdue": "#d70015", "agenda-due-soon": "#c93400", "agenda-event": "#8944ab",
163            "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182",
164        ]),
165        dark: palette([
166            "background": "#0d1117", "foreground": "#e6edf3", "cursor": "#58a6ff", "selection": "#388bfd66",
167            "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
168            "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
169            "todo": "#ff6961", "done": "#30d158", "priority": "#ff9f0a", "tags": "#8b949e",
170            "todo-next": "#409cff", "todo-waiting": "#ffd60a", "todo-cancelled": "#8e8e93",
171            "priority-a": "#ff6961", "priority-b": "#ff9f0a", "priority-c": "#98a6b8",
172            "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
173            "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
174            "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
175            "line-number": "#6e7681", "line-number-current": "#e6edf3",
176            "syntax-keyword": "#ff7b72", "syntax-string": "#a5d6ff", "syntax-comment": "#8b949e", "syntax-function": "#d2a8ff",
177            "syntax-type": "#ffa657", "syntax-number": "#56d4dd", "syntax-property": "#79c0ff", "syntax-label": "#d2a8ff",
178            "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03",
179            "agenda-date": "#e6edf3", "agenda-today": "#0a84ff", "agenda-time": "#98989d", "agenda-category": "#98989d",
180            "agenda-overdue": "#ff6961", "agenda-due-soon": "#ff9f0a", "agenda-event": "#da8fff",
181            "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633",
182        ])
183    )
184
185    // MARK: - Reading
186
187    /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
188    public static let typeKeys: Set<String> = ["font", "body-font", "font-size", "line-spacing", "heading-size-step", "theme-file"]
189
190    /// Whether a table holds theme colors.
191    public static func isThemeTable(_ name: String) -> Bool {
192        name == "theme" || name.hasPrefix("theme.")
193    }
194
195    /// `base` with the colors of `tables` laid over it, in order; problems for keys and
196    /// values it can't use.
197    public static func reading(_ tables: [TOML.Table], over base: ThemeSpec = .default, file: String = "config.toml") -> (ThemeSpec, [String]) {
198        var spec = base
199        var problems: [String] = []
200        let known = Set(slots.map(\.key))
201        for table in tables where isThemeTable(table.name) {
202            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
203                if table.name == "theme", typeKeys.contains(key) { continue }
204                guard let text = value.string, let color = RGBA(hex: text) else {
205                    problems.append("\(file): \(table.name).\(key) must be a color such as \"#1f2328\"")
206                    continue
207                }
208                switch table.name {
209                case "theme.todo":
210                    spec.todo[key] = color
211                case "theme.category":
212                    spec.category[key] = color
213                case "theme", "theme.light", "theme.dark":
214                    guard known.contains(key) else {
215                        problems.append("\(file): unknown theme color \(key)")
216                        continue
217                    }
218                    if table.name != "theme.dark" { spec.light[key] = color }
219                    if table.name != "theme.light" { spec.dark[key] = color }
220                default:
221                    problems.append("\(file): unknown table [\(table.name)]")
222                }
223            }
224        }
225        return (spec, problems)
226    }
227
228    /// The default theme written out, to copy colors from.
229    public static func defaultThemeFile() -> String {
230        var out = """
231            # orgstar's default theme, for reference: orgstar writes this file again each time it
232            # starts, so change colors in config.toml. A key set under [theme] colors both
233            # appearances; [theme.light] and [theme.dark] set one. Colors are "#rrggbb" or
234            # "#rrggbbaa". [theme.todo] colors TODO keywords by name, as org-todo-keyword-faces:
235            #
236            #   [theme.todo]
237            #   WAIT = "#bf8700"
238            #
239            # Otherwise a keyword takes its class's color: todo, todo-next, todo-waiting, done or
240            # todo-cancelled. [theme.category] colors agenda categories by name the same way;
241            # categories without one get a hue of their own from their name.
242            #
243            # A theme kept in its own file (with the same tables) is used with
244            # `theme-file = "name.toml"` under [theme] in config.toml.
245
246            """
247        for (name, colors) in [("theme.light", ThemeSpec.default.light), ("theme.dark", ThemeSpec.default.dark)] {
248            out += "\n[\(name)]\n"
249            for slot in slots {
250                guard let color = colors[slot.key] else {
251                    let line = "# \(slot.key) = \"#rrggbb\""
252                    out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
253                    continue
254                }
255                let line = "\(slot.key) = \"\(color.hex)\""
256                out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
257            }
258        }
259        return out
260    }
261}
262
263// MARK: - Agenda colors
264
265extension ThemeSpec {
266    /// The color classes of TODO keywords, by name: keywords of work under way and on hold,
267    /// and done keywords that cancel; the others are `todo` or `done`.
268    public enum TodoClass: String, Sendable {
269        case todo, next, waiting, done, cancelled
270
271        /// The theme key.
272        public var key: String {
273            switch self {
274            case .todo: "todo"
275            case .next: "todo-next"
276            case .waiting: "todo-waiting"
277            case .done: "done"
278            case .cancelled: "todo-cancelled"
279            }
280        }
281
282        static let nextWords: Set<String> = ["NEXT", "STRT", "STARTED", "START", "DOING", "ACTIVE", "INPROGRESS", "IN-PROGRESS"]
283        static let waitingWords: Set<String> = ["WAIT", "WAITING", "HOLD", "ONHOLD", "BLOCKED", "DEFERRED", "SOMEDAY", "MAYBE"]
284        static let cancelledWords: Set<String> = ["KILL", "KILLED", "CANCELLED", "CANCELED", "CANCEL", "SKIPPED", "SKIP", "ABORTED", "NO", "WONTFIX"]
285
286        public static func of(_ keyword: String, isDone: Bool) -> TodoClass {
287            let word = keyword.uppercased()
288            if isDone { return cancelledWords.contains(word) ? .cancelled : .done }
289            if nextWords.contains(word) { return .next }
290            if waitingWords.contains(word) { return .waiting }
291            return .todo
292        }
293    }
294
295    /// `[theme.todo]`'s color for the keyword, else its class's.
296    public func todoColor(_ keyword: String, isDone: Bool, dark isDark: Bool) -> RGBA? {
297        todo[keyword] ?? color(TodoClass.of(keyword, isDone: isDone).key, dark: isDark)
298    }
299
300    /// `priority-a`, `-b`, `-c`; `priority` for the others.
301    public func priorityColor(_ priority: String, dark isDark: Bool) -> RGBA? {
302        let key = ["A": "priority-a", "B": "priority-b", "C": "priority-c"][priority] ?? "priority"
303        return color(key, dark: isDark) ?? color("priority", dark: isDark)
304    }
305
306    /// The gutter's color: `agenda-overdue`, `agenda-due-soon`, `done`, else `agenda-time`.
307    public func statusColor(_ status: AgendaRow.Status, dark isDark: Bool) -> RGBA? {
308        switch status {
309        case .overdue: color("agenda-overdue", dark: isDark)
310        case .dueSoon: color("agenda-due-soon", dark: isDark)
311        case .done: color("done", dark: isDark)
312        case .normal: color("agenda-time", dark: isDark)
313        }
314    }
315
316    /// An event's calendar color, else `agenda-event`.
317    public func eventColor(_ event: AgendaEvent, dark isDark: Bool) -> RGBA? {
318        event.color ?? color("agenda-event", dark: isDark)
319    }
320
321    /// `[theme.category]`'s color for the category, else its hue (`categoryHue`) at a
322    /// saturation and lightness that read on the appearance's background.
323    public func categoryColor(_ name: String, dark isDark: Bool) -> RGBA {
324        if let set = category[name] { return set }
325        let hue = Self.categoryHue(name)
326        return isDark ? RGBA(hue: hue, saturation: 0.65, lightness: 0.70) : RGBA(hue: hue, saturation: 0.60, lightness: 0.40)
327    }
328
329    /// A hue in degrees from the category's name (FNV-1a of its UTF-8), the same on every run
330    /// and device.
331    public static func categoryHue(_ name: String) -> Double {
332        var hash: UInt32 = 2166136261
333        for byte in name.utf8 {
334            hash ^= UInt32(byte)
335            hash = hash &* 16777619
336        }
337        return Double(hash % 360)
338    }
339}
340
341extension RGBA {
342    /// From HSL: hue in degrees, saturation and lightness 0 to 1.
343    public init(hue: Double, saturation s: Double, lightness l: Double, alpha: Double = 1) {
344        let c = (1 - abs(2 * l - 1)) * s
345        let h = (hue.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360) / 60
346        let x = c * (1 - abs(h.truncatingRemainder(dividingBy: 2) - 1))
347        let (r, g, b): (Double, Double, Double) = switch Int(h) {
348        case 0: (c, x, 0)
349        case 1: (x, c, 0)
350        case 2: (0, c, x)
351        case 3: (0, x, c)
352        case 4: (x, 0, c)
353        default: (c, 0, x)
354        }
355        let m = l - c / 2
356        self.init(red: r + m, green: g + m, blue: b + m, alpha: alpha)
357    }
358}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form