#!/usr/bin/env python3 """The colourscheme of LLeMbas IDE, generated from the family's design tokens. scripts/gen-ide-theme.py writes ide/config/colors/llembas.lua scripts/gen-ide-theme.py --check exits 1 when that file is not what the tokens give scripts/gen-ide-theme.py --tokens FILE --out FILE The tokens file is the LLeMbas server's tokens.css, or the copy of its colour declarations in ide/tokens.css. Its two themes become the two halves of one colourscheme: `moria` when 'background' is dark, `shire` when it is light. Every colour the editor draws comes out of this file's output; the configuration itself names highlight groups, never colours. Standard library only. """ import argparse import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent THEMES = {"dark": "moria", "light": "shire"} NEEDED = [ "bg", "bg-sunken", "surface", "surface-raised", "surface-hover", "surface-active", "border", "border-strong", "ink", "ink-muted", "ink-faint", "ink-inverse", "accent", "accent-hover", "accent-ink", "accent-soft", "selection", "leaf", "leaf-hover", "leaf-soft", "danger", "danger-soft", "success", "success-soft", "warning", "warning-soft", ] def parse(css: str) -> dict: """{theme: {token: value}} for the theme blocks of a tokens file.""" out = {} for match in re.finditer(r"([^{}]*)\{([^{}]*)\}", css): names = re.findall(r'data-theme="([a-z0-9-]+)"', match.group(1)) if not names: continue decls = dict(re.findall(r"--([a-z0-9-]+):\s*([^;]+);", match.group(2))) for name in names: out.setdefault(name, {}).update({k: " ".join(v.split()) for k, v in decls.items()}) return out def rgb(value: str): value = value.strip() m = re.fullmatch(r"#([0-9A-Fa-f]{6})", value) if m: h = m.group(1) return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)), 1.0 m = re.fullmatch(r"rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([0-9.]+)\s*)?\)", value) if m: return (int(m.group(1)), int(m.group(2)), int(m.group(3))), float(m.group(4) or 1) raise ValueError(f"not a colour this generator reads: {value!r}") def mix(top, bottom, share): """`share` of top over bottom.""" return tuple(round(t * share + b * (1 - share)) for t, b in zip(top, bottom)) def hexa(c): return "#{:02X}{:02X}{:02X}".format(*c) def palette(tokens: dict) -> dict: """The tokens as opaque colours (a translucent one is laid over the background), plus the few mixes an editor needs that a web page does not.""" missing = [n for n in NEEDED if n not in tokens] if missing: raise ValueError("the tokens file lacks: " + ", ".join(missing)) bg, _ = rgb(tokens["bg"]) p = {} for name in NEEDED: colour, alpha = rgb(tokens[name]) p[name.replace("-", "_")] = colour if alpha >= 1 else mix(colour, bg, alpha) # What an editor needs between the tokens: all of them mixes of two tokens. p["line"] = mix(p["surface_hover"], p["bg"], 0.55) # the cursor's line p["ghost"] = mix(p["ink_faint"], p["bg"], 0.75) # text that is not there yet p["guide"] = mix(p["border"], p["bg"], 0.7) # whitespace, indent guides p["match"] = mix(p["warning"], p["bg"], 0.3) # a search match's background p["add_bg"] = mix(p["leaf"], p["bg"], 0.16) p["change_bg"] = mix(p["warning"], p["bg"], 0.14) p["delete_bg"] = mix(p["danger"], p["bg"], 0.16) p["text_bg"] = mix(p["warning"], p["bg"], 0.32) return {k: hexa(v) for k, v in p.items()} # group = (foreground, background, attributes) by palette name, or a link to another group. # One table for both themes: the palettes differ, the roles do not. GROUPS = [ # --- the editor --- ("Normal", "ink", "bg", ""), ("NormalNC", "ink", "bg", ""), ("NormalFloat", "ink", "surface", ""), ("FloatBorder", "border_strong", "surface", ""), ("FloatTitle", "leaf", "surface", "bold"), ("FloatFooter", "ink_faint", "surface", ""), ("Cursor", "bg", "ink", ""), ("CursorLine", None, "line", ""), ("CursorColumn", None, "line", ""), ("ColorColumn", None, "surface", ""), ("LineNr", "ink_faint", None, ""), ("CursorLineNr", "leaf", "line", "bold"), ("SignColumn", "ink_faint", "bg", ""), ("FoldColumn", "ink_faint", "bg", ""), ("Folded", "ink_muted", "surface", ""), ("WinSeparator", "border", None, ""), ("VertSplit", "border", None, ""), ("Visual", None, "selection", ""), ("VisualNOS", None, "selection", ""), ("Search", "ink", "match", ""), ("CurSearch", "ink_inverse", "warning", "bold"), ("IncSearch", "ink_inverse", "warning", "bold"), ("Substitute", "ink_inverse", "danger", ""), ("MatchParen", "accent", "surface_active", "bold"), ("NonText", "guide", None, ""), ("Whitespace", "guide", None, ""), ("SpecialKey", "guide", None, ""), ("EndOfBuffer", "bg", None, ""), ("Conceal", "ink_faint", None, ""), ("Directory", "accent", None, ""), ("Title", "leaf", None, "bold"), ("ErrorMsg", "danger", None, ""), ("WarningMsg", "warning", None, ""), ("MoreMsg", "accent", None, ""), ("ModeMsg", "ink_muted", None, ""), ("Question", "accent", None, ""), ("MsgArea", "ink", None, ""), ("MsgSeparator", "border", "bg", ""), ("QuickFixLine", None, "surface_active", "bold"), ("WildMenu", "accent_ink", "accent", ""), ("WinBar", "ink_muted", "bg", ""), ("WinBarNC", "ink_faint", "bg", ""), ("Pmenu", "ink", "surface_raised", ""), ("PmenuSel", "accent_ink", "accent", ""), ("PmenuKind", "ink_faint", "surface_raised", ""), ("PmenuExtra", "ink_faint", "surface_raised", ""), ("PmenuSbar", None, "surface_hover", ""), ("PmenuThumb", None, "border_strong", ""), ("PmenuMatch", "accent", None, "bold"), ("PmenuMatchSel", "accent_ink", None, "bold"), ("StatusLine", "ink", "surface_raised", ""), ("StatusLineNC", "ink_faint", "surface", ""), ("TabLine", "ink_muted", "surface", ""), ("TabLineSel", "ink", "bg", "bold"), ("TabLineFill", None, "bg_sunken", ""), ("SpellBad", None, None, "undercurl sp=danger"), ("SpellCap", None, None, "undercurl sp=warning"), ("SpellRare", None, None, "undercurl sp=accent"), ("SpellLocal", None, None, "undercurl sp=success"), # --- syntax --- ("Comment", "ink_faint", None, "italic"), ("Constant", "warning", None, ""), ("String", "leaf", None, ""), ("Character", "leaf", None, ""), ("Number", "warning", None, ""), ("Boolean", "warning", None, ""), ("Float", "warning", None, ""), ("Identifier", "ink", None, ""), ("Function", "accent_hover", None, ""), ("Statement", "accent", None, ""), ("Conditional", "accent", None, ""), ("Repeat", "accent", None, ""), ("Label", "accent", None, ""), ("Operator", "ink_muted", None, ""), ("Keyword", "accent", None, ""), ("Exception", "danger", None, ""), ("PreProc", "success", None, ""), ("Include", "accent", None, ""), ("Define", "success", None, ""), ("Macro", "success", None, ""), ("Type", "success", None, ""), ("StorageClass", "accent", None, ""), ("Structure", "success", None, ""), ("Typedef", "success", None, ""), ("Special", "accent_hover", None, ""), ("SpecialChar", "warning", None, ""), ("Tag", "accent", None, ""), ("Delimiter", "ink_muted", None, ""), ("SpecialComment", "ink_muted", None, "italic"), ("Debug", "danger", None, ""), ("Underlined", "accent", None, "underline"), ("Ignore", "ink_faint", None, ""), ("Error", "danger", None, ""), ("Todo", "ink_inverse", "warning", "bold"), ("Added", "leaf", None, ""), ("Changed", "warning", None, ""), ("Removed", "danger", None, ""), ("DiffAdd", None, "add_bg", ""), ("DiffChange", None, "change_bg", ""), ("DiffDelete", "danger", "delete_bg", ""), ("DiffText", None, "text_bg", "bold"), # --- Treesitter and LSP, where the default link is not the role --- ("@variable", "ink", None, ""), ("@variable.builtin", "danger", None, ""), ("@variable.parameter", "ink", None, "italic"), ("@variable.member", "ink_muted", None, ""), ("@property", "ink_muted", None, ""), ("@constant.builtin", "warning", None, ""), ("@module", "ink", None, ""), ("@constructor", "success", None, ""), ("@punctuation", "ink_muted", None, ""), ("@tag", "accent", None, ""), ("@tag.attribute", "success", None, ""), ("@tag.delimiter", "ink_faint", None, ""), ("@markup.heading", "leaf", None, "bold"), ("@markup.strong", None, None, "bold"), ("@markup.italic", None, None, "italic"), ("@markup.link", "accent", None, "underline"), ("@markup.raw", "warning", None, ""), ("@markup.list", "accent", None, ""), ("@markup.quote", "ink_muted", None, "italic"), ("LspReferenceText", None, "surface_active", ""), ("LspReferenceRead", None, "surface_active", ""), ("LspReferenceWrite", None, "surface_active", ""), ("LspInlayHint", "ghost", None, "italic"), ("LspSignatureActiveParameter", "warning", None, "bold"), # --- diagnostics --- ("DiagnosticError", "danger", None, ""), ("DiagnosticWarn", "warning", None, ""), ("DiagnosticInfo", "accent", None, ""), ("DiagnosticHint", "success", None, ""), ("DiagnosticOk", "leaf", None, ""), ("DiagnosticVirtualTextError", "danger", "danger_soft", ""), ("DiagnosticVirtualTextWarn", "warning", "warning_soft", ""), ("DiagnosticVirtualTextInfo", "accent", "accent_soft", ""), ("DiagnosticVirtualTextHint", "success", "success_soft", ""), ("DiagnosticUnderlineError", None, None, "undercurl sp=danger"), ("DiagnosticUnderlineWarn", None, None, "undercurl sp=warning"), ("DiagnosticUnderlineInfo", None, None, "undercurl sp=accent"), ("DiagnosticUnderlineHint", None, None, "undercurl sp=success"), ("DiagnosticUnnecessary", "ink_faint", None, ""), # --- the bars --- ("MiniStatuslineModeNormal", "ink_inverse", "leaf", "bold"), ("MiniStatuslineModeInsert", "accent_ink", "accent", "bold"), ("MiniStatuslineModeVisual", "ink_inverse", "warning", "bold"), ("MiniStatuslineModeReplace", "ink_inverse", "danger", "bold"), ("MiniStatuslineModeCommand", "ink_inverse", "success", "bold"), ("MiniStatuslineModeOther", "ink_inverse", "ink_muted", "bold"), ("MiniStatuslineDevinfo", "ink_muted", "surface_active", ""), ("MiniStatuslineFilename", "ink", "surface_raised", ""), ("MiniStatuslineFileinfo", "ink_muted", "surface_active", ""), ("MiniStatuslineInactive", "ink_faint", "surface", ""), ("MiniTablineCurrent", "ink", "bg", "bold"), ("MiniTablineVisible", "ink_muted", "surface", ""), ("MiniTablineHidden", "ink_faint", "bg_sunken", ""), ("MiniTablineModifiedCurrent", "warning", "bg", "bold"), ("MiniTablineModifiedVisible", "warning", "surface", ""), ("MiniTablineModifiedHidden", "warning", "bg_sunken", ""), ("MiniTablineFill", None, "bg_sunken", ""), ("MiniTablineTabpagesection", "ink_inverse", "leaf", "bold"), ("MiniTablineTrunc", "ink_faint", "bg_sunken", ""), # --- pickers, explorer, hints, git --- ("MiniPickMatchCurrent", None, "surface_active", "bold"), ("MiniPickMatchRanges", "accent", None, "bold"), ("MiniPickPrompt", "leaf", "surface", "bold"), ("MiniPickBorderText", "leaf", "surface", ""), ("MiniFilesTitleFocused", "leaf", "surface", "bold"), ("MiniFilesDirectory", "accent", None, ""), ("MiniFilesCursorLine", None, "surface_active", ""), ("MiniClueNextKey", "leaf", "surface", "bold"), ("MiniClueNextKeyWithPostkeys", "warning", "surface", "bold"), ("MiniClueDescGroup", "accent", "surface", ""), ("MiniClueDescSingle", "ink", "surface", ""), ("MiniClueSeparator", "border_strong", "surface", ""), ("MiniClueTitle", "leaf", "surface", "bold"), ("MiniDiffSignAdd", "leaf", None, ""), ("MiniDiffSignChange", "warning", None, ""), ("MiniDiffSignDelete", "danger", None, ""), ("MiniDiffOverAdd", None, "add_bg", ""), ("MiniDiffOverChange", None, "text_bg", ""), ("MiniDiffOverChangeBuf", None, "change_bg", ""), ("MiniDiffOverContext", None, "change_bg", ""), ("MiniDiffOverContextBuf", None, None, ""), ("MiniDiffOverDelete", None, "delete_bg", ""), ("MiniIconsAzure", "accent", None, ""), ("MiniIconsBlue", "accent", None, ""), ("MiniIconsCyan", "success", None, ""), ("MiniIconsGreen", "leaf", None, ""), ("MiniIconsGrey", "ink_muted", None, ""), ("MiniIconsOrange", "warning", None, ""), ("MiniIconsPurple", "accent_hover", None, ""), ("MiniIconsRed", "danger", None, ""), ("MiniIconsYellow", "warning", None, ""), ("BlinkCmpMenu", "ink", "surface_raised", ""), ("BlinkCmpMenuBorder", "border_strong", "surface_raised", ""), ("BlinkCmpMenuSelection", "accent_ink", "accent", ""), ("BlinkCmpLabelMatch", "accent", None, "bold"), ("BlinkCmpKind", "ink_faint", None, ""), ("BlinkCmpDoc", "ink", "surface", ""), ("BlinkCmpDocBorder", "border_strong", "surface", ""), # --- LLeMbas: the plugin's groups, and the IDE's own --- ("LLeMbasBrand", "leaf", None, "bold"), ("LLeMbasUserHeader", "accent", None, "bold"), ("LLeMbasAgentHeader", "leaf", None, "bold"), ("LLeMbasThought", "ink_faint", None, "italic"), ("LLeMbasToolPending", "warning", None, ""), ("LLeMbasToolDone", "success", None, ""), ("LLeMbasToolFail", "danger", None, ""), ("LLeMbasToolDenied", "danger", None, "italic"), ("LLeMbasPlanHeader", "accent", None, "bold"), ("LLeMbasDiffAdd", None, "add_bg", ""), ("LLeMbasDiffDelete", "danger", "delete_bg", ""), ("LLeMbasDiffHint", "ink_faint", None, "italic"), ("LLeMbasGhost", "ghost", None, "italic"), ("LLeMbasSeparator", "border", None, ""), ("LLeMbasIdeLeaf", "leaf", None, ""), ("LLeMbasIdeSign", "accent", None, ""), ("LLeMbasIdeTitle", "ink", None, "bold"), ("LLeMbasIdeVersion", "ink_faint", None, ""), ("LLeMbasIdeKey", "leaf", None, "bold"), ("LLeMbasIdeAction", "ink", None, ""), ("LLeMbasIdeMuted", "ink_faint", None, ""), ("LLeMbasIdeNote", "ink_muted", None, "italic"), ("LLeMbasIdeGood", "success", None, ""), ("LLeMbasIdeWarn", "warning", None, ""), ("LLeMbasIdeStatus", "leaf", "surface_raised", ""), ("LLeMbasIdeStatusOff", "ink_faint", "surface_raised", ""), # --- the layout: the top and the bottom bar share one ground, so no cell stands out by it --- ("LLeMbasBar", "ink_muted", "surface_raised", ""), ("LLeMbasBarKey", "leaf", "surface_raised", "bold"), ("LLeMbasBarTitle", "ink", "surface_raised", "bold"), ("LLeMbasBarSeparator", "border_strong", "surface_raised", ""), ("LLeMbasBarFact", "ink_faint", "surface_raised", ""), ("LLeMbasBarIdle", "leaf", "surface_raised", ""), ("LLeMbasBarBusy", "warning", "surface_raised", "bold"), ("LLeMbasBarWaiting", "accent", "surface_raised", "bold"), ("LLeMbasBarOff", "ink_faint", "surface_raised", ""), ("LLeMbasBarVim", "ink", "surface_active", ""), # --- the prompt, the settings lines, the tree --- ("LLeMbasPromptPrefix", "leaf", None, "bold"), ("LLeMbasChip", "accent", "accent_soft", ""), ("LLeMbasLineLabel", "ink_faint", None, ""), ("LLeMbasLineValue", "ink", None, ""), ("LLeMbasLineOff", "ink_faint", None, "italic"), ("LLeMbasLineCurrent", "leaf", None, "bold"), ("LLeMbasTreeDirectory", "accent", None, ""), ("LLeMbasTreeCurrent", None, "surface_active", "bold"), ("LLeMbasTreeChanged", "warning", None, ""), ("LLeMbasTreeAdded", "success", None, ""), ("LLeMbasTreeNew", "leaf", None, ""), ("LLeMbasTreeDeleted", "danger", None, ""), ("LLeMbasTreeConflict", "danger", None, "bold"), ] # The terminal's sixteen colours, by palette name. TERMINAL = [ "bg_sunken", "danger", "leaf", "warning", "accent", "accent_hover", "success", "ink_muted", "border_strong", "danger", "leaf_hover", "warning", "accent_hover", "accent_hover", "success", "ink", ] def render(themes: dict) -> str: palettes = {} for background, name in THEMES.items(): if name not in themes: raise ValueError(f'the tokens file has no data-theme="{name}" block') palettes[background] = palette(themes[name]) keys = sorted(palettes["dark"]) for _, fg, bg, attrs in GROUPS: for used in [fg, bg] + re.findall(r"sp=(\w+)", attrs): if used is not None and used not in keys: raise ValueError(f"a group names the colour {used}, which the palette lacks") out = [ "-- LLeMbas: the colourscheme of LLeMbas IDE. moria when 'background' is dark, shire when light.", "-- GENERATED by scripts/gen-ide-theme.py from the design tokens. Do not edit: change the tokens", "-- or the generator, and run it again. Your own colours belong in lua/user/init.lua.", "local palettes = {", ] for background in ("dark", "light"): out.append(f" {background} = {{ -- {THEMES[background]}") for key in keys: out.append(f' {key} = "{palettes[background][key]}",') out.append(" },") out += [ "}", "", "local groups = {", ] for name, fg, bg, attrs in GROUPS: parts = [] if fg: parts.append(f'fg = "{fg}"') if bg: parts.append(f'bg = "{bg}"') for attr in attrs.split(): if attr.startswith("sp="): parts.append(f'sp = "{attr[3:]}"') else: parts.append(f"{attr} = true") out.append(f' ["{name}"] = {{ {", ".join(parts)} }},') out += [ "}", "", "local terminal = { " + ", ".join(f'"{name}"' for name in TERMINAL) + " }", "", 'if vim.g.colors_name then vim.cmd("highlight clear") end', 'vim.g.colors_name = "llembas"', 'local p = palettes[vim.o.background == "light" and "light" or "dark"]', "for name, spec in pairs(groups) do", " local hl = {}", " for key, value in pairs(spec) do", ' if key == "fg" or key == "bg" or key == "sp" then hl[key] = p[value] else hl[key] = value end', " end", " vim.api.nvim_set_hl(0, name, hl)", "end", 'for i, name in ipairs(terminal) do vim.g["terminal_color_" .. (i - 1)] = p[name] end', "", "-- For the configuration: the palette in use, by token name.", "return p", "", ] return "\n".join(out) def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--tokens", type=Path, default=ROOT / "ide" / "tokens.css") ap.add_argument("--out", type=Path, default=ROOT / "ide" / "config" / "colors" / "llembas.lua") ap.add_argument("--check", action="store_true", help="write nothing; fail when the file is stale") args = ap.parse_args() try: text = render(parse(args.tokens.read_text(encoding="utf-8"))) except (OSError, ValueError) as err: print(f"gen-ide-theme: {err}", file=sys.stderr) return 2 if args.check: current = args.out.read_text(encoding="utf-8") if args.out.exists() else "" if current != text: print(f"gen-ide-theme: {args.out} is not what {args.tokens} gives; run scripts/gen-ide-theme.py", file=sys.stderr) return 1 print(f"gen-ide-theme: {args.out.name} matches the tokens") return 0 args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(text, encoding="utf-8") print(f"gen-ide-theme: wrote {args.out}") return 0 if __name__ == "__main__": sys.exit(main())