charmtheme

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 14 Imported by: 1

README

charm-theme

Unified, adaptive theming for Charm TUI libraries.

Define your theme once. Use it across huh, Lipgloss, and Glamour. Automatically adapts to light/dark terminals and gracefully degrades across color depths.

theme := charmtheme.DefaultTheme()

// Use with huh forms
form := huh.NewForm(...).WithTheme(theme.Huh())

// Use with Glamour markdown
renderer, _ := glamour.NewTermRenderer(theme.GlamourOption())

// Use with Lipgloss styles
heading := theme.Lipgloss(charmtheme.RoleHeading).Render("Hello!")

Why charm-theme?

The Problem: Building a polished CLI / TUI with Charmbracelet tools in Go often means coordinating colors and styles across Glamour (markdown), Lipgloss (styling), and huh (forms). Each library has its own theming API. Keeping them consistent is tedious and error-prone.

The Solution: One theme definition that drives all three libraries from a single source of truth.

// Without charm-theme: Configure each library separately
huhTheme := huh.ThemeBase().Focused(...)    // 50+ lines
glamourStyle := glamour.StyleConfig{...}    // 100+ lines
lipglossStyles := map[string]lipgloss.Style{...}  // Lots of duplication

// With charm-theme: One theme, three libraries
theme := charmtheme.DefaultTheme()
form.WithTheme(theme.Huh())
renderer, _ := glamour.NewTermRenderer(theme.GlamourOption())
heading := theme.Lipgloss(charmtheme.RoleHeading)

Features

  • 🎨 Unified theming - One theme definition for all Charm libraries
  • 🌓 Adaptive colors - Automatically adjusts for light/dark terminals
  • 📉 Graceful degradation - Works across all color depths (24-bit → 256 → 16 → mono)
  • 🎭 Built-in themes - DefaultTheme (opinionated), MinimalTheme (low-noise), and ready-made presets: DraculaTheme() → Chroma dracula, NordTheme() → nord, GruvboxTheme() → gruvbox, SolarizedDarkTheme() → solarized-dark, SolarizedLightTheme() → solarized-light.
  • ⚡ Quick customization - Feed up to three hex colors into FromBrandColors to derive a cohesive palette in seconds.
  • 🌍 Respects standards - Honors NO_COLOR, CLICOLOR, CLICOLOR_FORCE
  • 📝 Typography control - Bold, italic, prefixes, alignment
  • 📊 Table styling - Configure borders, dividers, headers
  • 💻 Code highlighting - Integrated Chroma syntax themes for code blocks
  • 🔧 Template-based - Glamour styles use JSON templates for easy customization
  • 🫧 Gum - In a future release, charm-theme will be able to export theme settings for gum , so your shell prompts match your TUI. (TODO)

Installation

go get github.com/greyhoundhq/charm-theme

Quick Start

package main

import (
    "fmt"

    "github.com/charmbracelet/huh"
    "github.com/charmbracelet/lipgloss"
    "github.com/charmbracelet/glamour"
    "github.com/greyhoundhq/charm-theme"
)

func main() {
    // 1. Pick a theme
    theme := charmtheme.DefaultTheme()

    // 2. Use with huh forms
    var name string
    form := huh.NewForm(
        huh.NewGroup(
            huh.NewInput().
                Title("What's your name?").
                Value(&name),
        ),
    ).WithTheme(theme.Huh())

    form.Run()

    // 3. Use with Lipgloss
    heading := theme.Lipgloss(charmtheme.RoleHeading)
    fmt.Println(heading.Render("Welcome, " + name + "!"))

    // 4. Use with Glamour
    markdown := "# Hello\n\nThis is **bold** and this is *italic*."
    renderer, _ := glamour.NewTermRenderer(theme.GlamourOption())
    out, _ := renderer.Render(markdown)
    fmt.Print(out)
}

Usage

Using Built-in Themes
// Opinionated, high-contrast defaults (magenta/pink accent, generous padding).
theme := charmtheme.DefaultTheme()

// Conservative, low-noise styling tuned for basic or CI terminals.
theme := charmtheme.MinimalTheme()

