charmtheme

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 21 Imported by: 1

README

charm-theme

One theme, three libraries, zero headaches.

charm-theme provides a unified theming system for Charmbracelet TUIs. Define your colors and styles once, then apply them consistently across Lipgloss, Huh, and Glamour. The theme automatically adapts to light/dark terminals and gracefully degrades for limited color palettes.


Why charm-theme?

Building a TUI with Charm libraries is great—until you need consistent styling. You end up defining colors three times, managing light/dark variants manually, and hoping your markdown headings match your form titles.

charm-theme solves this:

  • ✅ Define once, use everywhere — One palette for Lipgloss styles, Huh forms, and Glamour markdown
  • ✅ Automatic adaptation — Light/dark mode just works, no manual terminal detection
  • ✅ Semantic roles — Use RoleHeading, RoleError, RoleSuccess instead of hardcoded colors
  • ✅ Visual editor — Build themes interactively with live preview
  • ✅ Brand-aware — Generate complete themes from 1-3 brand colors
  • ✅ Color modifiers — Derive hover states and borders with $primary | darken 0.1

Quick Start

Installation
go get github.com/greyhoundhq/charm-theme
Basic Usage
package main

import (
    "fmt"
    "github.com/charmbracelet/glamour"
    "github.com/charmbracelet/huh"
    charmtheme "github.com/greyhoundhq/charm-theme"
)

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

    // 2. Use with Lipgloss (for custom styling)
    fmt.Println(theme.Render(charmtheme.RoleHeading, "Welcome!"))
    fmt.Println(theme.Render(charmtheme.RoleSuccess, "✓ Connected"))
    fmt.Println(theme.Render(charmtheme.RoleError, "✗ Failed"))

    // 3. Use with Huh (forms automatically styled)
    var username string
    form := huh.NewForm(
        huh.NewGroup(
            huh.NewInput().
                Title("Username").
                Value(&username),
        ),
    ).WithTheme(theme.Huh())
    
    form.Run()

    // 4. Use with Glamour (markdown rendering)
    renderer, _ := glamour.NewTermRenderer(theme.GlamourOption())
    output, _ := renderer.Render("# Hello\n\nThis is **themed** markdown!")
    fmt.Println(output)
}

That's it. Your heading colors, form highlights, and markdown styles are now consistent.


Theme Editor

Don't hand-write JSON themes. Use the visual editor instead:

# Install
go install github.com/greyhoundhq/charm-theme/cmd/theme-editor@latest

# Run
theme-editor my-theme.json

Open http://localhost:8080 in your browser to:

  • 🎨 Edit colors visually with live preview
  • 🔄 Toggle light/dark mode instantly
  • 🎯 Generate from brand colors automatically
  • 👁️ Preview across all three libraries (Lipgloss, Huh, Glamour)
  • 💾 Save and export to JSON

The editor renders a complete kitchen sink: headings, forms, tables, code blocks, and more. You see exactly how your theme looks before committing.


Core Concepts

Semantic Roles

Instead of hardcoding colors, use roles that describe intent:

theme.Render(charmtheme.RoleHeading, "Section Title")      // Primary color, bold
theme.Render(charmtheme.RoleSubheading, "Subsection")      // Secondary color
theme.Render(charmtheme.RoleBody, "Normal text")           // Default text color
theme.Render(charmtheme.RoleEmphasis, "Important")         // Accent color, italic
theme.Render(charmtheme.RoleCode, "func main()")           // Monospace styling
theme.Render(charmtheme.RoleSuccess, "✓ Saved")            // Green success color
theme.Render(charmtheme.RoleError, "✗ Failed")             // Red error color
theme.Render(charmtheme.RoleWarning, "⚠ Warning")          // Orange warning color

This ensures your app looks cohesive whether users choose a minimal theme, high-contrast theme, or custom brand theme.

Available Roles:

