initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-22 13:21:28 +02:00
commit 156bb18c91
50 files changed
+13466

No files matched your search

+335
View File
@@ -0,0 +1,335 @@
// Command genschema generates internal/schema/schema.json from Ghostty's
// src/config/Config.zig (for value types) and the output of
// `ghostty +show-config --default --docs` (for documentation and defaults).
//
// Usage:
//
// go run ./tools/genschema # uses installed ghostty, downloads Config.zig
// go run ./tools/genschema -zig Config.zig -docs docs.txt -version 1.3.1
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
func main() {
zigPath := flag.String("zig", "", "path to Config.zig (downloaded from GitHub if empty)")
docsPath := flag.String("docs", "", "path to `ghostty +show-config --default --docs` output (runs ghostty if empty)")
version := flag.String("version", "", "Ghostty version (detected from the installed ghostty if empty)")
out := flag.String("out", "internal/schema/schema.json", "output file")
flag.Parse()
var gh *ghostty.Ghostty
if *docsPath == "" || *version == "" {
var err error
gh, err = ghostty.Find("")
if err != nil {
log.Fatalf("ghostty not found (pass -docs and -version): %v", err)
}
}
if *version == "" {
*version = gh.Version
}
zigSrc, err := readZig(*zigPath, *version)
if err != nil {
log.Fatal(err)
}
var docs string
if *docsPath != "" {
b, err := os.ReadFile(*docsPath)
if err != nil {
log.Fatal(err)
}
docs = string(b)
} else {
docs, err = gh.DefaultsWithDocs()
if err != nil {
log.Fatal(err)
}
}
z := parseZig(zigSrc)
s := build(z, schema.ParseDocs(docs), *version)
b, err := json.MarshalIndent(s, "", " ")
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile(*out, append(b, '\n'), 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("wrote %s: %d options (Ghostty %s)\n", *out, len(s.Options), *version)
}
func readZig(path, version string) (string, error) {
if path != "" {
b, err := os.ReadFile(path)
return string(b), err
}
url := "https://raw.githubusercontent.com/ghostty-org/ghostty/v" + version + "/src/config/Config.zig"
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GET %s: %s", url, resp.Status)
}
b, err := io.ReadAll(resp.Body)
return string(b), err
}
// zigField is a top-level field of the Config struct.
type zigField struct {
key, typ string
doc []string
}
// zigType is an enum, union or packed struct declared in Config.zig.
type zigType struct {
kind string // "enum", "union", "packed"
members []string
payload bool // union has at least one variant carrying a value
}
type zigInfo struct {
fields []zigField
types map[string]*zigType
}
var (
reField = regexp.MustCompile(`^(?:@"([a-z0-9-]+)"|([a-z][a-z0-9_]*)): ([^=]+?)\s*=`)
reType = regexp.MustCompile(`^pub const (\w+) = (enum|union|packed struct)\b`)
reMember = regexp.MustCompile(`^ (@"[^"]+"|[a-z_][a-z0-9_]*)(\s*:\s*([^=,]+?))?(\s*=\s*([^,]+))?,\s*(//.*)?$`)
)
func parseZig(src string) *zigInfo {
info := &zigInfo{types: map[string]*zigType{}}
var doc []string
var cur *zigType
sc := bufio.NewScanner(strings.NewReader(src))
sc.Buffer(make([]byte, 1024*1024), 1024*1024)
for sc.Scan() {
line := sc.Text()
if cur != nil {
if line == "};" {
cur = nil
continue
}
m := reMember.FindStringSubmatch(line)
if m == nil {
continue
}
name := strings.Trim(strings.TrimPrefix(m[1], "@"), `"`)
typ := strings.TrimSpace(m[3])
switch cur.kind {
case "packed":
if typ == "bool" {
cur.members = append(cur.members, name)
}
case "union":
if typ == "" || typ == "void" {
cur.members = append(cur.members, name)
} else {
cur.payload = true
}
default:
if name != "_" {
cur.members = append(cur.members, name)
}
}
continue
}
if m := reType.FindStringSubmatch(line); m != nil {
kind := m[2]
if kind == "packed struct" {
kind = "packed"
}
cur = &zigType{kind: kind}
info.types[m[1]] = cur
doc = nil
continue
}
if strings.HasPrefix(line, "///") {
text := strings.TrimPrefix(line, "///")
doc = append(doc, strings.TrimPrefix(text, " "))
continue
}
if m := reField.FindStringSubmatch(line); m != nil {
key := m[1]
if key == "" {
key = m[2]
}
info.fields = append(info.fields, zigField{key: key, typ: strings.TrimSpace(m[3]), doc: doc})
}
doc = nil
}
return info
}
func ptr(f float64) *float64 { return &f }
// typeMap describes types that are not plain enums/unions/packed structs in
// Config.zig, or that need a dedicated editor.
var typeMap = map[string]schema.Option{
"bool": {Kind: schema.KindBool},
"?bool": {Kind: schema.KindBool},
"u8": {Kind: schema.KindInt, Min: ptr(0), Max: ptr(255)},
"u32": {Kind: schema.KindInt, Min: ptr(0), Max: ptr(4294967295)},
"usize": {Kind: schema.KindInt, Min: ptr(0)},
"?u64": {Kind: schema.KindInt, Min: ptr(0)},
"?i16": {Kind: schema.KindInt, Min: ptr(-32768), Max: ptr(32767)},
"f32": {Kind: schema.KindFloat},
"f64": {Kind: schema.KindFloat},
"?[:0]const u8": {Kind: schema.KindText},
"[:0]const u8": {Kind: schema.KindText},
"[]const u8": {Kind: schema.KindText},
"RepeatableString": {Kind: schema.KindText, Repeatable: true},
"FontStyle": {Kind: schema.KindChoice, Values: []string{"default", "false"}, Hint: "a style name such as Heavy, or default / false"},
"?MetricModifier": {Kind: schema.KindMetric},
"RepeatableFontVariation": {Kind: schema.KindText, Repeatable: true, Hint: "axis=value, e.g. wght=600"},
"RepeatableCodepointMap": {Kind: schema.KindText, Repeatable: true, Hint: "U+E000-U+E0FF,U+F000=Font Family"},
"RepeatableClipboardCodepointMap": {Kind: schema.KindText, Repeatable: true, Hint: "U+2500-U+257F=U+002B"},
"?Theme": {Kind: schema.KindTheme},
"Color": {Kind: schema.KindColor},
"?Color": {Kind: schema.KindColor},
"TerminalColor": {Kind: schema.KindColor, Values: []string{"cell-foreground", "cell-background"}},
"?TerminalColor": {Kind: schema.KindColor, Values: []string{"cell-foreground", "cell-background"}},
"?BoldColor": {Kind: schema.KindColor, Values: []string{"bright"}},
"?ColorList": {Kind: schema.KindColorList},
"?Path": {Kind: schema.KindPath},
"RepeatablePath": {Kind: schema.KindPath, Repeatable: true, Hint: "prefix with ? to make the file optional"},
"SelectionWordChars": {Kind: schema.KindText},
"Palette": {Kind: schema.KindPalette, Repeatable: true},
"terminal.CursorStyle": {Kind: schema.KindEnum, Values: []string{"block", "bar", "underline", "block_hollow"}},
"MouseScrollMultiplier": {Kind: schema.KindText, Hint: "a number, or precision:N,discrete:N"},
"?Command": {Kind: schema.KindText, Hint: "command line; prefix with direct: or shell: to control how it runs"},
"Duration": {Kind: schema.KindDuration},
"?Duration": {Kind: schema.KindDuration},
"RepeatableStringMap": {Kind: schema.KindText, Repeatable: true, Hint: "NAME=value"},
"RepeatableReadableIO": {Kind: schema.KindText, Repeatable: true, Hint: "raw:TEXT or path:FILE"},
"Keybinds": {Kind: schema.KindKeybind, Repeatable: true},
"KeyRemapSet": {Kind: schema.KindText, Repeatable: true, Hint: "from=to, e.g. ctrl=super"},
"WindowPadding": {Kind: schema.KindPadding},
"QuickTerminalSize": {Kind: schema.KindText, Hint: "e.g. 50%, 400px or 50%,500px"},
"RepeatableCommand": {Kind: schema.KindText, Repeatable: true, Hint: "title:NAME,action:ACTION[,description:TEXT]"},
"?inputpkg.OptionAsAlt": {Kind: schema.KindEnum, Values: []string{"false", "true", "left", "right"}},
"?build_config.ReleaseChannel": {Kind: schema.KindEnum, Values: []string{"stable", "tip"}},
}
// keyOverrides refine individual keys whose type alone is not specific
// enough.
var keyOverrides = map[string]func(*schema.Option){
"font-family": func(o *schema.Option) { o.Kind = schema.KindFont },
"font-family-bold": func(o *schema.Option) { o.Kind = schema.KindFont },
"font-family-italic": func(o *schema.Option) { o.Kind = schema.KindFont },
"font-family-bold-italic": func(o *schema.Option) { o.Kind = schema.KindFont },
"window-title-font-family": func(o *schema.Option) { o.Kind = schema.KindFont },
"font-feature": func(o *schema.Option) { o.Hint = "e.g. -calt, +ss01, cv01=2" },
"font-size": func(o *schema.Option) { o.Min = ptr(1) },
"background-opacity": func(o *schema.Option) { o.Min, o.Max = ptr(0), ptr(1) },
"background-image-opacity": func(o *schema.Option) { o.Min = ptr(0) },
"unfocused-split-opacity": func(o *schema.Option) { o.Min, o.Max = ptr(0.15), ptr(1) },
"cursor-opacity": func(o *schema.Option) { o.Min, o.Max = ptr(0), ptr(1) },
"faint-opacity": func(o *schema.Option) { o.Min, o.Max = ptr(0), ptr(1) },
"bell-audio-volume": func(o *schema.Option) { o.Min, o.Max = ptr(0), ptr(1) },
"minimum-contrast": func(o *schema.Option) { o.Min, o.Max = ptr(1), ptr(21) },
"macos-custom-icon": func(o *schema.Option) { o.Kind = schema.KindPath },
"working-directory": func(o *schema.Option) {
o.Hint = "home, inherit, or a directory path"
},
"background-blur": func(o *schema.Option) {
o.Hint = "true, false, a blur radius (e.g. 20) or a macOS glass style"
},
}
func build(z *zigInfo, docs []schema.DocEntry, version string) *schema.Schema {
docByKey := map[string]schema.DocEntry{}
for _, d := range docs {
docByKey[d.Key] = d
}
fieldByKey := map[string]zigField{}
for _, f := range z.fields {
fieldByKey[f.key] = f
}
s := &schema.Schema{GhosttyVersion: version}
add := func(key string, d schema.DocEntry, listed bool) {
f, ok := fieldByKey[key]
var o schema.Option
if ok {
o = optionForType(f.typ, z.types)
o.ZigType = f.typ
} else {
log.Printf("warning: %s not found in Config.zig, treating as text", key)
o = schema.Option{Kind: schema.KindText}
}
o.Key = key
o.Doc = d.Doc
o.Defaults = d.Defaults
o.NotListed = !listed
if fn := keyOverrides[key]; fn != nil {
fn(&o)
}
s.Options = append(s.Options, &o)
}
for _, d := range docs {
add(d.Key, d, true)
}
// Fields Ghostty accepts but cannot print with +show-config.
for _, f := range z.fields {
if _, ok := docByKey[f.key]; ok || skipField(f) {
continue
}
doc := strings.TrimSpace(strings.Join(f.doc, "\n"))
add(f.key, schema.DocEntry{Key: f.key, Doc: doc}, false)
}
return s
}
// skipField excludes fields that cannot be set from a config file.
func skipField(f zigField) bool {
switch f.key {
case "link": // parseCLI is not implemented
return true
}
return strings.HasPrefix(f.key, "_")
}
func optionForType(typ string, types map[string]*zigType) schema.Option {
if o, ok := typeMap[typ]; ok {
o.Values = append([]string(nil), o.Values...)
return o
}
name := strings.TrimPrefix(typ, "?")
t := types[name]
if t == nil {
log.Printf("warning: unknown type %s, treating as text", typ)
return schema.Option{Kind: schema.KindText}
}
switch t.kind {
case "packed":
return schema.Option{Kind: schema.KindFlags, Flags: t.members}
case "union":
if t.payload {
return schema.Option{Kind: schema.KindChoice, Values: t.members}
}
return schema.Option{Kind: schema.KindEnum, Values: t.members}
default:
return schema.Option{Kind: schema.KindEnum, Values: t.members}
}
}
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Regenerates the screenshots in docs/images. Runs ghosttyconf with a demo
# config in a detached tmux session, drives it with key presses and renders
# the captured screens with tools/termsvg. Needs tmux and Ghostty.
set -euo pipefail
cd "$(dirname "$0")/.."
OUT=docs/images
THEME=${THEME:-Catppuccin Mocha}
COLS=144
ROWS=34
SESSION=ghosttyconf-shots
tmp=$(mktemp -d)
trap 'tmux kill-session -t "$SESSION" 2>/dev/null || true; rm -rf "$tmp"' EXIT
go build -o "$tmp/ghosttyconf" .
go build -o "$tmp/termsvg" ./tools/termsvg
mkdir -p "$OUT" "$tmp/home/.config/ghostty"
cat > "$tmp/home/.config/ghostty/config.ghostty" <<'EOF'
# Ghostty configuration
# https://ghostty.org/docs/config
theme = Catppuccin Mocha
font-family = JetBrains Mono
font-size = 14
font-thicken = true
cursor-style = bar
cursor-color = #f5e0dc
selection-background = #585b70
window-padding-x = 12
window-padding-y = 8
window-save-state = always
background-opacity = 0.95
macos-titlebar-style = tabs
shell-integration-features = no-cursor,sudo,title
copy-on-select = clipboard
keybind = super+d=new_split:right
keybind = super+shift+d=new_split:down
keybind = super+k=unbind
keybind = ctrl+grave_accent=toggle_quick_terminal
EOF
# HOME points at the demo so the title bar shows ~/.config/ghostty/…
tmux new-session -d -s "$SESSION" -x $COLS -y $ROWS \
"cd '$tmp/home' && env HOME='$tmp/home' COLORTERM=truecolor '$tmp/ghosttyconf' --no-reload"
sleep 2
keys() {
for k in "$@"; do
tmux send-keys -t "$SESSION" "$k"
sleep 0.15
done
sleep 0.5
}
# raw sends a key as the kitty keyboard protocol encodes it, the way Ghostty
# reports keys while a binding is being recorded.
raw() {
tmux send-keys -t "$SESSION" -l "$1"
sleep 0.5
}
shot() {
tmux capture-pane -t "$SESSION" -e -p > "$tmp/$1.ans"
"$tmp/termsvg" -theme "$THEME" -title ghosttyconf -o "$OUT/$1.svg" "$tmp/$1.ans"
echo "wrote $OUT/$1.svg"
}
down() {
for _ in $(seq "$1"); do tmux send-keys -t "$SESSION" Down; done
sleep 0.5
}
shot main
# Theme picker with the live preview of the highlighted theme.
keys Enter t o k y o Down
shot picker
keys Escape
# Key binding manager: move new_split:right from super+d to super+\.
keys b / s p l i t Enter
down 11
keys Enter C-r
raw $'\e[?9u' # Ghostty's answer to the protocol query; tmux has none
raw $'\e[92;9u'
shot record
keys Enter Enter / s p l i t Enter
down 11
shot keybinds
keys Escape Escape
# Two more edits, then the list of unsaved changes.
keys Down Down +
down 9
keys space c
shot changes
+648
View File
@@ -0,0 +1,648 @@
// Command termsvg renders a terminal screen captured with
// "tmux capture-pane -e -p" as an SVG image in a window frame. Colors come
// from a Ghostty theme file. It is used to make the screenshots in docs/.
//
// termsvg -theme "Catppuccin Mocha" -title ghosttyconf -o out.svg < screen.ans
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
)
// Cell metrics in SVG units.
const (
cellW = 8.0
cellH = 17.0
fontSize = 13.4
baseline = 12.9
padding = 14.0
titleH = 34.0
margin = 18.0
)
const fontFamily = `ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, Consolas, 'DejaVu Sans Mono', monospace`
type color struct {
set bool
r, g, b uint8
}
func (c color) hex() string { return fmt.Sprintf("#%02x%02x%02x", c.r, c.g, c.b) }
func mix(a, b color, t float64) color {
f := func(x, y uint8) uint8 { return uint8(float64(x)*(1-t) + float64(y)*t + 0.5) }
return color{true, f(a.r, b.r), f(a.g, b.g), f(a.b, b.b)}
}
type theme struct {
fg, bg color
palette [256]color
}
// colorRef is a cell color before the theme is applied: -1 is the default,
// 0..255 a palette index, and rgb a direct color.
type colorRef struct {
index int
rgb color
}
var defaultColor = colorRef{index: -1}
type style struct {
fg, bg colorRef
bold, faint, italic, under, strike, rev bool
}
type cell struct {
r rune
st style
wide bool // first half of a double-width character
cont bool // second half of a double-width character
blank bool
}
func main() {
themeName := flag.String("theme", "Catppuccin Mocha", "Ghostty theme name or path to a theme file")
title := flag.String("title", "", "window title")
out := flag.String("o", "", "output file (default: stdout)")
cols := flag.Int("cols", 0, "screen width in cells (default: widest line)")
flag.Parse()
th, err := loadTheme(*themeName)
if err != nil {
fatal(err)
}
var in io.Reader = os.Stdin
if flag.NArg() == 1 {
f, err := os.Open(flag.Arg(0))
if err != nil {
fatal(err)
}
defer f.Close()
in = f
}
data, err := io.ReadAll(in)
if err != nil {
fatal(err)
}
rows := parse(string(data))
for len(rows) > 0 && blankRow(rows[len(rows)-1]) {
rows = rows[:len(rows)-1]
}
w := *cols
for _, r := range rows {
w = max(w, len(r))
}
svg := render(rows, w, th, *title)
if *out == "" {
os.Stdout.WriteString(svg)
return
}
if err := os.WriteFile(*out, []byte(svg), 0o644); err != nil {
fatal(err)
}
}
func fatal(err error) {
fmt.Fprintln(os.Stderr, "termsvg:", err)
os.Exit(1)
}
func blankRow(r []cell) bool {
for _, c := range r {
if !c.blank || c.st.bg != defaultColor {
return false
}
}
return true
}
// loadTheme reads a Ghostty theme (palette, background, foreground) and fills
// the rest of the 256 colors like xterm.
func loadTheme(name string) (*theme, error) {
path := name
if !strings.ContainsRune(name, '/') {
for _, dir := range []string{
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
} {
if p := filepath.Join(dir, name); fileExists(p) {
path = p
break
}
}
}
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("theme %q: %w", name, err)
}
defer f.Close()
th := &theme{}
xterm(&th.palette)
sc := bufio.NewScanner(f)
for sc.Scan() {
key, val, ok := strings.Cut(sc.Text(), "=")
if !ok {
continue
}
key, val = strings.TrimSpace(key), strings.TrimSpace(val)
switch key {
case "background":
th.bg = parseHex(val)
case "foreground":
th.fg = parseHex(val)
case "palette":
i, hex, ok := strings.Cut(val, "=")
if n, err := strconv.Atoi(strings.TrimSpace(i)); ok && err == nil && n >= 0 && n < 256 {
th.palette[n] = parseHex(strings.TrimSpace(hex))
}
}
}
if !th.bg.set {
th.bg = th.palette[0]
}
if !th.fg.set {
th.fg = th.palette[7]
}
return th, sc.Err()
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
func parseHex(s string) color {
s = strings.TrimPrefix(s, "#")
if len(s) != 6 {
return color{}
}
v, err := strconv.ParseUint(s, 16, 32)
if err != nil {
return color{}
}
return color{true, uint8(v >> 16), uint8(v >> 8), uint8(v)}
}
func xterm(p *[256]color) {
base := []string{"000000", "cd0000", "00cd00", "cdcd00", "0000ee", "cd00cd", "00cdcd", "e5e5e5",
"7f7f7f", "ff0000", "00ff00", "ffff00", "5c5cff", "ff00ff", "00ffff", "ffffff"}
for i, h := range base {
p[i] = parseHex(h)
}
steps := []uint8{0, 95, 135, 175, 215, 255}
for i := 0; i < 216; i++ {
p[16+i] = color{true, steps[i/36], steps[i/6%6], steps[i%6]}
}
for i := 0; i < 24; i++ {
v := uint8(8 + 10*i)
p[232+i] = color{true, v, v, v}
}
}
// parse turns the captured text into rows of cells.
func parse(s string) [][]cell {
// tmux only writes attribute changes, so the style carries over from one
// line to the next.
var rows [][]cell
st := style{fg: defaultColor, bg: defaultColor}
for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
var row []cell
for i := 0; i < len(line); {
if line[i] == 0x1b && i+1 < len(line) {
switch line[i+1] {
case '[':
j := i + 2
for j < len(line) && (line[j] < 0x40 || line[j] > 0x7e) {
j++
}
if j < len(line) && line[j] == 'm' {
sgr(&st, line[i+2:j])
}
i = j + 1
continue
case ']': // OSC, e.g. hyperlinks: skip up to BEL or ST
j := i + 2
for j < len(line) && line[j] != 0x07 && !(line[j] == 0x1b && j+1 < len(line) && line[j+1] == '\\') {
j++
}
if j < len(line) && line[j] == 0x1b {
j++
}
i = j + 1
continue
}
}
r, size := decodeRune(line[i:])
i += size
if r == '\t' {
for len(row)%8 != 0 || r == '\t' {
row = append(row, cell{r: ' ', st: st, blank: true})
r = 0
}
continue
}
if r < 0x20 {
continue
}
w := ansi.StringWidth(string(r))
if w == 0 {
continue
}
row = append(row, cell{r: r, st: st, wide: w == 2, blank: r == ' '})
if w == 2 {
row = append(row, cell{st: st, cont: true})
}
}
rows = append(rows, row)
}
return rows
}
func decodeRune(s string) (rune, int) {
for _, r := range s {
return r, len(string(r))
}
return 0, 1
}
func sgr(st *style, params string) {
if params == "" {
*st = style{fg: defaultColor, bg: defaultColor}
return
}
ps := strings.FieldsFunc(params, func(r rune) bool { return r == ';' || r == ':' })
num := func(i int) int {
if i >= len(ps) {
return 0
}
n, _ := strconv.Atoi(ps[i])
return n
}
for i := 0; i < len(ps); i++ {
switch n := num(i); {
case n == 0:
*st = style{fg: defaultColor, bg: defaultColor}
case n == 1:
st.bold = true
case n == 2:
st.faint = true
case n == 3:
st.italic = true
case n == 4:
st.under = true
case n == 7:
st.rev = true
case n == 9:
st.strike = true
case n == 22:
st.bold, st.faint = false, false
case n == 23:
st.italic = false
case n == 24:
st.under = false
case n == 27:
st.rev = false
case n == 29:
st.strike = false
case n >= 30 && n <= 37:
st.fg = colorRef{index: n - 30}
case n >= 40 && n <= 47:
st.bg = colorRef{index: n - 40}
case n >= 90 && n <= 97:
st.fg = colorRef{index: n - 90 + 8}
case n >= 100 && n <= 107:
st.bg = colorRef{index: n - 100 + 8}
case n == 39:
st.fg = defaultColor
case n == 49:
st.bg = defaultColor
case n == 38 || n == 48:
var c colorRef
switch num(i + 1) {
case 5:
c = colorRef{index: num(i+2) & 0xff}
i += 2
case 2:
c = colorRef{index: 256, rgb: color{true, uint8(num(i + 2)), uint8(num(i + 3)), uint8(num(i + 4))}}
i += 4
default:
continue
}
if n == 38 {
st.fg = c
} else {
st.bg = c
}
}
}
}
func (th *theme) resolve(c colorRef, def color) color {
switch {
case c.index < 0:
return def
case c.index < 256:
return th.palette[c.index]
default:
return c.rgb
}
}
// colors returns the effective foreground and background of a cell and
// whether the background differs from the screen's.
func (th *theme) colors(st style) (fg, bg color, ownBg bool) {
fg = th.resolve(st.fg, th.fg)
bg = th.resolve(st.bg, th.bg)
ownBg = st.bg != defaultColor
if st.rev {
fg, bg, ownBg = bg, fg, true
}
if st.faint {
fg = mix(fg, bg, 0.45)
}
return fg, bg, ownBg
}
// Box drawing characters drawn as lines so that borders connect.
type arms struct{ l, r, u, d, round, heavy bool }
var boxChars = map[rune]arms{
'─': {l: true, r: true}, '━': {l: true, r: true, heavy: true},
'│': {u: true, d: true}, '┃': {u: true, d: true, heavy: true},
'╭': {r: true, d: true, round: true}, '╮': {l: true, d: true, round: true},
'╰': {r: true, u: true, round: true}, '╯': {l: true, u: true, round: true},
'┌': {r: true, d: true}, '┐': {l: true, d: true},
'└': {r: true, u: true}, '┘': {l: true, u: true},
'├': {u: true, d: true, r: true}, '┤': {u: true, d: true, l: true},
'┬': {l: true, r: true, d: true}, '┴': {l: true, r: true, u: true},
'┼': {l: true, r: true, u: true, d: true},
}
// Block elements drawn as rectangles: x, y, w, h as fractions of the cell.
var blockChars = map[rune][4]float64{
'█': {0, 0, 1, 1}, '▀': {0, 0, 1, 0.5}, '▄': {0, 0.5, 1, 0.5},
'▌': {0, 0, 0.5, 1}, '▐': {0.5, 0, 0.5, 1},
}
func render(rows [][]cell, cols int, th *theme, title string) string {
termW := float64(cols)*cellW + 2*padding
termH := float64(len(rows))*cellH + 2*padding
winW, winH := termW, termH+titleH
totalW, totalH := winW+2*margin, winH+2*margin
var b strings.Builder
fmt.Fprintf(&b, `<svg xmlns="http://www.w3.org/2000/svg" width="%s" height="%s" viewBox="0 0 %s %s">`+"\n",
f(totalW), f(totalH), f(totalW), f(totalH))
b.WriteString(`<defs><filter id="shadow" x="-10%" y="-10%" width="120%" height="130%">` +
`<feDropShadow dx="0" dy="6" stdDeviation="7" flood-color="#000" flood-opacity="0.35"/></filter>` +
`<clipPath id="win"><rect x="0" y="0" width="` + f(winW) + `" height="` + f(winH) + `" rx="10"/></clipPath></defs>` + "\n")
fmt.Fprintf(&b, `<g transform="translate(%s %s)">`+"\n", f(margin), f(margin))
// Window frame and title bar, slightly lighter than the background.
bar := mix(th.bg, th.fg, 0.08)
fmt.Fprintf(&b, `<rect width="%s" height="%s" rx="10" fill="%s" filter="url(#shadow)"/>`+"\n", f(winW), f(winH), th.bg.hex())
fmt.Fprintf(&b, `<g clip-path="url(#win)"><rect width="%s" height="%s" fill="%s"/>`, f(winW), f(titleH), bar.hex())
fmt.Fprintf(&b, `<rect y="%s" width="%s" height="1" fill="%s"/></g>`+"\n", f(titleH-1), f(winW), mix(th.bg, th.fg, 0.14).hex())
for i, c := range []string{"#ff5f57", "#febc2e", "#28c840"} {
fmt.Fprintf(&b, `<circle cx="%s" cy="%s" r="6" fill="%s"/>`, f(20+float64(i)*20), f(titleH/2), c)
}
b.WriteString("\n")
if title != "" {
fmt.Fprintf(&b, `<text x="%s" y="%s" text-anchor="middle" fill="%s" font-family="-apple-system, 'Segoe UI', Helvetica, Arial, sans-serif" font-size="13" font-weight="600">%s</text>`+"\n",
f(winW/2), f(titleH/2+4.5), mix(th.fg, bar, 0.3).hex(), esc(title))
}
fmt.Fprintf(&b, `<g transform="translate(%s %s)">`+"\n", f(padding), f(titleH+padding))
backgrounds(&b, rows, th)
shapes(&b, rows, th)
text(&b, rows, th)
b.WriteString("</g>\n</g>\n</svg>\n")
return b.String()
}
func backgrounds(b *strings.Builder, rows [][]cell, th *theme) {
for y, row := range rows {
for x := 0; x < len(row); {
_, bg, own := th.colors(row[x].st)
n := 1
for x+n < len(row) {
_, bg2, own2 := th.colors(row[x+n].st)
if own2 != own || bg2 != bg {
break
}
n++
}
if own && bg != th.bg {
fmt.Fprintf(b, `<rect x="%s" y="%s" width="%s" height="%s" fill="%s"/>`+"\n",
f(float64(x)*cellW), f(float64(y)*cellH), f(float64(n)*cellW+0.6), f(cellH+0.6), bg.hex())
}
x += n
}
}
}
// shapes draws box drawing and block characters, one path per color.
func shapes(b *strings.Builder, rows [][]cell, th *theme) {
lines := map[string]*strings.Builder{}
heavy := map[string]*strings.Builder{}
var order []string
path := func(m map[string]*strings.Builder, c string) *strings.Builder {
p, ok := m[c]
if !ok {
p = &strings.Builder{}
m[c] = p
order = append(order, c)
}
return p
}
for y, row := range rows {
for x, c := range row {
fg, _, _ := th.colors(c.st)
x0, y0 := float64(x)*cellW, float64(y)*cellH
if r, ok := blockChars[c.r]; ok {
fmt.Fprintf(b, `<rect x="%s" y="%s" width="%s" height="%s" fill="%s"/>`+"\n",
f(x0+r[0]*cellW), f(y0+r[1]*cellH), f(r[2]*cellW+0.6), f(r[3]*cellH+0.6), fg.hex())
continue
}
a, ok := boxChars[c.r]
if !ok {
continue
}
m := lines
if a.heavy {
m = heavy
}
p := path(m, fg.hex())
cx, cy := x0+cellW/2, y0+cellH/2
if a.round {
// One quarter circle from the horizontal to the vertical arm.
hx := x0 + cellW
if a.l {
hx = x0
}
vy := y0 + cellH
if a.u {
vy = y0
}
rad := cellW / 2
sx := cx + rad
if a.l {
sx = cx - rad
}
sy := cy + rad
if a.u {
sy = cy - rad
}
fmt.Fprintf(p, "M%s %sH%sQ%s %s %s %sV%s", f(hx), f(cy), f(sx), f(cx), f(cy), f(cx), f(sy), f(vy))
continue
}
if a.l || a.r {
l, r := cx, cx
if a.l {
l = x0
}
if a.r {
r = x0 + cellW
}
fmt.Fprintf(p, "M%s %sH%s", f(l), f(cy), f(r))
}
if a.u || a.d {
u, d := cy, cy
if a.u {
u = y0
}
if a.d {
d = y0 + cellH
}
fmt.Fprintf(p, "M%s %sV%s", f(cx), f(u), f(d))
}
}
}
for _, c := range order {
if p, ok := lines[c]; ok {
fmt.Fprintf(b, `<path d="%s" fill="none" stroke="%s" stroke-width="1.2"/>`+"\n", p.String(), c)
}
if p, ok := heavy[c]; ok {
fmt.Fprintf(b, `<path d="%s" fill="none" stroke="%s" stroke-width="2.4"/>`+"\n", p.String(), c)
}
}
}
// text writes runs of equally styled characters. Each run is stretched to
// its exact cell width so that columns line up with any font.
func text(b *strings.Builder, rows [][]cell, th *theme) {
fmt.Fprintf(b, `<g font-family="%s" font-size="%s" xml:space="preserve">`+"\n", fontFamily, f(fontSize))
drawn := func(c cell) bool {
_, box := boxChars[c.r]
_, block := blockChars[c.r]
return !c.cont && !box && !block
}
for y, row := range rows {
for x := 0; x < len(row); {
c := row[x]
if !drawn(c) || (c.blank && !c.st.under && !c.st.strike) {
x++
continue
}
fg, _, _ := th.colors(c.st)
var s strings.Builder
n := 0
for x+n < len(row) {
d := row[x+n]
if d.cont {
n++
continue
}
fg2, _, _ := th.colors(d.st)
if !drawn(d) || fg2 != fg || d.st.bold != c.st.bold || d.st.italic != c.st.italic ||
d.st.under != c.st.under || d.st.strike != c.st.strike || d.wide {
break
}
s.WriteRune(d.r)
n++
}
if n == 0 { // a wide character starts its own run
s.WriteRune(c.r)
n = 2
}
str := strings.TrimRight(s.String(), " ")
if c.st.under || c.st.strike {
str = s.String()
}
// Renderers collapse runs of spaces despite xml:space, so text
// is split at them and every piece is placed on its own.
for _, p := range pieces(str, c.st.under || c.st.strike) {
attrs := ""
if c.st.bold {
attrs += ` font-weight="700"`
}
if c.st.italic {
attrs += ` font-style="italic"`
}
switch {
case c.st.under && c.st.strike:
attrs += ` text-decoration="underline line-through"`
case c.st.under:
attrs += ` text-decoration="underline"`
case c.st.strike:
attrs += ` text-decoration="line-through"`
}
fmt.Fprintf(b, `<text x="%s" y="%s" fill="%s" textLength="%s" lengthAdjust="spacingAndGlyphs"%s>%s</text>`+"\n",
f(float64(x+p.col)*cellW), f(float64(y)*cellH+baseline), fg.hex(), f(float64(p.cells)*cellW), attrs, esc(p.text))
}
x += n
}
}
b.WriteString("</g>\n")
}
type piece struct {
text string
col, cells int
}
// pieces splits s at runs of two or more spaces (or at every space when the
// spaces themselves are decorated, where they are replaced by no-break
// spaces instead).
func pieces(s string, keepSpaces bool) []piece {
if keepSpaces {
return []piece{{strings.ReplaceAll(s, " ", " "), 0, ansi.StringWidth(s)}}
}
var out []piece
col := 0
for s != "" {
lead := len(s) - len(strings.TrimLeft(s, " "))
col += lead
s = s[lead:]
end := strings.Index(s, " ")
if end < 0 {
end = len(s)
}
t := strings.TrimRight(s[:end], " ")
if t != "" {
w := ansi.StringWidth(t)
out = append(out, piece{t, col, w})
col += w
}
s = s[len(t):]
}
return out
}
func f(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
func esc(s string) string {
return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;").Replace(s)
}