DefaultTheme favors expressive typography (BoldHeadings, ItalicEmphasis, rounded borders) while MinimalTheme stays flat—no padding, terminal-default backgrounds, and muted accents. Start from whichever fits your CLI, then override individual fields.

Preset Themes

Need a recognizable palette fast? Use one of the bundled presets—each ships with matching Chroma syntax highlighting so Glamour output stays on-brand:

Function Palette Chroma style
charmtheme.DraculaTheme() Purple/pink Dracula palette dracula
charmtheme.NordTheme() Frosty blues/amber nord
charmtheme.GruvboxTheme() Gruvbox medium contrast gruvbox
charmtheme.SolarizedDarkTheme() Solarized dark solarized-dark
charmtheme.SolarizedLightTheme() Solarized light solarized-light
gruvbox := charmtheme.GruvboxTheme()
renderer, _ := glamour.NewTermRenderer(gruvbox.GlamourOption())
fmt.Println(gruvbox.RenderHeading("Gruvbox release notes"))
Custom Theme

Full control over every color and setting:

theme := charmtheme.Theme{
    // Colors - all use AdaptiveColor for light/dark support
    Primary: lipgloss.AdaptiveColor{
        Light: "#d7005f",  // Dark pink for light terminals
        Dark:  "#ff007c",  // Bright pink for dark terminals
    },
    Secondary: lipgloss.AdaptiveColor{
        Light: "#7c7c7c",
        Dark:  "#9ca3af",
    },
    // ... other colors ...

    // Typography
    HeaderPrefix:   "│ ",     // Prefix for section headers
    BoldHeadings:   true,     // Make headings bold
    BoldCommands:   true,     // Make command names bold
    ItalicEmphasis: true,     // Make emphasis text italic

    // Table styling
    UseTableBorders:   false,  // No outer borders
    UseColumnDividers: true,   // Column separators
    UseHeaderDivider:  true,   // Header underline

    // Layout
    AlignDescriptions: true,   // Vertical alignment in lists
    Compact:           false,
}
Generate From Brand Colors

If you already have brand colors, let charm-theme derive adaptive variants for you:

theme := charmtheme.FromBrandColors(charmtheme.BrandColors{
    Primary:   "#5f87af",
    Secondary: "#87af87",
    Accent:    "#d7875f",
})

heading := theme.Lipgloss(charmtheme.RoleHeading)
fmt.Println(heading.Render("Brand-based theme"))

FromBrandColors keeps semantic colors (success, error, warning, info) plus surfaces/text values from DefaultTheme, so you get predictable contrast and status hues while still picking up your brand personality.

Integrating with Each Library
Huh (Forms)
theme := charmtheme.DefaultTheme()

form := huh.NewForm(
    huh.NewGroup(
        huh.NewInput().Title("Name").Value(&name),
        huh.NewSelect[string]().
            Title("Environment").
            Options(
                huh.NewOption("Production", "prod"),
                huh.NewOption("Staging", "staging"),
            ).
            Value(&env),
    ),
).WithTheme(theme.Huh())  // ← Apply theme here

form.Run()
Glamour (Markdown)
theme := charmtheme.DefaultTheme()

// Get JSON style for current terminal mode
styleJSON, _ := theme.GlamourStyleJSON()

renderer, _ := glamour.NewTermRenderer(
    glamour.WithStylesFromJSONBytes([]byte(styleJSON)),
)

markdown := `
# My Document

This is **bold** and this is *italic*.

` + "```go\n" + `
func main() {
    fmt.Println("Syntax highlighted!")
}
` + "```\n" + `

| Column 1 | Column 2 |
|----------|----------|
| Data     | More     |
`

output, _ := renderer.Render(markdown)
fmt.Print(output)

Note: Glamour styling uses a JSON template approach. The theme automatically generates appropriate JSON for the current terminal mode (light/dark) and injects your theme colors. Code blocks use the theme's ChromaStyle for syntax highlighting.

Lipgloss (Styling)
theme := charmtheme.DefaultTheme()