Role Description
RoleHeading Primary headers (H1 equivalent)
RoleSubheading Secondary headers (H2 equivalent)
RoleBody Standard body text
RoleEmphasis Italicized or accented text
RoleStrong Bold or high-contrast text
RoleCode Inline code snippets
RoleSuccess Success messages (green)
RoleError Error messages (red)
RoleWarning Warning messages (orange)
RoleInfo Info messages (blue)
RoleButton Button styling
RoleSelection Selected items
RoleBorder Borders and dividers
RoleFieldLabel Form field labels
RoleFieldValue Form field values
RoleCommandName CLI command names
RoleFlagName CLI flag names
RoleTableHeader Table headers
RoleTableCell Table cells
Adaptive Colors

Every color has light and dark variants:

// Define adaptive color manually
theme.Colors["primary"] = charmtheme.AdaptiveColor(
    "#D700AF",  // Light mode (dark magenta on light bg)
    "#ff87d7",  // Dark mode (light magenta on dark bg)
)

// Or let the library derive the dark variant
theme.Colors["accent"] = charmtheme.AutoAdaptiveColor("#005F87")
// → Light: #005F87, Dark: auto-adjusted for contrast

The theme automatically selects the correct variant based on terminal background detection.

Color Modifiers

Create derived colors without picking new hex codes:

{
  "colors": {
    "primary": { "light": "#0000FF", "dark": "#5555FF" }
  },
  "styles": {
    "button": {
      "foreground": "$primary"
    },
    "button_hover": {
      "foreground": "$primary | lighten 0.2"
    },
    "border": {
      "foreground": "$primary | desaturate 0.5 | darken 0.2"
    }
  }
}

Supported operations:

  • lighten 0.1 — Increase brightness by 10%
  • darken 0.1 — Decrease brightness by 10%
  • saturate 0.1 — Increase color intensity by 10%
  • desaturate 0.1 — Reduce color intensity by 10%

Modifiers stack: $primary | darken 0.1 | desaturate 0.3


Creating Themes

Option 1: Brand Colors (Easiest)

Generate a complete theme from your brand colors:

theme := charmtheme.FromBrandColors(charmtheme.BrandColors{
    Primary:   "#E114E5",  // Your main brand color
    Secondary: "#7B61FF",  // Optional: secondary brand color
    Accent:    "#FF9F1C",  // Optional: accent color
})

The library automatically:

  • Generates light/dark variants
  • Creates contrast-safe text colors
  • Derives semantic status colors
  • Configures syntax highlighting

This is perfect for white-label CLIs or company-branded tools.

Option 2: Start from Default

Customize the opinionated default:

theme := charmtheme.DefaultTheme()

// Override specific colors
theme.Colors["primary"] = charmtheme.AdaptiveColor("#0ea5e9", "#38bdf8")
theme.Colors["accent"] = charmtheme.AdaptiveColor("#f97316", "#fb923c")

// Override specific styles
theme.Styles[string(charmtheme.RoleHeading)] = 
    theme.Styles[string(charmtheme.RoleHeading)].
        WithPrefix("▶ ").
        WithBold(false)

// Re-register Chroma style for syntax highlighting
theme = theme.WithCustomChroma()
Option 3: Use Minimal Theme

For basic terminals or subtle styling:

theme := charmtheme.MinimalTheme()

The minimal theme:

  • Uses fewer colors
  • Removes decorative prefixes
  • Disables italics and some bold text
  • Works better on limited color terminals
Option 4: Load from JSON

Save themes as portable JSON files:

theme, err := charmtheme.LoadTheme("config/theme.json")
if err != nil {
    log.Fatal(err)
}

Example JSON structure:

{
  "colors": {
    "primary": { "light": "#D700AF", "dark": "#ff87d7" },
    "secondary": { "light": "#870087", "dark": "#d787d7" },
    "accent": { "light": "#005F87", "dark": "#00afff" },
    "success": { "light": "#005F00", "dark": "#00af00" },
    "error": { "light": "#C10000", "dark": "#FF5C5C" },
    "text_normal": { "light": "#202020", "dark": "#E0E0E0" }
  },
  "styles": {
    "heading": {
      "foreground": "$primary",
      "bold": true,
      "prefix": "▌ ",
      "margin": [0, 0, 1, 0]
    },
    "code": {
      "foreground": "$accent",
      "background": "$surface"
    }
  }
}
Option 5: Merge Themes

Layer themes for user customization:

base := charmtheme.DefaultTheme()
userOverrides, _ := charmtheme.LoadTheme("~/.config/myapp/theme.json")

