// 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 compat []*schema.Compat } 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*(//.*)?$`) // Entries of the compatibility table: renamed keys, or a handler function. reCompat = regexp.MustCompile(`^\s*\.\{ "([a-z0-9-]+)", (?:cli\.compatibilityRenamed\(Config, "([a-z0-9-]+)"\)|(\w+)) \},`) reCompatValue = regexp.MustCompile(`std\.mem\.eql\(u8, value\w* orelse "", "([^"]+)"\)`) reCompatSets = regexp.MustCompile(`self\.@"([a-z0-9-]+)" =`) ) 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 } info.compat = parseCompat(src) return info } // parseCompat reads the `compatibility` table of Config.zig: keys and values // of older releases that Ghostty still accepts. A renamed key names its new // key; for a handler function, the values it compares against and the // options it assigns are taken from its body. func parseCompat(src string) []*schema.Compat { lines := strings.Split(src, "\n") var out []*schema.Compat inTable := false for _, line := range lines { switch { case strings.HasPrefix(line, "pub const compatibility = "): inTable = true case inTable && line == "});": inTable = false case inTable: m := reCompat.FindStringSubmatch(line) if m == nil { continue } c := &schema.Compat{Key: m[1], RenamedTo: m[2]} if m[3] != "" { body := funcBody(lines, m[3]) if body == "" { log.Printf("warning: compatibility handler %s not found", m[3]) } for _, v := range reCompatValue.FindAllStringSubmatch(body, -1) { c.Values = appendNew(c.Values, v[1]) } for _, v := range reCompatSets.FindAllStringSubmatch(body, -1) { if v[1] != c.Key { c.Sets = appendNew(c.Sets, v[1]) } } } out = append(out, c) } } return out } // funcBody returns the top-level function name, from its signature to the // closing brace. func funcBody(lines []string, name string) string { for i, line := range lines { if !strings.HasPrefix(line, "fn "+name+"(") { continue } for j := i; j < len(lines); j++ { if lines[j] == "}" { return strings.Join(lines[i:j+1], "\n") } } } return "" } func appendNew(list []string, v string) []string { for _, s := range list { if s == v { return list } } return append(list, v) } 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}, "WindowPaddingBalance": {Kind: schema.KindEnum, Values: []string{"false", "true", "equal"}}, // renderer/size.zig "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) } known := map[string]bool{} for _, o := range s.Options { known[o.Key] = true } for _, c := range z.compat { switch { case c.RenamedTo != "" && !known[c.RenamedTo]: log.Printf("warning: compatibility: %s is renamed to the unknown key %s", c.Key, c.RenamedTo) case known[c.Key] && len(c.Values) == 0: log.Printf("warning: compatibility: no old values found for %s", c.Key) case !known[c.Key] && c.RenamedTo == "" && len(c.Sets) == 0: log.Printf("warning: compatibility: no replacement found for %s", c.Key) } } s.Compat = z.compat 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 } // Limit(usize, 50_000_000) from limit.zig: a number, or "unlimited". if strings.HasPrefix(typ, "Limit(") { return schema.Option{Kind: schema.KindInt, Min: ptr(0), Values: []string{"unlimited"}} } 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} } }