// Use semantic roles
heading := theme.Lipgloss(charmtheme.RoleHeading)
error := theme.Lipgloss(charmtheme.RoleError)
success := theme.Lipgloss(charmtheme.RoleSuccess)
note := theme.Lipgloss(charmtheme.RoleFieldDescription)

fmt.Println(heading.Render("Configuration"))
fmt.Println(error.Render("✗ Build failed"))
fmt.Println(success.Render("✓ Tests passed"))
fmt.Println(note.Render("Last updated: 2 hours ago"))

// Optional convenience methods (sugar)
fmt.Println(theme.RenderError("✗ Build failed"))
fmt.Println(theme.RenderSuccess("✓ Tests passed"))
Semantic Roles

Roles use the Role prefix so you can ask for intent-driven colors rather than hard-coded hex values. Common assignments:

  • RoleHeading, RoleSubheading, RoleBody – document hierarchy.
  • RoleError, RoleWarning, RoleSuccess, RoleInfo – status messaging.
  • RoleCode, RoleEmphasis, RoleStrong – typographic emphasis and inline code.
  • RoleFieldLabel, RoleFieldValue, RoleFieldDescription – huh form elements.
  • RoleButton, RoleButtonActive, RoleSelection – actionable states.
  • RoleCommandName, RoleFlagName, RoleTableHeader, RoleTableCell – CLI help + tabular output.

type Role string means you can also invent your own roles:

const RoleTag charmtheme.Role = "tag"

style := theme.Lipgloss(RoleTag) // Falls back to TextNormal unless you override it.
Adapter Cheat Sheet
  • theme.Lipgloss(role) → lipgloss.Style
  • theme.RenderHeading/RenderError/... → sugar around common roles
  • theme.Huh() → *huh.Theme wired for focused/blurred states, selected prefixes, etc.
  • theme.GlamourStyleJSON() → rendered JSON string for inspection/customization
  • theme.GlamourOption() → pass straight into glamour.NewTermRenderer

Adaptive Behavior

Light/Dark Detection

Themes automatically detect terminal background and adjust colors:

theme := charmtheme.DefaultTheme()
// In light terminal: uses Light variant of each color
// In dark terminal: uses Dark variant of each color
// Detection is automatic - no configuration needed

// Glamour styles adapt too:
styleJSON, _ := theme.GlamourStyleJSON()  // Automatically uses correct variant
Code Syntax Highlighting

Code blocks in markdown are highlighted using Chroma:

theme := charmtheme.DefaultTheme()
theme.ChromaStyle = "dracula"  // Pick any Chroma style string

See Chroma's style list for valid names. Preset-specific defaults land alongside the preset themes in v0.2.0.

Color Degradation

Colors gracefully degrade based on terminal capabilities:

  • TrueColor (24-bit): Full RGB colors
  • 256-color: Closest ANSI 256 color
  • 16-color (ANSI): Closest basic ANSI color
  • Monochrome: Bold/underline/reverse for emphasis
Environment Variables

Respects standard color control variables:

  • NO_COLOR=1 - Disables all color output
  • CLICOLOR=0 - Disables color output
  • CLICOLOR_FORCE=1 - Forces color even in non-TTY
  • TERM=dumb - Uses monochrome mode

Typography & Layout

Header Prefixes

Add decorative prefixes to section headers:

theme := charmtheme.DefaultTheme()
theme.HeaderPrefix = "│ "  // Pipe prefix

// Renders as:
// │ Commands:
// │ Flags:
Vertical Alignment

Align descriptions for better readability:

theme.AlignDescriptions = true

// Without alignment:
// build      Build the project
// test       Run tests
// deploy     Deploy to production

// With alignment:
// build      Build the project
// test       Run tests
// deploy     Deploy to production
Table Styling

Configure markdown table rendering:

theme.UseTableBorders = false    // No outer borders
theme.UseColumnDividers = true   // Column separators
theme.UseHeaderDivider = true    // Divider under headers

// Renders as:
// Column 1 │ Column 2
// ─────────┼──────────
// Data     │ More

Theme Structure