theme := base.Apply(userOverrides)

This lets users customize just the parts they care about while inheriting sensible defaults.


Library-Specific Usage

Lipgloss

Use Render() for one-off styled text:

// Includes prefix, suffix, and full styling
fmt.Println(theme.Render(charmtheme.RoleHeading, "Welcome"))
// → "▌ Welcome" (colored, bold, with margin)

Use Lipgloss() for composable styles:

// Get raw style without decorations
style := theme.Lipgloss(charmtheme.RoleBody).
    Padding(1).
    Border(lipgloss.RoundedBorder())

fmt.Println(style.Render("Content"))
Huh (Forms)

Apply the theme once, all form elements styled:

var name, email string
var subscribe bool

form := huh.NewForm(
    huh.NewGroup(
        huh.NewInput().Title("Name").Value(&name),
        huh.NewInput().Title("Email").Value(&email),
        huh.NewConfirm().Title("Subscribe?").Value(&subscribe),
    ),
).WithTheme(theme.Huh())

form.Run()

The theme automatically styles:

  • Focus indicators
  • Text input cursors
  • Selected/unselected options
  • Buttons (focused/blurred)
  • Error messages
  • Descriptions and labels
Glamour (Markdown)

Render markdown with consistent styling:

renderer, err := glamour.NewTermRenderer(theme.GlamourOption())
if err != nil {
    log.Fatal(err)
}

markdown := `
# Project Status

## Services

| Name     | Status |
|----------|--------|
| API      | ✅ Up  |
| Worker   | ⚠️ Slow |
| Database | ✅ Up  |

**Note:** All systems operational.
`

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

Glamour automatically uses:

  • Your theme colors for headings, emphasis, links
  • Custom Chroma style for code blocks
  • Consistent table borders and spacing
  • Themed blockquotes

Advanced Usage

Custom Glamour Templates

Override the default Glamour template for full control:

import "text/template"

// Load custom template
tpl := template.Must(template.ParseFiles("./glamour-custom.json"))
theme := charmtheme.DefaultTheme().WithGlamourTemplate(tpl)

renderer, _ := glamour.NewTermRenderer(theme.GlamourOption())

See glamour_template.json for the default template structure.

Terminal Capabilities

For server-side rendering or explicit mode control:

caps := charmtheme.DetectTerminalCapabilities()
// → TerminalCapabilities{ColorProfile: TrueColor, HasDarkBg: true}

// Force specific mode for rendering
caps.HasDarkBg = false
jsonStr, _ := theme.GlamourStyleJSONFor(caps)

// Or for Glamour
renderer, _ := glamour.NewTermRenderer(theme.GlamourOptionFor(caps))
Extending Roles

Define custom roles for your app:

const (
    RoleTag    charmtheme.Role = "tag"
    RoleBadge  charmtheme.Role = "badge"
    RoleStatus charmtheme.Role = "status"
)

// Add to theme
theme.Styles["tag"] = charmtheme.StyleDefinition{}.
    WithForeground("$accent").
    WithBackground("$surface").
    WithBold(true)

// Use like any other role
fmt.Println(theme.Render(RoleTag, "v1.0.0"))
Exporting Themes

Share themes with others:

theme := charmtheme.DefaultTheme()
// ... customize ...

// Export to JSON
data, _ := theme.ToJSON()
os.WriteFile("my-theme.json", data, 0644)

Examples

The repository includes several complete examples:

Basic Usage
go run examples/basic/main.go

Shows minimal integration with all three libraries.

Custom Theme
go run examples/custom-theme/main.go

Demonstrates programmatic customization.

Brand Colors
go run examples/brand-colors/main.go

Generates theme from brand palette with deployment table example.

Kitchen Sink
go run examples/kitchen-sink/main.go

Comprehensive test suite showing all features:

  • Color palette audit
  • Typography samples
  • Markdown rendering
  • Interactive Huh form
  • Table formatting
  • Code syntax highlighting
# Export theme from kitchen sink
go run examples/kitchen-sink/main.go
# → Creates dist/kitchen-sink-theme.json

# Use exported theme
theme-editor examples/kitchen-sink/dist/kitchen-sink-theme.json
Green Screen Theme
go run examples/green-screen/main.go

