Files
nvim/lua/ghostty_theme.lua
T

553 lines
22 KiB
Lua

-- Colorscheme generated from Ghostty's currently active theme.
--
-- Colors are read from `ghostty +show-config` (resolved theme + user
-- overrides). Conditional themes (`theme = light:X,dark:Y`) are resolved
-- manually against the current OS appearance, because the CLI always
-- picks the light variant.
local M = {}
---------------------------------------------------------------------------
-- Color math
---------------------------------------------------------------------------
local function hex_to_rgb(hex)
hex = hex:gsub("^#", "")
if #hex == 3 then hex = hex:gsub(".", "%0%0") end
return tonumber(hex:sub(1, 2), 16), tonumber(hex:sub(3, 4), 16), tonumber(hex:sub(5, 6), 16)
end
local function rgb_to_hex(r, g, b)
local function c(x) return math.max(0, math.min(255, math.floor(x + 0.5))) end
return string.format("#%02x%02x%02x", c(r), c(g), c(b))
end
--- Mix `a` towards `b` by `t` (0 = a, 1 = b).
local function blend(a, b, t)
local r1, g1, b1 = hex_to_rgb(a)
local r2, g2, b2 = hex_to_rgb(b)
return rgb_to_hex(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t)
end
local function luminance(hex)
local function ch(x)
x = x / 255
return x <= 0.03928 and x / 12.92 or ((x + 0.055) / 1.055) ^ 2.4
end
local r, g, b = hex_to_rgb(hex)
return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b)
end
local function contrast(a, b)
local l1, l2 = luminance(a), luminance(b)
if l1 < l2 then l1, l2 = l2, l1 end
return (l1 + 0.05) / (l2 + 0.05)
end
--- Push `c` towards `towards` until it reaches `min` contrast against `bg`.
local function ensure_contrast(c, bg, towards, min)
local out, t = c, 0
while contrast(out, bg) < min and t < 1 do
t = t + 0.05
out = blend(c, towards, t)
end
return out
end
local function is_hex(v)
return type(v) == "string" and v:match("^#%x%x%x%x%x%x$") ~= nil
end
---------------------------------------------------------------------------
-- Reading Ghostty's config
---------------------------------------------------------------------------
-- Ghostty's built-in defaults, used for anything a theme leaves unset.
local DEFAULTS = {
background = "#282c34",
foreground = "#ffffff",
palette = {
[0] = "#1d1f21", "#cc6666", "#b5bd68", "#f0c674", "#81a2be", "#b294bb", "#8abeb7", "#c5c8c6",
"#666666", "#d54e53", "#b9ca4a", "#e7c547", "#7aa6da", "#c397d8", "#70c0b1", "#eaeaea",
},
}
local COLOR_KEYS = {
background = true,
foreground = true,
["cursor-color"] = true,
["cursor-text"] = true,
["selection-background"] = true,
["selection-foreground"] = true,
["background-opacity"] = true,
}
local function ghostty_bin()
if vim.fn.executable("ghostty") == 1 then return "ghostty" end
for _, p in ipairs({
"/Applications/Ghostty.app/Contents/MacOS/ghostty",
vim.fn.expand("~/Applications/Ghostty.app/Contents/MacOS/ghostty"),
}) do
if vim.fn.executable(p) == 1 then return p end
end
end
--- Parse ghostty config text into `into` (later keys override earlier ones).
local function parse(text, into, opts)
opts = opts or {}
into.palette = into.palette or {}
for line in text:gmatch("[^\r\n]+") do
local key, val = line:match("^%s*([%w%-]+)%s*=%s*(.-)%s*$")
if key then
val = val:gsub('^"(.*)"$', "%1")
if key == "palette" then
local idx, color = val:match("^(%d+)%s*=%s*(#?%x+)$")
if idx then into.palette[tonumber(idx)] = "#" .. color:gsub("^#", "") end
elseif key == "theme" and not opts.colors_only then
into.theme = val
elseif COLOR_KEYS[key] then
if val:match("^%x%x%x%x%x%x$") then val = "#" .. val end
into[key] = val
end
end
end
return into
end
local function read_file(path)
local f = io.open(path, "r")
if not f then return nil end
local s = f:read("*a")
f:close()
return s
end
local function system_is_dark()
if vim.fn.has("mac") == 1 then
local out = vim.fn.system({ "defaults", "read", "-g", "AppleInterfaceStyle" })
return vim.v.shell_error == 0 and out:match("Dark") ~= nil
end
if vim.fn.executable("gsettings") == 1 then
local out = vim.fn.system({ "gsettings", "get", "org.gnome.desktop.interface", "color-scheme" })
if vim.v.shell_error == 0 then return out:match("dark") ~= nil end
end
return true
end
local function xdg_config()
return vim.env.XDG_CONFIG_HOME or vim.fn.expand("~/.config")
end
local function user_config_files()
local files = {}
for _, p in ipairs({
xdg_config() .. "/ghostty/config",
xdg_config() .. "/ghostty/config.ghostty",
vim.fn.expand("~/Library/Application Support/com.mitchellh.ghostty/config"),
vim.fn.expand("~/Library/Application Support/com.mitchellh.ghostty/config.ghostty"),
}) do
if vim.fn.filereadable(p) == 1 then table.insert(files, p) end
end
return files
end
local function find_theme_file(name, bin)
if name:sub(1, 1) == "/" then return name end
local dirs = { xdg_config() .. "/ghostty/themes" }
if vim.env.GHOSTTY_RESOURCES_DIR then
table.insert(dirs, vim.env.GHOSTTY_RESOURCES_DIR .. "/themes")
end
if bin and bin:match("^/") then
table.insert(dirs, vim.fn.fnamemodify(bin, ":h:h") .. "/Resources/ghostty/themes")
end
vim.list_extend(dirs, {
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
})
for _, d in ipairs(dirs) do
local p = d .. "/" .. name
if vim.fn.filereadable(p) == 1 then return p end
end
end
--- Resolve `light:A,dark:B` by hand: defaults <- theme file <- user overrides.
local function resolve_conditional(theme, bin)
local light = theme:match("light:([^,]+)")
local dark = theme:match("dark:([^,]+)")
local name = vim.trim((system_is_dark() and dark or light) or "")
local cfg = { palette = {} }
local path = name ~= "" and find_theme_file(name, bin)
if path then parse(read_file(path) or "", cfg, { colors_only = true }) end
for _, f in ipairs(user_config_files()) do
parse(read_file(f) or "", cfg, { colors_only = true })
end
cfg.theme = theme
return cfg
end
--- Returns the active Ghostty colors, or nil if Ghostty isn't available.
function M.read()
local bin = ghostty_bin()
if not bin then return nil end
local out = vim.fn.system({ bin, "+show-config", "--no-pager" })
if vim.v.shell_error ~= 0 then return nil end
local cfg = parse(out, { palette = {} })
if cfg.theme and cfg.theme:match("light:") and cfg.theme:match("dark:") then
cfg = resolve_conditional(cfg.theme, bin)
end
return cfg
end
---------------------------------------------------------------------------
-- Palette -> highlight groups
---------------------------------------------------------------------------
local function build_palette(cfg)
local p = {}
local pal = cfg.palette or {}
for i = 0, 15 do
p[i] = is_hex(pal[i]) and pal[i] or DEFAULTS.palette[i]
end
local bg = is_hex(cfg.background) and cfg.background or DEFAULTS.background
local fg = is_hex(cfg.foreground) and cfg.foreground or DEFAULTS.foreground
if contrast(fg, bg) < 3 then fg = luminance(bg) > 0.4 and "#000000" or "#ffffff" end
local dark = luminance(bg) < luminance(fg)
local c = { bg = bg, fg = fg, dark = dark }
-- Accents: normal ANSI slots are the most reliable across themes
-- (e.g. Solarized repurposes the bright slots as greys).
local function accent(i)
return ensure_contrast(p[i], bg, fg, 3)
end
c.red = accent(1)
c.green = accent(2)
c.yellow = accent(3)
c.blue = accent(4)
c.magenta = accent(5)
c.cyan = accent(6)
c.orange = ensure_contrast(blend(p[1], p[3], 0.5), bg, fg, 3)
c.violet = ensure_contrast(blend(p[4], p[5], 0.5), bg, fg, 3)
-- Neutral shades derived from bg/fg so they always fit the theme.
c.bg1 = blend(bg, fg, 0.05)
c.bg2 = blend(bg, fg, 0.10)
c.bg3 = blend(bg, fg, 0.17)
c.bg4 = blend(bg, fg, 0.26)
c.fg_dim = blend(fg, bg, 0.25)
c.subtle = blend(fg, bg, 0.55)
-- Comments: bright black if readable, else a derived grey.
c.comment = contrast(p[8], bg) >= 2.5 and p[8] or ensure_contrast(blend(fg, bg, 0.5), bg, fg, 2.5)
c.sel_bg = is_hex(cfg["selection-background"]) and cfg["selection-background"] or c.bg4
c.sel_fg = is_hex(cfg["selection-foreground"]) and cfg["selection-foreground"] or nil
c.terminal = p
c.transparent = tonumber(cfg["background-opacity"] or "1") < 1
return c
end
local function highlights(c)
local bg = c.transparent and "NONE" or c.bg
local tint = function(col, t) return blend(c.bg, col, t) end
return {
-- Editor UI -----------------------------------------------------
Normal = { fg = c.fg, bg = bg },
NormalNC = { fg = c.fg, bg = bg },
NormalFloat = { fg = c.fg, bg = c.bg1 },
FloatBorder = { fg = c.bg4, bg = c.bg1 },
FloatTitle = { fg = c.blue, bg = c.bg1, bold = true },
FloatFooter = { fg = c.subtle, bg = c.bg1 },
WinSeparator = { fg = c.bg3 },
VertSplit = { link = "WinSeparator" },
ColorColumn = { bg = c.bg1 },
Conceal = { fg = c.subtle },
Cursor = { fg = c.bg, bg = c.fg },
lCursor = { link = "Cursor" },
CursorIM = { link = "Cursor" },
CursorLine = { bg = c.bg1 },
CursorColumn = { link = "CursorLine" },
CursorLineNr = { fg = c.yellow, bold = true },
LineNr = { fg = c.bg4 },
LineNrAbove = { link = "LineNr" },
LineNrBelow = { link = "LineNr" },
SignColumn = { bg = bg },
FoldColumn = { fg = c.subtle, bg = bg },
Folded = { fg = c.subtle, bg = c.bg1, italic = true },
EndOfBuffer = { fg = c.bg },
NonText = { fg = c.bg4 },
Whitespace = { fg = c.bg3 },
SpecialKey = { fg = c.bg4 },
Directory = { fg = c.blue },
Title = { fg = c.blue, bold = true },
Visual = { bg = c.sel_bg, fg = c.sel_fg },
VisualNOS = { link = "Visual" },
Search = { fg = c.bg, bg = c.yellow },
IncSearch = { fg = c.bg, bg = c.orange },
CurSearch = { link = "IncSearch" },
Substitute = { fg = c.bg, bg = c.red },
MatchParen = { bg = c.bg3, bold = true },
ModeMsg = { fg = c.fg, bold = true },
MsgArea = { fg = c.fg },
MoreMsg = { fg = c.green, bold = true },
Question = { fg = c.green },
ErrorMsg = { fg = c.red, bold = true },
WarningMsg = { fg = c.yellow, bold = true },
StatusLine = { fg = c.fg_dim, bg = c.bg2 },
StatusLineNC = { fg = c.subtle, bg = c.bg1 },
TabLine = { fg = c.subtle, bg = c.bg1 },
TabLineFill = { bg = c.bg1 },
TabLineSel = { fg = c.fg, bg = c.bg3, bold = true },
WinBar = { fg = c.fg_dim, bold = true },
WinBarNC = { fg = c.subtle },
Pmenu = { fg = c.fg, bg = c.bg1 },
PmenuSel = { bg = c.bg3, bold = true },
PmenuKind = { fg = c.blue, bg = c.bg1 },
PmenuKindSel = { fg = c.blue, bg = c.bg3 },
PmenuExtra = { fg = c.subtle, bg = c.bg1 },
PmenuExtraSel = { fg = c.subtle, bg = c.bg3 },
PmenuSbar = { bg = c.bg2 },
PmenuThumb = { bg = c.bg4 },
PmenuMatch = { fg = c.blue, bold = true },
PmenuMatchSel = { fg = c.blue, bold = true },
WildMenu = { link = "PmenuSel" },
QuickFixLine = { bg = c.bg2, bold = true },
SpellBad = { sp = c.red, undercurl = true },
SpellCap = { sp = c.yellow, undercurl = true },
SpellLocal = { sp = c.cyan, undercurl = true },
SpellRare = { sp = c.magenta, undercurl = true },
-- Syntax --------------------------------------------------------
Comment = { fg = c.comment, italic = true },
Constant = { fg = c.orange },
String = { fg = c.green },
Character = { fg = c.green },
Number = { fg = c.orange },
Boolean = { fg = c.orange },
Float = { fg = c.orange },
Identifier = { fg = c.fg },
Function = { fg = c.blue },
Statement = { fg = c.magenta },
Conditional = { fg = c.magenta },
Repeat = { fg = c.magenta },
Label = { fg = c.magenta },
Operator = { fg = c.cyan },
Keyword = { fg = c.magenta },
Exception = { fg = c.red },
PreProc = { fg = c.cyan },
Include = { fg = c.red },
Define = { fg = c.cyan },
Macro = { fg = c.cyan },
PreCondit = { fg = c.cyan },
Type = { fg = c.yellow },
StorageClass = { fg = c.yellow },
Structure = { fg = c.yellow },
Typedef = { fg = c.yellow },
Special = { fg = c.cyan },
SpecialChar = { fg = c.orange },
Tag = { fg = c.blue },
Delimiter = { fg = c.fg_dim },
SpecialComment = { fg = c.comment, bold = true },
Debug = { fg = c.red },
Underlined = { underline = true },
Bold = { bold = true },
Italic = { italic = true },
Ignore = { fg = c.subtle },
Error = { fg = c.red },
Todo = { fg = c.bg, bg = c.yellow, bold = true },
Added = { fg = c.green },
Changed = { fg = c.blue },
Removed = { fg = c.red },
-- Treesitter (the rest link to the groups above by default) -------
["@variable"] = { fg = c.fg },
["@variable.builtin"] = { fg = c.red, italic = true },
["@variable.parameter"] = { fg = c.fg_dim, italic = true },
["@variable.member"] = { fg = c.cyan },
["@property"] = { fg = c.cyan },
["@constant.builtin"] = { fg = c.orange, bold = true },
["@module"] = { fg = c.yellow },
["@function.builtin"] = { fg = c.cyan },
["@function.method"] = { fg = c.blue },
["@constructor"] = { fg = c.yellow },
["@keyword.return"] = { fg = c.red },
["@keyword.function"] = { fg = c.magenta },
["@keyword.import"] = { link = "Include" },
["@type.builtin"] = { fg = c.yellow, italic = true },
["@attribute"] = { fg = c.violet },
["@punctuation.bracket"] = { fg = c.fg_dim },
["@punctuation.delimiter"] = { fg = c.fg_dim },
["@punctuation.special"] = { fg = c.cyan },
["@string.escape"] = { fg = c.orange },
["@string.regexp"] = { fg = c.orange },
["@string.special.url"] = { fg = c.cyan, underline = true },
["@tag"] = { fg = c.blue },
["@tag.attribute"] = { fg = c.yellow, italic = true },
["@tag.delimiter"] = { fg = c.fg_dim },
["@markup.heading"] = { fg = c.blue, bold = true },
["@markup.heading.1"] = { fg = c.red, bold = true },
["@markup.heading.2"] = { fg = c.orange, bold = true },
["@markup.heading.3"] = { fg = c.yellow, bold = true },
["@markup.heading.4"] = { fg = c.green, bold = true },
["@markup.heading.5"] = { fg = c.blue, bold = true },
["@markup.heading.6"] = { fg = c.magenta, bold = true },
["@markup.strong"] = { bold = true },
["@markup.italic"] = { italic = true },
["@markup.strikethrough"] = { strikethrough = true },
["@markup.underline"] = { underline = true },
["@markup.quote"] = { fg = c.comment, italic = true },
["@markup.link"] = { fg = c.blue },
["@markup.link.label"] = { fg = c.blue },
["@markup.link.url"] = { fg = c.cyan, underline = true },
["@markup.raw"] = { fg = c.green },
["@markup.list"] = { fg = c.orange },
["@markup.list.checked"] = { fg = c.green },
["@markup.list.unchecked"] = { fg = c.subtle },
["@diff.plus"] = { link = "Added" },
["@diff.minus"] = { link = "Removed" },
["@diff.delta"] = { link = "Changed" },
["@comment.error"] = { fg = c.bg, bg = c.red, bold = true },
["@comment.warning"] = { fg = c.bg, bg = c.yellow, bold = true },
["@comment.todo"] = { link = "Todo" },
["@comment.note"] = { fg = c.bg, bg = c.blue, bold = true },
-- LSP -----------------------------------------------------------
LspReferenceText = { bg = c.bg2 },
LspReferenceRead = { bg = c.bg2 },
LspReferenceWrite = { bg = c.bg2, underline = true },
LspInlayHint = { fg = c.subtle, bg = c.bg1, italic = true },
LspCodeLens = { fg = c.subtle, italic = true },
LspSignatureActiveParameter = { fg = c.orange, bold = true },
["@lsp.type.namespace"] = { link = "@module" },
["@lsp.type.parameter"] = { link = "@variable.parameter" },
["@lsp.type.property"] = { link = "@property" },
["@lsp.mod.deprecated"] = { strikethrough = true },
-- Diagnostics ---------------------------------------------------
DiagnosticError = { fg = c.red },
DiagnosticWarn = { fg = c.yellow },
DiagnosticInfo = { fg = c.blue },
DiagnosticHint = { fg = c.cyan },
DiagnosticOk = { fg = c.green },
DiagnosticVirtualTextError = { fg = c.red, bg = tint(c.red, 0.1) },
DiagnosticVirtualTextWarn = { fg = c.yellow, bg = tint(c.yellow, 0.1) },
DiagnosticVirtualTextInfo = { fg = c.blue, bg = tint(c.blue, 0.1) },
DiagnosticVirtualTextHint = { fg = c.cyan, bg = tint(c.cyan, 0.1) },
DiagnosticUnderlineError = { sp = c.red, undercurl = true },
DiagnosticUnderlineWarn = { sp = c.yellow, undercurl = true },
DiagnosticUnderlineInfo = { sp = c.blue, undercurl = true },
DiagnosticUnderlineHint = { sp = c.cyan, undercurl = true },
DiagnosticUnnecessary = { fg = c.subtle },
DiagnosticDeprecated = { strikethrough = true },
-- Diff ----------------------------------------------------------
DiffAdd = { bg = tint(c.green, 0.18) },
DiffChange = { bg = tint(c.blue, 0.14) },
DiffDelete = { fg = c.red, bg = tint(c.red, 0.16) },
DiffText = { bg = tint(c.blue, 0.32) },
diffAdded = { link = "Added" },
diffRemoved = { link = "Removed" },
diffChanged = { link = "Changed" },
-- Plugins (most link to the groups above already) ---------------
GitSignsAdd = { fg = c.green },
GitSignsChange = { fg = c.blue },
GitSignsDelete = { fg = c.red },
GitSignsCurrentLineBlame = { fg = c.subtle, italic = true },
BlinkCmpMenu = { link = "Pmenu" },
BlinkCmpMenuBorder = { link = "FloatBorder" },
BlinkCmpMenuSelection = { link = "PmenuSel" },
BlinkCmpLabelMatch = { fg = c.blue, bold = true },
BlinkCmpLabelDeprecated = { fg = c.subtle, strikethrough = true },
BlinkCmpKind = { fg = c.blue },
BlinkCmpGhostText = { fg = c.subtle, italic = true },
BlinkCmpDoc = { link = "NormalFloat" },
BlinkCmpDocBorder = { link = "FloatBorder" },
MiniPickMatchCurrent = { link = "CursorLine" },
MiniPickMatchRanges = { fg = c.blue, bold = true },
MiniPickPrompt = { fg = c.fg, bg = c.bg1 },
MiniPickBorderText = { fg = c.blue, bg = c.bg1, bold = true },
MiniJump = { fg = c.bg, bg = c.magenta },
MiniJump2dSpot = { fg = c.orange, bold = true, nocombine = true },
MiniJump2dSpotAhead = { fg = c.cyan, nocombine = true },
MiniJump2dSpotUnique = { fg = c.yellow, bold = true, nocombine = true },
DapUIFloatBorder = { link = "FloatBorder" },
NvimDapVirtualText = { fg = c.subtle, italic = true },
TroubleNormal = { link = "NormalFloat" },
TroubleNormalNC = { link = "NormalFloat" },
SnacksNormal = { link = "NormalFloat" },
SnacksPickerMatch = { fg = c.blue, bold = true },
RenderMarkdownCode = { bg = c.bg1 },
RenderMarkdownCodeInline = { fg = c.green, bg = c.bg1 },
RenderMarkdownH1Bg = { bg = tint(c.red, 0.15) },
RenderMarkdownH2Bg = { bg = tint(c.orange, 0.15) },
RenderMarkdownH3Bg = { bg = tint(c.yellow, 0.15) },
RenderMarkdownH4Bg = { bg = tint(c.green, 0.15) },
RenderMarkdownH5Bg = { bg = tint(c.blue, 0.15) },
RenderMarkdownH6Bg = { bg = tint(c.magenta, 0.15) },
TodoBgTODO = { fg = c.bg, bg = c.blue, bold = true },
OilDir = { link = "Directory" },
}
end
---------------------------------------------------------------------------
-- Apply
---------------------------------------------------------------------------
M.colors = nil
local last_key
function M.apply(cfg)
local c = build_palette(cfg)
M.colors = c
if vim.g.colors_name then vim.cmd("hi clear") end
vim.o.termguicolors = true
vim.o.background = c.dark and "dark" or "light"
vim.g.colors_name = "ghostty"
for group, spec in pairs(highlights(c)) do
vim.api.nvim_set_hl(0, group, spec)
end
for i = 0, 15 do
vim.g["terminal_color_" .. i] = c.terminal[i]
end
last_key = vim.inspect(cfg)
end
--- Load the colorscheme. Returns false if Ghostty couldn't be read.
function M.load()
local cfg = M.read()
if not cfg then return false end
M.apply(cfg)
return true
end
--- Re-read Ghostty's config and re-apply only if the colors changed.
function M.refresh()
if vim.g.colors_name ~= "ghostty" then return end
local cfg = M.read()
if cfg and vim.inspect(cfg) ~= last_key then
M.apply(cfg)
vim.api.nvim_exec_autocmds("ColorScheme", { pattern = "ghostty", modeline = false })
end
end
function M.setup()
local group = vim.api.nvim_create_augroup("GhosttyTheme", { clear = true })
-- Picks up theme switches in Ghostty and OS light/dark changes.
vim.api.nvim_create_autocmd("FocusGained", {
group = group,
callback = function() M.refresh() end,
})
vim.api.nvim_create_user_command("GhosttyThemeReload", function()
last_key = nil
M.refresh()
end, { desc = "Re-read Ghostty's theme" })
end
return M