kazari

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 27 Imported by: 0

README

Kazari

Kazari

Go Reference Go Version

Kazari (飾り, "decoration") is a Go library that renders framed, syntax-highlighted HTML code blocks. It wraps Nuri (a pure Go Shiki port) or Chroma for tokenization and adds the presentation layer on top: editor and terminal frames, line markers, copy buttons, collapsible sections, dual-theme support, and 90+ CSS variables for styling. Think Expressive Code, but for Go.

Nuri and Chroma give you colored tokens, but not a finished code block. Kazari bridges that gap. Pass code and a meta string to engine.Render(), get back self-contained HTML. engine.CSS() and engine.JS() return the page-wide stylesheet and scripts to inject once. Everything renders server-side with no framework dependency.

Kazari code block example
A framed, syntax-highlighted code block rendered by Kazari with diff markers, line highlights, line numbers, copy, word wrap, and fullscreen buttons.

Features

Frames and chrome

  • Editor and terminal frames (macOS-style dots, colored or minimal)
  • Automatic frame detection: shell languages get terminal frames
  • Title bars with file icons and language badges
  • File name extraction from code comments (// config.go becomes the title)
  • Copy-to-clipboard, word wrap toggle, fullscreen with font size controls
  • Per-block theme toggle (light/dark independent of the page theme)

Markers and annotations

  • Line markers: highlight, insertion, deletion with colored backgrounds and border accents
  • Labeled line ranges ({"API":3-7})
  • Inline text and regex markers
  • Focus lines (dim everything except the focused range)
  • Diff+syntax hybrid: diff lang=go strips prefixes, applies ins/del markers, highlights as Go
  • Inline links: @[text](url) renders clickable links inside code

Collapsible sections

  • Threshold-based: auto-collapse blocks exceeding N lines with a preview and expand button
  • Range-based: collapse specific line ranges with collapse={3-10}
  • Four collapse styles: github, collapsible-start, collapsible-end, collapsible-auto

Themes

  • Dual-theme rendering: light and dark token colors baked into HTML via CSS custom properties
  • Theme switching is pure CSS. No JS, no flash on toggle or page load
  • Per-block theme override via meta string (theme="catppuccin-mocha")
  • Dark mode via CSS class selector, prefers-color-scheme, or both
  • OKLCH-based theme color adjustments (hue/chroma tinting)

Accessibility

  • Automatic WCAG contrast enforcement: token colors adjusted per-token to meet a configurable minimum ratio (default 5.5:1)
  • ARIA labels, live regions, screen reader announcements
  • all: revert style reset isolates blocks from page CSS

Integration

  • Goldmark extension for markdown rendering
  • :::code-group tabbed containers with tab sync
  • Mermaid pass-through
  • ANSI escape sequence rendering
  • i18n: en-US, fr-FR, ja-JP with per-string overrides

Install

go get github.com/frostybee/kazari@latest

Kazari requires a highlighter. For Nuri (recommended):

go get github.com/frostybee/nuri@latest

Or for Chroma:

go get github.com/alecthomas/chroma/v2@latest

Quick start

Render a code block

package main

import (
    "context"
    "fmt"

    "github.com/frostybee/kazari"
    kazarinuri "github.com/frostybee/kazari/nuri"
    "github.com/frostybee/nuri"
    "github.com/frostybee/nuri/bundle/core"
)

func main() {
    ctx := context.Background()
    hl, _ := nuri.New(ctx, nuri.WithFS(core.FS()))
    defer hl.Close(ctx)

    engine := kazari.New(
        kazari.WithHighlighter(kazarinuri.New(ctx, hl)),
        kazari.WithThemes("github-light", "github-dark"),
    )

    code := `func main() {
    fmt.Println("hello")
}`
    html, _ := engine.RenderWithMeta(code, `go title="main.go" showLineNumbers {2}`)

    fmt.Println(engine.CSS()) // inject once in <head>
    fmt.Println(html)         // per code block
    fmt.Println(engine.JS())  // inject once before </body>
}

engine.CSS() and engine.JS() return page-wide assets. Inject each once. engine.Render() / engine.RenderWithMeta() return per-block HTML.

With Goldmark

import (
    kazarimd "github.com/frostybee/kazari/goldmark"
    "github.com/yuin/goldmark"
)

md := goldmark.New(
    goldmark.WithExtensions(kazarimd.New(engine)),
)

// For code group support (:::code-group):
md := goldmark.New(
    goldmark.WithExtensions(
        kazarimd.New(engine),
        kazarimd.CodeGroups(engine),
    ),
)

With Chroma

import kazarichroma "github.com/frostybee/kazari/chroma"

hl := kazarichroma.New(kazarichroma.WithStyleMap(map[string]string{
    "github-light": "github",
    "github-dark":  "github-dark",
}))

engine := kazari.New(
    kazari.WithHighlighter(hl),
    kazari.WithThemes("github-light", "github-dark"),
)

Configuration

Kazari has three configuration layers. Each overrides the previous:

  1. Engine options set once at construction via kazari.New()
  2. Config file (kazari.config.yaml) loaded with kazari.WithConfigDir()
  3. Meta string for per-block overrides in the markdown fence info string (highest priority)

Engine options

engine := kazari.New(
    kazari.WithHighlighter(hl),
    kazari.WithThemes("github-light", "github-dark"),
    kazari.WithDarkMode(kazari.SelectorMode(".dark")),
    kazari.WithCopyButton(true),
    kazari.WithFullscreenButton(true),
    kazari.WithWrapButton(true),
    kazari.WithLineNumbers(true),
    kazari.WithCollapsible(kazari.CollapsibleConfig{
        LineThreshold:    15,
        PreviewLines:     5,
        DefaultCollapsed: true,
    }),
    kazari.WithMinContrast(5.5),
    kazari.WithMinify(true),
    kazari.WithLocale("en-US"),
)

See options.go and features.go for the full list of With* options.

Config file

Create kazari.config.yaml (or .json) in the project directory:

themes:
  light: github-light
  dark: github-dark
darkMode:
  kind: selector
  selector: ".dark"
copyButton: true
fullscreenButton: true
lineNumbers: false
collapsible:
  lineThreshold: 15
  previewLines: 5
languageDefaults:
  bash,sh,zsh:
    frame: terminal
styleOverrides:
  --kz-radius: "0.75rem"
  --kz-font-size: "0.85rem"

Load it as an engine option:

engine := kazari.New(
    kazari.WithHighlighter(hl),
    kazari.WithConfigDir("."),
)

Meta string

Per-block overrides go after the language in the opening fence:

```go title="main.go" showLineNumbers {2, 4-6}
Key Example Effect
title="..." title="config.go" Title bar text
showLineNumbers Enable line numbers
startLineNumber=N startLineNumber=10 First line number
frame= frame=terminal code, terminal, none, auto
theme="..." theme="dracula" Per-block theme override
wrap Enable word wrap
{N} or {N-M} {3, 5-8} Highlight lines
{"Label":N-M} {"API":3-7} Labeled highlight
ins={N-M} ins={3-5} Insertion markers
del={N-M} del={1} Deletion markers
ins="text" ins="new" Inline insertion marker
del="text" del="old" Inline deletion marker
"text" "highlight" Inline highlight marker
/regex/ /fmt\.\w+/ Regex inline marker
focus={N-M} focus={3-5} Focus lines (dim the rest)
collapse Force collapse
nocollapse Disable collapse
collapse={N-M} collapse={5-15} Collapse specific range
collapseThreshold=N collapseThreshold=20 Per-block threshold
lang= lang=go (on diff) Diff+syntax hybrid

CSS variables

All visual properties are controlled through --kz-* CSS custom properties (90+ variables). Override them in a stylesheet:

:root {
  --kz-radius: 0.75rem;
  --kz-font-size: 0.85rem;
  --kz-font-family: 'Fira Code', monospace;
  --kz-code-padding-block: 1.25rem;
  --kz-mark-bg: rgba(255, 200, 0, 0.15);
}

Or pass them as engine options:

kazari.WithStyleOverrides(map[string]string{
    "--kz-radius": "0.75rem",
})

kazari.WithThemedStyleOverrides(map[string]kazari.StyleValue{
    "--kz-radius": {Light: "0.75rem", Dark: "0.5rem"},
})

Pluggable highlighter

Kazari accepts any implementation of its Highlighter interface:

type Highlighter interface {
    Tokenize(code, lang, theme string) ([][]Token, error)
    GetThemeColors(theme string) (ThemeInfo, error)
    GetLoadedLanguages() []string
}

Adapters for Nuri and Chroma are provided in kazari/nuri and kazari/chroma. Implement the optional DualThemeTokenizer interface to halve dual-theme tokenization cost.

Development

Build and test

go build ./...
go test ./...
go test -v -run TestRender ./...

Demo site

The demo site generates pages comparing Nuri and Chroma output, a color contrast correction demo, and a performance benchmark.

cd demo/site && go run .

Output is written to demo/site/ (nuri-vs-shiki.html, nuri-vs-chroma.html, color-contrast.html, benchmark.html).

Contributing

  1. Fork and create a feature branch.
  2. Run go test ./... before submitting.
  3. Keep changes focused. One feature or fix per PR.

Questions and bug reports go to GitHub Issues.

Acknowledgments

Kazari is inspired by Expressive Code and brings its feature set to the Go ecosystem. The HTML structure, CSS patterns, and class conventions are derived from Expressive Code by Hippo (MIT License).

License

Copyright (c) 2026 FrostyBee.

Kazari is licensed under the MIT License. Kazari embeds CSS and JS patterns derived from Expressive Code (MIT). See THIRD-PARTY-NOTICE for full attribution.


Full API documentation: pkg.go.dev/github.com/frostybee/kazari

Documentation

Overview

Package kazari renders framed, syntax-highlighted HTML code blocks with full CSS customization via custom properties.

Index

Constants

View Source
const (
	FontStyleNone          = config.FontStyleNone
	FontStyleItalic        = config.FontStyleItalic
	FontStyleBold          = config.FontStyleBold
	FontStyleUnderline     = config.FontStyleUnderline
	FontStyleStrikethrough = config.FontStyleStrikethrough
)

Font style bitmask constants.

Variables

This section is empty.

Functions

func CreateInlineSVGURL

func CreateInlineSVGURL(svg string) string

CreateInlineSVGURL converts SVG markup into a data:image/svg+xml URL for use in CSS custom properties (e.g. custom file icons or terminal icons). Use single quotes for SVG attributes; double quotes are percent-encoded.

Types

type AdjustTargets

type AdjustTargets int

AdjustTargets selects which extracted colors a ThemeAdjustments affects.

const (
	AdjustBackgrounds AdjustTargets = 1 << iota // BG, SelectionBG, FoldBG
	AdjustForegrounds                           // FG, LineNumberFG
)

type AssetFile

type AssetFile struct {
	Content  string
	Hash     string // 8-char hex (FNV-1a)
	Filename string // e.g. "kazari-a1b2c3d4.css"
}

AssetFile holds content and its hashed filename.

type Assets

type Assets struct {
	CSS AssetFile
	JS  AssetFile
}

Assets holds CSS and JS output with content-hashed filenames.

type BlockDefaults

type BlockDefaults struct {
	Wrap           bool
	PreserveIndent bool
	HangingIndent  int
	LineNumbers    bool
	Frame          Frame
}

BlockDefaults holds default block rendering properties.

type BlockDefaultsFileConfig

type BlockDefaultsFileConfig struct {
	Wrap           *bool   `yaml:"wrap" json:"wrap"`
	PreserveIndent *bool   `yaml:"preserveIndent" json:"preserveIndent"`
	HangingIndent  *int    `yaml:"hangingIndent" json:"hangingIndent"`
	LineNumbers    *bool   `yaml:"lineNumbers" json:"lineNumbers"`
	Frame          *string `yaml:"frame" json:"frame"`
}

type CollapseOptions

type CollapseOptions struct {
	Enabled   bool           // true = force threshold-based collapse
	Disabled  bool           // true = force no collapse (nocollapse)
	Ranges    []Range        // specific ranges to collapse
	Style     *CollapseStyle // nil = use engine default
	Threshold *int           // nil = use engine default; overrides engine LineThreshold for this block
}

CollapseOptions holds per-block collapse configuration.

type CollapseStyle

type CollapseStyle int

CollapseStyle identifies the visual style for range-based collapsible sections.

const (
	CollapseGithub           CollapseStyle = iota // one-way expand, summary disappears
	CollapseCollapsibleStart                      // re-collapsible, summary above content
	CollapseCollapsibleEnd                        // re-collapsible, summary below content
	CollapseCollapsibleAuto                       // auto: end if section reaches last line, else start
)

type CollapsibleConfig

type CollapsibleConfig struct {
	LineThreshold         int
	PreviewLines          int
	DefaultCollapsed      bool
	PreserveIndent        bool
	Style                 CollapseStyle
	ExpandButtonText      string
	CollapseButtonText    string
	ExpandedAnnouncement  string // screen reader
	CollapsedAnnouncement string // screen reader
}

CollapsibleConfig configures threshold-based collapsible code blocks.

type CollapsibleFileConfig

type CollapsibleFileConfig struct {
	LineThreshold         *int    `yaml:"lineThreshold" json:"lineThreshold"`
	PreviewLines          *int    `yaml:"previewLines" json:"previewLines"`
	DefaultCollapsed      *bool   `yaml:"defaultCollapsed" json:"defaultCollapsed"`
	PreserveIndent        *bool   `yaml:"preserveIndent" json:"preserveIndent"`
	Style                 *string `yaml:"style" json:"style"`
	ExpandButtonText      *string `yaml:"expandButtonText" json:"expandButtonText"`
	CollapseButtonText    *string `yaml:"collapseButtonText" json:"collapseButtonText"`
	ExpandedAnnouncement  *string `yaml:"expandedAnnouncement" json:"expandedAnnouncement"`
	CollapsedAnnouncement *string `yaml:"collapsedAnnouncement" json:"collapsedAnnouncement"`
}

type DarkMode

type DarkMode interface {
	// contains filtered or unexported methods
}

DarkMode controls how dark mode CSS is generated.

func BothMode

func BothMode(selector string) DarkMode

BothMode combines media query with a class toggle override.

func MediaQueryMode

func MediaQueryMode() DarkMode

MediaQueryMode uses prefers-color-scheme media query for dark mode.

func SelectorMode

func SelectorMode(selector string) DarkMode

SelectorMode uses a CSS class selector for dark mode switching. Example: SelectorMode(".dark") produces :root.dark { ... }

type DarkModeFileConfig

type DarkModeFileConfig struct {
	Kind     string `yaml:"kind" json:"kind"`
	Selector string `yaml:"selector" json:"selector"`
}

type DualThemeTokenizer

type DualThemeTokenizer interface {
	TokenizeDual(code, lang, lightTheme, darkTheme string) (light, dark [][]Token, err error)
}

DualThemeTokenizer is an optional capability for highlighters that can resolve two themes from a single tokenization pass. TextMate scanning is theme-independent, so a capable highlighter halves dual-theme work. The two returned streams MUST have identical token boundaries (same line count, same per-line token count and Content). The engine type-asserts this interface on its Highlighter and falls back to two Tokenize calls when it is absent.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is the main entry point for rendering code blocks.

func New

func New(opts ...Option) *Engine

New creates a new Engine with the given options.

func (*Engine) Assets

func (e *Engine) Assets() Assets

Assets returns CSS and JS with content-hashed filenames.

func (*Engine) CSS

func (e *Engine) CSS() string

CSS returns the full stylesheet for this engine configuration.

func (*Engine) EnableCodeGroups

func (e *Engine) EnableCodeGroups()

EnableCodeGroups enables code group CSS/JS in engine output. Called automatically by kazarimd.CodeGroups(). It mutates the engine configuration without synchronization, so call it during setup before the engine is shared with concurrent Render, CSS, or JS callers.

func (*Engine) JS

func (e *Engine) JS() string

JS returns the JavaScript module for this engine configuration.

func (*Engine) Render

func (e *Engine) Render(code string, opts Options) (string, error)

Render renders a code block with structured options.

func (*Engine) RenderWithMeta

func (e *Engine) RenderWithMeta(code string, metaStr string) (string, error)

RenderWithMeta parses a meta string and renders the code block.

func (*Engine) ThemeCSS

func (e *Engine) ThemeCSS() string

ThemeCSS returns only theme variables and token switching CSS, without structural rules. Use this for secondary engines on multi-engine pages where one primary engine provides the full CSS via CSS().

func (*Engine) Tokenize

func (e *Engine) Tokenize(code string, lang string) ([][]Token, error)

Tokenize returns raw tokens for consumers building custom HTML.

type FileConfig

type FileConfig struct {
	Themes                   *ThemesFileConfig                  `yaml:"themes" json:"themes"`
	DarkMode                 *DarkModeFileConfig                `yaml:"darkMode" json:"darkMode"`
	CopyButton               *bool                              `yaml:"copyButton" json:"copyButton"`
	FullscreenButton         *bool                              `yaml:"fullscreenButton" json:"fullscreenButton"`
	WrapButton               *bool                              `yaml:"wrapButton" json:"wrapButton"`
	ThemeToggleButton        *bool                              `yaml:"themeToggleButton" json:"themeToggleButton"`
	LineNumbers              *bool                              `yaml:"lineNumbers" json:"lineNumbers"`
	FrameDetection           *bool                              `yaml:"frameDetection" json:"frameDetection"`
	FileNameExtraction       *bool                              `yaml:"fileNameExtraction" json:"fileNameExtraction"`
	LanguageBadge            *bool                              `yaml:"languageBadge" json:"languageBadge"`
	ThemedScrollbars         *bool                              `yaml:"themedScrollbars" json:"themedScrollbars"`
	ThemedSelection          *bool                              `yaml:"themedSelection" json:"themedSelection"`
	ContentExclusion         *bool                              `yaml:"contentExclusion" json:"contentExclusion"`
	MermaidPassThrough       *bool                              `yaml:"mermaidPassThrough" json:"mermaidPassThrough"`
	TerminalCommentStripping *bool                              `yaml:"terminalCommentStripping" json:"terminalCommentStripping"`
	DataLineCount            *bool                              `yaml:"dataLineCount" json:"dataLineCount"`
	FileIcons                *bool                              `yaml:"fileIcons" json:"fileIcons"`
	Links                    *bool                              `yaml:"links" json:"links"`
	StyleReset               *bool                              `yaml:"styleReset" json:"styleReset"`
	Minify                   *bool                              `yaml:"minify" json:"minify"`
	TabWidth                 *int                               `yaml:"tabWidth" json:"tabWidth"`
	MinContrast              *float64                           `yaml:"minContrast" json:"minContrast"`
	CascadeLayer             *string                            `yaml:"cascadeLayer" json:"cascadeLayer"`
	ThemeCSSRoot             *string                            `yaml:"themeCSSRoot" json:"themeCSSRoot"`
	Locale                   *string                            `yaml:"locale" json:"locale"`
	TerminalDotStyle         *string                            `yaml:"terminalDotStyle" json:"terminalDotStyle"`
	LanguageIconMode         *string                            `yaml:"languageIconMode" json:"languageIconMode"`
	Defaults                 *BlockDefaultsFileConfig           `yaml:"defaults" json:"defaults"`
	LanguageDefaults         map[string]BlockDefaultsFileConfig `yaml:"languageDefaults" json:"languageDefaults"`
	Collapsible              *CollapsibleFileConfig             `yaml:"collapsible" json:"collapsible"`
	LanguageAliases          map[string]string                  `yaml:"languageAliases" json:"languageAliases"`
	UIStrings                map[string]string                  `yaml:"uiStrings" json:"uiStrings"`
	StyleOverrides           map[string]any                     `yaml:"styleOverrides" json:"styleOverrides"`
}

FileConfig represents a Kazari configuration file (YAML or JSON). All fields use pointer types so omitted keys are distinguishable from zero values.

func ParseConfig

func ParseConfig(data []byte, format string) (*FileConfig, error)

ParseConfig parses config bytes in the given format ("yaml" or "json") and validates the result.

type Frame

type Frame int

Frame determines the code block's visual frame type.

const (
	FrameAuto     Frame = iota // auto-detect from language
	FrameCode                  // editor frame
	FrameTerminal              // terminal frame
	FrameNone                  // no frame
)

type Highlighter

type Highlighter interface {
	Tokenize(code, lang, theme string) ([][]Token, error)
	GetThemeColors(theme string) (ThemeInfo, error)
	GetLoadedLanguages() []string
}

Highlighter abstracts syntax highlighting. The default implementation wraps Nuri, but any implementation (including mocks) can be used.

type InlineMarker

type InlineMarker struct {
	Type    MarkerType
	Text    string
	IsRegex bool
}

InlineMarker represents an inline text marker.

type LangIconMode

type LangIconMode int

LangIconMode controls language icon display in the toolbar badge area.

const (
	LangIconNone    LangIconMode = iota // text label only (default)
	LangIconOnly                        // icon replaces text
	LangIconAndText                     // icon shown before text label
)

type LineMarker

type LineMarker struct {
	Type  MarkerType
	Lines []Range
	Label string // empty for unlabeled
}

LineMarker represents a line-level marker with optional label.

type MarkerType

type MarkerType int

MarkerType identifies the kind of line or inline marker.

const (
	MarkerMark MarkerType = iota // highlight (default, lowest priority)
	MarkerDel                    // deleted
	MarkerIns                    // inserted (highest priority)
)

Priority order: mark(0) < del(1) < ins(2). Higher value wins in overlap resolution.

type Option

type Option func(*engineBuilder)

Option configures the Engine during construction.

func FileConfigToOptions

func FileConfigToOptions(fc *FileConfig) ([]Option, error)

FileConfigToOptions converts a FileConfig into a slice of functional options.

func LoadConfig

func LoadConfig(path string) ([]Option, error)

LoadConfig reads a config file, detects format from extension, parses, validates, and returns functional options.

func WithCascadeLayer

func WithCascadeLayer(name string) Option

func WithCollapsible

func WithCollapsible(c CollapsibleConfig) Option

func WithConfigDir

func WithConfigDir(dir string) Option

WithConfigDir searches the given directory for a config file (kazari.config.yaml, .yml, or .json) and applies its options. If no config file is found, it is a silent no-op. Parse errors are reported via WarningHandler.

func WithContentExclusion

func WithContentExclusion(enabled bool) Option

func WithCopyButton

func WithCopyButton(enabled bool) Option

func WithDarkMode

func WithDarkMode(dm DarkMode) Option

func WithDataLineCount

func WithDataLineCount(enabled bool) Option

func WithDefaults

func WithDefaults(d BlockDefaults) Option

func WithFileIconResolver

func WithFileIconResolver(f func(ext string) string) Option

func WithFileIcons

func WithFileIcons(enabled bool) Option

func WithFileNameExtraction

func WithFileNameExtraction(enabled bool) Option

func WithFrameDetection

func WithFrameDetection(enabled bool) Option

func WithFullscreenButton

func WithFullscreenButton(enabled bool) Option

func WithHighlighter

func WithHighlighter(hl Highlighter) Option

func WithLanguageAliases

func WithLanguageAliases(m map[string]string) Option

func WithLanguageBadge

func WithLanguageBadge(enabled bool) Option

func WithLanguageDefaults

func WithLanguageDefaults(m map[string]BlockDefaults) Option

func WithLanguageIconMode

func WithLanguageIconMode(mode LangIconMode) Option

func WithLineNumbers

func WithLineNumbers(enabled bool) Option
func WithLinks(enabled bool) Option

func WithLocale

func WithLocale(loc string) Option

func WithMermaidPassThrough

func WithMermaidPassThrough(enabled bool) Option

func WithMinContrast

func WithMinContrast(ratio float64) Option

func WithMinify

func WithMinify(enabled bool) Option

func WithStyleOverrides

func WithStyleOverrides(overrides map[string]string) Option

func WithStyleReset

func WithStyleReset(enabled bool) Option

func WithTabWidth

func WithTabWidth(n int) Option

func WithTerminalCommentStripping

func WithTerminalCommentStripping(enabled bool) Option

func WithTerminalDotStyle

func WithTerminalDotStyle(style TerminalDotStyle) Option

func WithThemeAdjustments

func WithThemeAdjustments(adj ThemeAdjustments) Option

WithThemeAdjustments tints the extracted theme colors in OKLCH space, applied to both themes before the theme customizer runs.

func WithThemeCSSRoot

func WithThemeCSSRoot(selector string) Option

func WithThemeCustomizer

func WithThemeCustomizer(f func(themeName string, colors ThemeInfo) ThemeInfo) Option

func WithThemeToggle

func WithThemeToggle(enabled bool) Option

func WithThemedScrollbars

func WithThemedScrollbars(enabled bool) Option

func WithThemedSelectionColors

func WithThemedSelectionColors(enabled bool) Option

func WithThemedStyleOverrides

func WithThemedStyleOverrides(overrides map[string]StyleValue) Option

func WithThemes

func WithThemes(light, dark string) Option

func WithUIStrings

func WithUIStrings(overrides map[string]string) Option

func WithWarningHandler

func WithWarningHandler(f func(string)) Option

WithWarningHandler sets the function that receives non-fatal warnings, such as unknown language fallbacks. When unset, warnings go to log.Printf. Pass a no-op function to silence warnings entirely.

func WithWrapButton

func WithWrapButton(enabled bool) Option

type Options

type Options struct {
	Lang            string
	Title           string
	Theme           string
	Frame           *Frame // nil = use default
	LineNumbers     *bool  // nil = use default
	StartLineNumber *int   // nil = use default (1)
	Wrap            *bool  // nil = use default
	PreserveIndent  *bool  // nil = use default
	HangingIndent   *int   // nil = use default
	DiffLang        string // original language for diff+syntax hybrid (e.g., "go")
	LineMarkers     []LineMarker
	InlineMarkers   []InlineMarker
	FocusLines      []Range
	Collapse        *CollapseOptions
}

Options is the per-block configuration passed to Render or derived from meta string.

type Range

type Range struct {
	Start int
	End   int
}

Range represents an inclusive 1-based line range.

type StyleValue

type StyleValue struct {
	Value string // used when both themes share the same value
	Dark  string // dark theme override
	Light string // light theme override
}

StyleValue represents a CSS variable override that can be universal or per-theme.

func (StyleValue) DarkValue

func (sv StyleValue) DarkValue() string

DarkValue returns the value to use for the dark theme.

func (StyleValue) IsThemed

func (sv StyleValue) IsThemed() bool

IsThemed reports whether this value has per-theme overrides.

func (StyleValue) LightValue

func (sv StyleValue) LightValue() string

LightValue returns the value to use for the light theme.

type TerminalDotStyle

type TerminalDotStyle int

TerminalDotStyle determines how terminal frame dots are rendered.

const (
	DotsColored TerminalDotStyle = iota // macOS red/yellow/green DOM spans (default)
	DotsMinimal                         // CSS-only monochrome dots via SVG mask
)

type ThemeAdjustments

type ThemeAdjustments struct {
	Hue     *float64      // target hue in degrees (0-360); nil = unchanged
	Chroma  *float64      // target chroma (0-0.4 typical); nil = unchanged
	Targets AdjustTargets // bitmask; zero value = AdjustBackgrounds
}

ThemeAdjustments tints extracted theme colors in OKLCH space. Nil fields leave that channel unchanged. Adjustments apply to the editor colors used for CSS variables, not to individual syntax token colors.

type ThemeInfo

type ThemeInfo struct {
	FG           string // default foreground (e.g. "#24292f")
	BG           string // default background (e.g. "#ffffff")
	SelectionBG  string // editor.selectionBackground
	LineNumberFG string // editorLineNumber.foreground
	FoldBG       string // editor.foldBackground
}

ThemeInfo holds colors extracted from a syntax theme for CSS variable generation.

type ThemesFileConfig

type ThemesFileConfig struct {
	Light string `yaml:"light" json:"light"`
	Dark  string `yaml:"dark" json:"dark"`
}

type Token

type Token struct {
	Content   string
	Color     string // foreground hex color (e.g. "#cf222e")
	BgColor   string // background hex color (usually empty)
	FontStyle int    // bitmask: Italic=1, Bold=2, Underline=4, Strikethrough=8
}

Token represents a single colored token from the highlighter.

Directories

Path Synopsis
demo
nuri command
site command
visualcheck command
internal
css
js
svgutil
Package svgutil encodes inline SVG markup as CSS-safe data URLs.
Package svgutil encodes inline SVG markup as CSS-safe data URLs.

Jump to

Keyboard shortcuts

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