Custom retro terminal theme (shows building from scratch).

JSON Override
go run examples/json-override/main.go

Demonstrates theme merging and overrides.


Design Philosophy

  1. Opinionated defaults — The default theme should look great out of the box
  2. Escape hatches — Every default can be overridden
  3. Composability — Themes can be layered and merged
  4. Portability — JSON format for sharing and version control
  5. Developer ergonomics — Visual editor over hand-editing JSON
  6. Consistency — One source of truth for all libraries

Development

Running Tests
go test ./...
Running the Kitchen Sink
# Default theme, dark mode
go run examples/kitchen-sink/main.go

# Minimal theme
go run examples/kitchen-sink/main.go -theme minimal

# Custom theme file
go run examples/kitchen-sink/main.go -theme my-theme.json

# Force light mode preview
go run examples/kitchen-sink/main.go -bg light
Running the Theme Editor
# Start with new theme
go run cmd/theme-editor/main.go new-theme.json

# Edit existing theme
go run cmd/theme-editor/main.go -addr :3000 existing-theme.json

# Start with brand colors
go run cmd/theme-editor/main.go \
    -brand "#E114E5" \
    -brand-secondary "#7B61FF" \
    my-theme.json

Contributing

Contributions welcome! Please:

  1. Read AGENTS.md for development guidelines
  2. Run tests before submitting PRs
  3. Use the kitchen sink example to verify changes
  4. Update golden files if needed: UPDATE_GOLDEN=1 go test ./...

FAQ

Q: Why not just use lipgloss.AdaptiveColor directly?

A: You can, but you'd need to define every color three times (Lipgloss, Huh theme struct, Glamour JSON), manage semantic roles yourself, and handle markdown/syntax highlighting separately. charm-theme does this once.

Q: Can I use this with other TUI libraries?

A: The core color system works with anything, but the adapters are specific to Lipgloss/Huh/Glamour. You can access the raw colors via theme.Color("primary") and theme.ResolveColor(role).

Q: Does this work in non-TrueColor terminals?

A: Yes! Colors automatically degrade to ANSI256 or ANSI16 based on terminal capabilities via termenv.

Q: Can I preview themes without installing Go?

A: Not currently, but the theme editor could be packaged as a standalone binary in the future.

Q: How do I share themes with my team?

A: Export to JSON and commit to your repo. Users can override with personal themes via Apply().


License

MIT License - see LICENSE for details.


Credits

Built by greyhound using:

  • Lipgloss - Style definitions for TUIs
  • Huh - Interactive forms
  • Glamour - Markdown rendering
  • Chroma - Syntax highlighting
  • termenv - Terminal capability detection

Ready to make your TUI beautiful? Start with the Quick Start or jump straight to the Theme Editor.

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.

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 ApplyColorModifier added in v0.2.1

func ApplyColorModifier(c lipgloss.AdaptiveColor, op string, amount float64) lipgloss.AdaptiveColor

ApplyColorModifier applies a CSS-like transformation (lighten, darken, saturate, desaturate) to both variants of the adaptive color. amount is typically between 0.0 and 1.0 (e.g. 0.1 for 10%).

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 PadCodeBlock added in v0.2.1

func PadCodeBlock(code string, pad int) string

PadCodeBlock right-pads every line to the longest line and adds a solid background border of the given thickness. This helps code blocks render as a uniform rectangle when used with background-preserving Chroma formatters.

The returned string preserves original newlines; callers can wrap it in a Markdown fenced block or feed it directly to a Glamour renderer.

func PadFencedCodeBlocks added in v0.2.1

func PadFencedCodeBlocks(md string, pad int) string

PadFencedCodeBlocks applies PadCodeBlock to every fenced code block in the markdown string, preserving language tags and fences.

func ParseHex

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