type Theme struct {
    // Core palette
    Primary   lipgloss.AdaptiveColor  // Main brand color
    Secondary lipgloss.AdaptiveColor  // Supporting color
    Accent    lipgloss.AdaptiveColor  // Highlight color

    // Semantic colors
    Success lipgloss.AdaptiveColor
    Error   lipgloss.AdaptiveColor
    Warning lipgloss.AdaptiveColor
    Info    lipgloss.AdaptiveColor

    // Surface colors
    Background lipgloss.AdaptiveColor
    Surface    lipgloss.AdaptiveColor
    Muted      lipgloss.AdaptiveColor

    // Text roles
    TextNormal lipgloss.AdaptiveColor
    TextMuted  lipgloss.AdaptiveColor
    TextStrong lipgloss.AdaptiveColor

    // Typography preferences
    HeaderPrefix      string
    BoldHeadings      bool
    BoldCommands      bool
    ItalicEmphasis    bool

    // Table styling
    UseTableBorders   bool
    UseColumnDividers bool
    UseHeaderDivider  bool

    // Code highlighting
    ChromaStyle       string  // Chroma theme name (e.g. "dracula", "monokai")

    // Layout
    BorderRadius      int
    Padding           int
    Compact           bool
    AlignDescriptions bool
}

Examples

See the examples directory:

  • basic - Simple theme application
  • custom-theme - Creating custom themes
  • brand-colors - Generate a theme directly from your brand palette
  • all-libraries - Using the same role across huh, Lipgloss, and Glamour
  • presets - Renders the same markdown with Dracula, Nord, Gruvbox, and Solarized Dark themes

Design Philosophy

One source of truth - Define colors once, use everywhere. No more keeping Glamour styles, Lipgloss colors, and huh themes manually in sync.

Adaptive by default - Light and dark terminals should both look good without user configuration. Color depth limitations should degrade gracefully.

Semantic roles - Use RoleError not "red text". Meaning over mechanics.

Accessibility first - All built-in themes meet WCAG AA contrast requirements. Typography aids scanning and comprehension.

Zero magic - This library doesn't wrap or replace the Charm libraries. It just generates the right configuration objects for each. You're still using huh/Lipgloss/Glamour directly.


Compatibility

  • Go: 1.21+
  • huh: Any version with WithTheme()
  • Lipgloss: Any version with AdaptiveColor
  • Glamour: Any version with StyleConfig

FAQ

Does this replace huh/Lipgloss/Glamour?

No! This library generates theme configurations for those libraries. You still use huh, Lipgloss, and Glamour directly - charm-theme just makes it easier to keep them consistent.

Can I use this with just one library?

Yes! You can use charm-theme with just Lipgloss, or just huh, or any combination. The adapters are independent.

Will my TUI look good in both light and dark terminals?

Yes! All built-in themes use lipgloss.AdaptiveColor which automatically adjusts. Custom themes should do the same.

What about 16-color terminals?

Themes gracefully degrade. The closest ANSI color is automatically selected. MinimalTheme is specifically designed for limited-color terminals.

Can I override just one library's theme?

Yes! Each adapter (.Huh(), .GlamourStyleJSON(), .Lipgloss()) is independent. Generate the base theme, then customize one library's output if needed.

How does code highlighting work?

Code blocks in Glamour-rendered markdown use Chroma for syntax highlighting. Set theme.ChromaStyle to any Chroma theme name (e.g., "dracula", "github", "nord"). Preset themes will set sensible defaults once they land in v0.2.0.

Can I use custom Glamour templates?

Yes! The default Glamour JSON template is embedded, but you can provide your own. See the advanced customization guide for details.

How do I create a preset theme for my organization?
func MyCompanyTheme() charmtheme.Theme {
    return charmtheme.Theme{
        Primary: lipgloss.AdaptiveColor{
            Light: "#yourcolor",
            Dark:  "#yourcolor",
        },
        // ... configure all colors ...
    }
}

Then publish it, or keep it in your internal package.


Contributing

Contributions welcome! Especially:

  • New theme presets (Dracula, Nord, etc. - popular, well-known schemes)
  • Bug fixes
  • Documentation improvements
  • Examples