ParseHex parses strings in the form "#RRGGBB", "#RGB", "#RRGGBBAA", or "#RGBA" (leading # optional) into RGB components. Alpha values, when provided, are ignored for now. It returns errInvalidHex for malformed inputs.

func ToHex

func ToHex(r, g, b uint8) string

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

func ValidateThemeColors added in v0.2.1

func ValidateThemeColors(t Theme) error

ValidateThemeColors ensures all color values are valid hex strings (3/4/6/8 digits).

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 StyleDefinition added in v0.2.1

type StyleDefinition struct {
	Inherit       string `json:"inherit,omitempty"`
	Foreground    string `json:"foreground,omitempty"`
	Background    string `json:"background,omitempty"`
	Bold          bool   `json:"bold,omitempty"`
	Italic        bool   `json:"italic,omitempty"`
	Underline     bool   `json:"underline,omitempty"`
	Strikethrough bool   `json:"strikethrough,omitempty"`
	Padding       []int  `json:"padding,omitempty"`
	Margin        []int  `json:"margin,omitempty"`
	Prefix        string `json:"prefix,omitempty"`
	Suffix        string `json:"suffix,omitempty"`
	Border        string `json:"border,omitempty"`
	BorderColor   string `json:"border_color,omitempty"`
	// contains filtered or unexported fields
}

StyleDefinition describes a serializable styling rule that can be shared across adapters. All fields are optional and may inherit from a parent style via the Inherit field.

func (*StyleDefinition) UnmarshalJSON added in v0.2.1

func (sd *StyleDefinition) UnmarshalJSON(data []byte) error

func (StyleDefinition) WithBackground added in v0.2.1

func (sd StyleDefinition) WithBackground(ref string) StyleDefinition

WithBackground marks the Background field as explicitly set.

func (StyleDefinition) WithBold added in v0.2.1

func (sd StyleDefinition) WithBold(v bool) StyleDefinition

WithBold marks the Bold flag as explicitly set.

func (StyleDefinition) WithBorder added in v0.2.1

func (sd StyleDefinition) WithBorder(name string) StyleDefinition

WithBorder marks the Border field as explicitly set.

func (StyleDefinition) WithBorderColor added in v0.2.1

func (sd StyleDefinition) WithBorderColor(ref string) StyleDefinition

WithBorderColor marks the BorderColor field as explicitly set.

func (StyleDefinition) WithForeground added in v0.2.1

func (sd StyleDefinition) WithForeground(ref string) StyleDefinition

WithForeground marks the Foreground field as explicitly set.

func (StyleDefinition) WithItalic added in v0.2.1

func (sd StyleDefinition) WithItalic(v bool) StyleDefinition

WithItalic marks the Italic flag as explicitly set.

func (StyleDefinition) WithPrefix added in v0.2.1

func (sd StyleDefinition) WithPrefix(prefix string) StyleDefinition

WithPrefix marks the Prefix field as explicitly set.

func (StyleDefinition) WithStrikethrough added in v0.2.1

func (sd StyleDefinition) WithStrikethrough(v bool) StyleDefinition

WithStrikethrough marks the Strikethrough flag as explicitly set.

func (StyleDefinition) WithSuffix added in v0.2.1

func (sd StyleDefinition) WithSuffix(suffix string) StyleDefinition

WithSuffix marks the Suffix field as explicitly set.

func (StyleDefinition) WithUnderline added in v0.2.1

func (sd StyleDefinition) WithUnderline(v bool) StyleDefinition

WithUnderline marks the Underline flag as explicitly set.

type TerminalCapabilities

type TerminalCapabilities struct {
	ColorProfile termenv.Profile
	HasDarkBg    bool
}

TerminalCapabilities describes the color capabilities of the terminal.

func DetectTerminalCapabilities

func DetectTerminalCapabilities() TerminalCapabilities

DetectTerminalCapabilities inspects stdout to determine terminal support.

type Theme

type Theme struct {
	Colors map[string]lipgloss.AdaptiveColor `json:"colors" yaml:"colors"`
	Styles map[string]StyleDefinition        `json:"styles" yaml:"styles"`

	// ChromaStyle stores the registered Chroma theme used for Glamour code
	// blocks. It remains serialized so users can persist explicit overrides.
	ChromaStyle string `json:"chroma_style,omitempty" yaml:"chroma_style,omitempty"`
	// contains filtered or unexported fields
}

Theme is a data-driven representation of a charm-theme palette. Colors hold the adaptive palette, while Styles map semantic roles (and markdown-specific keys like "h1") to StyleDefinitions. Themes can be loaded from JSON/YAML or built programmatically.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns the opinionated default palette and style sheet.

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 LoadTheme added in v0.2.1

func LoadTheme(path string) (*Theme, error)

LoadTheme reads a JSON theme file from disk.

func MinimalTheme

func MinimalTheme() Theme

MinimalTheme returns a conservative theme tuned for basic terminals.

func UnmarshalTheme added in v0.2.1

func UnmarshalTheme(data []byte) (*Theme, error)

UnmarshalTheme parses raw JSON data into a Theme.

func (Theme) Apply added in v0.2.1

func (t Theme) Apply(other *Theme) Theme

Apply returns a new Theme where values from other override the receiver. Colors are replaced per-key; styles are deep-merged using StyleDefinition semantics so overrides can tweak a single field without redefining the whole style.

func (Theme) Color added in v0.2.1

func (t Theme) Color(ref string) lipgloss.AdaptiveColor

Color resolves a color reference. It supports: 1. Direct Hex: "#FFFFFF" 2. Variable Lookup: "$primary" 3. Modifiers: "$primary | darken 0.2"

func (Theme) GlamourOption

func (t Theme) GlamourOption() glamour.TermRendererOption

GlamourOption returns a Glamour renderer option that applies this theme using the detected terminal capabilities.

func (Theme) GlamourOptionFor added in v0.2.1

func (t Theme) GlamourOptionFor(caps TerminalCapabilities) glamour.TermRendererOption

GlamourOptionFor returns a Glamour renderer option that applies this theme for the provided terminal capabilities.

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) GlamourStyleJSONFor added in v0.2.1