Please open an issue before starting major work.


License

MIT License - see LICENSE for details.


Credits

Built on top of the amazing work by Charm:


Made with ✨ by greyhound

Documentation

Overview

Package charmtheme provides a unified theming system for Charmbracelet libraries (huh, Lipgloss, Glamour). Define your theme once and reuse it across adapters while automatically adapting to light/dark terminals.

Package charmtheme provides a unified, adaptive theming system for Charmbracelet TUIs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdaptiveColor

func AdaptiveColor(light, dark string) lipgloss.AdaptiveColor

AdaptiveColor constructs a lipgloss.AdaptiveColor from the given light/dark hex strings. Light should be tuned for light backgrounds, dark for dark backgrounds.

func AdjustBrightness

func AdjustBrightness(r, g, b uint8, factor float64) (uint8, uint8, uint8)

AdjustBrightness applies a multiplier to the HSL lightness component of the supplied RGB color. Values >1 increase brightness, <1 decrease brightness.

func AdjustSaturation

func AdjustSaturation(r, g, b uint8, factor float64) (uint8, uint8, uint8)

AdjustSaturation scales the HSL saturation component by the provided factor. Values >1 intensify the color, <1 desaturate it.

func AutoAdaptiveColor

func AutoAdaptiveColor(lightHex string) lipgloss.AdaptiveColor

AutoAdaptiveColor derives a dark-variant color from the provided light variant. The light hex is used as provided, while the dark variant goes through a brightness/saturation adjustment to keep contrast on dark terminals. If parsing the light color fails, the returned color uses the same value for both variants.

func DegradeColorForProfile

func DegradeColorForProfile(color lipgloss.AdaptiveColor, profile termenv.Profile, isDark bool) string

DegradeColorForProfile converts an adaptive color into a format suitable for the provided terminal profile. Colors automatically degrade for limited palettes while respecting adaptive light/dark variants.

func ParseHex

func ParseHex(hex string) (uint8, uint8, uint8, error)

ParseHex parses strings in the form "#RRGGBB" or "RRGGBB" into RGB components. It returns errInvalidHex for malformed inputs.

func ShouldUseColor

func ShouldUseColor() bool

ShouldUseColor returns whether the library should emit ANSI colors based on conventional environment variables.

func ToHex

func ToHex(r, g, b uint8) string