func (t Theme) GlamourStyleJSONFor(caps TerminalCapabilities) (string, error)

GlamourStyleJSONFor returns a Glamour JSON style config derived from Theme for the provided terminal capabilities. This is useful for server-side rendering scenarios where the desired background mode is known (e.g., a web preview toggling light/dark) and may differ from the host terminal.

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. Use this when you need to compose styles or use them in Bubble Tea models. Note: This returns the visual style (colors, bold, border) but does NOT include the Prefix or Suffix defined in the theme, as those are content decorations.

func (Theme) RegisterChromaStyle added in v0.2.1

func (t Theme) RegisterChromaStyle(baseName string) string

RegisterChromaStyle generates and registers a Chroma style derived from the theme's adaptive palette. It returns the registered style name which can be assigned to Theme.ChromaStyle.

func (Theme) Render added in v0.2.1

func (t Theme) Render(role Role, text ...string) string

Render applies the theme's style, prefix, and suffix to the provided text. Use this for one-off printing where you want the full "Themed" look, including decorations like "> " or "Error: ".

func (Theme) RenderMarkdown added in v0.2.1

func (t Theme) RenderMarkdown(md string) (string, error)

RenderMarkdown renders markdown using the theme's Glamour option, first padding fenced code blocks so their background fills align neatly. Padding defaults to 1.

func (Theme) RenderMarkdownWithPadding added in v0.2.1

func (t Theme) RenderMarkdownWithPadding(md string, pad int) (string, error)

RenderMarkdownWithPadding renders markdown after padding all fenced code blocks with the supplied pad thickness.

func (Theme) ResolveColor

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

ResolveColor now delegates to the StyleDefinition assigned to the role. If no style or color is found it falls back to the body text color.

func (Theme) ToJSON added in v0.2.1

func (t Theme) ToJSON() ([]byte, error)

ToJSON marshals the theme to indented JSON for exporting/sharing.

func (Theme) WithCustomChroma added in v0.2.1

func (t Theme) WithCustomChroma() Theme

WithCustomChroma returns a copy of the theme that registers and applies a Chroma style derived from its current palette.

func (Theme) WithGlamourTemplate added in v0.2.1

func (t Theme) WithGlamourTemplate(tpl *template.Template) Theme

WithGlamourTemplate returns a copy of the theme that uses the provided template when rendering Glamour styles. Passing nil clears the override and reverts to the built-in template.

Directories

Path Synopsis
cmd
theme-editor command
examples
basic command
brand-colors command
custom-theme command
debug-blocks command
green-screen command
json-override command
kitchen-sink command

Jump to

Keyboard shortcuts

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