ToHex formats RGB components as a canonical upper-case hex string (#RRGGBB).

Types

type BrandColors added in v0.2.0

type BrandColors struct {
	Primary   string
	Secondary string
	Accent    string
}

BrandColors represents a minimal brand palette used to derive a Theme. Empty fields are treated as "keep defaults" so callers can override only the colors they care about.

type Role

type Role string

Role represents a semantic UI element that needs consistent theming across libraries.

const (
	RoleHeading          Role = "heading"
	RoleSubheading       Role = "subheading"
	RoleBody             Role = "body"
	RoleCode             Role = "code"
	RoleEmphasis         Role = "emphasis"
	RoleStrong           Role = "strong"
	RoleError            Role = "error"
	RoleSuccess          Role = "success"
	RoleWarning          Role = "warning"
	RoleInfo             Role = "info"
	RoleFieldLabel       Role = "field_label"
	RoleFieldValue       Role = "field_value"
	RoleFieldDescription Role = "field_description"
	RoleButton           Role = "button"
	RoleButtonActive     Role = "button_active"
	RoleBorder           Role = "border"
	RoleSelection        Role = "selection"
	RoleCommandName      Role = "command_name"
	RoleCommandShort     Role = "command_short"
	RoleFlagName         Role = "flag_name"
	RoleFlagShort        Role = "flag_short"
	RoleTableHeader      Role = "table_header"
	RoleTableCell        Role = "table_cell"
)

type TerminalCapabilities

type TerminalCapabilities struct {
	ColorProfile termenv.Profile
	IsTTY        bool
	Width        int
	Height       int
	HasDarkBg    bool
}

TerminalCapabilities describes what the current terminal supports.

func DetectTerminalCapabilities

func DetectTerminalCapabilities() TerminalCapabilities

DetectTerminalCapabilities inspects stdout to determine terminal support.

type Theme

type Theme struct {
	// Core palette - adaptive for light/dark terminals
	Primary   lipgloss.AdaptiveColor
	Secondary lipgloss.AdaptiveColor
	Accent    lipgloss.AdaptiveColor

	// Semantic colors
	Success lipgloss.AdaptiveColor
	Error   lipgloss.AdaptiveColor
	Warning lipgloss.AdaptiveColor
	Info    lipgloss.AdaptiveColor

	// Surface colors
	Background lipgloss.AdaptiveColor
	Surface    lipgloss.AdaptiveColor
	Muted      lipgloss.AdaptiveColor

	// Text roles
	TextNormal lipgloss.AdaptiveColor
	TextMuted  lipgloss.AdaptiveColor
	TextStrong lipgloss.AdaptiveColor

	// Typography preferences
	HeaderPrefix   string
	BoldHeadings   bool
	BoldCommands   bool
	ItalicEmphasis bool

	// Table styling
	UseTableBorders   bool
	UseColumnDividers bool
	UseHeaderDivider  bool

	// Code highlighting
	ChromaStyle string

	// Layout
	BorderRadius      int
	Padding           int
	Compact           bool
	AlignDescriptions bool
}

Theme defines a unified color scheme and typography across Charm TUI libraries.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns an opinionated theme tuned for modern terminals.

func DraculaTheme added in v0.2.0

func DraculaTheme() Theme

DraculaTheme returns a Theme based on the popular Dracula palette.

func FromBrandColors added in v0.2.0

func FromBrandColors(b BrandColors) Theme

FromBrandColors generates a Theme from up to three brand colors. It starts from DefaultTheme to inherit typography, layout, and semantic defaults, then selectively overrides the core palette. Invalid hex inputs are ignored.

func GruvboxTheme added in v0.2.0

func GruvboxTheme() Theme

GruvboxTheme returns a Theme modeled after Gruvbox (medium contrast).

func MinimalTheme

func MinimalTheme() Theme

MinimalTheme is a conservative style designed for basic or low-color terminals.

func NordTheme added in v0.2.0

func NordTheme() Theme

NordTheme returns a Theme based on the Nord color palette.

func SolarizedDarkTheme added in v0.2.0

func SolarizedDarkTheme() Theme

SolarizedDarkTheme returns a Theme tuned for Solarized Dark terminals.

func SolarizedLightTheme added in v0.2.0

func SolarizedLightTheme() Theme

SolarizedLightTheme returns a Theme tuned for Solarized Light terminals.

func (Theme) GlamourOption

func (t Theme) GlamourOption() glamour.TermRendererOption

GlamourOption returns a Glamour renderer option that applies this theme.

func (Theme) GlamourStyleJSON

func (t Theme) GlamourStyleJSON() (string, error)

GlamourStyleJSON returns a Glamour JSON style config derived from Theme for the current terminal (light/dark, color depth, etc).

func (Theme) Huh

func (t Theme) Huh() *huh.Theme

Huh returns a huh.Theme configured using this Theme's palette.

func (Theme) Lipgloss

func (t Theme) Lipgloss(role Role) lipgloss.Style

Lipgloss returns a lipgloss.Style configured for the requested role.

func (Theme) RenderError

func (t Theme) RenderError(text string) string

func (Theme) RenderHeading

func (t Theme) RenderHeading(text string) string

RenderHeading renders heading text with the optional prefix applied.

func (Theme) RenderInfo

func (t Theme) RenderInfo(text string) string

func (Theme) RenderSuccess

func (t Theme) RenderSuccess(text string) string

func (Theme) RenderWarning

func (t Theme) RenderWarning(text string) string

func (Theme) ResolveColor

func (t Theme) ResolveColor(role Role) lipgloss.AdaptiveColor

ResolveColor maps a semantic role to the theme color best suited for it. If a role does not have a dedicated mapping it falls back to TextNormal.

Directories

Path Synopsis
examples
all-libraries command
basic command
brand-colors command
custom-theme command
presets command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL