commit 156bb18c91d7d8ff7c92fa702eefbb2c2696006c Author: Michael Wesemann Date: Thu Oct 22 13:21:28 2026 +0200 initial commit [141.14.140.180,mike] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0296743 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +.AppleDouble +.LSOverride +._* +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes + +# build output +/ghosttyconf +/bin/ + +# mgsh settings with the API token +.mgshrc diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..39a08b2 --- /dev/null +++ b/Makefile @@ -0,0 +1,24 @@ +BIN := ghosttyconf + +.PHONY: build install test schema screenshots clean + +build: + go build -o $(BIN) . + +install: + go install . + +test: + go test ./... + +# Regenerate the embedded option schema for the installed Ghostty version. +# Downloads src/config/Config.zig of that version from GitHub. +schema: + go run ./tools/genschema + +# Regenerate docs/images. Needs tmux and Ghostty. +screenshots: + ./tools/screenshots.sh + +clean: + rm -f $(BIN) diff --git a/README.md b/README.md new file mode 100644 index 0000000..289d136 --- /dev/null +++ b/README.md @@ -0,0 +1,199 @@ +

👻 ghosttyconf

+ +

+ A terminal editor for the Ghostty configuration.
+ Browse, search and edit every option, with the full documentation next to it. +

+ +

+ Go 1.24+ + Ghostty 1.3 + macOS and Linux +

+ +

+ ghosttyconf: categories, options and documentation +

+ +Ghostty is configured with a plain text file and close to two hundred options. +ghosttyconf puts all of them on one screen. It groups the options into +categories and shows each one's type, default and current value. Every option +gets the editor that fits it. Comments, blank lines and the order of your file +stay intact, and after saving, Ghostty reloads the configuration right away. + +--- + +## ✨ Highlights + +- 📚 **All options, documented.** All 201 options of Ghostty 1.3, in 19 + categories, with the documentation of *your* Ghostty version. +- 🎛 **An editor for every type.** Toggles, choice lists, checklists for flags, + number steppers, colors with live swatches, a list editor for repeatable + options, the 256-color palette. +- 🎨 **Theme and font pickers.** Filter more than 460 themes with a live color + preview, or pick from the font families Ghostty can find. +- ⌨️ **Key binding editor.** See Ghostty's built-in bindings merged with yours, + and change, unbind, restore or add bindings. Record shortcuts straight from + the keyboard. +- 🧷 **Your file stays yours.** Comments, blank lines and the order of + untouched lines are kept, and changed entries are rewritten in place. +- ✅ **Safe saving.** `ghostty +validate-config` checks every save first. The + old file is kept as a backup, writes are atomic, and symlinks into dotfile + repositories keep working. +- 🔄 **Instant apply.** After saving, the running Ghostty reloads its + configuration. +- 🔎 **Search, undo, diff.** Search names and documentation, undo step by step, + and review all unsaved changes before you save. + +## 🚀 Installation + +You need [Go](https://go.dev/dl/) 1.24 or newer and Ghostty. + +```sh +git clone https://git.micw.org/mike/ghosttyconf.git +cd ghosttyconf +make install # installs ghosttyconf into $(go env GOPATH)/bin +``` + +`make build` builds `./ghosttyconf` in the source directory instead. + +## 💡 Quick start + +```sh +ghosttyconf +``` + +This opens the config file Ghostty itself would load. Pick a category on the +left and an option on the right, then press `enter` to edit it. Changes are +marked yellow until you save them with `ctrl+s`. Press `?` for help at any time. + +```sh +ghosttyconf ~/dotfiles/ghostty/config # edit a specific file +ghosttyconf --print-path # which file would be edited? +``` + +## 🎨 Themes with a live preview + +Editing `theme` opens a picker over all themes Ghostty ships plus your own. +Type to filter. The preview shows the highlighted theme's colors before you +commit to it, and a note tells you which of your own color settings override +the theme. + +

Theme picker with preview

+ +Fonts work the same way: `font-family` and its bold/italic variants list the +families reported by `ghostty +list-fonts`. + +## ⌨️ Key bindings + +Press `b` to open the key binding editor. It shows every binding that is +*active*: Ghostty's built-in defaults merged with the entries in your file. +Each one is marked `default`, `changed`, `custom` or `unbound`. + +

Key binding editor

+ +- **Change any binding**, including built-in ones. Give it another key or + another action. +- **Unbind** (`d`) a key, **restore** (`r`) Ghostty's default, or **add** + (`a`) a new binding. +- **Filter** (`/`) by key, action or description. Searching `cmd+d` finds + `super+d`. Press `c` to show only your changes. +- See the **documentation of every action** with its parameters, and every + key that is bound to it. + +The editor writes the smallest possible set of entries. Moving `new_split:right` +from `super+d` to `super+\` becomes + +```ini +keybind = super+d=unbind +keybind = super+\=new_split:right +``` + +A binding set back to Ghostty's default disappears from your file again. + +### 🔴 Recording shortcuts + +In the binding form, press `ctrl+r` and then the shortcut. ghosttyconf turns on +the kitty keyboard protocol while it records, so `⌘`/super combinations arrive +too. Several combinations in a row record a sequence such as `ctrl+a>n`. A +warning appears if the key already does something else. + +

Recording a key combination

+ +## 💾 Saving and reloading + +`ctrl+s` saves, and `c` shows what is about to change: + +

Unsaved changes

+ +Every save runs these steps: + +1. **Validate.** The new file is checked with `ghostty +validate-config`. If + Ghostty complains, you see its messages and can go back or save anyway. +2. **Check the disk.** If another program changed the file since it was + loaded, you are asked before anything is overwritten. +3. **Back up.** The first save of a session keeps the previous version as + `config.ghostty.bak`. +4. **Write atomically.** The file is written through a temporary file, so it + is never half-written. Symlinks are followed and permissions kept. +5. **Reload.** The running Ghostty reloads its configuration, just like + `⌘⇧,` / `ctrl+shift+,`. + +| Platform | How the reload works | +| --- | --- | +| macOS | Ghostty's AppleScript command `perform action "reload_config"` (needs `macos-applescript = true`, the default) | +| Linux | `SIGUSR2` to your Ghostty processes, which the GTK app handles as a reload | + +Pass `--no-reload` to only save. + +## 🧭 Keys + +| Key | Action | +| --- | --- | +| `↑` `↓` / `j` `k` | move | +| `←` `→` / `tab` | switch between categories and options | +| `enter` | edit the selected option | +| `space` | toggle a boolean / cycle a choice | +| `+` `-` | increase / decrease a number | +| `r` / `del` | reset to the default (removes the line) | +| `/` | search option names and documentation | +| `b` | key binding editor | +| `shift+↑` `shift+↓` | scroll the documentation | +| `u` / `ctrl+z` | undo | +| `c` | show unsaved changes | +| `p` | hide options for other platforms | +| `ctrl+s` | validate, save and reload | +| `?` | help | +| `q` | quit | + +The mouse works too: click to select, click again to edit, and scroll with the +wheel. The [user guide](docs/guide.md) lists the keys of every editor. + +## ⚙️ Command line + +```text +ghosttyconf [flags] [config-file] + + --config config file to edit (default: the one Ghostty loads) + --ghostty ghostty binary (default: $PATH, then /Applications) + --no-reload do not reload Ghostty after saving + --offline do not run ghostty; use the built-in option list + --print-path print the config file that would be edited and exit +``` + +## 🔧 How it works + +The list of options, their types, enum values and flags is generated from +Ghostty's source (`src/config/Config.zig`) and built into the binary. At +startup, ghosttyconf asks the installed Ghostty for its documentation and +defaults (`ghostty +show-config --default --docs`), so the text always matches +your version. Themes, fonts, actions and validation also come from the +`ghostty` command line. Without Ghostty (`--offline`), the built-in data is +used. + +## 📖 Documentation + +- [User guide](docs/guide.md): every editor, key bindings in depth, saving, + reloading, troubleshooting +- [Development](docs/development.md): project layout, the schema generator, + tests and screenshots diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..1403e4d --- /dev/null +++ b/docs/development.md @@ -0,0 +1,143 @@ +# Development + +ghosttyconf is written in Go with [Bubble Tea](https://github.com/charmbracelet/bubbletea) +and [Lip Gloss](https://github.com/charmbracelet/lipgloss). It has no other +runtime dependencies. Everything Ghostty-specific comes either from the +embedded schema or from the `ghostty` command line. + +## Building and testing + +```sh +make build # ./ghosttyconf +make install # go install +make test # go test ./... +make schema # regenerate the option schema for the installed Ghostty +make screenshots # regenerate docs/images (needs tmux and Ghostty) +``` + +The code builds on macOS, Linux and the BSDs. Automatic reload is implemented +for macOS and Linux. Other platforms only save. + +## Project layout + +| Path | Content | +| --- | --- | +| `main.go` | flags, startup, wiring | +| `internal/schema` | the option schema: kinds, categories, platform detection, value validation; `schema.json` is embedded | +| `internal/config` | the comment- and layout-preserving config file model, atomic saving | +| `internal/ghostty` | finding and running the `ghostty` binary (docs, themes, fonts, actions, validation), config paths, reload | +| `internal/keybind` | trigger parsing and normalization, the merged binding set, decoding of recorded keys | +| `internal/colors` | hex and X11 color names | +| `internal/ui` | the Bubble Tea application: browser, editors, pickers, key binding manager, dialogs | +| `tools/genschema` | generator for `internal/schema/schema.json` | +| `tools/termsvg` | renders captured terminal screens as SVG (for the screenshots) | +| `tools/screenshots.sh` | drives ghosttyconf in tmux and writes `docs/images/*.svg` | + +## The schema + +Ghostty's own documentation (`ghostty +show-config --default --docs`) contains +names, defaults and descriptions, but not the *types* of options. Those come +from Ghostty's source. `tools/genschema` reads `src/config/Config.zig` and: + +- maps Zig field types to editor kinds (bool, enum, flags, int, float, color, + metric, duration, padding, path, theme, font, keybind, palette, …); +- resolves enums, tagged unions and packed structs declared in the file to + their values and flags; +- uses `typeMap` for types from other files and `keyOverrides` for options + whose type alone isn't specific enough; +- adds documentation and defaults from `+show-config`; +- sorts every option into one of the categories in + `internal/schema/categories.go`, and detects platform-specific options from + their names and documentation. + +The result is embedded in the binary. At startup, the documentation and +defaults are refreshed from the installed Ghostty, so they always match the +user's version. If an option is missing from the embedded schema, it is still +editable, as a text value. + +### Updating for a new Ghostty release + +```sh +make schema # = go run ./tools/genschema +``` + +This detects the installed Ghostty version, downloads `src/config/Config.zig` +of that tag from GitHub, and rewrites `internal/schema/schema.json`. Offline, +or for unreleased versions: + +```sh +go run ./tools/genschema -zig path/to/Config.zig -docs docs.txt -version 1.4.0 +``` + +Afterwards, run `make test` and check the generator's warnings about unknown +types. Those types need an entry in `typeMap`. + +## The config file model + +`internal/config` parses the file into lines: entries (`key = value`), +comments and blank lines, each with its original text. A line that isn't +edited is written back byte for byte. + +- `Set`/`SetAll` compute a minimal edit script (longest common subsequence) + between the old and new values of a key. Unchanged entries keep their place + and formatting, changed ones are rewritten in place, and new ones are + inserted after the last entry of the same key. +- `Save` writes a temporary file next to the target (resolving symlinks), + preserves permissions, optionally writes `.bak`, and renames the + temporary file over the target. +- `ChangedOnDisk` compares the modification time, so a file changed by + another program is never overwritten silently. + +## Key bindings + +`internal/keybind` mirrors Ghostty's own parser (`src/input/Binding.zig`): + +- `Split` separates trigger and action the way Ghostty does (`=` followed by + `=` or `+` belongs to the trigger, so `super+==…` works). +- `ParseTrigger` and `Normalize` understand modifier aliases (`cmd`, `opt`, + `control`), key names from `key.zig`, legacy names (`grave_accent`, `up`), + sequences (`a>b`) and prefixes (`global:`, `all:`, `unconsumed:`, + `performable:`). The merged view uses the normalized form, so different + spellings of the same trigger are recognized as one. +- `Set` combines Ghostty's default bindings with the user's entries (including + `clear`, `unbind` and `chain=`) into the *effective* bindings and their + sources. `Change`, `Unbind` and `Restore` turn edits in the UI into the + smallest list of config entries. + +### Recording + +While recording, the UI sends `CSI > 9 u` (push the kitty keyboard protocol +with "report all keys as escape codes") and `CSI ? u` (query). Ghostty then +reports every key as `CSI code ; mods u`, including super combinations. +Bubble Tea v1 doesn't know these sequences and passes them on as an +unexported message type, which `ui/term.go` reads by reflection. +`keybind.DecodeCSI` turns them into triggers. The protocol is popped again +when recording ends and when the program exits. + +This depends on a Bubble Tea internal. `TestRawSequenceFromBubbleTea` in +`internal/ui/term_test.go` feeds a real sequence through Bubble Tea's input +parser and fails if an upgrade changes how such sequences arrive. + +## Reloading + +| File | Mechanism | +| --- | --- | +| `reload_darwin.go` | `osascript`: `perform action "reload_config"` on Ghostty's first terminal, addressed by bundle id, only if Ghostty is running; translates AppleScript errors (-1743 permission, -1708 scripting disabled) into readable messages | +| `reload_linux.go` | `SIGUSR2` to every `ghostty` process of the user found in `/proc`, skipping CLI invocations (`ghostty +…`), which would be terminated by the signal | +| `reload_other.go` | not supported; the status line tells the user to reload manually | + +## Screenshots + +The images in `docs/images` are generated, not drawn: + +```sh +make screenshots # or: THEME="TokyoNight" ./tools/screenshots.sh +``` + +The script builds ghosttyconf and `tools/termsvg`, then runs ghosttyconf in a +detached tmux session (144×34) with a demo config and a temporary `$HOME`. It +sends key presses (kitty sequences for recorded keys) and captures each +screen with `tmux capture-pane -e`. `termsvg` renders the captures as SVG, +taking colors from a Ghostty theme file. Box drawing and block characters +are drawn as shapes so borders connect, and text runs are pinned to the cell +grid, so the images look the same with any monospace font. diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 0000000..8eb5f9a --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,301 @@ +# ghosttyconf user guide + +This guide covers everything ghosttyconf can do. For a quick overview, see +the [README](../README.md). + +- [Which file is edited](#which-file-is-edited) +- [The screen](#the-screen) +- [Finding options](#finding-options) +- [Editing values](#editing-values) +- [Repeatable options](#repeatable-options) +- [Themes, fonts and the palette](#themes-fonts-and-the-palette) +- [Key bindings](#key-bindings) +- [Saving](#saving) +- [Reloading Ghostty](#reloading-ghostty) +- [Troubleshooting](#troubleshooting) + +## Which file is edited + +Ghostty reads several config files at startup, one after another, and later +files override earlier ones: + +1. `$XDG_CONFIG_HOME/ghostty/config`, then `…/config.ghostty` + (`$XDG_CONFIG_HOME` defaults to `~/.config`) +2. on macOS only: `~/Library/Application Support/com.mitchellh.ghostty/config`, + then `…/config.ghostty` + +Without an argument, ghosttyconf opens the **last existing file in this list**, +because that file has the final say. If none exists yet, it creates +`config.ghostty` in the Application Support folder on macOS, or in +`~/.config/ghostty` elsewhere. The file is only written when you save. + +```sh +ghosttyconf --print-path # show the choice without starting the editor +ghosttyconf path/to/config # edit another file +``` + +Files pulled in with `config-file = …` are not opened automatically. To edit +one, pass its path. + +## The screen + +![Main screen](images/main.svg) + +| Area | Content | +| --- | --- | +| Top line | the edited file, Ghostty's version and the number of options | +| **Categories** (left) | `Set in Config` (everything in your file), `All Options`, then 19 topics such as Fonts, Window or Key bindings | +| **Options** (right) | name, current value and a marker for each option | +| **Documentation** (bottom) | type, default, current value, platform and Ghostty's documentation of the selected option | +| Status line | unsaved changes, results of saving and reloading | + +The markers in front of an option name mean: + +| Marker | Meaning | +| --- | --- | +| ● green | set in your config file | +| ● yellow | changed, not saved yet | +| ○ yellow | removed, not saved yet | +| `✗ invalid` (red) | the value in your file is not valid for this option | + +Keys in your file that Ghostty doesn't know (typos, options of a newer or +older Ghostty version) appear under **Set in Config** with a red name and an +explanation. They are kept as they are until you remove them with `r`. + +`←`/`→` or `tab` switch between the category and option lists. `shift+↑`/`↓` +(or `ctrl+u`/`ctrl+d`) scroll the documentation. Mouse clicks and the wheel work +in every list. + +## Finding options + +- **Search** with `/` (or `ctrl+f`). It searches all options: name matches + come first, then matches in the documentation. Several words must all match. + `enter` or `↓` jumps into the results, and `esc` clears the search. +- **Platform filter** with `p`. Hides options that only work on the other + operating system (`macos-*` on Linux, GTK options on macOS). +- **Set in Config** lists exactly what your file contains, in file order. + +## Editing values + +Press `enter` on an option. Booleans don't open an editor, they toggle +directly. With `space` you can toggle a boolean or step through a choice +without opening anything, and `+`/`-` change numbers in place. + +| Option type | Editor | Example | +| --- | --- | --- | +| boolean | toggles on `enter`/`space` | `font-thicken` | +| choice | list of allowed values | `cursor-style`, `macos-titlebar-style` | +| flags | checklist: `space` toggles, `a` all, `n` none, `d` defaults | `shell-integration-features` | +| number | text field, `↑`/`↓` step the value | `font-size`, `background-opacity` | +| metric | number or percentage | `adjust-cell-height` | +| color | text field with live swatch; hex or X11 names | `cursor-color`, `background` | +| padding, duration, text, path | text field with format hint | `window-padding-x`, `resize-overlay-duration` | +| theme | theme picker | `theme` | +| font | font picker | `font-family` | +| palette | 256-color table | `palette` | +| key binding | key binding editor | `keybind` | + +Text fields check the value while you type (`✓ valid` / `✗ …`). An empty field +resets the option to its default. + +**Reset** with `r` or `del` removes the option from your file, so Ghostty's +default applies again. **Undo** with `u` or `ctrl+z` goes back one change at a +time. `c` shows a diff of everything not saved yet. + +## Repeatable options + +Options that can appear several times, such as `font-family`, `env`, +`config-file` or `font-feature`, open a list editor: + +| Key | Action | +| --- | --- | +| `a` | add an entry | +| `enter` / `e` | edit the entry (on a built-in default: copy it into your file first) | +| `r` | edit the entry as raw text | +| `d` | delete the entry | +| `J` / `K` | move the entry down / up | +| `v` | show or hide Ghostty's built-in defaults | +| `esc` | done | + +The order matters for Ghostty (for example, the first `font-family` is the +primary font), and the list editor keeps it. + +## Themes, fonts and the palette + +![Theme picker](images/picker.svg) + +**Themes.** The picker lists all themes from `ghostty +list-themes`, including +your own in `~/.config/ghostty/themes`. Type to filter, and `tab` completes the +highlighted name. The preview below the list shows the highlighted theme's +prompt, file listing, syntax colors and palette. If your config sets colors +itself (`background`, `cursor-color`, `palette`, …), a note lists them, because +they take precedence over any theme. You can also type a value the list doesn't +know, such as `light:Catppuccin Latte,dark:Catppuccin Mocha`. + +**Fonts.** `font-family`, `font-family-bold` and the other font options offer +the families from `ghostty +list-fonts`. + +**Palette.** The palette editor shows all 256 colors. Colors you haven't set +come from your theme, or from Ghostty's defaults. `enter` edits a color, and +`d` resets it. + +## Key bindings + +Open the key binding editor with `b`, or with `enter` on the `keybind` +option. + +![Key binding editor](images/keybinds.svg) + +### What you see + +The table contains every binding that is in effect: Ghostty's built-in +bindings with the entries of your file applied on top. The **Source** column +tells where a binding comes from: + +| Source | Meaning | +| --- | --- | +| `default` | built into Ghostty, untouched | +| `changed` | a built-in key that you gave a different action | +| `custom` | a key that only your config binds | +| `unbound` | a built-in key that you switched off (`…=unbind`) | + +The panel on the right documents the selected action, including its parameters, +and lists every key that triggers it. + +| Key | Action | +| --- | --- | +| `enter` | change the selected binding | +| `a` | add a binding | +| `d` | unbind: the key no longer does anything in Ghostty | +| `r` | restore Ghostty's default for this key | +| `/` | filter by key, action or description | +| `c` | show only your changes | +| `s` | sort by action or by key | +| `R` | edit the raw `keybind` entries in a list editor | +| `esc` | done | + +Filtering understands the spellings Ghostty accepts. `cmd+d`, `command+d` and +`super+d` find the same binding, and an exact key match is listed first. + +### The binding form + +The form has two fields, **Trigger** and **Action**. `tab` moves between them. + +- **Trigger**: a key with modifiers (`super+shift+t`), a sequence + (`ctrl+a>n`), and optionally a prefix such as `global:`, `all:`, + `unconsumed:` or `performable:`. +- **Action**: type to search all actions. `↑`/`↓` choose, and `tab` completes. + The list shows a short description, and the documentation below explains the + parameters (`new_split:right`, `resize_split:up,10`, …). + +While you type, the form warns about unknown keys and actions, and about +triggers that already do something else. Saving a conflicting trigger replaces +the other binding. + +### Recording a shortcut + +![Recording a shortcut](images/record.svg) + +Press `ctrl+r` in the form and then the shortcut. Pressing several combinations +records a sequence. `backspace` removes the last key, `enter` finishes and +`esc` cancels. + +While recording, ghosttyconf asks the terminal for the kitty keyboard protocol. +Ghostty supports it, so it reports `⌘`/super and keys that normally send +nothing. In terminals without the protocol, a warning says that super +combinations may not arrive. + +Shortcuts that Ghostty or macOS handle themselves never reach the program, so +they can't be recorded. This includes any shortcut Ghostty currently has +bound, such as `super+t` for a new tab. Type those into the field instead. + +### What ends up in the file + +The editor keeps your file minimal and readable: + +- Changing an entry of your own rewrites that line in place. +- Moving a built-in binding to another key unbinds the old key and adds the + new one: + + ```ini + keybind = super+d=unbind + keybind = super+\=new_split:right + ``` + +- A binding you set back to Ghostty's default is removed from the file. +- `keybind = clear` (removes all built-in bindings), `chain=` entries and + prefixes are understood and preserved. + +## Saving + +`ctrl+s` saves. Quitting with unsaved changes asks whether to save, discard +or go back. + +1. **Validation.** The new config is written to a temporary file and checked + with `ghostty +validate-config`. Problems are listed with their messages, + and you can go back to editing or save anyway. Ghostty itself ignores + invalid lines and uses the defaults for them. +2. **Changes on disk.** If the file was modified by another program after + ghosttyconf loaded it, you are asked before overwriting it. +3. **Backup.** The first save of every session copies the previous file to + `.bak` next to it. +4. **Atomic write.** The file is replaced through a temporary file in the same + directory, so it is always either the old or the new version. If the config + is a symlink (for example into a dotfiles repository), the target is + written and the link stays. File permissions are kept. + +Everything you didn't touch stays exactly as it was: comments, blank lines, +the order of lines and their formatting. A changed value is rewritten on its +own line. New entries of a repeatable option go after its existing ones, and +new options go after the last entry in the file, so trailing comments stay at +the end. + +## Reloading Ghostty + +After a successful save, ghosttyconf asks the running Ghostty to reload its +configuration, the same as `⌘⇧,` on macOS or `ctrl+shift+,` on Linux. The +status line reports the result. + +**macOS.** The reload uses Ghostty's AppleScript support: + +```applescript +tell application id "com.mitchellh.ghostty" to perform action "reload_config" on first terminal +``` + +- This needs `macos-applescript = true`, which is the default. +- Inside Ghostty, this works without any prompt. In another terminal app, macOS + asks once whether that app may control Ghostty (System Settings → Privacy & + Security → Automation). +- Ghostty is never started just to reload it. + +**Linux.** ghosttyconf sends `SIGUSR2` to your Ghostty processes, which the GTK +app handles as "reload config". Short-lived CLI calls such as +`ghostty +list-themes` are skipped. + +A few options don't change open windows. For example, `macos-titlebar-style` +only applies to new windows, and `language` needs a full restart of Ghostty. +The documentation of an option mentions this where it matters. + +Use `--no-reload` to only save. The status line then reminds you of the +shortcut. + +## Troubleshooting + +**"Ghostty refused the AppleScript command"**: your config sets +`macos-applescript = false`. Reload manually, or allow AppleScript. + +**"not allowed to control Ghostty"**: the terminal you run ghosttyconf in +has no Automation permission for Ghostty. Enable it in System Settings → +Privacy & Security → Automation, or run ghosttyconf inside Ghostty. + +**Options or documentation look outdated**: ghosttyconf takes the +documentation from the installed Ghostty. If Ghostty can't be found, pass +`--ghostty /path/to/ghostty`. The option list itself is built in. After a new +Ghostty release, see [Development](development.md#updating-for-a-new-ghostty-release). + +**A key combination can't be recorded**: Ghostty or macOS handled it before +ghosttyconf could see it. Type it into the trigger field. + +**Validation fails for an entry you didn't touch**: the problem was already +in your file. ghosttyconf marks invalid values in red. Fix or reset them, or +save anyway. diff --git a/docs/images/changes.svg b/docs/images/changes.svg new file mode 100644 index 0000000..080d2a7 --- /dev/null +++ b/docs/images/changes.svg @@ -0,0 +1,139 @@ + + + + + + +ghosttyconf + + + + + + + + + +Ghostty Config Editor +~/.config/ghostty/config.ghostty +Ghostty 1.3.1 · 201 options +Categories +Set in Config (15) +▸ +Set in Config +15 +● +theme +Catppuccin Mocha +All Options +201 +● +font-family +JetBrains Mono +● +font-size +14.5 +Fonts +21 +● +font-thicken +true +Font Metrics +11 +● +cursor-style +bar +Colors & Theme +18 +● +cursor-color +#f5e0dc +Background +8 +● +selection-background +#585b70 +Cursor +7 +● +window-padding-x +Unsaved changes (3) +Window +29 +● +window-padding-y +Tabs & Splits +6 +● +window-save-state +font-size +Mouse & Selection +12 +● +background-opacity +- font-size = 14 +Clipboard +7 +▸ +● +macos-titlebar-style ++ font-size = 14.5 +Keyboard +4 +● +shell-integration-fe +macos-titlebar-style +Shell & Commands +15 +● +copy-on-select +- macos-titlebar-style = tabs +Scrolling +4 +● +keybind ++ macos-titlebar-style = hidden +Notifications & Bell +9 +keybind +Quick Terminal +9 +Documentation · 0% · s +- keybind = super+d=new_split:right +Shaders +2 +macos-titlebar-style ++ keybind = super+d=unbind +macOS +18 ++ keybind = super+\=new_split:right +Linux & GTK +17 +Type +one of native +Config Files +2 +Default +transparent +esc +Close +Advanced +2 +Value +hidden +● set +Platform +macOS only +Category +macOS +The style of the macOS titlebar. Available values are: "native", "transparent", "tabs", and "hidden". +The "native" style uses the native macOS titlebar with zero customization. The titlebar will match your window +theme (see +window-theme +). +● 3 unsaved +↑↓ move · enter edit · space toggle · +/- adjust · r reset · u undo · / search · ctrl+s save · ? help · q quit + + + + diff --git a/docs/images/keybinds.svg b/docs/images/keybinds.svg new file mode 100644 index 0000000..55f8ba9 --- /dev/null +++ b/docs/images/keybinds.svg @@ -0,0 +1,123 @@ + + + + + + +ghosttyconf + + + + + + +Ghostty Config Editor +~/.config/ghostty/config.ghostty +Ghostty 1.3.1 · 201 options +Edit keybind +Documentation +Type +key binding (trigger=action) +new_split +93 active · +0 changed +· +2 custom +· +2 unbound +showing all, sorted by action +Create a new split in the specified direction. +/ +split +Valid arguments: +Key +Action +Source +super+w +close_surface +default +• +right +, +down +, +left +, +up +super+alt+w +close_tab:this +default +super+shift+w +close_window +default +Creates a new split in the corresponding direction. +super+ctrl+= +equalize_splits +default +super+alt+arrow_down +goto_split:down +default +• +auto +super+alt+arrow_left +goto_split:left +default +super+] +goto_split:next +default +Creates a new split along the larger direction. +super+[ +goto_split:previous +default +For example, if the parent split is currently wider than i… +super+alt+arrow_right +goto_split:right +default +then a left-right split would be created, and vice versa. +super+alt+arrow_up +goto_split:up +default +super+shift+d +new_split:down +default +Keys bound to new_split: +▸ +super+\ +new_split:right +custom +super+d +new_split:right                         +unbound +• +super+shift+d +→ +new_split:down +(default) +super+ctrl+arrow_down +resize_split:down,10 +default +• +super+\ +→ +new_split:right +(custom) +super+ctrl+arrow_left +resize_split:left,10 +default +super+ctrl+arrow_right +resize_split:right,10 +default +super+ctrl+arrow_up +resize_split:up,10 +default +super+shift+enter +toggle_split_zoom +default +Added in your config. +new_split +Create a new split in the specified direction. +enter change · a add · d unbind · r restore · / filter · c changes only · s sort · R raw · esc done · shift+↑↓ scroll docs + + + + diff --git a/docs/images/main.svg b/docs/images/main.svg new file mode 100644 index 0000000..62dd846 --- /dev/null +++ b/docs/images/main.svg @@ -0,0 +1,131 @@ + + + + + + +ghosttyconf + + + + + + + + +Ghostty Config Editor +~/.config/ghostty/config.ghostty +Ghostty 1.3.1 · 201 options +Categories +Set in Config (15) +▸ +Set in Config +15 +▸ +● +theme +Catppuccin Mocha +All Options +201 +● +font-family +JetBrains Mono +● +font-size +14 +Fonts +21 +● +font-thicken +true +Font Metrics +11 +● +cursor-style +bar +Colors & Theme +18 +● +cursor-color +#f5e0dc +Background +8 +● +selection-background +#585b70 +Cursor +7 +● +window-padding-x +12 +Window +29 +● +window-padding-y +8 +Tabs & Splits +6 +● +window-save-state +always +Mouse & Selection +12 +● +background-opacity +0.95 +Clipboard +7 +● +macos-titlebar-style +tabs +Keyboard +4 +● +shell-integration-features +no-cursor,sudo,title +Shell & Commands +15 +● +copy-on-select +clipboard +Scrolling +4 +● +keybind +1 custom +· +1 unbound +Notifications & Bell +9 +Quick Terminal +9 +Documentation · 0% · shift+↑↓ scroll +Shaders +2 +theme +macOS +18 +Linux & GTK +17 +Type +theme name (or light:NAME,dark:NAME) +Config Files +2 +Default +(unset) +Advanced +2 +Value +Catppuccin Mocha +● set in config +Category +Colors & Theme +A theme to use. This can be a built-in theme name, a custom theme name, or an absolute path to a custom theme +file. Ghostty also supports specifying a different theme to use for light and dark mode. Each option is documented +below. +If the theme is an absolute pathname, Ghostty will attempt to load that file as a theme. If that file does not +↑↓ move · enter edit · space toggle · +/- adjust · r reset · u undo · / search · ctrl+s save · ? help · q quit + + + + diff --git a/docs/images/picker.svg b/docs/images/picker.svg new file mode 100644 index 0000000..48b2969 --- /dev/null +++ b/docs/images/picker.svg @@ -0,0 +1,125 @@ + + + + + + +ghosttyconf + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Ghostty Config Editor +~/.config/ghostty/config.ghostty +Ghostty 1.3.1 · 201 options +Edit theme +Documentation · 0% · shift+↑↓ scroll +Type +theme name (or light:NAME,dark:NAME) +theme +Default +(unset) +Current +Catppuccin Mocha +A theme to use. This can be a built-in theme name, a custom +theme name, or an absolute path to a custom theme file. +Search: +tokyo +Ghostty also supports specifying a different theme to use for +Your config also sets cursor-color, selection-background, which take +light and dark mode. Each option is documented below. +precedence over the theme. +5 of 463 +If the theme is an absolute pathname, Ghostty will attempt to +TokyoNight +load that file as a theme. If that file does not exist or is +▸ +TokyoNight Day +inaccessible, an error will be logged and no other +TokyoNight Moon +directories will be searched. +TokyoNight Night +TokyoNight Storm +If the theme is not an absolute pathname, two different +directories will be searched for a file name that matches the +theme. This is case sensitive on systems with case-sensitive +filesystems. It is an error for a theme name to include path +separators unless it is an absolute pathname. +The first directory is the +themes +subdirectory of your +Ghostty configuration directory. This is +$XDG_CONFIG_HOME/ghostty/themes +or +~/.config/ghostty/themes +. +user@host +~/src +$ ls --color +docs +build.sh +error.log +notes.md +The second directory is the +themes +subdirectory of the +import +os +# comment +dimmed +Ghostty resources directory. Ghostty ships with a multitude +of themes that will be installed into this directory. On +macOS, this list is in the +Ghostty.app/Contents/Resources/ghostty/themes +directory. On +Linux, this list is in the +share/ghostty/themes +directory +type to filter · ↑↓ choose · tab complete · enter select · esc cancel · shift+↑↓ scroll docs + + + + diff --git a/docs/images/record.svg b/docs/images/record.svg new file mode 100644 index 0000000..30801fe --- /dev/null +++ b/docs/images/record.svg @@ -0,0 +1,89 @@ + + + + + + +ghosttyconf + + + + + + + +Ghostty Config Editor +~/.config/ghostty/config.ghostty +Ghostty 1.3.1 · 201 options +Edit keybind +Documentation · 0% · shift+↑↓ scroll +Type +key binding (trigger=action) +keybind +Change super+d +(built-in binding) +Key bindings. The format is +trigger=action +. Duplicate +triggers will overwrite previously set values. The list of +● REC +Press the key combination now. +actions is available in the documentation or using the +ghostty +list-actions +command. +Trigger › +super+\ +Trigger: ++ +-separated list of keys and modifiers. Example: +enter finish · esc cancel · backspace remove last key +ctrl+a +, +ctrl+shift+b +, +up +. +Press several combinations in a row to record a sequence (ctrl+a>n). +If the key is a single Unicode codepoint, the trigger will +Keys that Ghostty or macOS already use (e.g. a current Ghostty +match any presses that produce that codepoint. These are +shortcut) never reach this program: type those instead. +impacted by keyboard layouts. For example, +a +will match the +a +key on a QWERTY keyboard, but will match the +q +key on a +AZERTY keyboard (assuming US physical layout). +For Unicode codepoints, matching is done by comparing the set +of modifiers with the unmodified codepoint. The unmodified +codepoint is sometimes called an "unshifted character" in +other software, but all modifiers are considered, not only +shift. For example, +ctrl+a +will match +a +but not +ctrl+shift+a +(which is +A +on a US keyboard). +Further, codepoint matching is case-insensitive and the +unmodified codepoint is always case folded for comparison. As +a result, +ctrl+A +configured will match when +ctrl+a +is +pressed. Note that this means some key combinations are +impossible depending on keyboard layout. For example, +ctrl+_ +is impossible on a US keyboard because +_ +is +recording: press keys · enter finish · esc cancel · shift+↑↓ scroll docs + + + + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b0bf2dd --- /dev/null +++ b/go.mod @@ -0,0 +1,32 @@ +module ghosttyconf + +go 1.24.2 + +require ( + github.com/charmbracelet/bubbles v1.0.0 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.0 + github.com/charmbracelet/x/ansi v0.11.9 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/colorprofile v0.4.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.27 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..31fb037 --- /dev/null +++ b/go.sum @@ -0,0 +1,50 @@ +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc= +github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= +github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= +github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.27 h1:Feg/Oou5zI/wnpgDF6omIU0OokC9GxLC/WRknhVlIR0= +github.com/mattn/go-runewidth v0.0.27/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/internal/colors/colors.go b/internal/colors/colors.go new file mode 100644 index 0000000..048d8e4 --- /dev/null +++ b/internal/colors/colors.go @@ -0,0 +1,117 @@ +// Package colors parses colors the way Ghostty does: hex values (with or +// without a leading '#', 3 or 6 digits) and X11 color names. +package colors + +import ( + "bufio" + _ "embed" + "fmt" + "strconv" + "strings" + "sync" +) + +// rgb.txt is copied from Ghostty's src/terminal/res/rgb.txt. +// +//go:embed rgb.txt +var rgbTxt string + +var ( + namesOnce sync.Once + names map[string]string // lowercase name -> "#rrggbb" +) + +func loadNames() { + names = make(map[string]string, 800) + sc := bufio.NewScanner(strings.NewReader(rgbTxt)) + for sc.Scan() { + line := sc.Text() + if strings.HasPrefix(line, "!") || strings.TrimSpace(line) == "" { + continue + } + fields := strings.Fields(line) + if len(fields) < 4 { + continue + } + r, err1 := strconv.Atoi(fields[0]) + g, err2 := strconv.Atoi(fields[1]) + b, err3 := strconv.Atoi(fields[2]) + if err1 != nil || err2 != nil || err3 != nil { + continue + } + name := strings.ToLower(strings.Join(fields[3:], " ")) + names[name] = fmt.Sprintf("#%02x%02x%02x", r, g, b) + } +} + +// Hex converts a Ghostty color value to "#rrggbb". It reports false if the +// value is not a valid color. +func Hex(value string) (string, bool) { + v := strings.TrimSpace(unquote(value)) + if v == "" { + return "", false + } + namesOnce.Do(loadNames) + if h, ok := names[strings.ToLower(v)]; ok { + return h, true + } + h := strings.TrimPrefix(v, "#") + if !isHex(h) { + return "", false + } + switch len(h) { + case 3: + return strings.ToLower("#" + string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})), true + case 6: + return strings.ToLower("#" + h), true + } + return "", false +} + +// Valid reports whether value is a color Ghostty accepts. +func Valid(value string) bool { + _, ok := Hex(value) + return ok +} + +// RGB returns the components of a color value. +func RGB(value string) (r, g, b uint8, ok bool) { + h, ok := Hex(value) + if !ok { + return 0, 0, 0, false + } + n, err := strconv.ParseUint(h[1:], 16, 32) + if err != nil { + return 0, 0, 0, false + } + return uint8(n >> 16), uint8(n >> 8), uint8(n), true +} + +// Luminance returns the relative brightness in the range 0..1, used to pick +// a readable text color on top of a swatch. +func Luminance(value string) float64 { + r, g, b, ok := RGB(value) + if !ok { + return 0 + } + return (0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 255 +} + +func isHex(s string) bool { + if s == "" { + return false + } + for _, c := range s { + if !strings.ContainsRune("0123456789abcdefABCDEF", c) { + return false + } + } + return true +} + +func unquote(s string) string { + if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' { + return s[1 : len(s)-1] + } + return s +} diff --git a/internal/colors/rgb.txt b/internal/colors/rgb.txt new file mode 100644 index 0000000..7096643 --- /dev/null +++ b/internal/colors/rgb.txt @@ -0,0 +1,782 @@ +255 250 250 snow +248 248 255 ghost white +248 248 255 GhostWhite +245 245 245 white smoke +245 245 245 WhiteSmoke +220 220 220 gainsboro +255 250 240 floral white +255 250 240 FloralWhite +253 245 230 old lace +253 245 230 OldLace +250 240 230 linen +250 235 215 antique white +250 235 215 AntiqueWhite +255 239 213 papaya whip +255 239 213 PapayaWhip +255 235 205 blanched almond +255 235 205 BlanchedAlmond +255 228 196 bisque +255 218 185 peach puff +255 218 185 PeachPuff +255 222 173 navajo white +255 222 173 NavajoWhite +255 228 181 moccasin +255 248 220 cornsilk +255 255 240 ivory +255 250 205 lemon chiffon +255 250 205 LemonChiffon +255 245 238 seashell +240 255 240 honeydew +245 255 250 mint cream +245 255 250 MintCream +240 255 255 azure +240 248 255 alice blue +240 248 255 AliceBlue +230 230 250 lavender +255 240 245 lavender blush +255 240 245 LavenderBlush +255 228 225 misty rose +255 228 225 MistyRose +255 255 255 white + 0 0 0 black + 47 79 79 dark slate gray + 47 79 79 DarkSlateGray + 47 79 79 dark slate grey + 47 79 79 DarkSlateGrey +105 105 105 dim gray +105 105 105 DimGray +105 105 105 dim grey +105 105 105 DimGrey +112 128 144 slate gray +112 128 144 SlateGray +112 128 144 slate grey +112 128 144 SlateGrey +119 136 153 light slate gray +119 136 153 LightSlateGray +119 136 153 light slate grey +119 136 153 LightSlateGrey +190 190 190 gray +190 190 190 grey +190 190 190 x11 gray +190 190 190 X11Gray +190 190 190 x11 grey +190 190 190 X11Grey +128 128 128 web gray +128 128 128 WebGray +128 128 128 web grey +128 128 128 WebGrey +211 211 211 light grey +211 211 211 LightGrey +211 211 211 light gray +211 211 211 LightGray + 25 25 112 midnight blue + 25 25 112 MidnightBlue + 0 0 128 navy + 0 0 128 navy blue + 0 0 128 NavyBlue +100 149 237 cornflower blue +100 149 237 CornflowerBlue + 72 61 139 dark slate blue + 72 61 139 DarkSlateBlue +106 90 205 slate blue +106 90 205 SlateBlue +123 104 238 medium slate blue +123 104 238 MediumSlateBlue +132 112 255 light slate blue +132 112 255 LightSlateBlue + 0 0 205 medium blue + 0 0 205 MediumBlue + 65 105 225 royal blue + 65 105 225 RoyalBlue + 0 0 255 blue + 30 144 255 dodger blue + 30 144 255 DodgerBlue + 0 191 255 deep sky blue + 0 191 255 DeepSkyBlue +135 206 235 sky blue +135 206 235 SkyBlue +135 206 250 light sky blue +135 206 250 LightSkyBlue + 70 130 180 steel blue + 70 130 180 SteelBlue +176 196 222 light steel blue +176 196 222 LightSteelBlue +173 216 230 light blue +173 216 230 LightBlue +176 224 230 powder blue +176 224 230 PowderBlue +175 238 238 pale turquoise +175 238 238 PaleTurquoise + 0 206 209 dark turquoise + 0 206 209 DarkTurquoise + 72 209 204 medium turquoise + 72 209 204 MediumTurquoise + 64 224 208 turquoise + 0 255 255 cyan + 0 255 255 aqua +224 255 255 light cyan +224 255 255 LightCyan + 95 158 160 cadet blue + 95 158 160 CadetBlue +102 205 170 medium aquamarine +102 205 170 MediumAquamarine +127 255 212 aquamarine + 0 100 0 dark green + 0 100 0 DarkGreen + 85 107 47 dark olive green + 85 107 47 DarkOliveGreen +143 188 143 dark sea green +143 188 143 DarkSeaGreen + 46 139 87 sea green + 46 139 87 SeaGreen + 60 179 113 medium sea green + 60 179 113 MediumSeaGreen + 32 178 170 light sea green + 32 178 170 LightSeaGreen +152 251 152 pale green +152 251 152 PaleGreen + 0 255 127 spring green + 0 255 127 SpringGreen +124 252 0 lawn green +124 252 0 LawnGreen + 0 255 0 green + 0 255 0 lime + 0 255 0 x11 green + 0 255 0 X11Green + 0 128 0 web green + 0 128 0 WebGreen +127 255 0 chartreuse + 0 250 154 medium spring green + 0 250 154 MediumSpringGreen +173 255 47 green yellow +173 255 47 GreenYellow + 50 205 50 lime green + 50 205 50 LimeGreen +154 205 50 yellow green +154 205 50 YellowGreen + 34 139 34 forest green + 34 139 34 ForestGreen +107 142 35 olive drab +107 142 35 OliveDrab +189 183 107 dark khaki +189 183 107 DarkKhaki +240 230 140 khaki +238 232 170 pale goldenrod +238 232 170 PaleGoldenrod +250 250 210 light goldenrod yellow +250 250 210 LightGoldenrodYellow +255 255 224 light yellow +255 255 224 LightYellow +255 255 0 yellow +255 215 0 gold +238 221 130 light goldenrod +238 221 130 LightGoldenrod +218 165 32 goldenrod +184 134 11 dark goldenrod +184 134 11 DarkGoldenrod +188 143 143 rosy brown +188 143 143 RosyBrown +205 92 92 indian red +205 92 92 IndianRed +139 69 19 saddle brown +139 69 19 SaddleBrown +160 82 45 sienna +205 133 63 peru +222 184 135 burlywood +245 245 220 beige +245 222 179 wheat +244 164 96 sandy brown +244 164 96 SandyBrown +210 180 140 tan +210 105 30 chocolate +178 34 34 firebrick +165 42 42 brown +233 150 122 dark salmon +233 150 122 DarkSalmon +250 128 114 salmon +255 160 122 light salmon +255 160 122 LightSalmon +255 165 0 orange +255 140 0 dark orange +255 140 0 DarkOrange +255 127 80 coral +240 128 128 light coral +240 128 128 LightCoral +255 99 71 tomato +255 69 0 orange red +255 69 0 OrangeRed +255 0 0 red +255 105 180 hot pink +255 105 180 HotPink +255 20 147 deep pink +255 20 147 DeepPink +255 192 203 pink +255 182 193 light pink +255 182 193 LightPink +219 112 147 pale violet red +219 112 147 PaleVioletRed +176 48 96 maroon +176 48 96 x11 maroon +176 48 96 X11Maroon +128 0 0 web maroon +128 0 0 WebMaroon +199 21 133 medium violet red +199 21 133 MediumVioletRed +208 32 144 violet red +208 32 144 VioletRed +255 0 255 magenta +255 0 255 fuchsia +238 130 238 violet +221 160 221 plum +218 112 214 orchid +186 85 211 medium orchid +186 85 211 MediumOrchid +153 50 204 dark orchid +153 50 204 DarkOrchid +148 0 211 dark violet +148 0 211 DarkViolet +138 43 226 blue violet +138 43 226 BlueViolet +160 32 240 purple +160 32 240 x11 purple +160 32 240 X11Purple +128 0 128 web purple +128 0 128 WebPurple +147 112 219 medium purple +147 112 219 MediumPurple +216 191 216 thistle +255 250 250 snow1 +238 233 233 snow2 +205 201 201 snow3 +139 137 137 snow4 +255 245 238 seashell1 +238 229 222 seashell2 +205 197 191 seashell3 +139 134 130 seashell4 +255 239 219 AntiqueWhite1 +238 223 204 AntiqueWhite2 +205 192 176 AntiqueWhite3 +139 131 120 AntiqueWhite4 +255 228 196 bisque1 +238 213 183 bisque2 +205 183 158 bisque3 +139 125 107 bisque4 +255 218 185 PeachPuff1 +238 203 173 PeachPuff2 +205 175 149 PeachPuff3 +139 119 101 PeachPuff4 +255 222 173 NavajoWhite1 +238 207 161 NavajoWhite2 +205 179 139 NavajoWhite3 +139 121 94 NavajoWhite4 +255 250 205 LemonChiffon1 +238 233 191 LemonChiffon2 +205 201 165 LemonChiffon3 +139 137 112 LemonChiffon4 +255 248 220 cornsilk1 +238 232 205 cornsilk2 +205 200 177 cornsilk3 +139 136 120 cornsilk4 +255 255 240 ivory1 +238 238 224 ivory2 +205 205 193 ivory3 +139 139 131 ivory4 +240 255 240 honeydew1 +224 238 224 honeydew2 +193 205 193 honeydew3 +131 139 131 honeydew4 +255 240 245 LavenderBlush1 +238 224 229 LavenderBlush2 +205 193 197 LavenderBlush3 +139 131 134 LavenderBlush4 +255 228 225 MistyRose1 +238 213 210 MistyRose2 +205 183 181 MistyRose3 +139 125 123 MistyRose4 +240 255 255 azure1 +224 238 238 azure2 +193 205 205 azure3 +131 139 139 azure4 +131 111 255 SlateBlue1 +122 103 238 SlateBlue2 +105 89 205 SlateBlue3 + 71 60 139 SlateBlue4 + 72 118 255 RoyalBlue1 + 67 110 238 RoyalBlue2 + 58 95 205 RoyalBlue3 + 39 64 139 RoyalBlue4 + 0 0 255 blue1 + 0 0 238 blue2 + 0 0 205 blue3 + 0 0 139 blue4 + 30 144 255 DodgerBlue1 + 28 134 238 DodgerBlue2 + 24 116 205 DodgerBlue3 + 16 78 139 DodgerBlue4 + 99 184 255 SteelBlue1 + 92 172 238 SteelBlue2 + 79 148 205 SteelBlue3 + 54 100 139 SteelBlue4 + 0 191 255 DeepSkyBlue1 + 0 178 238 DeepSkyBlue2 + 0 154 205 DeepSkyBlue3 + 0 104 139 DeepSkyBlue4 +135 206 255 SkyBlue1 +126 192 238 SkyBlue2 +108 166 205 SkyBlue3 + 74 112 139 SkyBlue4 +176 226 255 LightSkyBlue1 +164 211 238 LightSkyBlue2 +141 182 205 LightSkyBlue3 + 96 123 139 LightSkyBlue4 +198 226 255 SlateGray1 +185 211 238 SlateGray2 +159 182 205 SlateGray3 +108 123 139 SlateGray4 +202 225 255 LightSteelBlue1 +188 210 238 LightSteelBlue2 +162 181 205 LightSteelBlue3 +110 123 139 LightSteelBlue4 +191 239 255 LightBlue1 +178 223 238 LightBlue2 +154 192 205 LightBlue3 +104 131 139 LightBlue4 +224 255 255 LightCyan1 +209 238 238 LightCyan2 +180 205 205 LightCyan3 +122 139 139 LightCyan4 +187 255 255 PaleTurquoise1 +174 238 238 PaleTurquoise2 +150 205 205 PaleTurquoise3 +102 139 139 PaleTurquoise4 +152 245 255 CadetBlue1 +142 229 238 CadetBlue2 +122 197 205 CadetBlue3 + 83 134 139 CadetBlue4 + 0 245 255 turquoise1 + 0 229 238 turquoise2 + 0 197 205 turquoise3 + 0 134 139 turquoise4 + 0 255 255 cyan1 + 0 238 238 cyan2 + 0 205 205 cyan3 + 0 139 139 cyan4 +151 255 255 DarkSlateGray1 +141 238 238 DarkSlateGray2 +121 205 205 DarkSlateGray3 + 82 139 139 DarkSlateGray4 +127 255 212 aquamarine1 +118 238 198 aquamarine2 +102 205 170 aquamarine3 + 69 139 116 aquamarine4 +193 255 193 DarkSeaGreen1 +180 238 180 DarkSeaGreen2 +155 205 155 DarkSeaGreen3 +105 139 105 DarkSeaGreen4 + 84 255 159 SeaGreen1 + 78 238 148 SeaGreen2 + 67 205 128 SeaGreen3 + 46 139 87 SeaGreen4 +154 255 154 PaleGreen1 +144 238 144 PaleGreen2 +124 205 124 PaleGreen3 + 84 139 84 PaleGreen4 + 0 255 127 SpringGreen1 + 0 238 118 SpringGreen2 + 0 205 102 SpringGreen3 + 0 139 69 SpringGreen4 + 0 255 0 green1 + 0 238 0 green2 + 0 205 0 green3 + 0 139 0 green4 +127 255 0 chartreuse1 +118 238 0 chartreuse2 +102 205 0 chartreuse3 + 69 139 0 chartreuse4 +192 255 62 OliveDrab1 +179 238 58 OliveDrab2 +154 205 50 OliveDrab3 +105 139 34 OliveDrab4 +202 255 112 DarkOliveGreen1 +188 238 104 DarkOliveGreen2 +162 205 90 DarkOliveGreen3 +110 139 61 DarkOliveGreen4 +255 246 143 khaki1 +238 230 133 khaki2 +205 198 115 khaki3 +139 134 78 khaki4 +255 236 139 LightGoldenrod1 +238 220 130 LightGoldenrod2 +205 190 112 LightGoldenrod3 +139 129 76 LightGoldenrod4 +255 255 224 LightYellow1 +238 238 209 LightYellow2 +205 205 180 LightYellow3 +139 139 122 LightYellow4 +255 255 0 yellow1 +238 238 0 yellow2 +205 205 0 yellow3 +139 139 0 yellow4 +255 215 0 gold1 +238 201 0 gold2 +205 173 0 gold3 +139 117 0 gold4 +255 193 37 goldenrod1 +238 180 34 goldenrod2 +205 155 29 goldenrod3 +139 105 20 goldenrod4 +255 185 15 DarkGoldenrod1 +238 173 14 DarkGoldenrod2 +205 149 12 DarkGoldenrod3 +139 101 8 DarkGoldenrod4 +255 193 193 RosyBrown1 +238 180 180 RosyBrown2 +205 155 155 RosyBrown3 +139 105 105 RosyBrown4 +255 106 106 IndianRed1 +238 99 99 IndianRed2 +205 85 85 IndianRed3 +139 58 58 IndianRed4 +255 130 71 sienna1 +238 121 66 sienna2 +205 104 57 sienna3 +139 71 38 sienna4 +255 211 155 burlywood1 +238 197 145 burlywood2 +205 170 125 burlywood3 +139 115 85 burlywood4 +255 231 186 wheat1 +238 216 174 wheat2 +205 186 150 wheat3 +139 126 102 wheat4 +255 165 79 tan1 +238 154 73 tan2 +205 133 63 tan3 +139 90 43 tan4 +255 127 36 chocolate1 +238 118 33 chocolate2 +205 102 29 chocolate3 +139 69 19 chocolate4 +255 48 48 firebrick1 +238 44 44 firebrick2 +205 38 38 firebrick3 +139 26 26 firebrick4 +255 64 64 brown1 +238 59 59 brown2 +205 51 51 brown3 +139 35 35 brown4 +255 140 105 salmon1 +238 130 98 salmon2 +205 112 84 salmon3 +139 76 57 salmon4 +255 160 122 LightSalmon1 +238 149 114 LightSalmon2 +205 129 98 LightSalmon3 +139 87 66 LightSalmon4 +255 165 0 orange1 +238 154 0 orange2 +205 133 0 orange3 +139 90 0 orange4 +255 127 0 DarkOrange1 +238 118 0 DarkOrange2 +205 102 0 DarkOrange3 +139 69 0 DarkOrange4 +255 114 86 coral1 +238 106 80 coral2 +205 91 69 coral3 +139 62 47 coral4 +255 99 71 tomato1 +238 92 66 tomato2 +205 79 57 tomato3 +139 54 38 tomato4 +255 69 0 OrangeRed1 +238 64 0 OrangeRed2 +205 55 0 OrangeRed3 +139 37 0 OrangeRed4 +255 0 0 red1 +238 0 0 red2 +205 0 0 red3 +139 0 0 red4 +255 20 147 DeepPink1 +238 18 137 DeepPink2 +205 16 118 DeepPink3 +139 10 80 DeepPink4 +255 110 180 HotPink1 +238 106 167 HotPink2 +205 96 144 HotPink3 +139 58 98 HotPink4 +255 181 197 pink1 +238 169 184 pink2 +205 145 158 pink3 +139 99 108 pink4 +255 174 185 LightPink1 +238 162 173 LightPink2 +205 140 149 LightPink3 +139 95 101 LightPink4 +255 130 171 PaleVioletRed1 +238 121 159 PaleVioletRed2 +205 104 137 PaleVioletRed3 +139 71 93 PaleVioletRed4 +255 52 179 maroon1 +238 48 167 maroon2 +205 41 144 maroon3 +139 28 98 maroon4 +255 62 150 VioletRed1 +238 58 140 VioletRed2 +205 50 120 VioletRed3 +139 34 82 VioletRed4 +255 0 255 magenta1 +238 0 238 magenta2 +205 0 205 magenta3 +139 0 139 magenta4 +255 131 250 orchid1 +238 122 233 orchid2 +205 105 201 orchid3 +139 71 137 orchid4 +255 187 255 plum1 +238 174 238 plum2 +205 150 205 plum3 +139 102 139 plum4 +224 102 255 MediumOrchid1 +209 95 238 MediumOrchid2 +180 82 205 MediumOrchid3 +122 55 139 MediumOrchid4 +191 62 255 DarkOrchid1 +178 58 238 DarkOrchid2 +154 50 205 DarkOrchid3 +104 34 139 DarkOrchid4 +155 48 255 purple1 +145 44 238 purple2 +125 38 205 purple3 + 85 26 139 purple4 +171 130 255 MediumPurple1 +159 121 238 MediumPurple2 +137 104 205 MediumPurple3 + 93 71 139 MediumPurple4 +255 225 255 thistle1 +238 210 238 thistle2 +205 181 205 thistle3 +139 123 139 thistle4 + 0 0 0 gray0 + 0 0 0 grey0 + 3 3 3 gray1 + 3 3 3 grey1 + 5 5 5 gray2 + 5 5 5 grey2 + 8 8 8 gray3 + 8 8 8 grey3 + 10 10 10 gray4 + 10 10 10 grey4 + 13 13 13 gray5 + 13 13 13 grey5 + 15 15 15 gray6 + 15 15 15 grey6 + 18 18 18 gray7 + 18 18 18 grey7 + 20 20 20 gray8 + 20 20 20 grey8 + 23 23 23 gray9 + 23 23 23 grey9 + 26 26 26 gray10 + 26 26 26 grey10 + 28 28 28 gray11 + 28 28 28 grey11 + 31 31 31 gray12 + 31 31 31 grey12 + 33 33 33 gray13 + 33 33 33 grey13 + 36 36 36 gray14 + 36 36 36 grey14 + 38 38 38 gray15 + 38 38 38 grey15 + 41 41 41 gray16 + 41 41 41 grey16 + 43 43 43 gray17 + 43 43 43 grey17 + 46 46 46 gray18 + 46 46 46 grey18 + 48 48 48 gray19 + 48 48 48 grey19 + 51 51 51 gray20 + 51 51 51 grey20 + 54 54 54 gray21 + 54 54 54 grey21 + 56 56 56 gray22 + 56 56 56 grey22 + 59 59 59 gray23 + 59 59 59 grey23 + 61 61 61 gray24 + 61 61 61 grey24 + 64 64 64 gray25 + 64 64 64 grey25 + 66 66 66 gray26 + 66 66 66 grey26 + 69 69 69 gray27 + 69 69 69 grey27 + 71 71 71 gray28 + 71 71 71 grey28 + 74 74 74 gray29 + 74 74 74 grey29 + 77 77 77 gray30 + 77 77 77 grey30 + 79 79 79 gray31 + 79 79 79 grey31 + 82 82 82 gray32 + 82 82 82 grey32 + 84 84 84 gray33 + 84 84 84 grey33 + 87 87 87 gray34 + 87 87 87 grey34 + 89 89 89 gray35 + 89 89 89 grey35 + 92 92 92 gray36 + 92 92 92 grey36 + 94 94 94 gray37 + 94 94 94 grey37 + 97 97 97 gray38 + 97 97 97 grey38 + 99 99 99 gray39 + 99 99 99 grey39 +102 102 102 gray40 +102 102 102 grey40 +105 105 105 gray41 +105 105 105 grey41 +107 107 107 gray42 +107 107 107 grey42 +110 110 110 gray43 +110 110 110 grey43 +112 112 112 gray44 +112 112 112 grey44 +115 115 115 gray45 +115 115 115 grey45 +117 117 117 gray46 +117 117 117 grey46 +120 120 120 gray47 +120 120 120 grey47 +122 122 122 gray48 +122 122 122 grey48 +125 125 125 gray49 +125 125 125 grey49 +127 127 127 gray50 +127 127 127 grey50 +130 130 130 gray51 +130 130 130 grey51 +133 133 133 gray52 +133 133 133 grey52 +135 135 135 gray53 +135 135 135 grey53 +138 138 138 gray54 +138 138 138 grey54 +140 140 140 gray55 +140 140 140 grey55 +143 143 143 gray56 +143 143 143 grey56 +145 145 145 gray57 +145 145 145 grey57 +148 148 148 gray58 +148 148 148 grey58 +150 150 150 gray59 +150 150 150 grey59 +153 153 153 gray60 +153 153 153 grey60 +156 156 156 gray61 +156 156 156 grey61 +158 158 158 gray62 +158 158 158 grey62 +161 161 161 gray63 +161 161 161 grey63 +163 163 163 gray64 +163 163 163 grey64 +166 166 166 gray65 +166 166 166 grey65 +168 168 168 gray66 +168 168 168 grey66 +171 171 171 gray67 +171 171 171 grey67 +173 173 173 gray68 +173 173 173 grey68 +176 176 176 gray69 +176 176 176 grey69 +179 179 179 gray70 +179 179 179 grey70 +181 181 181 gray71 +181 181 181 grey71 +184 184 184 gray72 +184 184 184 grey72 +186 186 186 gray73 +186 186 186 grey73 +189 189 189 gray74 +189 189 189 grey74 +191 191 191 gray75 +191 191 191 grey75 +194 194 194 gray76 +194 194 194 grey76 +196 196 196 gray77 +196 196 196 grey77 +199 199 199 gray78 +199 199 199 grey78 +201 201 201 gray79 +201 201 201 grey79 +204 204 204 gray80 +204 204 204 grey80 +207 207 207 gray81 +207 207 207 grey81 +209 209 209 gray82 +209 209 209 grey82 +212 212 212 gray83 +212 212 212 grey83 +214 214 214 gray84 +214 214 214 grey84 +217 217 217 gray85 +217 217 217 grey85 +219 219 219 gray86 +219 219 219 grey86 +222 222 222 gray87 +222 222 222 grey87 +224 224 224 gray88 +224 224 224 grey88 +227 227 227 gray89 +227 227 227 grey89 +229 229 229 gray90 +229 229 229 grey90 +232 232 232 gray91 +232 232 232 grey91 +235 235 235 gray92 +235 235 235 grey92 +237 237 237 gray93 +237 237 237 grey93 +240 240 240 gray94 +240 240 240 grey94 +242 242 242 gray95 +242 242 242 grey95 +245 245 245 gray96 +245 245 245 grey96 +247 247 247 gray97 +247 247 247 grey97 +250 250 250 gray98 +250 250 250 grey98 +252 252 252 gray99 +252 252 252 grey99 +255 255 255 gray100 +255 255 255 grey100 +169 169 169 dark grey +169 169 169 DarkGrey +169 169 169 dark gray +169 169 169 DarkGray + 0 0 139 dark blue + 0 0 139 DarkBlue + 0 139 139 dark cyan + 0 139 139 DarkCyan +139 0 139 dark magenta +139 0 139 DarkMagenta +139 0 0 dark red +139 0 0 DarkRed +144 238 144 light green +144 238 144 LightGreen +220 20 60 crimson + 75 0 130 indigo +128 128 0 olive +102 51 153 rebecca purple +102 51 153 RebeccaPurple +192 192 192 silver + 0 128 128 teal diff --git a/internal/config/file.go b/internal/config/file.go new file mode 100644 index 0000000..f1ae9b2 --- /dev/null +++ b/internal/config/file.go @@ -0,0 +1,435 @@ +// Package config reads and writes Ghostty config files while preserving +// everything the editor does not touch: comments, blank lines, ordering and +// formatting of untouched entries. +package config + +import ( + "bytes" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "time" +) + +// Line is one line of a config file. +type Line struct { + Raw string // original text; regenerated when the entry changes + Key string // empty for comments, blank lines and unparsable lines + Value string // raw value text after '=', trimmed (quotes are kept) +} + +// IsEntry reports whether the line is a key/value entry. +func (l Line) IsEntry() bool { return l.Key != "" } + +// File is a parsed config file. +type File struct { + Path string + Exists bool + ModTime time.Time + Lines []Line +} + +// Load reads path. A missing file yields an empty File that will be created +// on save. +func Load(path string) (*File, error) { + f := &File{Path: path} + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return f, nil + } + if err != nil { + return nil, err + } + if fi, err := os.Stat(path); err == nil { + f.ModTime = fi.ModTime() + } + f.Exists = true + f.Lines = Parse(data) + return f, nil +} + +// Parse splits config data into lines. +func Parse(data []byte) []Line { + text := strings.ReplaceAll(string(data), "\r\n", "\n") + text = strings.TrimSuffix(text, "\n") + if text == "" { + return nil + } + parts := strings.Split(text, "\n") + lines := make([]Line, len(parts)) + for i, raw := range parts { + lines[i] = parseLine(raw) + } + return lines +} + +func parseLine(raw string) Line { + l := Line{Raw: raw} + t := strings.TrimSpace(raw) + if t == "" || strings.HasPrefix(t, "#") { + return l + } + key, value, found := strings.Cut(t, "=") + key = strings.TrimSpace(key) + if key == "" || strings.ContainsAny(key, " \t") { + return l + } + l.Key = key + if found { + l.Value = strings.TrimSpace(value) + } + return l +} + +// FormatLine renders a key/value entry. +func FormatLine(key, value string) string { + if value == "" { + value = `""` + } else if strings.TrimSpace(value) != value && !isQuoted(value) { + value = `"` + value + `"` + } + return key + " = " + value +} + +func isQuoted(v string) bool { + return len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' +} + +func newEntry(key, value string) Line { + return Line{Raw: FormatLine(key, value), Key: key, Value: value} +} + +// Clone returns a deep copy (used for undo snapshots). +func (f *File) Clone() *File { + c := *f + c.Lines = append([]Line(nil), f.Lines...) + return &c +} + +// Has reports whether key is set in the file. +func (f *File) Has(key string) bool { + for _, l := range f.Lines { + if l.Key == key { + return true + } + } + return false +} + +// Get returns the effective (last) value of key. +func (f *File) Get(key string) (string, bool) { + for i := len(f.Lines) - 1; i >= 0; i-- { + if f.Lines[i].Key == key { + return f.Lines[i].Value, true + } + } + return "", false +} + +// GetAll returns every value of key in file order. +func (f *File) GetAll(key string) []string { + var out []string + for _, l := range f.Lines { + if l.Key == key { + out = append(out, l.Value) + } + } + return out +} + +// Keys returns the distinct keys set in the file, in order of appearance. +func (f *File) Keys() []string { + var out []string + seen := map[string]bool{} + for _, l := range f.Lines { + if l.Key != "" && !seen[l.Key] { + seen[l.Key] = true + out = append(out, l.Key) + } + } + return out +} + +// Set assigns a single value. The first existing entry is updated in place +// and any further entries for the key are removed; otherwise a new entry is +// appended. +func (f *File) Set(key, value string) { + f.SetAll(key, []string{value}) +} + +// SetAll replaces all entries of key with values while disturbing the file +// as little as possible: entries whose value is unchanged stay where they +// are (with their original formatting), changed entries are rewritten in +// place, removed ones are dropped and additional ones are inserted after +// the preceding entry of the same key. An empty slice removes the key. +func (f *File) SetAll(key string, values []string) { + if len(values) == 0 { + f.Unset(key) + return + } + var pos []int // line indexes of the existing entries + var old []string + for i, l := range f.Lines { + if l.Key == key { + pos = append(pos, i) + old = append(old, l.Value) + } + } + if len(pos) == 0 { + at := f.insertPos() + entries := make([]Line, len(values)) + for i, v := range values { + entries[i] = newEntry(key, v) + } + f.Lines = append(f.Lines[:at:at], append(entries, f.Lines[at:]...)...) + return + } + + replace := map[int]Line{} // line index -> new content + remove := map[int]bool{} // line indexes to drop + after := map[int][]Line{} // new entries to insert after a line index + before := map[int][]Line{} // new entries to insert before a line index + last := -1 // line index of the last kept/replaced entry + var dels []int // pending deleted entries in the current gap + var ins []string // pending inserted values in the current gap + flushGap := func() { + // Pair deletions with insertions as in-place edits. + n := min(len(dels), len(ins)) + for k := 0; k < n; k++ { + replace[pos[dels[k]]] = newEntry(key, ins[k]) + last = pos[dels[k]] + } + for _, d := range dels[n:] { + remove[pos[d]] = true + } + for _, v := range ins[n:] { + if last >= 0 { + after[last] = append(after[last], newEntry(key, v)) + } else { + before[pos[0]] = append(before[pos[0]], newEntry(key, v)) + } + } + dels, ins = nil, nil + } + for _, op := range diff(old, values) { + switch op.kind { + case opKeep: + flushGap() + last = pos[op.i] + case opDel: + dels = append(dels, op.i) + case opIns: + ins = append(ins, values[op.j]) + } + } + flushGap() + + lines := make([]Line, 0, len(f.Lines)+len(values)) + for i, l := range f.Lines { + lines = append(lines, before[i]...) + switch { + case remove[i]: + case replace[i].Key != "": + lines = append(lines, replace[i]) + default: + lines = append(lines, l) + } + lines = append(lines, after[i]...) + } + f.Lines = lines +} + +// insertPos is where new keys are appended: after the last entry, so that +// trailing comments stay at the end of the file. +func (f *File) insertPos() int { + for i := len(f.Lines) - 1; i >= 0; i-- { + if f.Lines[i].IsEntry() { + return i + 1 + } + } + return len(f.Lines) +} + +type opKind int + +const ( + opKeep opKind = iota + opDel + opIns +) + +type diffOp struct { + kind opKind + i, j int // index into old (keep, del) and new (keep, ins) +} + +// diff computes a minimal edit script from a to b using the longest common +// subsequence. Lists are short (at most a few hundred entries). +func diff(a, b []string) []diffOp { + m, n := len(a), len(b) + lcs := make([][]int, m+1) + for i := range lcs { + lcs[i] = make([]int, n+1) + } + for i := m - 1; i >= 0; i-- { + for j := n - 1; j >= 0; j-- { + if a[i] == b[j] { + lcs[i][j] = lcs[i+1][j+1] + 1 + } else { + lcs[i][j] = max(lcs[i+1][j], lcs[i][j+1]) + } + } + } + var ops []diffOp + i, j := 0, 0 + for i < m && j < n { + switch { + case a[i] == b[j]: + ops = append(ops, diffOp{opKeep, i, j}) + i++ + j++ + case lcs[i+1][j] >= lcs[i][j+1]: + ops = append(ops, diffOp{opDel, i, j}) + i++ + default: + ops = append(ops, diffOp{opIns, i, j}) + j++ + } + } + for ; i < m; i++ { + ops = append(ops, diffOp{opDel, i, j}) + } + for ; j < n; j++ { + ops = append(ops, diffOp{opIns, i, j}) + } + return ops +} + +// Change is one entry of a diff between two value lists. +type Change struct { + Removed bool // the value was removed, otherwise added + Value string +} + +// Diff lists the values removed from and added to a repeatable option, in +// file order. Values present in both lists are left out. +func Diff(old, new []string) []Change { + var out []Change + for _, op := range diff(old, new) { + switch op.kind { + case opDel: + out = append(out, Change{true, old[op.i]}) + case opIns: + out = append(out, Change{false, new[op.j]}) + } + } + return out +} + +// Unset removes every entry of key. +func (f *File) Unset(key string) { + kept := f.Lines[:0:0] + for _, l := range f.Lines { + if l.Key != key { + kept = append(kept, l) + } + } + f.Lines = kept +} + +// Bytes renders the file. +func (f *File) Bytes() []byte { + var b bytes.Buffer + for _, l := range f.Lines { + b.WriteString(l.Raw) + b.WriteByte('\n') + } + return b.Bytes() +} + +// Equal reports whether two files render identically. +func (f *File) Equal(o *File) bool { + return bytes.Equal(f.Bytes(), o.Bytes()) +} + +// ChangedOnDisk reports whether the file was modified by someone else since +// it was loaded or last saved. +func (f *File) ChangedOnDisk() bool { + fi, err := os.Stat(f.Path) + if err != nil { + return f.Exists + } + return !f.Exists || !fi.ModTime().Equal(f.ModTime) +} + +// target returns the real file behind Path, so that saving a symlinked +// config (e.g. from a dotfiles repository) keeps the symlink intact. +func (f *File) target() string { + if t, err := filepath.EvalSymlinks(f.Path); err == nil { + return t + } + return f.Path +} + +// WriteTemp writes the file's content to a temporary file next to the +// target, so that relative config-file includes resolve the same way. +func (f *File) WriteTemp() (string, error) { + target := f.target() + dir := filepath.Dir(target) + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(target)+".ghosttyconf-*") + if err != nil { + return "", err + } + if _, err := tmp.Write(f.Bytes()); err != nil { + tmp.Close() + os.Remove(tmp.Name()) + return "", err + } + if err := tmp.Close(); err != nil { + os.Remove(tmp.Name()) + return "", err + } + return tmp.Name(), nil +} + +// Save atomically replaces the file on disk. When backup is true and the +// file exists, the previous version is kept as .bak. +func (f *File) Save(backup bool) error { + target := f.target() + mode := fs.FileMode(0o644) + if fi, err := os.Stat(target); err == nil { + mode = fi.Mode().Perm() + if backup { + old, err := os.ReadFile(target) + if err != nil { + return fmt.Errorf("read for backup: %w", err) + } + if err := os.WriteFile(target+".bak", old, mode); err != nil { + return fmt.Errorf("write backup: %w", err) + } + } + } + tmp, err := f.WriteTemp() + if err != nil { + return err + } + if err := os.Chmod(tmp, mode); err != nil { + os.Remove(tmp) + return err + } + if err := os.Rename(tmp, target); err != nil { + os.Remove(tmp) + return err + } + f.Exists = true + if fi, err := os.Stat(f.Path); err == nil { + f.ModTime = fi.ModTime() + } + return nil +} diff --git a/internal/config/file_test.go b/internal/config/file_test.go new file mode 100644 index 0000000..056df77 --- /dev/null +++ b/internal/config/file_test.go @@ -0,0 +1,202 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +const sample = `# My Ghostty config +font-family = Hack Nerd Font Mono +font-size=15 + +keybind = a=new_tab +# split navigation +keybind = b=goto_split:next + +theme = "Dracula" +# trailing comment +` + +func parse(t *testing.T, s string) *File { + t.Helper() + return &File{Lines: Parse([]byte(s))} +} + +func TestRoundTripPreservesEverything(t *testing.T) { + f := parse(t, sample) + if got := string(f.Bytes()); got != sample { + t.Fatalf("round trip changed the file:\n%s", got) + } + if v, _ := f.Get("font-size"); v != "15" { + t.Errorf("font-size = %q", v) + } + if v, _ := f.Get("theme"); v != `"Dracula"` { + t.Errorf("theme should keep its quotes, got %q", v) + } + if got := f.Keys(); strings.Join(got, ",") != "font-family,font-size,keybind,theme" { + t.Errorf("keys = %v", got) + } +} + +func TestSetUpdatesInPlace(t *testing.T) { + f := parse(t, sample) + f.Set("font-size", "16") + want := strings.Replace(sample, "font-size=15", "font-size = 16", 1) + if got := string(f.Bytes()); got != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } +} + +func TestSetAppendsAfterLastEntry(t *testing.T) { + f := parse(t, sample) + f.Set("cursor-style", "bar") + want := strings.Replace(sample, "theme = \"Dracula\"\n", "theme = \"Dracula\"\ncursor-style = bar\n", 1) + if got := string(f.Bytes()); got != want { + t.Fatalf("got:\n%s", got) + } +} + +func TestSetRemovesDuplicates(t *testing.T) { + f := parse(t, "a = 1\nb = 2\na = 3\n") + f.Set("a", "4") + if got := string(f.Bytes()); got != "a = 4\nb = 2\n" { + t.Fatalf("got:\n%s", got) + } +} + +func TestSetAllKeepsPositions(t *testing.T) { + tests := []struct { + name string + values []string + want string + }{ + { + name: "append", + values: []string{"a=new_tab", "b=goto_split:next", "c=close_surface"}, + want: "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\nkeybind = c=close_surface\n", + }, + { + name: "edit second", + values: []string{"a=new_tab", "b=goto_split:previous"}, + want: "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:previous\n", + }, + { + name: "delete first", + values: []string{"b=goto_split:next"}, + want: "# split navigation\nkeybind = b=goto_split:next\n", + }, + { + name: "insert at front", + values: []string{"z=reset", "a=new_tab", "b=goto_split:next"}, + want: "keybind = z=reset\nkeybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\n", + }, + { + name: "swap", + values: []string{"b=goto_split:next", "a=new_tab"}, + // The comment stays attached to the entry it describes. + want: "# split navigation\nkeybind = b=goto_split:next\nkeybind = a=new_tab\n", + }, + } + const base = "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\n" + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := parse(t, base) + f.SetAll("keybind", tt.values) + if got := string(f.Bytes()); got != tt.want { + t.Fatalf("got:\n%s\nwant:\n%s", got, tt.want) + } + if got := f.GetAll("keybind"); strings.Join(got, "|") != strings.Join(tt.values, "|") { + t.Fatalf("values = %v", got) + } + }) + } +} + +func TestUnset(t *testing.T) { + f := parse(t, sample) + f.Unset("keybind") + if f.Has("keybind") { + t.Fatal("keybind still present") + } + if !strings.Contains(string(f.Bytes()), "# split navigation") { + t.Fatal("comments must be kept") + } +} + +func TestFormatLineQuoting(t *testing.T) { + cases := map[string]string{ + "bar": "k = bar", + "": `k = ""`, + " x": `k = " x"`, + `"quoted"`: `k = "quoted"`, + } + for in, want := range cases { + if got := FormatLine("k", in); got != want { + t.Errorf("FormatLine(%q) = %q, want %q", in, got, want) + } + } +} + +func TestSaveBackupAndSymlink(t *testing.T) { + dir := t.TempDir() + real := filepath.Join(dir, "real.ghostty") + link := filepath.Join(dir, "config.ghostty") + if err := os.WriteFile(real, []byte("font-size = 12\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(real, link); err != nil { + t.Fatal(err) + } + f, err := Load(link) + if err != nil { + t.Fatal(err) + } + f.Set("font-size", "14") + if err := f.Save(true); err != nil { + t.Fatal(err) + } + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatal("symlink was replaced") + } + got, _ := os.ReadFile(real) + if string(got) != "font-size = 14\n" { + t.Fatalf("saved content = %q", got) + } + bak, _ := os.ReadFile(real + ".bak") + if string(bak) != "font-size = 12\n" { + t.Fatalf("backup content = %q", bak) + } + if fi, _ := os.Stat(real); fi.Mode().Perm() != 0o600 { + t.Fatalf("permissions changed to %v", fi.Mode().Perm()) + } + if f.ChangedOnDisk() { + t.Fatal("file should not be reported as changed after our own save") + } +} + +func TestLoadMissingFile(t *testing.T) { + f, err := Load(filepath.Join(t.TempDir(), "nope")) + if err != nil { + t.Fatal(err) + } + if f.Exists || len(f.Lines) != 0 { + t.Fatal("expected empty, non-existing file") + } +} + +func TestDiffListsOnlyChanges(t *testing.T) { + old := []string{"super+d=new_split:right", "super+shift+d=new_split:down", "super+k=unbind"} + new := []string{"super+shift+d=new_split:down", "super+k=unbind", "super+d=unbind", `super+\=new_split:right`} + got := Diff(old, new) + want := []Change{{true, "super+d=new_split:right"}, {false, "super+d=unbind"}, {false, `super+\=new_split:right`}} + if len(got) != len(want) { + t.Fatalf("Diff = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("Diff = %v, want %v", got, want) + } + } +} diff --git a/internal/ghostty/ghostty.go b/internal/ghostty/ghostty.go new file mode 100644 index 0000000..e7e0e2d --- /dev/null +++ b/internal/ghostty/ghostty.go @@ -0,0 +1,264 @@ +// Package ghostty talks to the installed Ghostty binary: it locates it, +// reads documentation, defaults, themes, fonts and actions from it, and +// validates config files with `ghostty +validate-config`. +package ghostty + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" + "strings" + "time" +) + +// Ghostty is an installed Ghostty binary. +type Ghostty struct { + Bin string + Version string +} + +var ( + reVersion = regexp.MustCompile(`Ghostty (\d+\.\d+\.\d+\S*)`) + reValidation = regexp.MustCompile(`^.+?:(\d+):(.*)$`) +) + +// Find locates the ghostty binary. An explicit path takes precedence, then +// $PATH, then the usual macOS application locations. +func Find(explicit string) (*Ghostty, error) { + var candidates []string + if explicit != "" { + candidates = append(candidates, explicit) + } else { + if p, err := exec.LookPath("ghostty"); err == nil { + candidates = append(candidates, p) + } + if runtime.GOOS == "darwin" { + candidates = append(candidates, + "/Applications/Ghostty.app/Contents/MacOS/ghostty", + filepath.Join(os.Getenv("HOME"), "Applications/Ghostty.app/Contents/MacOS/ghostty"), + ) + } + } + for _, c := range candidates { + if fi, err := os.Stat(c); err != nil || fi.IsDir() { + continue + } + g := &Ghostty{Bin: c} + out, err := g.run(5*time.Second, "+version") + if err != nil { + continue + } + if m := reVersion.FindStringSubmatch(out); m != nil { + g.Version = m[1] + } + return g, nil + } + if explicit != "" { + return nil, fmt.Errorf("%s is not a usable ghostty binary", explicit) + } + return nil, errors.New("ghostty binary not found") +} + +func (g *Ghostty) run(timeout time.Duration, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cmd := exec.CommandContext(ctx, g.Bin, args...) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + // Keep Ghostty from treating our pipe as an interactive terminal. + cmd.Stdin = nil + err := cmd.Run() + if err != nil && stdout.Len() == 0 { + msg := strings.TrimSpace(stderr.String()) + if msg == "" { + msg = err.Error() + } + return "", fmt.Errorf("ghostty %s: %s", strings.Join(args, " "), msg) + } + return stdout.String(), err +} + +// DefaultsWithDocs returns `ghostty +show-config --default --docs`. +func (g *Ghostty) DefaultsWithDocs() (string, error) { + out, err := g.run(10*time.Second, "+show-config", "--default", "--docs") + if err != nil && out == "" { + return "", err + } + return out, nil +} + +// Themes lists all available theme names. +func (g *Ghostty) Themes() ([]string, error) { + out, err := g.run(10*time.Second, "+list-themes", "--plain") + if out == "" && err != nil { + return nil, err + } + var names []string + seen := map[string]bool{} + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + // Lines look like "Dracula (resources)" or "Mine (user)". + if i := strings.LastIndex(line, " ("); i > 0 && strings.HasSuffix(line, ")") { + line = line[:i] + } + if !seen[line] { + seen[line] = true + names = append(names, line) + } + } + return names, nil +} + +// Fonts lists the font families Ghostty can find. +func (g *Ghostty) Fonts() ([]string, error) { + out, err := g.run(20*time.Second, "+list-fonts") + if out == "" && err != nil { + return nil, err + } + var families []string + seen := map[string]bool{} + for _, line := range strings.Split(out, "\n") { + if line == "" || line[0] == ' ' || line[0] == '\t' { + continue + } + line = strings.TrimSpace(line) + if !seen[line] { + seen[line] = true + families = append(families, line) + } + } + sort.Slice(families, func(i, j int) bool { + return strings.ToLower(families[i]) < strings.ToLower(families[j]) + }) + return families, nil +} + +// Action is a keybinding action. +type Action struct { + Name string + Summary string // first line of the documentation + Doc string +} + +// Actions lists all keybinding actions with their documentation. +func (g *Ghostty) Actions() ([]Action, error) { + out, err := g.run(10*time.Second, "+list-actions", "--docs") + if out == "" && err != nil { + return nil, err + } + return parseActions(out), nil +} + +func parseActions(out string) []Action { + var actions []Action + var cur *Action + var doc []string + flush := func() { + if cur == nil { + return + } + cur.Doc = strings.TrimSpace(strings.Join(doc, "\n")) + if i := strings.Index(cur.Doc, "\n\n"); i >= 0 { + cur.Summary = strings.ReplaceAll(cur.Doc[:i], "\n", " ") + } else { + cur.Summary = strings.ReplaceAll(cur.Doc, "\n", " ") + } + actions = append(actions, *cur) + } + for _, line := range strings.Split(out, "\n") { + if line != "" && line[0] != ' ' && strings.HasSuffix(line, ":") { + flush() + cur = &Action{Name: strings.TrimSuffix(line, ":")} + doc = nil + continue + } + if cur != nil { + doc = append(doc, strings.TrimPrefix(line, " ")) + } + } + flush() + return actions +} + +// ValidationError is one problem reported by `ghostty +validate-config`. +type ValidationError struct { + Line int // 0 if unknown + Message string +} + +func (e ValidationError) String() string { + if e.Line > 0 { + return fmt.Sprintf("line %d: %s", e.Line, e.Message) + } + return e.Message +} + +// Validate runs `ghostty +validate-config` on path. +func (g *Ghostty) Validate(path string) ([]ValidationError, error) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + out, runErr := g.run(15*time.Second, "+validate-config", "--config-file="+abs) + var errs []ValidationError + sc := bufio.NewScanner(strings.NewReader(out)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" { + continue + } + // Lines look like "/path/to/config:3:font-size: invalid value". + e := ValidationError{Message: line} + if m := reValidation.FindStringSubmatch(line); m != nil { + e.Line, _ = strconv.Atoi(m[1]) + e.Message = m[2] + } + errs = append(errs, e) + } + if runErr != nil && len(errs) == 0 { + var exitErr *exec.ExitError + if !errors.As(runErr, &exitErr) { + return nil, runErr + } + errs = append(errs, ValidationError{Message: "ghostty reported an invalid configuration"}) + } + return errs, nil +} + +// ResourcesDir returns Ghostty's resources directory (where the bundled +// themes live), or "". +func (g *Ghostty) ResourcesDir() string { + if d := os.Getenv("GHOSTTY_RESOURCES_DIR"); d != "" { + return d + } + if g == nil { + return "" + } + bin, err := filepath.EvalSymlinks(g.Bin) + if err != nil { + bin = g.Bin + } + dir := filepath.Dir(bin) + for _, c := range []string{ + filepath.Join(dir, "../Resources/ghostty"), // macOS app bundle + filepath.Join(dir, "../share/ghostty"), // Linux prefix install + } { + if fi, err := os.Stat(filepath.Join(c, "themes")); err == nil && fi.IsDir() { + return filepath.Clean(c) + } + } + return "" +} diff --git a/internal/ghostty/paths.go b/internal/ghostty/paths.go new file mode 100644 index 0000000..952aea1 --- /dev/null +++ b/internal/ghostty/paths.go @@ -0,0 +1,140 @@ +package ghostty + +import ( + "bufio" + "os" + "path/filepath" + "runtime" + "strings" +) + +func xdgConfigDir() string { + if d := os.Getenv("XDG_CONFIG_HOME"); d != "" { + return filepath.Join(d, "ghostty") + } + return filepath.Join(os.Getenv("HOME"), ".config", "ghostty") +} + +func macConfigDir() string { + return filepath.Join(os.Getenv("HOME"), "Library", "Application Support", "com.mitchellh.ghostty") +} + +// ConfigCandidates lists the files Ghostty loads by default, in load order. +func ConfigCandidates() []string { + xdg := xdgConfigDir() + c := []string{filepath.Join(xdg, "config"), filepath.Join(xdg, "config.ghostty")} + if runtime.GOOS == "darwin" { + mac := macConfigDir() + c = append(c, filepath.Join(mac, "config"), filepath.Join(mac, "config.ghostty")) + } + return c +} + +// DefaultConfigPath picks the config file to edit: the last existing file +// in Ghostty's load order (it has the final say), or the preferred location +// for a new file. +func DefaultConfigPath() string { + c := ConfigCandidates() + for i := len(c) - 1; i >= 0; i-- { + if fi, err := os.Stat(c[i]); err == nil && !fi.IsDir() { + return c[i] + } + } + if runtime.GOOS == "darwin" { + return filepath.Join(macConfigDir(), "config.ghostty") + } + return filepath.Join(xdgConfigDir(), "config.ghostty") +} + +// ExistingConfigFiles returns all default config files that exist. +func ExistingConfigFiles() []string { + var out []string + for _, c := range ConfigCandidates() { + if fi, err := os.Stat(c); err == nil && !fi.IsDir() { + out = append(out, c) + } + } + return out +} + +// Theme holds the colors of a theme file, used for previews. +type Theme struct { + Name string + Background string + Foreground string + Cursor string + Selection string + Palette [16]string +} + +// ThemeDirs returns the directories searched for themes, user dirs first. +func (g *Ghostty) ThemeDirs() []string { + dirs := []string{filepath.Join(xdgConfigDir(), "themes")} + if runtime.GOOS == "darwin" { + dirs = append(dirs, filepath.Join(macConfigDir(), "themes")) + } + if r := g.ResourcesDir(); r != "" { + dirs = append(dirs, filepath.Join(r, "themes")) + } + return dirs +} + +// LoadTheme reads a theme by name (or absolute path) for previewing. +func (g *Ghostty) LoadTheme(name string) (*Theme, error) { + var path string + if filepath.IsAbs(name) { + path = name + } else { + for _, d := range g.ThemeDirs() { + p := filepath.Join(d, name) + if _, err := os.Stat(p); err == nil { + path = p + break + } + } + } + if path == "" { + return nil, os.ErrNotExist + } + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + t := &Theme{Name: name} + sc := bufio.NewScanner(f) + for sc.Scan() { + key, value, ok := strings.Cut(sc.Text(), "=") + if !ok { + continue + } + key, value = strings.TrimSpace(key), strings.TrimSpace(value) + switch key { + case "background": + t.Background = value + case "foreground": + t.Foreground = value + case "cursor-color": + t.Cursor = value + case "selection-background": + t.Selection = value + case "palette": + idx, color, ok := strings.Cut(value, "=") + if !ok { + continue + } + var n int + for _, c := range strings.TrimSpace(idx) { + if c < '0' || c > '9' { + n = -1 + break + } + n = n*10 + int(c-'0') + } + if n >= 0 && n < 16 { + t.Palette[n] = strings.TrimSpace(color) + } + } + } + return t, sc.Err() +} diff --git a/internal/ghostty/reload.go b/internal/ghostty/reload.go new file mode 100644 index 0000000..2091678 --- /dev/null +++ b/internal/ghostty/reload.go @@ -0,0 +1,38 @@ +package ghostty + +import ( + "bytes" + "errors" +) + +// ErrNotRunning is returned by Reload when no Ghostty instance was found. +var ErrNotRunning = errors.New("Ghostty is not running") + +// ErrReloadUnsupported is returned by Reload on platforms where Ghostty +// cannot be asked to reload from outside. +var ErrReloadUnsupported = errors.New("automatic reload is not supported on this platform") + +// Reload asks every running Ghostty instance to reload its configuration, +// as if the reload_config action (⌘⇧, / ctrl+shift+,) had been triggered. +// +// On macOS this uses Ghostty's AppleScript "perform action" command, on +// Linux the SIGUSR2 handler of the GTK app. +func Reload() error { + return reload() +} + +// isCLIAction reports whether a NUL-separated command line runs a Ghostty +// CLI action ("ghostty +validate-config", …) rather than the app. Like +// Ghostty, it only looks at arguments before "-e". +func isCLIAction(cmdline []byte) bool { + args := bytes.Split(bytes.TrimRight(cmdline, "\x00"), []byte{0}) + for _, a := range args[1:] { + if string(a) == "-e" { + break + } + if bytes.HasPrefix(a, []byte("+")) { + return true + } + } + return false +} diff --git a/internal/ghostty/reload_darwin.go b/internal/ghostty/reload_darwin.go new file mode 100644 index 0000000..4e01ede --- /dev/null +++ b/internal/ghostty/reload_darwin.go @@ -0,0 +1,58 @@ +package ghostty + +import ( + "bytes" + "context" + "errors" + "fmt" + "os/exec" + "strings" + "time" +) + +// The bundle id is used instead of the name so that the script never +// launches a different app, and the "is running" check keeps it from +// starting Ghostty when it is closed. +const reloadScript = ` +if application id "com.mitchellh.ghostty" is running then + tell application id "com.mitchellh.ghostty" + if (count of terminals) is 0 then return "no terminals" + return perform action "reload_config" on first terminal + end tell +else + return "not running" +end if` + +func reload() error { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "osascript", "-e", reloadScript) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + out := strings.TrimSpace(stdout.String()) + if err != nil { + msg := strings.TrimSpace(stderr.String()) + switch { + case errors.Is(ctx.Err(), context.DeadlineExceeded): + return errors.New("osascript timed out (is a permission dialog open?)") + case strings.Contains(msg, "-1743"): + return errors.New("not allowed to control Ghostty; allow it in System Settings → Privacy & Security → Automation") + case strings.Contains(msg, "-1708"), strings.Contains(msg, "-10000"): + return errors.New("Ghostty refused the AppleScript command (is macos-applescript = false set?)") + case msg != "": + return fmt.Errorf("osascript: %s", msg) + } + return fmt.Errorf("osascript: %w", err) + } + switch out { + case "true": + return nil + case "not running": + return ErrNotRunning + case "no terminals": + return errors.New("Ghostty has no open terminal to send the reload to") + default: + return fmt.Errorf("Ghostty did not perform reload_config (%s)", out) + } +} diff --git a/internal/ghostty/reload_linux.go b/internal/ghostty/reload_linux.go new file mode 100644 index 0000000..754f851 --- /dev/null +++ b/internal/ghostty/reload_linux.go @@ -0,0 +1,61 @@ +package ghostty + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +// reload sends SIGUSR2 to the user's running Ghostty apps, which makes the +// GTK app reload its configuration. +func reload() error { + pids := ghosttyApps("/proc", os.Getuid()) + if len(pids) == 0 { + return ErrNotRunning + } + var errs []error + for _, pid := range pids { + if err := syscall.Kill(pid, syscall.SIGUSR2); err != nil { + errs = append(errs, err) + } + } + if len(errs) == len(pids) { + return errors.Join(errs...) + } + return nil +} + +// ghosttyApps finds Ghostty GUI processes owned by uid. CLI invocations +// such as "ghostty +list-themes" are skipped: they do not handle SIGUSR2 and +// would be terminated by it. +func ghosttyApps(proc string, uid int) []int { + entries, err := os.ReadDir(proc) + if err != nil { + return nil + } + var pids []int + for _, e := range entries { + pid, err := strconv.Atoi(e.Name()) + if err != nil || pid == os.Getpid() { + continue + } + dir := filepath.Join(proc, e.Name()) + comm, err := os.ReadFile(filepath.Join(dir, "comm")) + if err != nil || strings.TrimSpace(string(comm)) != "ghostty" { + continue + } + var st syscall.Stat_t + if err := syscall.Stat(dir, &st); err != nil || int(st.Uid) != uid { + continue + } + cmdline, err := os.ReadFile(filepath.Join(dir, "cmdline")) + if err != nil || isCLIAction(cmdline) { + continue + } + pids = append(pids, pid) + } + return pids +} diff --git a/internal/ghostty/reload_other.go b/internal/ghostty/reload_other.go new file mode 100644 index 0000000..c5ffc1c --- /dev/null +++ b/internal/ghostty/reload_other.go @@ -0,0 +1,7 @@ +//go:build !darwin && !linux + +package ghostty + +func reload() error { + return ErrReloadUnsupported +} diff --git a/internal/ghostty/reload_test.go b/internal/ghostty/reload_test.go new file mode 100644 index 0000000..a3613af --- /dev/null +++ b/internal/ghostty/reload_test.go @@ -0,0 +1,18 @@ +package ghostty + +import "testing" + +func TestIsCLIAction(t *testing.T) { + cases := map[string]bool{ + "/usr/bin/ghostty\x00": false, + "ghostty\x00--gtk-single-instance=true\x00": false, + "ghostty\x00+list-themes\x00": true, + "ghostty\x00--config-file=x\x00+show-config\x00": true, + "ghostty\x00-e\x00vim\x00+10\x00file\x00": false, + } + for cmdline, want := range cases { + if got := isCLIAction([]byte(cmdline)); got != want { + t.Errorf("isCLIAction(%q) = %v, want %v", cmdline, got, want) + } + } +} diff --git a/internal/keybind/keybind.go b/internal/keybind/keybind.go new file mode 100644 index 0000000..915b03b --- /dev/null +++ b/internal/keybind/keybind.go @@ -0,0 +1,288 @@ +// Package keybind understands Ghostty key bindings: it splits and +// normalizes triggers the same way Ghostty's src/input/Binding.zig does, +// computes the effective set of bindings from Ghostty's defaults plus the +// user's `keybind` entries, and translates edits of that set back into +// config entries. +package keybind + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +// Split splits "trigger=action". It mirrors Ghostty's parser: an '=' that is +// directly followed by '+' or '=' belongs to the trigger, so "ctrl+==reset" +// and "=+ctrl=reset" both bind the '=' key. +func Split(v string) (trigger, action string) { + for i := 0; i < len(v); i++ { + if v[i] != '=' { + continue + } + if i < len(v)-1 && (v[i+1] == '+' || v[i+1] == '=') { + continue + } + return strings.TrimSpace(v[:i]), strings.TrimSpace(v[i+1:]) + } + return strings.TrimSpace(v), "" +} + +// Flag prefixes that may precede a trigger, e.g. "global:ctrl+grave". +var flagPrefixes = []string{"all:", "global:", "unconsumed:", "performable:"} + +// StripFlags separates leading flag prefixes from a trigger. +func StripFlags(trigger string) (flags, rest string) { + rest = trigger + for { + found := false + for _, p := range flagPrefixes { + if strings.HasPrefix(rest, p) { + flags += p + rest = rest[len(p):] + found = true + } + } + if !found { + return flags, rest + } + } +} + +// Modifier names in the order Ghostty prints them. +var modOrder = []string{"super", "ctrl", "alt", "shift", "caps_lock", "num_lock"} + +var modAliases = map[string]string{ + "super": "super", "cmd": "super", "command": "super", + "ctrl": "ctrl", "control": "ctrl", + "alt": "alt", "opt": "alt", "option": "alt", + "shift": "shift", + "caps_lock": "caps_lock", + "num_lock": "num_lock", +} + +// keyNames are Ghostty's physical key names (src/input/key.zig, 1.3). +var keyNames = map[string]bool{} + +func init() { + for _, k := range strings.Fields(`backquote backslash bracket_left bracket_right comma + digit_0 digit_1 digit_2 digit_3 digit_4 digit_5 digit_6 digit_7 digit_8 digit_9 equal + intl_backslash intl_ro intl_yen key_a key_b key_c key_d key_e key_f key_g key_h key_i + key_j key_k key_l key_m key_n key_o key_p key_q key_r key_s key_t key_u key_v key_w key_x + key_y key_z minus period quote semicolon slash alt_left alt_right backspace caps_lock + context_menu control_left control_right enter meta_left meta_right shift_left shift_right + space tab convert kana_mode non_convert delete end help home insert page_down page_up + arrow_down arrow_left arrow_right arrow_up num_lock numpad_0 numpad_1 numpad_2 numpad_3 + numpad_4 numpad_5 numpad_6 numpad_7 numpad_8 numpad_9 numpad_add numpad_backspace + numpad_clear numpad_clear_entry numpad_comma numpad_decimal numpad_divide numpad_enter + numpad_equal numpad_memory_add numpad_memory_clear numpad_memory_recall + numpad_memory_store numpad_memory_subtract numpad_multiply numpad_paren_left + numpad_paren_right numpad_subtract numpad_separator numpad_up numpad_down numpad_right + numpad_left numpad_begin numpad_home numpad_end numpad_insert numpad_delete + numpad_page_up numpad_page_down escape f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 + f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 f25 fn_lock print_screen scroll_lock pause + browser_back browser_favorites browser_forward browser_home browser_refresh + browser_search browser_stop eject launch_app_1 launch_app_2 launch_mail media_play_pause + media_select media_stop media_track_next media_track_previous power sleep + audio_volume_down audio_volume_mute audio_volume_up wake_up copy cut paste catch_all`) { + keyNames[k] = true + } +} + +// compatKeys are the Ghostty 1.1 key names that 1.2+ still accepts. +var compatKeys = map[string]string{ + "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", + "six": "6", "seven": "7", "eight": "8", "nine": "9", "plus": "+", "apostrophe": "'", + "grave_accent": "backquote", "left_bracket": "bracket_left", "right_bracket": "bracket_right", + "up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right", + "kp_add": "numpad_add", "kp_subtract": "numpad_subtract", "kp_multiply": "numpad_multiply", + "kp_divide": "numpad_divide", "kp_decimal": "numpad_decimal", "kp_enter": "numpad_enter", + "kp_equal": "numpad_equal", "kp_separator": "numpad_separator", "kp_left": "numpad_left", + "kp_right": "numpad_right", "kp_up": "numpad_up", "kp_down": "numpad_down", + "kp_page_up": "numpad_page_up", "kp_page_down": "numpad_page_down", "kp_home": "numpad_home", + "kp_end": "numpad_end", "kp_insert": "numpad_insert", "kp_delete": "numpad_delete", + "kp_begin": "numpad_begin", "left_shift": "shift_left", "right_shift": "shift_right", + "left_control": "control_left", "right_control": "control_right", "left_alt": "alt_left", + "right_alt": "alt_right", "left_super": "meta_left", "right_super": "meta_right", +} + +func init() { + for i := 0; i <= 9; i++ { + compatKeys[fmt.Sprintf("kp_%d", i)] = fmt.Sprintf("numpad_%d", i) + } + // "physical:" variants of the compatibility names. + for k, v := range map[string]string{ + "zero": "digit_0", "one": "digit_1", "two": "digit_2", "three": "digit_3", "four": "digit_4", + "five": "digit_5", "six": "digit_6", "seven": "digit_7", "eight": "digit_8", "nine": "digit_9", + "apostrophe": "quote", "grave_accent": "backquote", "left_bracket": "bracket_left", + "right_bracket": "bracket_right", "up": "arrow_up", "down": "arrow_down", + "left": "arrow_left", "right": "arrow_right", + } { + compatKeys["physical:"+k] = v + } + for i := 0; i <= 9; i++ { + compatKeys[fmt.Sprintf("physical:kp_%d", i)] = fmt.Sprintf("numpad_%d", i) + } +} + +// Trigger is one key combination of a (possibly multi-key) trigger. +type Trigger struct { + Mods []string // canonical modifier names in modOrder + Key string // canonical key: a physical key name or a single character +} + +func (t Trigger) String() string { + parts := append(append([]string(nil), t.Mods...), t.Key) + return strings.Join(parts, "+") +} + +// ParseTrigger parses a single key combination such as "cmd+shift+t" the +// way Ghostty does. Unknown multi-character key names are an error. +func ParseTrigger(s string) (Trigger, error) { + var t Trigger + if s == "" { + return t, fmt.Errorf("empty trigger") + } + mods := map[string]bool{} + keySet := false + // Same loop as Ghostty: an empty part is a literal '+' key. + for rem := s; len(rem) > 0; { + idx := strings.IndexByte(rem, '+') + if idx < 0 { + idx = len(rem) + } + part := rem[:idx] + if idx >= len(rem) { + rem = "" + } else { + rem = rem[idx+1:] + } + if m, ok := modAliases[part]; ok { + if mods[m] { + return t, fmt.Errorf("modifier %q is repeated", part) + } + mods[m] = true + continue + } + if keySet { + return t, fmt.Errorf("only one key per combination is allowed (use > for sequences)") + } + keySet = true + key, err := canonicalKey(part) + if err != nil { + return t, err + } + t.Key = key + } + if !keySet { + return t, fmt.Errorf("the trigger has modifiers but no key") + } + for _, m := range modOrder { + if mods[m] { + t.Mods = append(t.Mods, m) + } + } + return t, nil +} + +func canonicalKey(part string) (string, error) { + if part == "" { + return "+", nil // "ctrl++" binds the plus key + } + if keyNames[part] { + return part, nil + } + if utf8.RuneCountInString(part) == 1 { + r, _ := utf8.DecodeRuneInString(part) + // Unicode keys match case-insensitively. + return string(unicode.ToLower(r)), nil + } + if k := fromW3C(part); k != "" { + return k, nil + } + if k, ok := compatKeys[part]; ok { + return k, nil + } + return "", fmt.Errorf("unknown key %q", part) +} + +// fromW3C converts W3C key codes such as "KeyA", "ArrowUp" or "Numpad0" to +// Ghostty's names. +func fromW3C(s string) string { + if s == "" || !unicode.IsUpper(rune(s[0])) { + return "" + } + var b strings.Builder + for i, r := range s { + if i > 0 && (unicode.IsUpper(r) || (unicode.IsDigit(r) && !unicode.IsDigit(rune(s[i-1])) && s[:i] != "F")) { + b.WriteByte('_') + } + b.WriteRune(unicode.ToLower(r)) + } + if keyNames[b.String()] { + return b.String() + } + return "" +} + +// Normalize returns a canonical identity for a trigger (including flag +// prefixes and sequences), so that "cmd+shift+t", "shift+super+T" and +// "global:super+shift+t" compare equal. Ghostty stores bindings by trigger; +// flags are attributes of a binding, not part of its identity. +func Normalize(trigger string) (string, error) { + _, rest := StripFlags(strings.TrimSpace(trigger)) + if rest == "" { + return "", fmt.Errorf("empty trigger") + } + var parts []string + for _, p := range splitSequence(rest) { + t, err := ParseTrigger(p) + if err != nil { + return "", err + } + parts = append(parts, t.String()) + } + return strings.Join(parts, ">"), nil +} + +// NormalizeLoose is Normalize that falls back to the trimmed input for +// triggers it cannot parse, so that unknown syntax still gets an identity. +func NormalizeLoose(trigger string) string { + if n, err := Normalize(trigger); err == nil { + return n + } + _, rest := StripFlags(strings.TrimSpace(trigger)) + return strings.ToLower(rest) +} + +// splitSequence splits "ctrl+a>n" at '>' separators. A '>' that is itself +// the key (e.g. "shift+>") is kept. +func splitSequence(s string) []string { + var parts []string + start := 0 + for i := 0; i < len(s); i++ { + if s[i] != '>' || i == start || s[i-1] == '+' { + continue + } + parts = append(parts, s[start:i]) + start = i + 1 + } + return append(parts, s[start:]) +} + +// Action names are lowercase with underscores; the parameter follows ':'. +func ActionName(action string) string { + name, _, _ := strings.Cut(action, ":") + return strings.TrimSpace(name) +} + +// FormatMods renders modifiers in Ghostty's order. +func FormatMods(mods map[string]bool) []string { + var out []string + for _, m := range modOrder { + if mods[m] { + out = append(out, m) + } + } + return out +} diff --git a/internal/keybind/keybind_test.go b/internal/keybind/keybind_test.go new file mode 100644 index 0000000..c23a5ba --- /dev/null +++ b/internal/keybind/keybind_test.go @@ -0,0 +1,250 @@ +package keybind + +import ( + "strings" + "testing" +) + +func TestSplit(t *testing.T) { + cases := map[string][2]string{ + "ctrl+a=new_tab": {"ctrl+a", "new_tab"}, + "==text:=": {"=", "text:="}, + "ctrl+==text:=hello": {"ctrl+=", "text:=hello"}, + "=+ctrl=text:=hello": {"=+ctrl", "text:=hello"}, + "super+shift+,=reload": {"super+shift+,", "reload"}, + "ctrl+a>n=new_window": {"ctrl+a>n", "new_window"}, + "§=goto_split:next": {"§", "goto_split:next"}, + "super++=increase": {"super++", "increase"}, + } + for in, want := range cases { + tr, ac := Split(in) + if tr != want[0] || ac != want[1] { + t.Errorf("Split(%q) = %q, %q", in, tr, ac) + } + } +} + +func TestNormalize(t *testing.T) { + same := [][]string{ + {"cmd+shift+t", "shift+super+T", "command+shift+t", "global:super+shift+t"}, + {"ctrl+up", "control+arrow_up", "ctrl+ArrowUp"}, + {"super++", "super+plus"}, + {"opt+grave_accent", "alt+backquote"}, + {"ctrl+a>n", "control+a>N"}, + {"super+=", "cmd+="}, + } + for _, group := range same { + want, err := Normalize(group[0]) + if err != nil { + t.Fatalf("%s: %v", group[0], err) + } + for _, g := range group[1:] { + got, err := Normalize(g) + if err != nil || got != want { + t.Errorf("Normalize(%q) = %q, %v; want %q", g, got, err, want) + } + } + } + for _, bad := range []string{"ctrl+ctrl+a", "ctrl+", "ctrl+a+b", "ctrl+bogus"} { + if _, err := Normalize(bad); err == nil && bad != "ctrl+" { + t.Errorf("Normalize(%q) should fail", bad) + } + } +} + +var defaults = []string{ + "super+t=new_tab", + "super+w=close_surface", + "super+d=new_split:right", + "super+arrow_right=text:\\x05", +} + +func values(s *Set) string { return strings.Join(s.Values(), " | ") } + +func find(t *testing.T, s *Set, trigger string) Binding { + t.Helper() + n, _ := Normalize(trigger) + for _, b := range s.Bindings() { + if b.Norm == n { + return b + } + } + t.Fatalf("no binding for %s", trigger) + return Binding{} +} + +func TestEffective(t *testing.T) { + s := NewSet(defaults, []string{ + "super+w=unbind", + "cmd+t=new_window", + "ctrl+a>n=new_tab", + "chain=toggle_fullscreen", + }) + if b := find(t, s, "super+t"); b.Source != Changed || b.Action != "new_window" || b.Default != "new_tab" { + t.Errorf("super+t = %+v", b) + } + if b := find(t, s, "super+w"); b.Source != Unbound { + t.Errorf("super+w = %+v", b) + } + if b := find(t, s, "ctrl+a>n"); b.Source != Custom || len(b.Chain) != 1 || b.Chain[0] != "toggle_fullscreen" { + t.Errorf("ctrl+a>n = %+v", b) + } + if b := find(t, s, "super+d"); b.Source != Default || b.InConfig { + t.Errorf("super+d = %+v", b) + } +} + +func TestClear(t *testing.T) { + s := NewSet(defaults, []string{"clear", "super+t=new_tab"}) + if b := find(t, s, "super+t"); b.Source != Default || !b.InConfig { + t.Errorf("super+t = %+v", b) + } + if b := find(t, s, "super+d"); b.Source != Unbound { + t.Errorf("super+d should be unbound after clear: %+v", b) + } + s.Restore(find(t, s, "super+d")) + if got := values(s); got != "clear | super+t=new_tab | super+d=new_split:right" { + t.Errorf("restore after clear: %s", got) + } +} + +func TestChangeDefaultAction(t *testing.T) { + s := NewSet(defaults, nil) + b := find(t, s, "super+d") + if err := s.Change(&b, "super+d=new_split:down"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "super+d=new_split:down" { + t.Errorf("got %s", got) + } +} + +func TestMoveDefaultBinding(t *testing.T) { + s := NewSet(defaults, nil) + b := find(t, s, "super+d") + if err := s.Change(&b, "super+shift+d=new_split:right"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "super+d=unbind | super+shift+d=new_split:right" { + t.Errorf("got %s", got) + } +} + +func TestMoveUserBindingRevertsToDefault(t *testing.T) { + s := NewSet(defaults, []string{"super+arrow_right=goto_window:next"}) + b := find(t, s, "super+arrow_right") + if err := s.Change(&b, "super+alt+arrow_right=goto_window:next"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "super+alt+arrow_right=goto_window:next" { + t.Errorf("got %s", got) + } + if b := find(t, s, "super+arrow_right"); b.Source != Default { + t.Errorf("old trigger should fall back to the default: %+v", b) + } +} + +func TestMoveUserBindingKeepsPosition(t *testing.T) { + s := NewSet(defaults, []string{"a=new_tab", "super+arrow_right=goto_window:next", "b=new_window"}) + b := find(t, s, "super+arrow_right") + if err := s.Change(&b, "super+shift+k=goto_window:next"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "a=new_tab | super+shift+k=goto_window:next | b=new_window" { + t.Errorf("got %s", got) + } +} + +func TestChangeReplacesConflictInPlace(t *testing.T) { + s := NewSet(defaults, []string{"ctrl+x=copy_to_clipboard", "ctrl+y=paste_from_clipboard"}) + b := find(t, s, "ctrl+y") + if err := s.Change(&b, "ctrl+x=paste_from_clipboard"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "ctrl+x=paste_from_clipboard" { + t.Errorf("got %s", got) + } +} + +func TestChangeBackToDefaultRemovesEntry(t *testing.T) { + s := NewSet(defaults, []string{"# not a keybind", "super+t=new_window"}) + b := find(t, s, "super+t") + if err := s.Change(&b, "super+t=new_tab"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "# not a keybind" { + t.Errorf("got %s", got) + } +} + +func TestUnbindAndRestore(t *testing.T) { + s := NewSet(defaults, []string{"super+t=new_window", "ctrl+q=quit"}) + s.Unbind(find(t, s, "super+t")) + s.Unbind(find(t, s, "ctrl+q")) + if got := values(s); got != "super+t=unbind" { + t.Errorf("after unbind: %s", got) + } + s.Restore(find(t, s, "super+t")) + if got := values(s); got != "" { + t.Errorf("after restore: %s", got) + } +} + +func TestChainMovesWithBinding(t *testing.T) { + s := NewSet(nil, []string{"ctrl+a=new_tab", "chain=toggle_fullscreen"}) + b := find(t, s, "ctrl+a") + if err := s.Change(&b, "ctrl+b=new_tab"); err != nil { + t.Fatal(err) + } + if got := values(s); got != "ctrl+b=new_tab | chain=toggle_fullscreen" { + t.Errorf("got %s", got) + } +} + +func TestDecodeCSI(t *testing.T) { + cases := map[string]string{ + "\x1b[116;9u": "super+t", + "\x1b[116;10u": "super+shift+t", + "\x1b[44;10u": "super+shift+,", + "\x1b[97;5u": "ctrl+a", + "\x1b[167;9u": "super+§", + "\x1b[1;9C": "super+arrow_right", + "\x1b[5;3~": "alt+page_up", + "\x1b[13;2u": "shift+enter", + "\x1b[57399;5u": "ctrl+numpad_0", + "\x1b[57376u": "f13", + "\x1b[97:65;2u": "shift+a", + } + for seq, want := range cases { + c, ok := DecodeCSI([]byte(seq)) + if !ok || c.String() != want { + t.Errorf("DecodeCSI(%q) = %q, %v; want %q", seq, c.String(), ok, want) + } + } + if c, ok := DecodeCSI([]byte("\x1b[57441;2u")); !ok || !c.Modifier { + t.Error("left shift should be reported as a modifier key") + } + if _, ok := DecodeCSI([]byte("\x1b[?9u")); ok { + t.Error("kitty reply is not a key") + } +} + +func TestDecodeKeyName(t *testing.T) { + cases := map[string]string{ + "ctrl+a": "ctrl+a", + "alt+shift+up": "alt+shift+arrow_up", + "ctrl+shift+up": "ctrl+shift+arrow_up", + "f5": "f5", + "A": "shift+a", + "pgdown": "page_down", + "shift+tab": "shift+tab", + "alt+x": "alt+x", + "+": "+", + } + for in, want := range cases { + c, ok := DecodeKeyName(in) + if !ok || c.String() != want { + t.Errorf("DecodeKeyName(%q) = %q, %v; want %q", in, c.String(), ok, want) + } + } +} diff --git a/internal/keybind/record.go b/internal/keybind/record.go new file mode 100644 index 0000000..f2407aa --- /dev/null +++ b/internal/keybind/record.go @@ -0,0 +1,223 @@ +package keybind + +import ( + "strconv" + "strings" + "unicode/utf8" +) + +// Key recording. +// +// While recording, the editor asks the terminal for the kitty keyboard +// protocol (flags 1|8: disambiguate escape codes, report all keys as escape +// codes). Ghostty then reports every key press, including ones with the +// super/cmd modifier, as "CSI code ; modifiers u" (or the legacy +// "CSI 1 ; modifiers A" forms for arrows and function keys). Terminals +// without the protocol send classic sequences, which are decoded from the +// key names Bubble Tea produces. + +// PushKitty and PopKitty enable and restore the kitty keyboard protocol. +// QueryKitty asks the terminal for the current flags; a terminal that +// supports the protocol answers with "CSI ? flags u". +const ( + PushKitty = "\x1b[>9u" + PopKitty = "\x1b[ 1 { + modField = params[1] + } + c := Combo{Mods: decodeMods(modField)} + + switch { + case final == 'u': + codeStr, _, _ := strings.Cut(params[0], ":") // drop shifted/base-layout keys + code, err := strconv.Atoi(codeStr) + if err != nil { + return Combo{}, false + } + if code >= 57441 && code <= 57452 { + c.Modifier = true // shift, ctrl, alt, super, hyper, meta, … keys + return c, true + } + if name, ok := kittyFunctional[code]; ok { + c.Key = name + if code == 57358 || code == 57360 { + c.Modifier = true // lock keys + } + return c, true + } + if code < 32 || !utf8.ValidRune(rune(code)) { + return Combo{}, false + } + c.Key = string(rune(code)) + return c, true + case final == '~': + code, err := strconv.Atoi(params[0]) + if err != nil { + return Combo{}, false + } + name, ok := tildeKeys[code] + if !ok { + return Combo{}, false + } + c.Key = name + return c, true + default: + name, ok := legacyFinal[final] + if !ok { + return Combo{}, false + } + c.Key = name + return c, true + } +} + +var legacyNames = map[string]string{ + "up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right", + "pgup": "page_up", "pgdown": "page_down", "home": "home", "end": "end", + "insert": "insert", "delete": "delete", "tab": "tab", "enter": "enter", + "esc": "escape", "backspace": "backspace", " ": "space", "space": "space", +} + +// DecodeKeyName converts a Bubble Tea key name ("ctrl+a", "alt+shift+up", +// "f5", "A") into a combination. Classic terminal input cannot represent +// super/cmd, and shifted symbols arrive as the symbol itself. +func DecodeKeyName(name string) (Combo, bool) { + c := Combo{Mods: map[string]bool{}} + if name == "" { + return c, false + } + switch name { + case "shift+tab": + c.Mods["shift"] = true + c.Key = "tab" + return c, true + case "ctrl+@", "ctrl+ ": + c.Mods["ctrl"] = true + c.Key = "space" + return c, true + } + rest := name + for { + found := false + for _, m := range []string{"ctrl+", "alt+", "shift+"} { + if strings.HasPrefix(rest, m) && len(rest) > len(m) { + c.Mods[strings.TrimSuffix(m, "+")] = true + rest = rest[len(m):] + found = true + } + } + if !found { + break + } + } + if k, ok := legacyNames[rest]; ok { + c.Key = k + return c, true + } + if len(rest) >= 2 && rest[0] == 'f' { + if n, err := strconv.Atoi(rest[1:]); err == nil && n >= 1 && n <= 25 { + c.Key = rest + return c, true + } + } + if utf8.RuneCountInString(rest) == 1 { + r, _ := utf8.DecodeRuneInString(rest) + if r >= 'A' && r <= 'Z' { + c.Mods["shift"] = true + r += 'a' - 'A' + } + c.Key = string(r) + return c, true + } + return c, false +} diff --git a/internal/keybind/set.go b/internal/keybind/set.go new file mode 100644 index 0000000..51814dd --- /dev/null +++ b/internal/keybind/set.go @@ -0,0 +1,326 @@ +package keybind + +import ( + "fmt" + "strings" +) + +// Source tells where an effective binding comes from. +type Source int + +const ( + Default Source = iota // Ghostty's built-in binding + Changed // a built-in trigger the user bound to another action + Custom // a user binding on a trigger without built-in binding + Unbound // a built-in binding the user removed +) + +func (s Source) String() string { + switch s { + case Changed: + return "changed" + case Custom: + return "custom" + case Unbound: + return "unbound" + } + return "default" +} + +// Entry is one parsed `keybind` value. +type Entry struct { + Value string + Flags string // e.g. "global:" + Trigger string // without flags, as written + Norm string // canonical identity of the trigger + Action string + Clear bool // "keybind = clear" + Chain bool // "keybind = chain=ACTION" +} + +// ParseEntry parses a raw `keybind` config value. +func ParseEntry(v string) Entry { + v = strings.TrimSpace(v) + if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' { + v = v[1 : len(v)-1] + } + e := Entry{Value: v} + if v == "clear" { + e.Clear = true + return e + } + t, a := Split(v) + e.Action = a + if t == "chain" { + e.Chain = true + return e + } + e.Flags, e.Trigger = StripFlags(t) + e.Norm = NormalizeLoose(t) + return e +} + +// Binding is one row of the effective key binding table. +type Binding struct { + Norm string + Trigger string // as written, including flag prefixes + Action string + Chain []string // actions chained with "chain=" + Source Source + Default string // Ghostty's built-in action for this trigger, if any + InConfig bool // the user's config has an entry for this trigger +} + +// group is a binding entry together with the "chain=" entries after it. +type group struct { + entries []string + e Entry +} + +func (g group) chain() []string { return g.entries[1:] } + +// Set is the user's keybind entries on top of Ghostty's defaults. +type Set struct { + defaults []Entry + defByNorm map[string]Entry + groups []group +} + +// NewSet builds a set from Ghostty's default values and the user's values. +func NewSet(defaults, user []string) *Set { + s := &Set{defByNorm: map[string]Entry{}} + for _, d := range defaults { + e := ParseEntry(d) + if e.Norm == "" || e.Action == "" { + continue + } + if _, dup := s.defByNorm[e.Norm]; !dup { + s.defaults = append(s.defaults, e) + } + s.defByNorm[e.Norm] = e + } + for _, v := range user { + e := ParseEntry(v) + if e.Chain && len(s.groups) > 0 && !s.groups[len(s.groups)-1].e.Clear { + last := &s.groups[len(s.groups)-1] + last.entries = append(last.entries, v) + continue + } + s.groups = append(s.groups, group{entries: []string{v}, e: e}) + } + return s +} + +// Values returns the user's keybind entries. +func (s *Set) Values() []string { + var out []string + for _, g := range s.groups { + out = append(out, g.entries...) + } + return out +} + +// HasClear reports whether the user's entries contain "clear". +func (s *Set) HasClear() bool { + for _, g := range s.groups { + if g.e.Clear { + return true + } + } + return false +} + +// effective computes the active bindings in insertion order. +func (s *Set) effective() (map[string]*Binding, []string) { + m := map[string]*Binding{} + var order []string + put := func(b *Binding) { + if _, ok := m[b.Norm]; !ok { + order = append(order, b.Norm) + } + m[b.Norm] = b + } + for _, d := range s.defaults { + put(&Binding{Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Default, Default: d.Action}) + } + for _, g := range s.groups { + e := g.e + switch { + case e.Clear: + m, order = map[string]*Binding{}, nil + case e.Chain || e.Norm == "": + case e.Action == "unbind": + delete(m, e.Norm) + default: + b := &Binding{Norm: e.Norm, Trigger: e.Flags + e.Trigger, Action: e.Action, InConfig: true, Source: Custom} + for _, c := range g.chain() { + _, a := Split(c) + b.Chain = append(b.Chain, a) + } + if d, ok := s.defByNorm[e.Norm]; ok { + b.Default = d.Action + b.Source = Changed + if d.Action == e.Action && d.Flags == e.Flags && len(b.Chain) == 0 { + b.Source = Default + } + } + put(b) + } + } + return m, order +} + +// Bindings returns every effective binding plus the built-in bindings that +// were removed (as Unbound). +func (s *Set) Bindings() []Binding { + m, order := s.effective() + var out []Binding + for _, n := range order { + if b, ok := m[n]; ok { + out = append(out, *b) + } + } + for _, d := range s.defaults { + if _, ok := m[d.Norm]; ok { + continue + } + out = append(out, Binding{ + Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Unbound, + Default: d.Action, InConfig: s.lastGroup(d.Norm) >= 0, + }) + } + return out +} + +// Lookup returns the effective binding for a trigger identity. +func (s *Set) Lookup(norm string) (Binding, bool) { + m, _ := s.effective() + if b, ok := m[norm]; ok { + return *b, true + } + return Binding{}, false +} + +// lastGroup returns the index of the last user group for norm, or -1. +func (s *Set) lastGroup(norm string) int { + for i := len(s.groups) - 1; i >= 0; i-- { + if s.groups[i].e.Norm == norm && !s.groups[i].e.Chain && !s.groups[i].e.Clear { + return i + } + } + return -1 +} + +// drop removes all user groups for norm except the one at keep (-1 for +// none) and returns the new index of the kept group. +func (s *Set) drop(norm string, keep int) int { + var out []group + newKeep := -1 + for i, g := range s.groups { + if g.e.Norm == norm && !g.e.Clear && !g.e.Chain && i != keep { + continue + } + if i == keep { + newKeep = len(out) + } + out = append(out, g) + } + s.groups = out + return newKeep +} + +func (s *Set) active(norm string) (Binding, bool) { return s.Lookup(norm) } + +func (s *Set) appendValue(v string) { + s.groups = append(s.groups, group{entries: []string{v}, e: ParseEntry(v)}) +} + +// Change binds value ("trigger=action"). When old is given, that binding is +// being edited: if its trigger changes, a built-in binding is unbound from +// its old trigger, while a user binding simply moves (the old trigger falls +// back to Ghostty's default, if it has one). Any other binding of the new +// trigger is replaced. +func (s *Set) Change(old *Binding, value string) error { + ne := ParseEntry(value) + if ne.Clear || ne.Chain || ne.Norm == "" || ne.Action == "" { + return fmt.Errorf("expected trigger=action") + } + if _, err := Normalize(ne.Flags + ne.Trigger); err != nil { + return err + } + + // The user's own entry for the edited binding, if any. + oldIdx := -1 + if old != nil && old.Source != Unbound { + if i := s.lastGroup(old.Norm); i >= 0 && s.groups[i].e.Action != "unbind" { + oldIdx = i + } + } + var chain []string + if oldIdx >= 0 { + chain = s.groups[oldIdx].chain() + } + g := group{entries: append([]string{ne.Value}, chain...), e: ne} + + var idx int + switch { + case oldIdx >= 0 && old.Source != Default: + // Rewrite the user's entry in place, then remove other entries for + // the old and the new trigger. If the trigger changed, the old one + // falls back to Ghostty's default (if it has one). + s.groups[oldIdx] = g + idx = s.drop(old.Norm, oldIdx) + idx = s.drop(ne.Norm, idx) + default: + if old != nil && old.Norm != ne.Norm && old.Source == Default { + // Moving a built-in binding: the old trigger must stop doing it. + s.drop(old.Norm, -1) + if _, still := s.active(old.Norm); still { + _, trigger := StripFlags(old.Trigger) + s.appendValue(trigger + "=unbind") + } + } + idx = s.drop(ne.Norm, s.lastGroup(ne.Norm)) + if idx >= 0 { + s.groups[idx] = g + } else { + s.groups = append(s.groups, g) + idx = len(s.groups) - 1 + } + } + + // A binding identical to Ghostty's default needs no config entry. + if d, ok := s.defByNorm[ne.Norm]; ok && d.Action == ne.Action && d.Flags == ne.Flags && len(chain) == 0 { + saved := append([]group(nil), s.groups...) + s.groups = append(s.groups[:idx:idx], s.groups[idx+1:]...) + if b, ok := s.active(ne.Norm); !ok || b.Action != ne.Action { + s.groups = saved // needed after all (e.g. after "clear") + } + } + return nil +} + +// Unbind removes the binding of b's trigger. +func (s *Set) Unbind(b Binding) { + if b.Source == Unbound { + return + } + s.drop(b.Norm, -1) + if _, still := s.active(b.Norm); still { + _, trigger := StripFlags(b.Trigger) + s.appendValue(trigger + "=unbind") + } +} + +// Restore resets b's trigger to Ghostty's built-in behavior: the built-in +// binding if there is one, otherwise no binding. +func (s *Set) Restore(b Binding) { + s.drop(b.Norm, -1) + d, ok := s.defByNorm[b.Norm] + if !ok { + return + } + if cur, active := s.active(b.Norm); !active || cur.Action != d.Action { + s.appendValue(d.Value) // e.g. after "keybind = clear" + } +} diff --git a/internal/schema/categories.go b/internal/schema/categories.go new file mode 100644 index 0000000..452caf2 --- /dev/null +++ b/internal/schema/categories.go @@ -0,0 +1,172 @@ +package schema + +import ( + "regexp" + "strings" +) + +// Ghostty itself has no option categories; these groupings exist only to +// make the editor easier to navigate. +const ( + CatFonts = "Fonts" + CatFontMetrics = "Font Metrics" + CatColors = "Colors & Theme" + CatBackground = "Background" + CatCursor = "Cursor" + CatWindow = "Window" + CatTabsSplits = "Tabs & Splits" + CatMouse = "Mouse & Selection" + CatClipboard = "Clipboard" + CatKeyboard = "Keyboard" + CatShell = "Shell & Commands" + CatScrolling = "Scrolling" + CatNotifications = "Notifications & Bell" + CatQuickTerminal = "Quick Terminal" + CatShaders = "Shaders" + CatMacOS = "macOS" + CatLinux = "Linux & GTK" + CatConfigFiles = "Config Files" + CatAdvanced = "Advanced" +) + +var categoryOrder = []string{ + CatFonts, CatFontMetrics, CatColors, CatBackground, CatCursor, CatWindow, + CatTabsSplits, CatMouse, CatClipboard, CatKeyboard, CatShell, CatScrolling, + CatNotifications, CatQuickTerminal, CatShaders, CatMacOS, CatLinux, + CatConfigFiles, CatAdvanced, +} + +// exact key assignments, checked before the prefix rules below. +var categoryByKey = map[string]string{ + "keybind": CatKeyboard, + "key-remap": CatKeyboard, + "macos-option-as-alt": CatKeyboard, + "vt-kam-allowed": CatKeyboard, + "config-file": CatConfigFiles, + "config-default-files": CatConfigFiles, + "cursor-click-to-move": CatMouse, + "theme": CatColors, + "background": CatColors, + "foreground": CatColors, + "bold-color": CatColors, + "minimum-contrast": CatColors, + "faint-opacity": CatColors, + "alpha-blending": CatColors, + "osc-color-report-format": CatColors, + "window-colorspace": CatColors, + "selection-foreground": CatColors, + "selection-background": CatColors, + "window-title-font-family": CatWindow, + "freetype-load-flags": CatFonts, + "grapheme-width-method": CatFonts, + "window-new-tab-position": CatTabsSplits, + "window-show-tab-bar": CatTabsSplits, + "window-inherit-working-directory": CatShell, + "tab-inherit-working-directory": CatShell, + "split-inherit-working-directory": CatShell, + "scrollback-limit": CatScrolling, + "scrollbar": CatScrolling, + "scroll-to-bottom": CatScrolling, + "mouse-scroll-multiplier": CatScrolling, + "focus-follows-mouse": CatMouse, + "click-repeat-interval": CatMouse, + "right-click-action": CatMouse, + "copy-on-select": CatClipboard, + "command": CatShell, + "initial-command": CatShell, + "env": CatShell, + "input": CatShell, + "working-directory": CatShell, + "wait-after-command": CatShell, + "abnormal-command-exit-runtime": CatShell, + "term": CatShell, + "enquiry-response": CatShell, + "command-palette-entry": CatShell, + "app-notifications": CatNotifications, + "desktop-notifications": CatNotifications, + "progress-style": CatNotifications, + "auto-update": CatMacOS, + "auto-update-channel": CatMacOS, + "class": CatLinux, + "async-backend": CatLinux, + "language": CatLinux, + "maximize": CatWindow, + "fullscreen": CatWindow, + "title": CatWindow, + "initial-window": CatWindow, + "confirm-close-surface": CatWindow, + "undo-timeout": CatWindow, +} + +var categoryPrefixes = []struct { + prefix, cat string +}{ + {"quick-terminal-", CatQuickTerminal}, + {"gtk-quick-terminal-", CatQuickTerminal}, + {"custom-shader", CatShaders}, + {"adjust-cursor-", CatCursor}, + {"adjust-", CatFontMetrics}, + {"font-", CatFonts}, + {"cursor-", CatCursor}, + {"background-", CatBackground}, + {"palette", CatColors}, + {"search-", CatColors}, + {"split-", CatTabsSplits}, + {"unfocused-split-", CatTabsSplits}, + {"mouse-", CatMouse}, + {"selection-", CatMouse}, + {"link", CatMouse}, + {"clipboard-", CatClipboard}, + {"shell-integration", CatShell}, + {"bell-", CatNotifications}, + {"notify-on-", CatNotifications}, + {"macos-", CatMacOS}, + {"gtk-", CatLinux}, + {"linux-", CatLinux}, + {"x11-", CatLinux}, + {"window-", CatWindow}, + {"resize-overlay", CatWindow}, + {"quit-after-", CatWindow}, +} + +func categorize(key string) string { + if c, ok := categoryByKey[key]; ok { + return c + } + for _, p := range categoryPrefixes { + if strings.HasPrefix(key, p.prefix) { + return p.cat + } + } + return CatAdvanced +} + +// platform reports which OS an option is limited to, based on its key +// prefix and on sentences like "This is only supported on macOS." in its +// documentation. Notes about individual values (e.g. "(macOS only)" in a +// list item) or about several platforms are ignored. +func platform(o *Option) string { + switch { + case strings.HasPrefix(o.Key, "macos-"): + return "macOS" + case strings.HasPrefix(o.Key, "gtk-"), strings.HasPrefix(o.Key, "linux-"), + strings.HasPrefix(o.Key, "x11-"): + return "Linux" + } + text := strings.Join(strings.Fields(o.Doc), " ") + for _, sentence := range strings.SplitAfter(text, ". ") { + m := rePlatformNote.FindStringSubmatch(strings.ToLower(strings.TrimSpace(sentence))) + if m == nil { + continue + } + if m[1] == "macos" || m[2] == "macos" { + return "macOS" + } + return "Linux" + } + return "" +} + +var rePlatformNote = regexp.MustCompile( + `^(?:note: )?(?:(?:this|it)(?: \w+)? (?:is )?)?(?:currently )?only (?:supported|implemented|available) on (macos|linux|gtk)\b(?: \(gtk\))?[.,;]?$` + + `|^(macos|gtk|linux) only\.?$`) diff --git a/internal/schema/schema.go b/internal/schema/schema.go new file mode 100644 index 0000000..39e7682 --- /dev/null +++ b/internal/schema/schema.go @@ -0,0 +1,334 @@ +// Package schema describes every Ghostty configuration option: its value +// kind, allowed values, documentation and default values. +// +// The type information is generated from Ghostty's Config.zig (see +// tools/genschema) and embedded into the binary. Documentation and defaults +// are refreshed at runtime from the installed Ghostty binary when available, +// so they always match the version the user actually runs. +package schema + +import ( + _ "embed" + "encoding/json" + "fmt" + "sort" + "strconv" + "strings" +) + +// Kind describes how the value of an option is edited and validated. +type Kind string + +const ( + KindBool Kind = "bool" + KindEnum Kind = "enum" // one of Values + KindChoice Kind = "choice" // one of Values or a custom value + KindFlags Kind = "flags" // comma separated set of Flags, "no-" prefix disables + KindInt Kind = "int" // integer within Min/Max + KindFloat Kind = "float" // floating point number + KindColor Kind = "color" // hex or X11 color name, plus optional Values + KindColorList Kind = "colorlist" // comma separated colors + KindMetric Kind = "metric" // integer or percentage, e.g. "2" or "-10%" + KindDuration Kind = "duration" // e.g. "750ms", "1h30m" + KindPadding Kind = "padding" // "2" or "2,4" + KindText Kind = "text" + KindPath Kind = "path" + KindTheme Kind = "theme" + KindFont Kind = "font" + KindKeybind Kind = "keybind" + KindPalette Kind = "palette" +) + +// Option is a single configuration key. +type Option struct { + Key string `json:"key"` + ZigType string `json:"zigType,omitempty"` + Kind Kind `json:"kind"` + Repeatable bool `json:"repeatable,omitempty"` + Values []string `json:"values,omitempty"` + Flags []string `json:"flags,omitempty"` + Min *float64 `json:"min,omitempty"` + Max *float64 `json:"max,omitempty"` + Hint string `json:"hint,omitempty"` + Doc string `json:"doc,omitempty"` + Defaults []string `json:"defaults,omitempty"` + // NotListed marks options that Ghostty accepts but does not print + // with `+show-config`. They are kept even when refreshing from a live + // Ghostty binary. + NotListed bool `json:"notListed,omitempty"` + + Category string `json:"-"` + Platform string `json:"-"` // "", "macOS" or "Linux" +} + +// Default returns the default value for scalar options ("" when unset). +func (o *Option) Default() string { + if len(o.Defaults) == 0 { + return "" + } + return o.Defaults[len(o.Defaults)-1] +} + +// DefaultList returns the default entries of a repeatable option, ignoring +// the empty placeholder entry Ghostty prints for empty lists. +func (o *Option) DefaultList() []string { + var out []string + for _, d := range o.Defaults { + if d != "" { + out = append(out, d) + } + } + return out +} + +// TypeLabel is a short human readable description of the value type. +func (o *Option) TypeLabel() string { + var s string + switch o.Kind { + case KindBool: + s = "boolean" + case KindEnum: + s = "one of " + strings.Join(o.Values, ", ") + case KindChoice: + s = strings.Join(o.Values, ", ") + " or custom value" + case KindFlags: + s = "flags: " + strings.Join(o.Flags, ", ") + case KindInt: + s = "integer" + if o.Min != nil && o.Max != nil { + s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max)) + } else if o.Min != nil { + s += fmt.Sprintf(" (%s or more)", num(*o.Min)) + } + case KindFloat: + s = "number" + if o.Min != nil && o.Max != nil { + s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max)) + } else if o.Min != nil { + s += fmt.Sprintf(" (%s or more)", num(*o.Min)) + } + case KindColor: + s = "color (#rrggbb or X11 name)" + if len(o.Values) > 0 { + s += " or " + strings.Join(o.Values, ", ") + } + case KindColorList: + s = "comma separated colors" + case KindMetric: + s = "integer or percentage (e.g. 2, -10%)" + case KindDuration: + s = "duration (e.g. 500ms, 5s, 1h30m)" + case KindPadding: + s = "pixels, optionally two values (e.g. 2 or 2,4)" + case KindPath: + s = "file path" + case KindTheme: + s = "theme name (or light:NAME,dark:NAME)" + case KindFont: + s = "font family" + case KindKeybind: + s = "key binding (trigger=action)" + case KindPalette: + s = "palette entries (N=color)" + default: + s = "text" + } + if o.Repeatable && o.Kind != KindKeybind && o.Kind != KindPalette { + s = "list of " + s + } + return s +} + +// Schema is the full set of known options. +type Schema struct { + GhosttyVersion string `json:"ghosttyVersion"` + Options []*Option `json:"options"` + // Source describes where docs and defaults came from. + Source string `json:"-"` + + byKey map[string]*Option +} + +//go:embed schema.json +var embedded []byte + +// Embedded returns the schema compiled into the binary. +func Embedded() (*Schema, error) { + var s Schema + if err := json.Unmarshal(embedded, &s); err != nil { + return nil, fmt.Errorf("decode embedded schema: %w", err) + } + s.Source = "built-in (Ghostty " + s.GhosttyVersion + ")" + s.finish() + return &s, nil +} + +// Lookup returns the option for key, or nil. +func (s *Schema) Lookup(key string) *Option { + return s.byKey[key] +} + +func (s *Schema) finish() { + s.byKey = make(map[string]*Option, len(s.Options)) + for _, o := range s.Options { + o.Category = categorize(o.Key) + o.Platform = platform(o) + s.byKey[o.Key] = o + } +} + +// Refresh replaces docs and defaults with the output of +// `ghostty +show-config --default --docs` from the installed Ghostty. +// Options unknown to the installed version are dropped; options unknown to +// the embedded schema are added with an inferred kind. +func (s *Schema) Refresh(docsOutput, version string) { + parsed := ParseDocs(docsOutput) + if len(parsed) == 0 { + return + } + var opts []*Option + seen := make(map[string]bool) + for _, p := range parsed { + seen[p.Key] = true + o := s.byKey[p.Key] + if o == nil { + o = inferOption(p) + } + o.Doc = p.Doc + o.Defaults = p.Defaults + opts = append(opts, o) + } + for _, o := range s.Options { + if !seen[o.Key] && o.NotListed { + opts = append(opts, o) + } + } + s.Options = opts + if version != "" { + s.GhosttyVersion = version + } + s.Source = "Ghostty " + s.GhosttyVersion + s.finish() +} + +// inferOption guesses the kind of an option the embedded schema does not +// know about (e.g. one added in a newer Ghostty release). +func inferOption(p DocEntry) *Option { + o := &Option{Key: p.Key, Kind: KindText, Repeatable: len(p.Defaults) > 1} + d := "" + if len(p.Defaults) > 0 { + d = p.Defaults[0] + } + switch { + case d == "true" || d == "false": + o.Kind = KindBool + case isNumber(d): + o.Kind = KindFloat + } + return o +} + +func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) } + +func isNumber(s string) bool { + if s == "" { + return false + } + var f float64 + _, err := fmt.Sscanf(s, "%g", &f) + return err == nil && strings.TrimLeft(s, "-+0123456789.") == "" +} + +// DocEntry is one key parsed from `+show-config --default --docs`. +type DocEntry struct { + Key string + Doc string + Defaults []string +} + +// ParseDocs parses the output of `ghostty +show-config --default --docs`. +// Keys that directly follow another key without their own comment block +// share the previous documentation (e.g. font-family-bold). +func ParseDocs(out string) []DocEntry { + var ( + entries []DocEntry + index = map[string]int{} + pending []string + lastDoc string + ) + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSuffix(line, "\r") + switch { + case strings.HasPrefix(line, "#"): + text := strings.TrimPrefix(line, "#") + text = strings.TrimPrefix(text, " ") + pending = append(pending, text) + case strings.TrimSpace(line) == "": + continue + default: + key, value, ok := splitShowConfigLine(line) + if !ok { + continue + } + if len(pending) > 0 { + lastDoc = strings.TrimRight(strings.Join(pending, "\n"), "\n ") + pending = nil + } + if i, ok := index[key]; ok { + entries[i].Defaults = append(entries[i].Defaults, value) + continue + } + index[key] = len(entries) + entries = append(entries, DocEntry{Key: key, Doc: lastDoc, Defaults: []string{value}}) + } + } + return entries +} + +// splitShowConfigLine splits "key = value". The value is kept verbatim +// because leading whitespace can be significant (selection-word-chars). +func splitShowConfigLine(line string) (key, value string, ok bool) { + i := strings.Index(line, " =") + if i <= 0 { + return "", "", false + } + key = line[:i] + if strings.ContainsAny(key, " \t") { + return "", "", false + } + value = strings.TrimPrefix(line[i+2:], " ") + return key, value, true +} + +// Categories returns category names in display order, restricted to those +// that contain at least one option. +func (s *Schema) Categories() []string { + present := map[string]bool{} + for _, o := range s.Options { + present[o.Category] = true + } + var out []string + for _, c := range categoryOrder { + if present[c] { + out = append(out, c) + delete(present, c) + } + } + var rest []string + for c := range present { + rest = append(rest, c) + } + sort.Strings(rest) + return append(out, rest...) +} + +// InCategory returns the options of a category in schema order. +func (s *Schema) InCategory(cat string) []*Option { + var out []*Option + for _, o := range s.Options { + if o.Category == cat { + out = append(out, o) + } + } + return out +} diff --git a/internal/schema/schema.json b/internal/schema/schema.json new file mode 100644 index 0000000..268c423 --- /dev/null +++ b/internal/schema/schema.json @@ -0,0 +1,2711 @@ +{ + "ghosttyVersion": "1.3.1", + "options": [ + { + "key": "language", + "zigType": "?[:0]const u8", + "kind": "text", + "doc": "Set Ghostty's graphical user interface language to a language other than the\nsystem default language. For example:\n\n language = de\n\nwill force the strings in Ghostty's graphical user interface to be in German\nrather than the system default.\n\nThis will not affect the language used by programs run _within_ Ghostty.\nThose will continue to use the default system language. There are also many\nnon-GUI elements in Ghostty that are not translated - this setting will have\nno effect on those.\n\nWarning: This setting cannot be reloaded at runtime. To change the language\nyou must fully restart Ghostty.\n\nGTK only.\nAvailable since 1.3.0.", + "defaults": [ + "" + ] + }, + { + "key": "font-family", + "zigType": "RepeatableString", + "kind": "font", + "repeatable": true, + "doc": "The font families to use.\n\nYou can generate the list of valid values using the CLI:\n\n ghostty +list-fonts\n\nThis configuration can be repeated multiple times to specify preferred\nfallback fonts when the requested codepoint is not available in the primary\nfont. This is particularly useful for multiple languages, symbolic fonts,\netc.\n\nNotes on emoji specifically: On macOS, Ghostty by default will always use\nApple Color Emoji and on Linux will always use Noto Emoji. You can\noverride this behavior by specifying a font family here that contains\nemoji glyphs.\n\nThe specific styles (bold, italic, bold italic) do not need to be\nexplicitly set. If a style is not set, then the regular style (font-family)\nwill be searched for stylistic variants. If a stylistic variant is not\nfound, Ghostty will use the regular style. This prevents falling back to a\ndifferent font family just to get a style such as bold. This also applies\nif you explicitly specify a font family for a style. For example, if you\nset `font-family-bold = FooBar` and \"FooBar\" cannot be found, Ghostty will\nuse whatever font is set for `font-family` for the bold style.\n\nFinally, some styles may be synthesized if they are not supported.\nFor example, if a font does not have an italic style and no alternative\nitalic font is specified, Ghostty will synthesize an italic style by\napplying a slant to the regular style. If you want to disable these\nsynthesized styles then you can use the `font-style` configurations\nas documented below.\n\nYou can disable styles completely by using the `font-style` set of\nconfigurations. See the documentation for `font-style` for more information.\n\nIf you want to overwrite a previous set value rather than append a fallback,\nspecify the value as `\"\"` (empty string) to reset the list and then set the\nnew values. For example:\n\n font-family = \"\"\n font-family = \"My Favorite Font\"\n\nSetting any of these as CLI arguments will automatically clear the\nvalues set in configuration files so you don't need to specify\n`--font-family=\"\"` before setting a new value. You only need to specify\nthis within config files if you want to clear previously set values in\nconfiguration files or on the CLI if you want to clear values set on the\nCLI.", + "defaults": [ + "" + ] + }, + { + "key": "font-family-bold", + "zigType": "RepeatableString", + "kind": "font", + "repeatable": true, + "doc": "The font families to use.\n\nYou can generate the list of valid values using the CLI:\n\n ghostty +list-fonts\n\nThis configuration can be repeated multiple times to specify preferred\nfallback fonts when the requested codepoint is not available in the primary\nfont. This is particularly useful for multiple languages, symbolic fonts,\netc.\n\nNotes on emoji specifically: On macOS, Ghostty by default will always use\nApple Color Emoji and on Linux will always use Noto Emoji. You can\noverride this behavior by specifying a font family here that contains\nemoji glyphs.\n\nThe specific styles (bold, italic, bold italic) do not need to be\nexplicitly set. If a style is not set, then the regular style (font-family)\nwill be searched for stylistic variants. If a stylistic variant is not\nfound, Ghostty will use the regular style. This prevents falling back to a\ndifferent font family just to get a style such as bold. This also applies\nif you explicitly specify a font family for a style. For example, if you\nset `font-family-bold = FooBar` and \"FooBar\" cannot be found, Ghostty will\nuse whatever font is set for `font-family` for the bold style.\n\nFinally, some styles may be synthesized if they are not supported.\nFor example, if a font does not have an italic style and no alternative\nitalic font is specified, Ghostty will synthesize an italic style by\napplying a slant to the regular style. If you want to disable these\nsynthesized styles then you can use the `font-style` configurations\nas documented below.\n\nYou can disable styles completely by using the `font-style` set of\nconfigurations. See the documentation for `font-style` for more information.\n\nIf you want to overwrite a previous set value rather than append a fallback,\nspecify the value as `\"\"` (empty string) to reset the list and then set the\nnew values. For example:\n\n font-family = \"\"\n font-family = \"My Favorite Font\"\n\nSetting any of these as CLI arguments will automatically clear the\nvalues set in configuration files so you don't need to specify\n`--font-family=\"\"` before setting a new value. You only need to specify\nthis within config files if you want to clear previously set values in\nconfiguration files or on the CLI if you want to clear values set on the\nCLI.", + "defaults": [ + "" + ] + }, + { + "key": "font-family-italic", + "zigType": "RepeatableString", + "kind": "font", + "repeatable": true, + "doc": "The font families to use.\n\nYou can generate the list of valid values using the CLI:\n\n ghostty +list-fonts\n\nThis configuration can be repeated multiple times to specify preferred\nfallback fonts when the requested codepoint is not available in the primary\nfont. This is particularly useful for multiple languages, symbolic fonts,\netc.\n\nNotes on emoji specifically: On macOS, Ghostty by default will always use\nApple Color Emoji and on Linux will always use Noto Emoji. You can\noverride this behavior by specifying a font family here that contains\nemoji glyphs.\n\nThe specific styles (bold, italic, bold italic) do not need to be\nexplicitly set. If a style is not set, then the regular style (font-family)\nwill be searched for stylistic variants. If a stylistic variant is not\nfound, Ghostty will use the regular style. This prevents falling back to a\ndifferent font family just to get a style such as bold. This also applies\nif you explicitly specify a font family for a style. For example, if you\nset `font-family-bold = FooBar` and \"FooBar\" cannot be found, Ghostty will\nuse whatever font is set for `font-family` for the bold style.\n\nFinally, some styles may be synthesized if they are not supported.\nFor example, if a font does not have an italic style and no alternative\nitalic font is specified, Ghostty will synthesize an italic style by\napplying a slant to the regular style. If you want to disable these\nsynthesized styles then you can use the `font-style` configurations\nas documented below.\n\nYou can disable styles completely by using the `font-style` set of\nconfigurations. See the documentation for `font-style` for more information.\n\nIf you want to overwrite a previous set value rather than append a fallback,\nspecify the value as `\"\"` (empty string) to reset the list and then set the\nnew values. For example:\n\n font-family = \"\"\n font-family = \"My Favorite Font\"\n\nSetting any of these as CLI arguments will automatically clear the\nvalues set in configuration files so you don't need to specify\n`--font-family=\"\"` before setting a new value. You only need to specify\nthis within config files if you want to clear previously set values in\nconfiguration files or on the CLI if you want to clear values set on the\nCLI.", + "defaults": [ + "" + ] + }, + { + "key": "font-family-bold-italic", + "zigType": "RepeatableString", + "kind": "font", + "repeatable": true, + "doc": "The font families to use.\n\nYou can generate the list of valid values using the CLI:\n\n ghostty +list-fonts\n\nThis configuration can be repeated multiple times to specify preferred\nfallback fonts when the requested codepoint is not available in the primary\nfont. This is particularly useful for multiple languages, symbolic fonts,\netc.\n\nNotes on emoji specifically: On macOS, Ghostty by default will always use\nApple Color Emoji and on Linux will always use Noto Emoji. You can\noverride this behavior by specifying a font family here that contains\nemoji glyphs.\n\nThe specific styles (bold, italic, bold italic) do not need to be\nexplicitly set. If a style is not set, then the regular style (font-family)\nwill be searched for stylistic variants. If a stylistic variant is not\nfound, Ghostty will use the regular style. This prevents falling back to a\ndifferent font family just to get a style such as bold. This also applies\nif you explicitly specify a font family for a style. For example, if you\nset `font-family-bold = FooBar` and \"FooBar\" cannot be found, Ghostty will\nuse whatever font is set for `font-family` for the bold style.\n\nFinally, some styles may be synthesized if they are not supported.\nFor example, if a font does not have an italic style and no alternative\nitalic font is specified, Ghostty will synthesize an italic style by\napplying a slant to the regular style. If you want to disable these\nsynthesized styles then you can use the `font-style` configurations\nas documented below.\n\nYou can disable styles completely by using the `font-style` set of\nconfigurations. See the documentation for `font-style` for more information.\n\nIf you want to overwrite a previous set value rather than append a fallback,\nspecify the value as `\"\"` (empty string) to reset the list and then set the\nnew values. For example:\n\n font-family = \"\"\n font-family = \"My Favorite Font\"\n\nSetting any of these as CLI arguments will automatically clear the\nvalues set in configuration files so you don't need to specify\n`--font-family=\"\"` before setting a new value. You only need to specify\nthis within config files if you want to clear previously set values in\nconfiguration files or on the CLI if you want to clear values set on the\nCLI.", + "defaults": [ + "" + ] + }, + { + "key": "font-style", + "zigType": "FontStyle", + "kind": "choice", + "values": [ + "default", + "false" + ], + "hint": "a style name such as Heavy, or default / false", + "doc": "The named font style to use for each of the requested terminal font styles.\nThis looks up the style based on the font style string advertised by the\nfont itself. For example, \"Iosevka Heavy\" has a style of \"Heavy\".\n\nYou can also use these fields to completely disable a font style. If you set\nthe value of the configuration below to literal `false` then that font style\nwill be disabled. If the running program in the terminal requests a disabled\nfont style, the regular font style will be used instead.\n\nThese are only valid if its corresponding font-family is also specified. If\nno font-family is specified, then the font-style is ignored unless you're\ndisabling the font style.", + "defaults": [ + "default" + ] + }, + { + "key": "font-style-bold", + "zigType": "FontStyle", + "kind": "choice", + "values": [ + "default", + "false" + ], + "hint": "a style name such as Heavy, or default / false", + "doc": "The named font style to use for each of the requested terminal font styles.\nThis looks up the style based on the font style string advertised by the\nfont itself. For example, \"Iosevka Heavy\" has a style of \"Heavy\".\n\nYou can also use these fields to completely disable a font style. If you set\nthe value of the configuration below to literal `false` then that font style\nwill be disabled. If the running program in the terminal requests a disabled\nfont style, the regular font style will be used instead.\n\nThese are only valid if its corresponding font-family is also specified. If\nno font-family is specified, then the font-style is ignored unless you're\ndisabling the font style.", + "defaults": [ + "default" + ] + }, + { + "key": "font-style-italic", + "zigType": "FontStyle", + "kind": "choice", + "values": [ + "default", + "false" + ], + "hint": "a style name such as Heavy, or default / false", + "doc": "The named font style to use for each of the requested terminal font styles.\nThis looks up the style based on the font style string advertised by the\nfont itself. For example, \"Iosevka Heavy\" has a style of \"Heavy\".\n\nYou can also use these fields to completely disable a font style. If you set\nthe value of the configuration below to literal `false` then that font style\nwill be disabled. If the running program in the terminal requests a disabled\nfont style, the regular font style will be used instead.\n\nThese are only valid if its corresponding font-family is also specified. If\nno font-family is specified, then the font-style is ignored unless you're\ndisabling the font style.", + "defaults": [ + "default" + ] + }, + { + "key": "font-style-bold-italic", + "zigType": "FontStyle", + "kind": "choice", + "values": [ + "default", + "false" + ], + "hint": "a style name such as Heavy, or default / false", + "doc": "The named font style to use for each of the requested terminal font styles.\nThis looks up the style based on the font style string advertised by the\nfont itself. For example, \"Iosevka Heavy\" has a style of \"Heavy\".\n\nYou can also use these fields to completely disable a font style. If you set\nthe value of the configuration below to literal `false` then that font style\nwill be disabled. If the running program in the terminal requests a disabled\nfont style, the regular font style will be used instead.\n\nThese are only valid if its corresponding font-family is also specified. If\nno font-family is specified, then the font-style is ignored unless you're\ndisabling the font style.", + "defaults": [ + "default" + ] + }, + { + "key": "font-synthetic-style", + "zigType": "FontSyntheticStyle", + "kind": "flags", + "flags": [ + "bold", + "italic", + "bold-italic" + ], + "doc": "Control whether Ghostty should synthesize a style if the requested style is\nnot available in the specified font-family.\n\nGhostty can synthesize bold, italic, and bold italic styles if the font\ndoes not have a specific style. For bold, this is done by drawing an\noutline around the glyph of varying thickness. For italic, this is done by\napplying a slant to the glyph. For bold italic, both of these are applied.\n\nSynthetic styles are not perfect and will generally not look as good\nas a font that has the style natively. However, they are useful to\nprovide styled text when the font does not have the style.\n\nSet this to \"false\" or \"true\" to disable or enable synthetic styles\ncompletely. You can disable specific styles using \"no-bold\", \"no-italic\",\nand \"no-bold-italic\". You can disable multiple styles by separating them\nwith a comma. For example, \"no-bold,no-italic\".\n\nAvailable style keys are: `bold`, `italic`, `bold-italic`.\n\nIf synthetic styles are disabled, then the regular style will be used\ninstead if the requested style is not available. If the font has the\nrequested style, then the font will be used as-is since the style is\nnot synthetic.\n\nWarning: An easy mistake is to disable `bold` or `italic` but not\n`bold-italic`. Disabling only `bold` or `italic` will NOT disable either\nin the `bold-italic` style. If you want to disable `bold-italic`, you must\nexplicitly disable it. You cannot partially disable `bold-italic`.\n\nBy default, synthetic styles are enabled.", + "defaults": [ + "bold,italic,bold-italic" + ] + }, + { + "key": "font-feature", + "zigType": "RepeatableString", + "kind": "text", + "repeatable": true, + "hint": "e.g. -calt, +ss01, cv01=2", + "doc": "Apply a font feature. To enable multiple font features you can repeat\nthis multiple times or use a comma-separated list of feature settings.\n\nThe syntax for feature settings is as follows, where `feat` is a feature:\n\n * Enable features with e.g. `feat`, `+feat`, `feat on`, `feat=1`.\n * Disabled features with e.g. `-feat`, `feat off`, `feat=0`.\n * Set a feature value with e.g. `feat=2`, `feat = 3`, `feat 4`.\n * Feature names may be wrapped in quotes, meaning this config should be\n syntactically compatible with the `font-feature-settings` CSS property.\n\nThe syntax is fairly loose, but invalid settings will be silently ignored.\n\nThe font feature will apply to all fonts rendered by Ghostty. A future\nenhancement will allow targeting specific faces.\n\nTo disable programming ligatures, use `-calt` since this is the typical\nfeature name for programming ligatures. To look into what font features\nyour font has and what they do, use a font inspection tool such as\n[fontdrop.info](https://fontdrop.info).\n\nTo generally disable most ligatures, use `-calt, -liga, -dlig`.", + "defaults": [ + "" + ] + }, + { + "key": "font-size", + "zigType": "f32", + "kind": "float", + "min": 1, + "doc": "Font size in points. This value can be a non-integer and the nearest integer\npixel size will be selected. If you have a high dpi display where 1pt = 2px\nthen you can get an odd numbered pixel size by specifying a half point.\n\nFor example, 13.5pt @ 2px/pt = 27px\n\nChanging this configuration at runtime will only affect existing\nterminals that have NOT manually adjusted their font size in some way\n(e.g. increased or decreased the font size). Terminals that have manually\nadjusted their font size will retain their manually adjusted size.\nOtherwise, the font size of existing terminals will be updated on\nreload.\n\nOn Linux with GTK, font size is scaled according to both display-wide and\ntext-specific scaling factors, which are often managed by your desktop\nenvironment (e.g. the GNOME display scale and large text settings).", + "defaults": [ + "13" + ] + }, + { + "key": "font-variation", + "zigType": "RepeatableFontVariation", + "kind": "text", + "repeatable": true, + "hint": "axis=value, e.g. wght=600", + "doc": "A repeatable configuration to set one or more font variations values for\na variable font. A variable font is a single font, usually with a filename\nending in `-VF.ttf` or `-VF.otf` that contains one or more configurable axes\nfor things such as weight, slant, etc. Not all fonts support variations;\nonly fonts that explicitly state they are variable fonts will work.\n\nThe format of this is `id=value` where `id` is the axis identifier. An axis\nidentifier is always a 4 character string, such as `wght`. To get the list\nof supported axes, look at your font documentation or use a font inspection\ntool.\n\nInvalid ids and values are usually ignored. For example, if a font only\nsupports weights from 100 to 700, setting `wght=800` will do nothing (it\nwill not be clamped to 700). You must consult your font's documentation to\nsee what values are supported.\n\nCommon axes are: `wght` (weight), `slnt` (slant), `ital` (italic), `opsz`\n(optical size), `wdth` (width), `GRAD` (gradient), etc.", + "defaults": [ + "" + ] + }, + { + "key": "font-variation-bold", + "zigType": "RepeatableFontVariation", + "kind": "text", + "repeatable": true, + "hint": "axis=value, e.g. wght=600", + "doc": "A repeatable configuration to set one or more font variations values for\na variable font. A variable font is a single font, usually with a filename\nending in `-VF.ttf` or `-VF.otf` that contains one or more configurable axes\nfor things such as weight, slant, etc. Not all fonts support variations;\nonly fonts that explicitly state they are variable fonts will work.\n\nThe format of this is `id=value` where `id` is the axis identifier. An axis\nidentifier is always a 4 character string, such as `wght`. To get the list\nof supported axes, look at your font documentation or use a font inspection\ntool.\n\nInvalid ids and values are usually ignored. For example, if a font only\nsupports weights from 100 to 700, setting `wght=800` will do nothing (it\nwill not be clamped to 700). You must consult your font's documentation to\nsee what values are supported.\n\nCommon axes are: `wght` (weight), `slnt` (slant), `ital` (italic), `opsz`\n(optical size), `wdth` (width), `GRAD` (gradient), etc.", + "defaults": [ + "" + ] + }, + { + "key": "font-variation-italic", + "zigType": "RepeatableFontVariation", + "kind": "text", + "repeatable": true, + "hint": "axis=value, e.g. wght=600", + "doc": "A repeatable configuration to set one or more font variations values for\na variable font. A variable font is a single font, usually with a filename\nending in `-VF.ttf` or `-VF.otf` that contains one or more configurable axes\nfor things such as weight, slant, etc. Not all fonts support variations;\nonly fonts that explicitly state they are variable fonts will work.\n\nThe format of this is `id=value` where `id` is the axis identifier. An axis\nidentifier is always a 4 character string, such as `wght`. To get the list\nof supported axes, look at your font documentation or use a font inspection\ntool.\n\nInvalid ids and values are usually ignored. For example, if a font only\nsupports weights from 100 to 700, setting `wght=800` will do nothing (it\nwill not be clamped to 700). You must consult your font's documentation to\nsee what values are supported.\n\nCommon axes are: `wght` (weight), `slnt` (slant), `ital` (italic), `opsz`\n(optical size), `wdth` (width), `GRAD` (gradient), etc.", + "defaults": [ + "" + ] + }, + { + "key": "font-variation-bold-italic", + "zigType": "RepeatableFontVariation", + "kind": "text", + "repeatable": true, + "hint": "axis=value, e.g. wght=600", + "doc": "A repeatable configuration to set one or more font variations values for\na variable font. A variable font is a single font, usually with a filename\nending in `-VF.ttf` or `-VF.otf` that contains one or more configurable axes\nfor things such as weight, slant, etc. Not all fonts support variations;\nonly fonts that explicitly state they are variable fonts will work.\n\nThe format of this is `id=value` where `id` is the axis identifier. An axis\nidentifier is always a 4 character string, such as `wght`. To get the list\nof supported axes, look at your font documentation or use a font inspection\ntool.\n\nInvalid ids and values are usually ignored. For example, if a font only\nsupports weights from 100 to 700, setting `wght=800` will do nothing (it\nwill not be clamped to 700). You must consult your font's documentation to\nsee what values are supported.\n\nCommon axes are: `wght` (weight), `slnt` (slant), `ital` (italic), `opsz`\n(optical size), `wdth` (width), `GRAD` (gradient), etc.", + "defaults": [ + "" + ] + }, + { + "key": "font-codepoint-map", + "zigType": "RepeatableCodepointMap", + "kind": "text", + "repeatable": true, + "hint": "U+E000-U+E0FF,U+F000=Font Family", + "doc": "Force one or a range of Unicode codepoints to map to a specific named font.\nThis is useful if you want to support special symbols or if you want to use\nspecific glyphs that render better for your specific font.\n\nThe syntax is `codepoint=fontname` where `codepoint` is either a single\ncodepoint or a range. Codepoints must be specified as full Unicode\nhex values, such as `U+ABCD`. Codepoints ranges are specified as\n`U+ABCD-U+DEFG`. You can specify multiple ranges for the same font separated\nby commas, such as `U+ABCD-U+DEFG,U+1234-U+5678=fontname`. The font name is\nthe same value as you would use for `font-family`.\n\nThis configuration can be repeated multiple times to specify multiple\ncodepoint mappings.\n\nChanging this configuration at runtime will only affect new terminals,\ni.e. new windows, tabs, etc.", + "defaults": [ + "" + ] + }, + { + "key": "clipboard-codepoint-map", + "zigType": "RepeatableClipboardCodepointMap", + "kind": "text", + "repeatable": true, + "hint": "U+2500-U+257F=U+002B", + "doc": "Map specific Unicode codepoints to replacement values when copying text\nto clipboard.\n\nThis configuration allows you to replace specific Unicode characters with\nother characters or strings when copying terminal content to the clipboard.\nThis is useful for converting special terminal symbols to more compatible\ncharacters for pasting into other applications.\n\nThe syntax is similar to `font-codepoint-map`:\n- Single codepoint: `U+1234=U+ABCD` or `U+1234=replacement_text`\n- Codepoint range: `U+1234-U+5678=U+ABCD`\n\nExamples:\n- `clipboard-codepoint-map = U+2500=U+002D` (box drawing horizontal → hyphen)\n- `clipboard-codepoint-map = U+2502=U+007C` (box drawing vertical → pipe)\n- `clipboard-codepoint-map = U+03A3=SUM` (Greek sigma → \"SUM\")\n\nThis configuration can be repeated multiple times to specify multiple\nmappings. Later entries take priority over earlier ones for overlapping\nranges.\n\nNote: This only applies to text copying operations, not URL copying.", + "defaults": [ + "" + ] + }, + { + "key": "font-thicken", + "zigType": "bool", + "kind": "bool", + "doc": "Draw fonts with a thicker stroke, if supported.\nThis is currently only supported on macOS.", + "defaults": [ + "false" + ] + }, + { + "key": "font-thicken-strength", + "zigType": "u8", + "kind": "int", + "min": 0, + "max": 255, + "doc": "Strength of thickening when `font-thicken` is enabled.\n\nValid values are integers between `0` and `255`. `0` does not correspond to\n*no* thickening, rather it corresponds to the lightest available thickening.\n\nHas no effect when `font-thicken` is set to `false`.\n\nThis is currently only supported on macOS.", + "defaults": [ + "255" + ] + }, + { + "key": "font-shaping-break", + "zigType": "FontShapingBreak", + "kind": "flags", + "flags": [ + "cursor" + ], + "doc": "Locations to break font shaping into multiple runs.\n\nA \"run\" is a contiguous segment of text that is shaped together. \"Shaping\"\nis the process of converting text (codepoints) into glyphs (renderable\ncharacters). This is how ligatures are formed, among other things.\nFor example, if a coding font turns \"!=\" into a single glyph, then it\nmust see \"!\" and \"=\" next to each other in a single run. When a run\nis broken, the text is shaped separately. To continue our example, if\n\"!\" is at the end of one run and \"=\" is at the start of the next run,\nthen the ligature will not be formed.\n\nGhostty breaks runs at certain points to improve readability or usability.\nFor example, Ghostty by default will break runs under the cursor so that\ntext editing can see the individual characters rather than a ligature.\nThis configuration lets you configure this behavior.\n\nCombine values with a comma to set multiple options. Prefix an\noption with \"no-\" to disable it. Enabling and disabling options\ncan be done at the same time.\n\nAvailable options:\n\n * `cursor` - Break runs under the cursor.\n\nAvailable since: 1.2.0", + "defaults": [ + "cursor" + ] + }, + { + "key": "alpha-blending", + "zigType": "AlphaBlending", + "kind": "enum", + "values": [ + "native", + "linear", + "linear-corrected" + ], + "doc": "What color space to use when performing alpha blending.\n\nThis affects the appearance of text and of any images with transparency.\nAdditionally, custom shaders will receive colors in the configured space.\n\nOn macOS the default is `native`, on all other platforms the default is\n`linear-corrected`.\n\nValid values:\n\n* `native` - Perform alpha blending in the native color space for the OS.\n On macOS this corresponds to Display P3, and on Linux it's sRGB.\n\n* `linear` - Perform alpha blending in linear space. This will eliminate\n the darkening artifacts around the edges of text that are very visible\n when certain color combinations are used (e.g. red / green), but makes\n dark text look much thinner than normal and light text much thicker.\n This is also sometimes known as \"gamma correction\".\n\n* `linear-corrected` - Same as `linear`, but with a correction step applied\n for text that makes it look nearly or completely identical to `native`,\n but without any of the darkening artifacts.\n\nAvailable since: 1.1.0", + "defaults": [ + "native" + ] + }, + { + "key": "adjust-cell-width", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "All of the configurations behavior adjust various metrics determined by the\nfont. The values can be integers (1, -1, etc.) or a percentage (20%, -15%,\netc.). In each case, the values represent the amount to change the original\nvalue.\n\nFor example, a value of `1` increases the value by 1; it does not set it to\nliterally 1. A value of `20%` increases the value by 20%. And so on.\n\nThere is little to no validation on these values so the wrong values (e.g.\n`-100%`) can cause the terminal to be unusable. Use with caution and reason.\n\nSome values are clamped to minimum or maximum values. This can make it\nappear that certain values are ignored. For example, many `*-thickness`\nadjustments cannot go below 1px.\n\n`adjust-cell-height` has some additional behaviors to describe:\n\n * The font will be centered vertically in the cell.\n\n * The cursor will remain the same size as the font, but may be\n adjusted separately with `adjust-cursor-height`.\n\n * Powerline glyphs will be adjusted along with the cell height so\n that things like status lines continue to look aligned.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-cell-height", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "All of the configurations behavior adjust various metrics determined by the\nfont. The values can be integers (1, -1, etc.) or a percentage (20%, -15%,\netc.). In each case, the values represent the amount to change the original\nvalue.\n\nFor example, a value of `1` increases the value by 1; it does not set it to\nliterally 1. A value of `20%` increases the value by 20%. And so on.\n\nThere is little to no validation on these values so the wrong values (e.g.\n`-100%`) can cause the terminal to be unusable. Use with caution and reason.\n\nSome values are clamped to minimum or maximum values. This can make it\nappear that certain values are ignored. For example, many `*-thickness`\nadjustments cannot go below 1px.\n\n`adjust-cell-height` has some additional behaviors to describe:\n\n * The font will be centered vertically in the cell.\n\n * The cursor will remain the same size as the font, but may be\n adjusted separately with `adjust-cursor-height`.\n\n * Powerline glyphs will be adjusted along with the cell height so\n that things like status lines continue to look aligned.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-font-baseline", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Distance in pixels or percentage adjustment from the bottom of the cell to the text baseline.\nIncrease to move baseline UP, decrease to move baseline DOWN.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-underline-position", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Distance in pixels or percentage adjustment from the top of the cell to the top of the underline.\nIncrease to move underline DOWN, decrease to move underline UP.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-underline-thickness", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Thickness in pixels of the underline.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-strikethrough-position", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Distance in pixels or percentage adjustment from the top of the cell to the top of the strikethrough.\nIncrease to move strikethrough DOWN, decrease to move strikethrough UP.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-strikethrough-thickness", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Thickness in pixels or percentage adjustment of the strikethrough.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-overline-position", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Distance in pixels or percentage adjustment from the top of the cell to the top of the overline.\nIncrease to move overline DOWN, decrease to move overline UP.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-overline-thickness", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Thickness in pixels or percentage adjustment of the overline.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-cursor-thickness", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Thickness in pixels or percentage adjustment of the bar cursor and outlined rect cursor.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-cursor-height", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Height in pixels or percentage adjustment of the cursor. Currently applies to all cursor types:\nbar, rect, and outlined rect.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-box-thickness", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Thickness in pixels or percentage adjustment of box drawing characters.\nSee the notes about adjustments in `adjust-cell-width`.", + "defaults": [ + "" + ] + }, + { + "key": "adjust-icon-height", + "zigType": "?MetricModifier", + "kind": "metric", + "doc": "Height in pixels or percentage adjustment of maximum height for nerd font icons.\n\nA positive (negative) value will increase (decrease) the maximum icon\nheight. This may not affect all icons equally: the effect depends on whether\nthe default size of the icon is height-constrained, which in turn depends on\nthe aspect ratio of both the icon and your primary font.\n\nCertain icons designed for box drawing and terminal graphics, such as\nPowerline symbols, are not affected by this option.\n\nSee the notes about adjustments in `adjust-cell-width`.\n\nAvailable in: 1.2.0", + "defaults": [ + "" + ] + }, + { + "key": "grapheme-width-method", + "zigType": "GraphemeWidthMethod", + "kind": "enum", + "values": [ + "legacy", + "unicode" + ], + "doc": "The method to use for calculating the cell width of a grapheme cluster.\nThe default value is `unicode` which uses the Unicode standard to determine\ngrapheme width. This results in correct grapheme width but may result in\ncursor-desync issues with some programs (such as shells) that may use a\nlegacy method such as `wcswidth`.\n\nValid values are:\n\n* `legacy` - Use a legacy method to determine grapheme width, such as\n wcswidth This maximizes compatibility with legacy programs but may result\n in incorrect grapheme width for certain graphemes such as skin-tone\n emoji, non-English characters, etc.\n\n This is called \"legacy\" and not something more specific because the\n behavior is undefined and we want to retain the ability to modify it.\n For example, we may or may not use libc `wcswidth` now or in the future.\n\n* `unicode` - Use the Unicode standard to determine grapheme width.\n\nIf a running program explicitly enables terminal mode 2027, then `unicode`\nwidth will be forced regardless of this configuration. When mode 2027 is\nreset, this configuration will be used again.\n\nThis configuration can be changed at runtime but will not affect existing\nterminals. Only new terminals will use the new configuration.", + "defaults": [ + "unicode" + ] + }, + { + "key": "freetype-load-flags", + "zigType": "FreetypeLoadFlags", + "kind": "flags", + "flags": [ + "hinting", + "force-autohint", + "monochrome", + "autohint", + "light" + ], + "doc": "FreeType load flags to enable. The format of this is a list of flags to\nenable separated by commas. If you prefix a flag with `no-` then it is\ndisabled. If you omit a flag, its default value is used, so you must\nexplicitly disable flags you don't want. You can also use `true` or `false`\nto turn all flags on or off.\n\nThis configuration only applies to Ghostty builds that use FreeType.\nThis is usually the case only for Linux builds. macOS uses CoreText\nand does not have an equivalent configuration.\n\nAvailable flags:\n\n * `hinting` - Enable or disable hinting. Enabled by default.\n\n * `force-autohint` - Always use the freetype auto-hinter instead of\n the font's native hinter. Disabled by default.\n\n * `monochrome` - Instructs renderer to use 1-bit monochrome rendering.\n This will disable anti-aliasing, and probably not look very good unless\n you're using a pixel font. Disabled by default.\n\n * `autohint` - Enable the freetype auto-hinter. Enabled by default.\n\n * `light` - Use a light hinting style, better preserving glyph shapes.\n This is the most common setting in GTK apps and therefore also Ghostty's\n default. This has no effect if `monochrome` is enabled. Enabled by\n default.\n\nExample: `hinting`, `no-hinting`, `force-autohint`, `no-force-autohint`", + "defaults": [ + "hinting,no-force-autohint,no-monochrome,autohint,light" + ] + }, + { + "key": "theme", + "zigType": "?Theme", + "kind": "theme", + "doc": "A theme to use. This can be a built-in theme name, a custom theme\nname, or an absolute path to a custom theme file. Ghostty also supports\nspecifying a different theme to use for light and dark mode. Each\noption is documented below.\n\nIf the theme is an absolute pathname, Ghostty will attempt to load that\nfile as a theme. If that file does not exist or is inaccessible, an error\nwill be logged and no other directories will be searched.\n\nIf the theme is not an absolute pathname, two different directories will be\nsearched for a file name that matches the theme. This is case sensitive on\nsystems with case-sensitive filesystems. It is an error for a theme name to\ninclude path separators unless it is an absolute pathname.\n\nThe first directory is the `themes` subdirectory of your Ghostty\nconfiguration directory. This is `$XDG_CONFIG_HOME/ghostty/themes` or\n`~/.config/ghostty/themes`.\n\nThe second directory is the `themes` subdirectory of the Ghostty resources\ndirectory. Ghostty ships with a multitude of themes that will be installed\ninto this directory. On macOS, this list is in the\n`Ghostty.app/Contents/Resources/ghostty/themes` directory. On Linux, this\nlist is in the `share/ghostty/themes` directory (wherever you installed the\nGhostty \"share\" directory.\n\nTo see a list of available themes, run `ghostty +list-themes`.\n\nA theme file is simply another Ghostty configuration file. They share\nthe same syntax and same configuration options. A theme can set any valid\nconfiguration option so please do not use a theme file from an untrusted\nsource. The built-in themes are audited to only set safe configuration\noptions.\n\nSome options cannot be set within theme files. The reason these are not\nsupported should be self-evident. A theme file cannot set `theme` or\n`config-file`. At the time of writing this, Ghostty will not show any\nwarnings or errors if you set these options in a theme file but they will\nbe silently ignored.\n\nAny additional colors specified via background, foreground, palette, etc.\nwill override the colors specified in the theme.\n\nTo specify a different theme for light and dark mode, use the following\nsyntax: `light:theme-name,dark:theme-name`. For example:\n`light:Rose Pine Dawn,dark:Rose Pine`. Whitespace around all values are\ntrimmed and order of light and dark does not matter. Both light and dark\nmust be specified in this form. In this form, the theme used will be\nbased on the current desktop environment theme.\n\nThere are some known bugs with light/dark mode theming. These will\nbe fixed in a future update:\n\n - macOS: titlebar tabs style is not updated when switching themes.", + "defaults": [ + "" + ] + }, + { + "key": "background", + "zigType": "Color", + "kind": "color", + "doc": "Background color for the window.\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "#282c34" + ] + }, + { + "key": "foreground", + "zigType": "Color", + "kind": "color", + "doc": "Foreground color for the window.\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "#ffffff" + ] + }, + { + "key": "background-image", + "zigType": "?Path", + "kind": "path", + "doc": "Background image for the terminal.\n\nThis should be a path to a PNG or JPEG file, other image formats are\nnot yet supported.\n\nThe background image is currently per-terminal, not per-window. If\nyou are a heavy split user, the background image will be repeated across\nsplits. A future improvement to Ghostty will address this.\n\nWARNING: Background images are currently duplicated in VRAM per-terminal.\nFor sufficiently large images, this could lead to a large increase in\nmemory usage (specifically VRAM usage). A future Ghostty improvement\nwill resolve this by sharing image textures across terminals.\n\nAvailable since: 1.2.0", + "defaults": [ + "" + ] + }, + { + "key": "background-image-opacity", + "zigType": "f32", + "kind": "float", + "min": 0, + "doc": "Background image opacity.\n\nThis is relative to the value of `background-opacity`.\n\nA value of `1.0` (the default) will result in the background image being\nplaced on top of the general background color, and then the combined result\nwill be adjusted to the opacity specified by `background-opacity`.\n\nA value less than `1.0` will result in the background image being mixed\nwith the general background color before the combined result is adjusted\nto the configured `background-opacity`.\n\nA value greater than `1.0` will result in the background image having a\nhigher opacity than the general background color. For instance, if the\nconfigured `background-opacity` is `0.5` and `background-image-opacity`\nis set to `1.5`, then the final opacity of the background image will be\n`0.5 * 1.5 = 0.75`.\n\nAvailable since: 1.2.0", + "defaults": [ + "1" + ] + }, + { + "key": "background-image-position", + "zigType": "BackgroundImagePosition", + "kind": "enum", + "values": [ + "top-left", + "top-center", + "top-right", + "center-left", + "center-center", + "center-right", + "bottom-left", + "bottom-center", + "bottom-right", + "center" + ], + "doc": "Background image position.\n\nValid values are:\n * `top-left`\n * `top-center`\n * `top-right`\n * `center-left`\n * `center`\n * `center-right`\n * `bottom-left`\n * `bottom-center`\n * `bottom-right`\n\nThe default value is `center`.\n\nAvailable since: 1.2.0", + "defaults": [ + "center" + ] + }, + { + "key": "background-image-fit", + "zigType": "BackgroundImageFit", + "kind": "enum", + "values": [ + "contain", + "cover", + "stretch", + "none" + ], + "doc": "Background image fit.\n\nValid values are:\n\n * `contain`\n\n Preserving the aspect ratio, scale the background image to the largest\n size that can still be contained within the terminal, so that the whole\n image is visible.\n\n * `cover`\n\n Preserving the aspect ratio, scale the background image to the smallest\n size that can completely cover the terminal. This may result in one or\n more edges of the image being clipped by the edge of the terminal.\n\n * `stretch`\n\n Stretch the background image to the full size of the terminal, without\n preserving the aspect ratio.\n\n * `none`\n\n Don't scale the background image.\n\nThe default value is `contain`.\n\nAvailable since: 1.2.0", + "defaults": [ + "contain" + ] + }, + { + "key": "background-image-repeat", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to repeat the background image or not.\n\nIf this is set to true, the background image will be repeated if there\nwould otherwise be blank space around it because it doesn't completely\nfill the terminal area.\n\nThe default value is `false`.\n\nAvailable since: 1.2.0", + "defaults": [ + "false" + ] + }, + { + "key": "selection-foreground", + "zigType": "?TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for selection. If this is not set, then\nthe selection color is just the inverted window background and foreground\n(note: not to be confused with the cell bg/fg).\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.\nSince version 1.2.0, this can also be set to `cell-foreground` to match\nthe cell foreground color, or `cell-background` to match the cell\nbackground color.", + "defaults": [ + "" + ] + }, + { + "key": "selection-background", + "zigType": "?TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for selection. If this is not set, then\nthe selection color is just the inverted window background and foreground\n(note: not to be confused with the cell bg/fg).\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.\nSince version 1.2.0, this can also be set to `cell-foreground` to match\nthe cell foreground color, or `cell-background` to match the cell\nbackground color.", + "defaults": [ + "" + ] + }, + { + "key": "selection-clear-on-typing", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to clear selected text when typing. This defaults to `true`.\nThis is typical behavior for most terminal emulators as well as\ntext input fields. If you set this to `false`, then the selected text\nwill not be cleared when typing.\n\n\"Typing\" is specifically defined as any non-modifier (shift, control,\nalt, etc.) keypress that produces data to be sent to the application\nrunning within the terminal (e.g. the shell). Additionally, selection\nis cleared when any preedit or composition state is started (e.g.\nwhen typing languages such as Japanese).\n\nIf this is `false`, then the selection can still be manually\ncleared by clicking once or by pressing `escape`.\n\nAvailable since: 1.2.0", + "defaults": [ + "true" + ] + }, + { + "key": "selection-clear-on-copy", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to clear selected text after copying. This defaults to `false`.\n\nWhen set to `true`, the selection will be automatically cleared after\nany copy operation that invokes the `copy_to_clipboard` keyboard binding.\nImportantly, this will not clear the selection if the copy operation\nwas invoked via `copy-on-select`.\n\nWhen set to `false`, the selection remains visible after copying, allowing\nto see what was copied and potentially perform additional operations\non the same selection.", + "defaults": [ + "false" + ] + }, + { + "key": "selection-word-chars", + "zigType": "SelectionWordChars", + "kind": "text", + "doc": "Characters that mark word boundaries during text selection operations such\nas double-clicking. When selecting a word, the selection will stop at any\nof these characters.\n\nThis is similar to the `WORDCHARS` environment variable in zsh, except this\nspecifies the boundary characters rather than the word characters. The\ndefault includes common delimiters and punctuation that typically separate\nwords in code and prose.\n\nEach character in this string becomes a word boundary. Multi-byte UTF-8\ncharacters are supported, but only single codepoints can be specified.\nMulti-codepoint sequences (e.g. emoji) are not supported.\n\nThe null character (U+0000) is always treated as a boundary and does not\nneed to be included in this configuration.\n\nDefault: `` \\t'\"│`|:;,()[]{}\u003c\u003e$ ``\n\nTo add or remove specific characters, you can set this to a custom value.\nFor example, to treat semicolons as part of words:\n\n selection-word-chars = \" \\t'\\\"│`|:,()[]{}\u003c\u003e$\"\n\nAvailable since: 1.3.0", + "defaults": [ + " \t'\"│`|:;,()[]{}\u003c\u003e$" + ] + }, + { + "key": "minimum-contrast", + "zigType": "f64", + "kind": "float", + "min": 1, + "max": 21, + "doc": "The minimum contrast ratio between the foreground and background colors.\nThe contrast ratio is a value between 1 and 21. A value of 1 allows for no\ncontrast (e.g. black on black). This value is the contrast ratio as defined\nby the [WCAG 2.0 specification](https://www.w3.org/TR/WCAG20/).\n\nIf you want to avoid invisible text (same color as background), a value of\n1.1 is a good value. If you want to avoid text that is difficult to read, a\nvalue of 3 or higher is a good value. The higher the value, the more likely\nthat text will become black or white.\n\nThis value does not apply to Emoji or images.", + "defaults": [ + "1" + ] + }, + { + "key": "palette", + "zigType": "Palette", + "kind": "palette", + "repeatable": true, + "doc": "Color palette for the 256 color form that many terminal applications use.\nThe syntax of this configuration is `N=COLOR` where `N` is 0 to 255 (for\nthe 256 colors in the terminal color table) and `COLOR` is a typical RGB\ncolor code such as `#AABBCC` or `AABBCC`, or a named X11 color. For example,\n`palette = 5=#BB78D9` will set the 'purple' color.\n\nThe palette index can be in decimal, binary, octal, or hexadecimal.\nDecimal is assumed unless a prefix is used: `0b` for binary, `0o` for octal,\nand `0x` for hexadecimal.\n\nFor definitions on the color indices and what they canonically map to,\n[see this cheat sheet](https://www.ditig.com/256-colors-cheat-sheet).\n\nFor most themes, you only need to set the first 16 colors (0–15) since the\nrest of the palette (16–255) will be automatically generated by\ndefault (see `palette-generate` for more details).", + "defaults": [ + "0=#1d1f21", + "1=#cc6666", + "2=#b5bd68", + "3=#f0c674", + "4=#81a2be", + "5=#b294bb", + "6=#8abeb7", + "7=#c5c8c6", + "8=#666666", + "9=#d54e53", + "10=#b9ca4a", + "11=#e7c547", + "12=#7aa6da", + "13=#c397d8", + "14=#70c0b1", + "15=#eaeaea", + "16=#000000", + "17=#00005f", + "18=#000087", + "19=#0000af", + "20=#0000d7", + "21=#0000ff", + "22=#005f00", + "23=#005f5f", + "24=#005f87", + "25=#005faf", + "26=#005fd7", + "27=#005fff", + "28=#008700", + "29=#00875f", + "30=#008787", + "31=#0087af", + "32=#0087d7", + "33=#0087ff", + "34=#00af00", + "35=#00af5f", + "36=#00af87", + "37=#00afaf", + "38=#00afd7", + "39=#00afff", + "40=#00d700", + "41=#00d75f", + "42=#00d787", + "43=#00d7af", + "44=#00d7d7", + "45=#00d7ff", + "46=#00ff00", + "47=#00ff5f", + "48=#00ff87", + "49=#00ffaf", + "50=#00ffd7", + "51=#00ffff", + "52=#5f0000", + "53=#5f005f", + "54=#5f0087", + "55=#5f00af", + "56=#5f00d7", + "57=#5f00ff", + "58=#5f5f00", + "59=#5f5f5f", + "60=#5f5f87", + "61=#5f5faf", + "62=#5f5fd7", + "63=#5f5fff", + "64=#5f8700", + "65=#5f875f", + "66=#5f8787", + "67=#5f87af", + "68=#5f87d7", + "69=#5f87ff", + "70=#5faf00", + "71=#5faf5f", + "72=#5faf87", + "73=#5fafaf", + "74=#5fafd7", + "75=#5fafff", + "76=#5fd700", + "77=#5fd75f", + "78=#5fd787", + "79=#5fd7af", + "80=#5fd7d7", + "81=#5fd7ff", + "82=#5fff00", + "83=#5fff5f", + "84=#5fff87", + "85=#5fffaf", + "86=#5fffd7", + "87=#5fffff", + "88=#870000", + "89=#87005f", + "90=#870087", + "91=#8700af", + "92=#8700d7", + "93=#8700ff", + "94=#875f00", + "95=#875f5f", + "96=#875f87", + "97=#875faf", + "98=#875fd7", + "99=#875fff", + "100=#878700", + "101=#87875f", + "102=#878787", + "103=#8787af", + "104=#8787d7", + "105=#8787ff", + "106=#87af00", + "107=#87af5f", + "108=#87af87", + "109=#87afaf", + "110=#87afd7", + "111=#87afff", + "112=#87d700", + "113=#87d75f", + "114=#87d787", + "115=#87d7af", + "116=#87d7d7", + "117=#87d7ff", + "118=#87ff00", + "119=#87ff5f", + "120=#87ff87", + "121=#87ffaf", + "122=#87ffd7", + "123=#87ffff", + "124=#af0000", + "125=#af005f", + "126=#af0087", + "127=#af00af", + "128=#af00d7", + "129=#af00ff", + "130=#af5f00", + "131=#af5f5f", + "132=#af5f87", + "133=#af5faf", + "134=#af5fd7", + "135=#af5fff", + "136=#af8700", + "137=#af875f", + "138=#af8787", + "139=#af87af", + "140=#af87d7", + "141=#af87ff", + "142=#afaf00", + "143=#afaf5f", + "144=#afaf87", + "145=#afafaf", + "146=#afafd7", + "147=#afafff", + "148=#afd700", + "149=#afd75f", + "150=#afd787", + "151=#afd7af", + "152=#afd7d7", + "153=#afd7ff", + "154=#afff00", + "155=#afff5f", + "156=#afff87", + "157=#afffaf", + "158=#afffd7", + "159=#afffff", + "160=#d70000", + "161=#d7005f", + "162=#d70087", + "163=#d700af", + "164=#d700d7", + "165=#d700ff", + "166=#d75f00", + "167=#d75f5f", + "168=#d75f87", + "169=#d75faf", + "170=#d75fd7", + "171=#d75fff", + "172=#d78700", + "173=#d7875f", + "174=#d78787", + "175=#d787af", + "176=#d787d7", + "177=#d787ff", + "178=#d7af00", + "179=#d7af5f", + "180=#d7af87", + "181=#d7afaf", + "182=#d7afd7", + "183=#d7afff", + "184=#d7d700", + "185=#d7d75f", + "186=#d7d787", + "187=#d7d7af", + "188=#d7d7d7", + "189=#d7d7ff", + "190=#d7ff00", + "191=#d7ff5f", + "192=#d7ff87", + "193=#d7ffaf", + "194=#d7ffd7", + "195=#d7ffff", + "196=#ff0000", + "197=#ff005f", + "198=#ff0087", + "199=#ff00af", + "200=#ff00d7", + "201=#ff00ff", + "202=#ff5f00", + "203=#ff5f5f", + "204=#ff5f87", + "205=#ff5faf", + "206=#ff5fd7", + "207=#ff5fff", + "208=#ff8700", + "209=#ff875f", + "210=#ff8787", + "211=#ff87af", + "212=#ff87d7", + "213=#ff87ff", + "214=#ffaf00", + "215=#ffaf5f", + "216=#ffaf87", + "217=#ffafaf", + "218=#ffafd7", + "219=#ffafff", + "220=#ffd700", + "221=#ffd75f", + "222=#ffd787", + "223=#ffd7af", + "224=#ffd7d7", + "225=#ffd7ff", + "226=#ffff00", + "227=#ffff5f", + "228=#ffff87", + "229=#ffffaf", + "230=#ffffd7", + "231=#ffffff", + "232=#080808", + "233=#121212", + "234=#1c1c1c", + "235=#262626", + "236=#303030", + "237=#3a3a3a", + "238=#444444", + "239=#4e4e4e", + "240=#585858", + "241=#626262", + "242=#6c6c6c", + "243=#767676", + "244=#808080", + "245=#8a8a8a", + "246=#949494", + "247=#9e9e9e", + "248=#a8a8a8", + "249=#b2b2b2", + "250=#bcbcbc", + "251=#c6c6c6", + "252=#d0d0d0", + "253=#dadada", + "254=#e4e4e4", + "255=#eeeeee" + ] + }, + { + "key": "palette-generate", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to automatically generate the extended 256 color palette\n(indices 16–255) from the base 16 ANSI colors.\n\nThis lets theme authors specify only the base 16 colors and have the\nrest of the palette be automatically generated in a consistent and\naesthetic way.\n\nWhen enabled, the 6×6×6 color cube and 24-step grayscale ramp are\nderived from interpolations of the base palette, giving a more cohesive\nlook. Colors that have been explicitly set via `palette` are never\noverwritten.\n\nThe default value is false (disabled), because many legacy programs\nusing the 256-color palette hardcode assumptions about what these\ncolors are (mostly assuming the xterm 256 color palette). However, this\nis still a very useful tool for theme authors and users who want\nto customize their palette without having to specify all 256 colors.\n\nFor more information on how the generation works, see here:\nhttps://gist.github.com/jake-stewart/0a8ea46159a7da2c808e5be2177e1783\n\nAvailable since: 1.3.0", + "defaults": [ + "false" + ] + }, + { + "key": "palette-harmonious", + "zigType": "bool", + "kind": "bool", + "doc": "Invert the palette colors generated when `palette-generate` is enabled,\nso that the colors go in reverse order. This allows palette-based\napplications to work well in both light and dark mode since the\npalettes are always relatively good colors.\n\nThis defaults to off because some legacy terminal applications\nhardcode the assumption that palette indices 16–231 are ordered from\ndarkest to lightest, so enabling this would make them unreadable.\nThis is not a generally good assumption and we encourage modern\nterminal applications to use the indices in a more semantic way.\n\nThis has no effect if `palette-generate` is disabled.\n\nFor more information see `palette-generate`.\n\nAvailable since: 1.3.0", + "defaults": [ + "false" + ] + }, + { + "key": "cursor-color", + "zigType": "?TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The color of the cursor. If this is not set, a default will be chosen.\n\nDirect colors can be specified as either hex (`#RRGGBB` or `RRGGBB`)\nor a named X11 color.\n\nAdditionally, special values can be used to set the color to match\nother colors at runtime:\n\n * `cell-foreground` - Match the cell foreground color.\n (Available since: 1.2.0)\n\n * `cell-background` - Match the cell background color.\n (Available since: 1.2.0)", + "defaults": [ + "" + ] + }, + { + "key": "cursor-opacity", + "zigType": "f64", + "kind": "float", + "min": 0, + "max": 1, + "doc": "The opacity level (opposite of transparency) of the cursor. A value of 1\nis fully opaque and a value of 0 is fully transparent. A value less than 0\nor greater than 1 will be clamped to the nearest valid value. Note that a\nsufficiently small value such as 0.3 may be effectively invisible and may\nmake it difficult to find the cursor.", + "defaults": [ + "1" + ] + }, + { + "key": "cursor-style", + "zigType": "terminal.CursorStyle", + "kind": "enum", + "values": [ + "block", + "bar", + "underline", + "block_hollow" + ], + "doc": "The style of the cursor. This sets the default style. A running program can\nstill request an explicit cursor style using escape sequences (such as `CSI\nq`). Shell configurations will often request specific cursor styles.\n\nNote that shell integration will automatically set the cursor to a bar at\na prompt, regardless of this configuration. You can disable that behavior\nby specifying `shell-integration-features = no-cursor` or disabling shell\nintegration entirely.\n\nValid values are:\n\n * `block`\n * `bar`\n * `underline`\n * `block_hollow`", + "defaults": [ + "block" + ] + }, + { + "key": "cursor-style-blink", + "zigType": "?bool", + "kind": "bool", + "doc": "Sets the default blinking state of the cursor. This is just the default\nstate; running programs may override the cursor style using `DECSCUSR` (`CSI\nq`).\n\nIf this is not set, the cursor blinks by default. Note that this is not the\nsame as a \"true\" value, as noted below.\n\nIf this is not set at all (`null`), then Ghostty will respect DEC Mode 12\n(AT\u0026T cursor blink) as an alternate approach to turning blinking on/off. If\nthis is set to any value other than null, DEC mode 12 will be ignored but\n`DECSCUSR` will still be respected.\n\nValid values are:\n\n * ` ` (blank)\n * `true`\n * `false`", + "defaults": [ + "" + ] + }, + { + "key": "cursor-text", + "zigType": "?TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The color of the text under the cursor. If this is not set, a default will\nbe chosen.\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.\nSince version 1.2.0, this can also be set to `cell-foreground` to match\nthe cell foreground color, or `cell-background` to match the cell\nbackground color.", + "defaults": [ + "" + ] + }, + { + "key": "cursor-click-to-move", + "zigType": "bool", + "kind": "bool", + "doc": "Enables the ability to move the cursor at prompts by clicking on a\nlocation in the prompt text.\n\nThis feature requires shell integration, specifically prompt marking\nvia `OSC 133`. Some shells like Fish (v4) and Nu (0.111+) natively\nsupport this while others may require additional configuration or\nGhostty's shell integration features to be enabled.\n\nDepending on the shell, this works either by translating your click\nposition into a series of synthetic arrow key movements or by sending\na click event directly to the shell. In either case, some unexpected\nbehavior around edge cases is possible.", + "defaults": [ + "true" + ] + }, + { + "key": "mouse-hide-while-typing", + "zigType": "bool", + "kind": "bool", + "doc": "Hide the mouse immediately when typing. The mouse becomes visible again\nwhen the mouse is used (button, movement, etc.). Platform-specific behavior\nmay dictate other scenarios where the mouse is shown. For example on macOS,\nthe mouse is shown again when a new window, tab, or split is created.", + "defaults": [ + "false" + ] + }, + { + "key": "scroll-to-bottom", + "zigType": "ScrollToBottom", + "kind": "flags", + "flags": [ + "keystroke", + "output" + ], + "doc": "When to scroll the surface to the bottom. The format of this is a list of\noptions to enable separated by commas. If you prefix an option with `no-`\nthen it is disabled. If you omit an option, its default value is used.\n\nAvailable options:\n\n- `keystroke` If set, scroll the surface to the bottom when the user\n presses a key that results in data being sent to the PTY (basically\n anything but modifiers or keybinds that are processed by Ghostty).\n\n- `output` If set, scroll the surface to the bottom if there is new data\n to display (e.g., when new lines are printed to the terminal).\n\nThe default is `keystroke, no-output`.", + "defaults": [ + "keystroke,no-output" + ] + }, + { + "key": "mouse-shift-capture", + "zigType": "MouseShiftCapture", + "kind": "enum", + "values": [ + "false", + "true", + "always", + "never" + ], + "doc": "Determines whether running programs can detect the shift key pressed with a\nmouse click. Typically, the shift key is used to extend mouse selection.\n\nThe default value of `false` means that the shift key is not sent with\nthe mouse protocol and will extend the selection. This value can be\nconditionally overridden by the running program with the `XTSHIFTESCAPE`\nsequence.\n\nThe value `true` means that the shift key is sent with the mouse protocol\nbut the running program can override this behavior with `XTSHIFTESCAPE`.\n\nThe value `never` is the same as `false` but the running program cannot\noverride this behavior with `XTSHIFTESCAPE`. The value `always` is the\nsame as `true` but the running program cannot override this behavior with\n`XTSHIFTESCAPE`.\n\nIf you always want shift to extend mouse selection even if the program\nrequests otherwise, set this to `never`.\n\nValid values are:\n\n * `true`\n * `false`\n * `always`\n * `never`", + "defaults": [ + "false" + ] + }, + { + "key": "mouse-reporting", + "zigType": "bool", + "kind": "bool", + "doc": "Enable or disable mouse reporting. When set to `false`, mouse events will\nnot be reported to terminal applications even if they request it. This\nallows you to always use the mouse for selection and other terminal UI\ninteractions without applications capturing mouse input.\n\nWhen set to `true` (the default), terminal applications can request mouse\nreporting and will receive mouse events according to their requested mode.\n\nThis can be toggled at runtime using the `toggle_mouse_reporting` keybind\naction.", + "defaults": [ + "true" + ] + }, + { + "key": "mouse-scroll-multiplier", + "zigType": "MouseScrollMultiplier", + "kind": "text", + "hint": "a number, or precision:N,discrete:N", + "doc": "Multiplier for scrolling distance with the mouse wheel.\n\nA prefix of `precision:` or `discrete:` can be used to set the multiplier\nonly for scrolling with the specific type of devices. These can be\ncomma-separated to set both types of multipliers at the same time, e.g.\n`precision:0.1,discrete:3`. If no prefix is used, the multiplier applies\nto all scrolling devices. Specifying a prefix was introduced in Ghostty\n1.2.1.\n\nThe value will be clamped to [0.01, 10,000]. Both of these are extreme\nand you're likely to have a bad experience if you set either extreme.\n\nThe default value is \"3\" for discrete devices and \"1\" for precision devices.", + "defaults": [ + "precision:1,discrete:3" + ] + }, + { + "key": "background-opacity", + "zigType": "f64", + "kind": "float", + "min": 0, + "max": 1, + "doc": "The opacity level (opposite of transparency) of the background. A value of\n1 is fully opaque and a value of 0 is fully transparent. A value less than 0\nor greater than 1 will be clamped to the nearest valid value.\n\nOn macOS, background opacity is disabled when the terminal enters native\nfullscreen. This is because the background becomes gray and it can cause\nwidgets to show through which isn't generally desirable.\n\nOn macOS, changing this configuration requires restarting Ghostty completely.", + "defaults": [ + "1" + ] + }, + { + "key": "background-opacity-cells", + "zigType": "bool", + "kind": "bool", + "doc": "Applies background opacity to cells with an explicit background color\nset.\n\nNormally, `background-opacity` is only applied to the window background.\nIf a cell has an explicit background color set, such as red, then that\nbackground color will be fully opaque. An effect of this is that some\nterminal applications that repaint the background color of the terminal\nsuch as a Neovim and Tmux may not respect the `background-opacity`\n(by design).\n\nSetting this to `true` will apply the `background-opacity` to all cells\nregardless of whether they have an explicit background color set or not.\n\nAvailable since: 1.2.0", + "defaults": [ + "false" + ] + }, + { + "key": "background-blur", + "zigType": "BackgroundBlur", + "kind": "choice", + "values": [ + "false", + "true", + "macos-glass-regular", + "macos-glass-clear" + ], + "hint": "true, false, a blur radius (e.g. 20) or a macOS glass style", + "doc": "Whether to blur the background when `background-opacity` is less than 1.\n\nValid values are:\n\n * a nonnegative integer specifying the *blur intensity*\n * `false`, equivalent to a blur intensity of 0\n * `true`, equivalent to the default blur intensity of 20, which is\n reasonable for a good looking blur. Higher blur intensities may\n cause strange rendering and performance issues.\n\nOn macOS 26.0 and later, there are additional special values that\ncan be set to use the native macOS glass effects:\n\n * `macos-glass-regular` - Standard glass effect with some opacity\n * `macos-glass-clear` - Highly transparent glass effect\n\nIf the macOS values are set, then this implies `background-blur = true`\non non-macOS platforms.\n\nSupported on macOS and on some Linux desktop environments, including:\n\n * KDE Plasma (Wayland and X11)\n\nWarning: the exact blur intensity is _ignored_ under KDE Plasma, and setting\nthis setting to either `true` or any positive blur intensity value would\nachieve the same effect. The reason is that KWin, the window compositor\npowering Plasma, only has one global blur setting and does not allow\napplications to specify individual blur settings.\n\nTo configure KWin's global blur setting, open System Settings and go to\n\"Apps \u0026 Windows\" \u003e \"Window Management\" \u003e \"Desktop Effects\" and select the\n\"Blur\" plugin. If disabled, enable it by ticking the checkbox to the left.\nThen click on the \"Configure\" button and there will be two sliders that\nallow you to set background blur and noise intensities for all apps,\nincluding Ghostty.\n\nAll other Linux desktop environments are as of now unsupported. Users may\nneed to set environment-specific settings and/or install third-party plugins\nin order to support background blur, as there isn't a unified interface for\ndoing so.", + "defaults": [ + "false" + ] + }, + { + "key": "unfocused-split-opacity", + "zigType": "f64", + "kind": "float", + "min": 0.15, + "max": 1, + "doc": "The opacity level (opposite of transparency) of an unfocused split.\nUnfocused splits by default are slightly faded out to make it easier to see\nwhich split is focused. To disable this feature, set this value to 1.\n\nA value of 1 is fully opaque and a value of 0 is fully transparent. Because\n\"0\" is not useful (it makes the window look very weird), the minimum value\nis 0.15. This value still looks weird but you can at least see what's going\non. A value outside of the range 0.15 to 1 will be clamped to the nearest\nvalid value.", + "defaults": [ + "0.7" + ] + }, + { + "key": "unfocused-split-fill", + "zigType": "?Color", + "kind": "color", + "doc": "The color to dim the unfocused split. Unfocused splits are dimmed by\nrendering a semi-transparent rectangle over the split. This sets the color of\nthat rectangle and can be used to carefully control the dimming effect.\n\nThis will default to the background color.\n\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "" + ] + }, + { + "key": "split-divider-color", + "zigType": "?Color", + "kind": "color", + "doc": "The color of the split divider. If this is not set, a default will be chosen.\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.\n\nAvailable since: 1.1.0", + "defaults": [ + "" + ] + }, + { + "key": "split-preserve-zoom", + "zigType": "SplitPreserveZoom", + "kind": "flags", + "flags": [ + "navigation" + ], + "doc": "Control when Ghostty preserves a zoomed split. Under normal circumstances,\nany operation that changes focus or layout of the split tree in a window\nwill unzoom any zoomed split. This configuration allows you to control\nthis behavior.\n\nThis can be set to `navigation` to preserve the zoomed split state\nwhen navigating to another split (e.g. via `goto_split`). This will\nchange the zoomed split to the newly focused split instead of unzooming.\n\nAny options can also be prefixed with `no-` to disable that option.\n\nExample: `split-preserve-zoom = navigation`\n\nAvailable since: 1.3.0", + "defaults": [ + "no-navigation" + ] + }, + { + "key": "search-foreground", + "zigType": "TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for search matches. This only applies\nto non-focused search matches, also known as candidate matches.\n\nValid values:\n\n - Hex (`#RRGGBB` or `RRGGBB`)\n - Named X11 color\n - \"cell-foreground\" to match the cell foreground color\n - \"cell-background\" to match the cell background color\n\nThe default value is black text on a golden yellow background.", + "defaults": [ + "#000000" + ] + }, + { + "key": "search-background", + "zigType": "TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for search matches. This only applies\nto non-focused search matches, also known as candidate matches.\n\nValid values:\n\n - Hex (`#RRGGBB` or `RRGGBB`)\n - Named X11 color\n - \"cell-foreground\" to match the cell foreground color\n - \"cell-background\" to match the cell background color\n\nThe default value is black text on a golden yellow background.", + "defaults": [ + "#ffe082" + ] + }, + { + "key": "search-selected-foreground", + "zigType": "TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for the currently selected search match.\nThis is the focused match that will be jumped to when using next/previous\nsearch navigation.\n\nValid values:\n\n - Hex (`#RRGGBB` or `RRGGBB`)\n - Named X11 color\n - \"cell-foreground\" to match the cell foreground color\n - \"cell-background\" to match the cell background color\n\nThe default value is black text on a soft peach background.", + "defaults": [ + "#000000" + ] + }, + { + "key": "search-selected-background", + "zigType": "TerminalColor", + "kind": "color", + "values": [ + "cell-foreground", + "cell-background" + ], + "doc": "The foreground and background color for the currently selected search match.\nThis is the focused match that will be jumped to when using next/previous\nsearch navigation.\n\nValid values:\n\n - Hex (`#RRGGBB` or `RRGGBB`)\n - Named X11 color\n - \"cell-foreground\" to match the cell foreground color\n - \"cell-background\" to match the cell background color\n\nThe default value is black text on a soft peach background.", + "defaults": [ + "#f2a57e" + ] + }, + { + "key": "command", + "zigType": "?Command", + "kind": "text", + "hint": "command line; prefix with direct: or shell: to control how it runs", + "doc": "The command to run, usually a shell. If this is not an absolute path, it'll\nbe looked up in the `PATH`. If this is not set, a default will be looked up\nfrom your system. The rules for the default lookup are:\n\n * `SHELL` environment variable\n\n * `passwd` entry (user information)\n\nThis can contain additional arguments to run the command with. If additional\narguments are provided, the command will be executed using `/bin/sh -c`\nto offload shell argument expansion.\n\nTo avoid shell expansion altogether, prefix the command with `direct:`, e.g.\n`direct:nvim foo`. This will avoid the roundtrip to `/bin/sh` but will also\nnot support any shell parsing such as arguments with spaces, filepaths with\n`~`, globs, etc. (Available since: 1.2.0)\n\nYou can also explicitly prefix the command with `shell:` to always wrap the\ncommand in a shell. This can be used to ensure our heuristics to choose the\nright mode are not used in case they are wrong. (Available since: 1.2.0)\n\nThis command will be used for all new terminal surfaces, i.e. new windows,\ntabs, etc. If you want to run a command only for the first terminal surface\ncreated when Ghostty starts, use the `initial-command` configuration.\n\nGhostty supports the common `-e` flag for executing a command with\narguments. For example, `ghostty -e fish --with --custom --args`.\nThis flag sets the `initial-command` configuration, see that for more\ninformation.", + "defaults": [ + "" + ] + }, + { + "key": "initial-command", + "zigType": "?Command", + "kind": "text", + "hint": "command line; prefix with direct: or shell: to control how it runs", + "doc": "This is the same as \"command\", but only applies to the first terminal\nsurface created when Ghostty starts. Subsequent terminal surfaces will use\nthe `command` configuration.\n\nAfter the first terminal surface is created (or closed), there is no\nway to run this initial command again automatically. As such, setting\nthis at runtime works but will only affect the next terminal surface\nif it is the first one ever created.\n\nIf you're using the `ghostty` CLI there is also a shortcut to set this\nwith arguments directly: you can use the `-e` flag. For example: `ghostty -e\nfish --with --custom --args`. The `-e` flag automatically forces some\nother behaviors as well:\n\n * Disables shell expansion since the input is expected to already\n be shell-expanded by the upstream (e.g. the shell used to type in\n the `ghostty -e` command).\n\n * `gtk-single-instance=false` - This ensures that a new instance is\n launched and the CLI args are respected.\n\n * `quit-after-last-window-closed=true` - This ensures that the Ghostty\n process will exit when the command exits. Additionally, the\n `quit-after-last-window-closed-delay` is unset.\n\n * `shell-integration=detect` (if not `none`) - This prevents forcibly\n injecting any configured shell integration into the command's\n environment. With `-e` its highly unlikely that you're executing a\n shell and forced shell integration is likely to cause problems\n (e.g. by wrapping your command in a shell, setting env vars, etc.).\n This is a safety measure to prevent unexpected behavior. If you want\n shell integration with a `-e`-executed command, you must either\n name your binary appropriately or source the shell integration script\n manually.", + "defaults": [ + "" + ] + }, + { + "key": "notify-on-command-finish", + "zigType": "NotifyOnCommandFinish", + "kind": "enum", + "values": [ + "never", + "unfocused", + "always" + ], + "doc": "Controls when command finished notifications are sent. There are\nthree options:\n\n* `never` - Never send notifications (the default).\n* `unfocused` - Only send notifications if the surface that the command is\n running in is not focused.\n* `always` - Always send notifications.\n\nCommand finished notifications requires that either shell integration is\nenabled, or that your shell sends OSC 133 escape sequences to mark the start\nand end of commands.\n\nOn GTK, there is a context menu item that will enable command finished\nnotifications for a single command, overriding the `never` and `unfocused`\noptions.\n\nAvailable since 1.3.0.", + "defaults": [ + "never" + ] + }, + { + "key": "notify-on-command-finish-action", + "zigType": "NotifyOnCommandFinishAction", + "kind": "flags", + "flags": [ + "bell", + "notify" + ], + "doc": "If command finished notifications are enabled, this controls how the user is\nnotified.\n\nAvailable options:\n\n* `bell` - enabled by default\n* `notify` - disabled by default\n\nOptions can be combined by listing them as a comma separated list. Options\ncan be negated by prefixing them with `no-`. For example `no-bell,notify`.\n\nAvailable since 1.3.0.", + "defaults": [ + "bell,no-notify" + ] + }, + { + "key": "notify-on-command-finish-after", + "zigType": "Duration", + "kind": "duration", + "doc": "If command finished notifications are enabled, this controls how long a\ncommand must have been running before a notification will be sent. The\ndefault is five seconds.\n\nThe duration is specified as a series of numbers followed by time units.\nWhitespace is allowed between numbers and units. Each number and unit will\nbe added together to form the total duration.\n\nThe allowed time units are as follows:\n\n * `y` - 365 SI days, or 8760 hours, or 31536000 seconds. No adjustments\n are made for leap years or leap seconds.\n * `d` - one SI day, or 86400 seconds.\n * `h` - one hour, or 3600 seconds.\n * `m` - one minute, or 60 seconds.\n * `s` - one second.\n * `ms` - one millisecond, or 0.001 second.\n * `us` or `µs` - one microsecond, or 0.000001 second.\n * `ns` - one nanosecond, or 0.000000001 second.\n\nExamples:\n * `1h30m`\n * `45s`\n\nUnits can be repeated and will be added together. This means that\n`1h1h` is equivalent to `2h`. This is confusing and should be avoided.\nA future update may disallow this.\n\nThe maximum value is `584y 49w 23h 34m 33s 709ms 551µs 615ns`. Any\nvalue larger than this will be clamped to the maximum value.\n\nAvailable since 1.3.0", + "defaults": [ + "5s" + ] + }, + { + "key": "env", + "zigType": "RepeatableStringMap", + "kind": "text", + "repeatable": true, + "hint": "NAME=value", + "doc": "Extra environment variables to pass to commands launched in a terminal\nsurface. The format is `env=KEY=VALUE`.\n\n`env = foo=bar`\n`env = bar=baz`\n\nSetting `env` to an empty string will reset the entire map to default\n(empty).\n\n`env =`\n\nSetting a key to an empty string will remove that particular key and\ncorresponding value from the map.\n\n`env = foo=bar`\n`env = foo=`\n\nwill result in `foo` not being passed to the launched commands.\n\nSetting a key multiple times will overwrite previous entries.\n\n`env = foo=bar`\n`env = foo=baz`\n\nwill result in `foo=baz` being passed to the launched commands.\n\nThese environment variables will override any existing environment\nvariables set by Ghostty. For example, if you set `GHOSTTY_RESOURCES_DIR`\nthen the value you set here will override the value Ghostty typically\nautomatically injects.\n\nThese environment variables _will not_ be passed to commands run by Ghostty\nfor other purposes, like `open` or `xdg-open` used to open URLs in your\nbrowser.\n\nAvailable since: 1.2.0", + "defaults": [ + "" + ] + }, + { + "key": "input", + "zigType": "RepeatableReadableIO", + "kind": "text", + "repeatable": true, + "hint": "raw:TEXT or path:FILE", + "doc": "Data to send as input to the command on startup.\n\nThe configured `command` will be launched using the typical rules,\nthen the data specified as this input will be written to the pty\nbefore any other input can be provided.\n\nThe bytes are sent as-is with no additional encoding. Therefore, be\ncautious about input that can contain control characters, because this\ncan be used to execute programs in a shell.\n\nThe format of this value is:\n\n * `raw:\u003cstring\u003e` - Send raw text as-is. This uses Zig string literal\n syntax so you can specify control characters and other standard\n escapes.\n\n * `path:\u003cpath\u003e` - Read a filepath and send the contents. The path\n must be to a file with finite length. e.g. don't use a device\n such as `/dev/stdin` or `/dev/urandom` as these will block\n terminal startup indefinitely. Files are limited to 10MB\n in size to prevent excessive memory usage. If you have files\n larger than this you should write a script to read the file\n and send it to the terminal.\n\nIf no valid prefix is found, it is assumed to be a `raw:` input.\nThis is an ergonomic choice to allow you to simply write\n`input = \"Hello, world!\"` (a common case) without needing to prefix\nevery value with `raw:`.\n\nThis can be repeated multiple times to send more data. The data\nis concatenated directly with no separator characters in between\n(e.g. no newline).\n\nIf any of the input sources do not exist, then none of the input\nwill be sent. Input sources are not verified until the terminal\nis starting, so missing paths will not show up in config validation.\n\nChanging this configuration at runtime will only affect new\nterminals.\n\nAvailable since: 1.2.0", + "defaults": [ + "" + ] + }, + { + "key": "wait-after-command", + "zigType": "bool", + "kind": "bool", + "doc": "If true, keep the terminal open after the command exits. Normally, the\nterminal window closes when the running command (such as a shell) exits.\nWith this true, the terminal window will stay open until any keypress is\nreceived.\n\nThis is primarily useful for scripts or debugging.", + "defaults": [ + "false" + ] + }, + { + "key": "abnormal-command-exit-runtime", + "zigType": "u32", + "kind": "int", + "min": 0, + "max": 4294967295, + "doc": "The number of milliseconds of runtime below which we consider a process exit\nto be abnormal. This is used to show an error message when the process exits\ntoo quickly.\n\nOn Linux, this must be paired with a non-zero exit code. On macOS, we allow\nany exit code because of the way shell processes are launched via the login\ncommand.", + "defaults": [ + "250" + ] + }, + { + "key": "scrollback-limit", + "zigType": "usize", + "kind": "int", + "min": 0, + "doc": "The size of the scrollback buffer in bytes. This also includes the active\nscreen. No matter what this is set to, enough memory will always be\nallocated for the visible screen and anything leftover is the limit for\nthe scrollback.\n\nWhen this limit is reached, the oldest lines are removed from the\nscrollback.\n\nScrollback currently exists completely in memory. This means that the\nlarger this value, the larger potential memory usage. Scrollback is\nallocated lazily up to this limit, so if you set this to a very large\nvalue, it will not immediately consume a lot of memory.\n\nThis size is per terminal surface, not for the entire application.\n\nIt is not currently possible to set an unlimited scrollback buffer.\nThis is a future planned feature.\n\nThis can be changed at runtime but will only affect new terminal surfaces.", + "defaults": [ + "10000000" + ] + }, + { + "key": "scrollbar", + "zigType": "Scrollbar", + "kind": "enum", + "values": [ + "system", + "never" + ], + "doc": "Control when the scrollbar is shown to scroll the scrollback buffer.\n\nThe default value is `system`.\n\nValid values:\n\n * `system` - Respect the system settings for when to show scrollbars.\n For example, on macOS, this will respect the \"Scrollbar behavior\"\n system setting which by default usually only shows scrollbars while\n actively scrolling or hovering the gutter.\n\n * `never` - Never show a scrollbar. You can still scroll using the mouse,\n keybind actions, etc. but you will not have a visual UI widget showing\n a scrollbar.", + "defaults": [ + "system" + ] + }, + { + "key": "link-url", + "zigType": "bool", + "kind": "bool", + "doc": "Match a regular expression against the terminal text and associate clicking\nit with an action. This can be used to match URLs, file paths, etc. Actions\ncan be opening using the system opener (e.g. `open` or `xdg-open`) or\nexecuting any arbitrary binding action.\n\nLinks that are configured earlier take precedence over links that are\nconfigured later.\n\nA default link that matches a URL and opens it in the system opener always\nexists. This can be disabled using `link-url`.\n\nTODO: This can't currently be set!\nEnable URL matching. URLs are matched on hover with control (Linux) or\ncommand (macOS) pressed and open using the default system application for\nthe linked URL.\n\nThe URL matcher is always lowest priority of any configured links (see\n`link`). If you want to customize URL matching, use `link` and disable this.", + "defaults": [ + "true" + ] + }, + { + "key": "link-previews", + "zigType": "LinkPreviews", + "kind": "enum", + "values": [ + "false", + "true", + "osc8" + ], + "doc": "Show link previews for a matched URL.\n\nWhen true, link previews are shown for all matched URLs. When false, link\npreviews are never shown. When set to \"osc8\", link previews are only shown\nfor hyperlinks created with the OSC 8 sequence (in this case, the link text\ncan differ from the link destination).\n\nAvailable since: 1.2.0", + "defaults": [ + "true" + ] + }, + { + "key": "maximize", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to start the window in a maximized state. This setting applies\nto new windows and does not apply to tabs, splits, etc. However, this setting\nwill apply to all new windows, not just the first one.\n\nAvailable since: 1.1.0", + "defaults": [ + "false" + ] + }, + { + "key": "fullscreen", + "zigType": "Fullscreen", + "kind": "enum", + "values": [ + "false", + "true", + "non-native", + "non-native-visible-menu", + "non-native-padded-notch" + ], + "doc": "Start new windows in fullscreen. This setting applies to new windows and\ndoes not apply to tabs, splits, etc. However, this setting will apply to all\nnew windows, not just the first one.\n\nAllowable values are:\n\n * `false` - Don't start in fullscreen (default)\n * `true` - Start in native fullscreen\n * `non-native` - (macOS only) Start in non-native fullscreen, hiding the\n menu bar. This is faster than native fullscreen since it doesn't use\n animations. On non-macOS platforms, this behaves the same as `true`.\n * `non-native-visible-menu` - (macOS only) Start in non-native fullscreen,\n keeping the menu bar visible. On non-macOS platforms, behaves like `true`.\n * `non-native-padded-notch` - (macOS only) Start in non-native fullscreen,\n hiding the menu bar but padding for the notch on applicable devices.\n On non-macOS platforms, behaves like `true`.\n\nImportant: tabs DO NOT WORK with non-native fullscreen modes. Non-native\nfullscreen removes the titlebar and macOS native tabs require the titlebar.\nIf you use tabs, use `true` (native) instead.\n\nOn macOS, `true` (native fullscreen) does not work if `window-decoration`\nis set to `false`, because native fullscreen on macOS requires window\ndecorations.", + "defaults": [ + "false" + ] + }, + { + "key": "title", + "zigType": "?[:0]const u8", + "kind": "text", + "doc": "The title Ghostty will use for the window. This will force the title of the\nwindow to be this title at all times and Ghostty will ignore any set title\nescape sequences programs (such as Neovim) may send.\n\nIf you want a blank title, set this to one or more spaces by quoting\nthe value. For example, `title = \" \"`. This effectively hides the title.\nThis is necessary because setting a blank value resets the title to the\ndefault value of the running program.\n\nThis configuration can be reloaded at runtime. If it is set, the title\nwill update for all windows. If it is unset, the next title change escape\nsequence will be honored but previous changes will not retroactively\nbe set. This latter case may require you to restart programs such as Neovim\nto get the new title.", + "defaults": [ + "" + ] + }, + { + "key": "class", + "zigType": "?[:0]const u8", + "kind": "text", + "doc": "The setting that will change the application class value.\n\nThis controls the class field of the `WM_CLASS` X11 property (when running\nunder X11), the Wayland application ID (when running under Wayland), and the\nbus name that Ghostty uses to connect to DBus.\n\nNote that changing this value between invocations will create new, separate\ninstances, of Ghostty when running with `gtk-single-instance=true`. See that\noption for more details.\n\nChanging this value may break launching Ghostty from `.desktop` files, via\nDBus activation, or systemd user services as the system is expecting Ghostty\nto connect to DBus using the default `class` when it is launched.\n\nThe class name must follow the requirements defined [in the GTK\ndocumentation](https://docs.gtk.org/gio/type_func.Application.id_is_valid.html).\n\nThe default is `com.mitchellh.ghostty`.\n\nThis only affects GTK builds.", + "defaults": [ + "" + ] + }, + { + "key": "x11-instance-name", + "zigType": "?[:0]const u8", + "kind": "text", + "doc": "This controls the instance name field of the `WM_CLASS` X11 property when\nrunning under X11. It has no effect otherwise.\n\nThe default is `ghostty`.\n\nThis only affects GTK builds.", + "defaults": [ + "" + ] + }, + { + "key": "working-directory", + "zigType": "?WorkingDirectory", + "kind": "choice", + "values": [ + "home", + "inherit" + ], + "hint": "home, inherit, or a directory path", + "doc": "The directory to change to after starting the command.\n\nThis setting is secondary to the `window-inherit-working-directory`\nsetting. If a previous Ghostty terminal exists in the same process,\n`window-inherit-working-directory` will take precedence. Otherwise, this\nsetting will be used. Typically, this setting is used only for the first\nwindow.\n\nThe default is `inherit` except in special scenarios listed next. On macOS,\nif Ghostty can detect it is launched from launchd (double-clicked) or\n`open`, then it defaults to `home`. On Linux with GTK, if Ghostty can detect\nit was launched from a desktop launcher, then it defaults to `home`.\n\nThe value of this must be an absolute path, a path prefixed with `~/`\n(the tilde will be expanded to the user's home directory), or\none of the special values below:\n\n * `home` - The home directory of the executing user.\n\n * `inherit` - The working directory of the launching process.", + "defaults": [ + "" + ] + }, + { + "key": "keybind", + "zigType": "Keybinds", + "kind": "keybind", + "repeatable": true, + "doc": "Key bindings. The format is `trigger=action`. Duplicate triggers will\noverwrite previously set values. The list of actions is available in\nthe documentation or using the `ghostty +list-actions` command.\n\nTrigger: `+`-separated list of keys and modifiers. Example: `ctrl+a`,\n`ctrl+shift+b`, `up`.\n\nIf the key is a single Unicode codepoint, the trigger will match\nany presses that produce that codepoint. These are impacted by\nkeyboard layouts. For example, `a` will match the `a` key on a\nQWERTY keyboard, but will match the `q` key on a AZERTY keyboard\n(assuming US physical layout).\n\nFor Unicode codepoints, matching is done by comparing the set of\nmodifiers with the unmodified codepoint. The unmodified codepoint is\nsometimes called an \"unshifted character\" in other software, but all\nmodifiers are considered, not only shift. For example, `ctrl+a` will match\n`a` but not `ctrl+shift+a` (which is `A` on a US keyboard).\n\nFurther, codepoint matching is case-insensitive and the unmodified\ncodepoint is always case folded for comparison. As a result,\n`ctrl+A` configured will match when `ctrl+a` is pressed. Note that\nthis means some key combinations are impossible depending on keyboard\nlayout. For example, `ctrl+_` is impossible on a US keyboard because\n`_` is `shift+-` and `ctrl+shift+-` is not equal to `ctrl+_` (because\nthe modifiers don't match!). More details on impossible key combinations\ncan be found at this excellent source written by Qt developers:\nhttps://doc.qt.io/qt-6/qkeysequence.html#keyboard-layout-issues\n\nPhysical key codes can be specified by using any of the key codes\nas specified by the [W3C specification](https://www.w3.org/TR/uievents-code/).\nFor example, `KeyA` will match the physical `a` key on a US standard\nkeyboard regardless of the keyboard layout. These are case-sensitive.\n\nFor aesthetic reasons, the w3c codes also support snake case. For\nexample, `key_a` is equivalent to `KeyA`. The only exceptions are\nfunction keys, e.g. `F1` is `f1` (no underscore). This is a consequence\nof our internal code using snake case but is purposely supported\nand tested so it is safe to use. It allows an all-lowercase binding\nwhich I find more aesthetically pleasing.\n\nFunction keys such as `insert`, `up`, `f5`, etc. are also specified\nusing the keys as specified by the previously linked W3C specification.\n\nPhysical keys always match with a higher priority than Unicode codepoints,\nso if you specify both `a` and `KeyA`, the physical key will always be used\nregardless of what order they are configured.\n\nThe special key `catch_all` can be used to match any key that is not\notherwise bound. This can be combined with modifiers, for example\n`ctrl+catch_all` will match any key pressed with `ctrl` that is not\notherwise bound. When looking up a binding, Ghostty first tries to match\n`catch_all` with modifiers. If no match is found and the event has\nmodifiers, it falls back to `catch_all` without modifiers.\n\nValid modifiers are `shift`, `ctrl` (alias: `control`), `alt` (alias: `opt`,\n`option`), and `super` (alias: `cmd`, `command`). You may use the modifier\nor the alias. When debugging keybinds, the non-aliased modifier will always\nbe used in output.\n\nNote: The fn or \"globe\" key on keyboards are not supported as a\nmodifier. This is a limitation of the operating systems and GUI toolkits\nthat Ghostty uses.\n\nSome additional notes for triggers:\n\n * modifiers cannot repeat, `ctrl+ctrl+a` is invalid.\n\n * modifiers and keys can be in any order, `shift+a+ctrl` is *weird*,\n but valid.\n\n * only a single key input is allowed, `ctrl+a+b` is invalid.\n\nYou may also specify multiple triggers separated by `\u003e` to require a\nsequence of triggers to activate the action. For example,\n`ctrl+a\u003en=new_window` will only trigger the `new_window` action if the\nuser presses `ctrl+a` followed separately by `n`. In other software, this\nis sometimes called a leader key, a key chord, a key table, etc. There\nis no hardcoded limit on the number of parts in a sequence.\n\nWarning: If you define a sequence as a CLI argument to `ghostty`,\nyou probably have to quote the keybind since `\u003e` is a special character\nin most shells. Example: ghostty --keybind='ctrl+a\u003en=new_window'\n\nA trigger sequence has some special handling:\n\n * Ghostty will wait an indefinite amount of time for the next key in\n the sequence. There is no way to specify a timeout. The only way to\n force the output of a prefix key is to assign another keybind to\n specifically output that key (e.g. `ctrl+a\u003ectrl+a=text:foo`) or\n press an unbound key which will send both keys to the program.\n\n * If an unbound key is pressed during a sequence and a `catch_all`\n binding exists that would `ignore` the input, the entire sequence\n is dropped and nothing happens. Otherwise, the entire sequence is\n encoded and sent to the running program as if no keybind existed.\n\n * If a prefix in a sequence is previously bound, the sequence will\n override the previous binding. For example, if `ctrl+a` is bound to\n `new_window` and `ctrl+a\u003en` is bound to `new_tab`, pressing `ctrl+a`\n will do nothing.\n\n * Adding to the above, if a previously bound sequence prefix is\n used in a new, non-sequence binding, the entire previously bound\n sequence will be unbound. For example, if you bind `ctrl+a\u003en` and\n `ctrl+a\u003et`, and then bind `ctrl+a` directly, both `ctrl+a\u003en` and\n `ctrl+a\u003et` will become unbound.\n\n * Trigger sequences are not allowed for `global:` or `all:`-prefixed\n triggers. This is a limitation we could remove in the future.\n\nAction is the action to take when the trigger is satisfied. It takes the\nformat `action` or `action:param`. The latter form is only valid if the\naction requires a parameter.\n\n * `ignore` - Do nothing, ignore the key input. This can be used to\n black hole certain inputs to have no effect.\n\n * `unbind` - Remove the binding. This makes it so the previous action\n is removed, and the key will be sent through to the child command\n if it is printable. Unbind will remove any matching trigger,\n including `physical:`-prefixed triggers without specifying the\n prefix.\n\n * `csi:text` - Send a CSI sequence. e.g. `csi:A` sends \"cursor up\".\n\n * `esc:text` - Send an escape sequence. e.g. `esc:d` deletes to the\n end of the word to the right.\n\n * `text:text` - Send a string. Uses Zig string literal syntax.\n e.g. `text:\\x15` sends Ctrl-U.\n\n * All other actions can be found in the documentation or by using the\n `ghostty +list-actions` command.\n\nSome notes for the action:\n\n * The parameter is taken as-is after the `:`. Double quotes or\n other mechanisms are included and NOT parsed. If you want to\n send a string value that includes spaces, wrap the entire\n trigger/action in double quotes. Example: `--keybind=\"up=csi:A B\"`\n\nThere are some additional special values that can be specified for\nkeybind:\n\n * `keybind=clear` will clear all set keybindings. Warning: this\n removes ALL keybindings up to this point, including the default\n keybindings.\n\nThe keybind trigger can be prefixed with some special values to change\nthe behavior of the keybind. These are:\n\n * `all:`\n\n Make the keybind apply to all terminal surfaces. By default,\n keybinds only apply to the focused terminal surface. If this is true,\n then the keybind will be sent to all terminal surfaces. This only\n applies to actions that are surface-specific. For actions that\n are already global (e.g. `quit`), this prefix has no effect.\n\n Available since: 1.0.0\n\n * `global:`\n\n Make the keybind global. By default, keybinds only work within Ghostty\n and under the right conditions (application focused, sometimes terminal\n focused, etc.). If you want a keybind to work globally across your system\n (e.g. even when Ghostty is not focused), specify this prefix.\n This prefix implies `all:`.\n\n Note: this does not work in all environments; see the additional notes\n below for more information.\n\n Available since: 1.0.0 on macOS, 1.2.0 on GTK\n\n * `unconsumed:`\n\n Do not consume the input. By default, a keybind will consume the input,\n meaning that the associated encoding (if any) will not be sent to the\n running program in the terminal. If you wish to send the encoded value\n to the program, specify the `unconsumed:` prefix before the entire\n keybind. For example: `unconsumed:ctrl+a=reload_config`. `global:` and\n `all:`-prefixed keybinds will always consume the input regardless of\n this setting. Since they are not associated with a specific terminal\n surface, they're never encoded.\n\n Available since: 1.0.0\n\n * `performable:`\n\n Only consume the input if the action is able to be performed.\n For example, the `copy_to_clipboard` action will only consume the input\n if there is a selection to copy. If there is no selection, Ghostty\n behaves as if the keybind was not set. This has no effect with `global:`\n or `all:`-prefixed keybinds. For key sequences, this will reset the\n sequence if the action is not performable (acting identically to not\n having a keybind set at all).\n\n Performable keybinds will not appear as menu shortcuts in the\n application menu. This is because the menu shortcuts force the\n action to be performed regardless of the state of the terminal.\n Performable keybinds will still work, they just won't appear as\n a shortcut label in the menu.\n\n Available since: 1.1.0\n\nKeybind triggers are not unique per prefix combination. For example,\n`ctrl+a` and `global:ctrl+a` are not two separate keybinds. The keybind\nset later will overwrite the keybind set earlier. In this case, the\n`global:` keybind will be used.\n\nMultiple prefixes can be specified. For example,\n`global:unconsumed:ctrl+a=reload_config` will make the keybind global\nand not consume the input to reload the config.\n\nNote: `global:` is only supported on macOS and certain Linux platforms.\n\nOn macOS, this feature requires accessibility permissions to be granted\nto Ghostty. When a `global:` keybind is specified and Ghostty is launched\nor reloaded, Ghostty will attempt to request these permissions.\nIf the permissions are not granted, the keybind will not work. On macOS,\nyou can find these permissions in System Preferences -\u003e Privacy \u0026 Security\n-\u003e Accessibility.\n\nOn Linux, you need a desktop environment that implements the\n[Global Shortcuts](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.GlobalShortcuts.html)\nprotocol as a part of its XDG desktop protocol implementation.\nDesktop environments that are known to support (or not support)\nglobal shortcuts include:\n\n - Users using KDE Plasma (since [5.27](https://kde.org/announcements/plasma/5/5.27.0/#wayland))\n and GNOME (since [48](https://release.gnome.org/48/#and-thats-not-all)) should be able\n to use global shortcuts with little to no configuration.\n\n - Some manual configuration is required on Hyprland. Consult the steps\n outlined on the [Hyprland Wiki](https://wiki.hyprland.org/Configuring/Binds/#dbus-global-shortcuts)\n to set up global shortcuts correctly.\n (Important: [`xdg-desktop-portal-hyprland`](https://wiki.hyprland.org/Hypr-Ecosystem/xdg-desktop-portal-hyprland/)\n must also be installed!)\n\n - Notably, global shortcuts have not been implemented on wlroots-based\n compositors like Sway (see [upstream issue](https://github.com/emersion/xdg-desktop-portal-wlr/issues/240)).\n\n## Chained Actions\n\nA keybind can have multiple actions by using the `chain` keyword for\nsubsequent actions. When a keybind is activated, all chained actions are\nexecuted in order. The syntax is:\n\n```ini\nkeybind = ctrl+a=new_window\nkeybind = chain=goto_split:left\n```\n\nThis binds `ctrl+a` to first open a new window, then move focus to the\nleft split. Each `chain` entry appends an action to the most recently\ndefined keybind. You can chain as many actions as you want:\n\n```ini\nkeybind = ctrl+a=new_window\nkeybind = chain=goto_split:left\nkeybind = chain=toggle_fullscreen\n```\n\nChained actions cannot have prefixes like `global:` or `unconsumed:`.\nThe flags from the original keybind apply to the entire chain.\n\nChained actions work with key sequences as well. For example:\n\n```ini\nkeybind = ctrl+a\u003en=new_window\nkeybind = chain=goto_split:left\n````\n\nChains with key sequences apply to the most recent binding in the\nsequence.\n\nChained keybinds are available since Ghostty 1.3.0.\n\n## Key Tables\n\nYou may also create a named set of keybindings known as a \"key table.\"\nA key table must be explicitly activated for the bindings to become\navailable. This can be used to implement features such as a\n\"copy mode\", \"vim mode\", etc. Generically, this can implement modal\nkeyboard input.\n\nKey tables are defined using the syntax `\u003ctable\u003e/\u003cbinding\u003e`. The\n`\u003cbinding\u003e` value is everything documented above for keybinds. The\n`\u003ctable\u003e` value is the name of the key table. Table names can contain\nanything except `/`, `=`, `+`, and `\u003e`. The characters `+` and `\u003e` are\nreserved for keybind syntax (modifier combinations and key sequences).\nFor example `foo/ctrl+a=new_window` defines a binding within a table\nnamed `foo`.\n\nTables are activated and deactivated using the binding actions\n`activate_key_table:\u003cname\u003e` and `deactivate_key_table`. Other table\nrelated binding actions also exist; see the documentation for a full list.\nThese are the primary way to interact with key tables.\n\nBinding lookup proceeds from the innermost table outward, so keybinds in\nthe default table remain available unless explicitly unbound in an inner\ntable.\n\nA key table has some special syntax and handling:\n\n * `\u003cname\u003e/` (with no binding) defines and clears a table, resetting all\n of its keybinds and settings.\n\n * You cannot activate a table that is already the innermost table; such\n attempts are ignored. However, the same table can appear multiple times\n in the stack as long as it is not innermost (e.g., `A -\u003e B -\u003e A -\u003e B`\n is valid, but `A -\u003e B -\u003e B` is not).\n\n * A table can be activated in one-shot mode using\n `activate_key_table_once:\u003cname\u003e`. A one-shot table is automatically\n deactivated when any non-catch-all binding is invoked.\n\n * Key sequences work within tables: `foo/ctrl+a\u003ectrl+b=new_window`.\n If an invalid key is pressed, the sequence ends but the table remains\n active.\n\n * Chain actions work within tables, the `chain` keyword applies to\n the most recently defined binding in the table. e.g. if you set\n `table/ctrl+a=new_window` you can chain by using `chain=text:hello`.\n Important: chain itself doesn't get prefixed with the table name,\n since it applies to the most recent binding in any table.\n\n * Prefixes like `global:` work within tables:\n `foo/global:ctrl+a=new_window`.\n\nKey tables are available since Ghostty 1.3.0.", + "defaults": [ + "super+shift+,=reload_config", + "super+,=open_config", + "copy=copy_to_clipboard:mixed", + "paste=paste_from_clipboard", + "super+c=copy_to_clipboard:mixed", + "super+v=paste_from_clipboard", + "super+==increase_font_size:1", + "super++=increase_font_size:1", + "super+-=decrease_font_size:1", + "super+0=reset_font_size", + "super+ctrl+shift+j=write_screen_file:copy,plain", + "super+shift+j=write_screen_file:paste,plain", + "super+alt+shift+j=write_screen_file:open,plain", + "shift+arrow_left=adjust_selection:left", + "shift+arrow_right=adjust_selection:right", + "shift+arrow_up=adjust_selection:up", + "shift+arrow_down=adjust_selection:down", + "shift+page_up=adjust_selection:page_up", + "shift+page_down=adjust_selection:page_down", + "shift+home=adjust_selection:home", + "shift+end=adjust_selection:end", + "ctrl+shift+tab=previous_tab", + "ctrl+tab=next_tab", + "super+digit_1=goto_tab:1", + "super+1=goto_tab:1", + "super+digit_2=goto_tab:2", + "super+2=goto_tab:2", + "super+digit_3=goto_tab:3", + "super+3=goto_tab:3", + "super+digit_4=goto_tab:4", + "super+4=goto_tab:4", + "super+digit_5=goto_tab:5", + "super+5=goto_tab:5", + "super+digit_6=goto_tab:6", + "super+6=goto_tab:6", + "super+digit_7=goto_tab:7", + "super+7=goto_tab:7", + "super+digit_8=goto_tab:8", + "super+8=goto_tab:8", + "super+9=last_tab", + "super+enter=toggle_fullscreen", + "super+shift+enter=toggle_split_zoom", + "super+shift+p=toggle_command_palette", + "super+q=quit", + "super+k=clear_screen", + "super+a=select_all", + "super+shift+t=undo", + "super+z=undo", + "super+shift+z=redo", + "super+home=scroll_to_top", + "super+end=scroll_to_bottom", + "super+page_up=scroll_page_up", + "super+page_down=scroll_page_down", + "super+j=scroll_to_selection", + "super+shift+arrow_up=jump_to_prompt:-1", + "super+shift+arrow_down=jump_to_prompt:1", + "super+n=new_window", + "super+w=close_surface", + "super+alt+w=close_tab:this", + "super+shift+w=close_window", + "super+alt+shift+w=close_all_windows", + "super+t=new_tab", + "super+shift+[=previous_tab", + "super+shift+]=next_tab", + "super+d=new_split:right", + "super+shift+d=new_split:down", + "super+[=goto_split:previous", + "super+]=goto_split:next", + "super+alt+arrow_up=goto_split:up", + "super+alt+arrow_down=goto_split:down", + "super+alt+arrow_left=goto_split:left", + "super+alt+arrow_right=goto_split:right", + "super+ctrl+arrow_up=resize_split:up,10", + "super+ctrl+arrow_down=resize_split:down,10", + "super+ctrl+arrow_left=resize_split:left,10", + "super+ctrl+arrow_right=resize_split:right,10", + "super+ctrl+==equalize_splits", + "super+arrow_up=jump_to_prompt:-1", + "super+arrow_down=jump_to_prompt:1", + "super+f=start_search", + "super+e=search_selection", + "super+shift+f=end_search", + "escape=end_search", + "super+g=navigate_search:next", + "super+shift+g=navigate_search:previous", + "super+alt+i=inspector:toggle", + "super+ctrl+f=toggle_fullscreen", + "super+shift+v=paste_from_selection", + "super+arrow_right=text:\\\\x05", + "super+arrow_left=text:\\\\x01", + "super+backspace=text:\\\\x15", + "alt+arrow_left=esc:b", + "alt+arrow_right=esc:f" + ] + }, + { + "key": "key-remap", + "zigType": "KeyRemapSet", + "kind": "text", + "repeatable": true, + "hint": "from=to, e.g. ctrl=super", + "doc": "Remap modifier keys within Ghostty. This allows you to swap or reassign\nmodifier keys at the application level without affecting system-wide\nsettings.\n\nThe format is `from=to` where both `from` and `to` are modifier key names.\nYou can use generic names like `ctrl`, `alt`, `shift`, `super` (macOS:\n`cmd`/`command`) or sided names like `left_ctrl`, `right_alt`, etc.\n\nThis will NOT change keyboard layout or key encodings outside of Ghostty.\nFor example, on macOS, `option+a` may still produce `å` even if `option` is\nremapped to `ctrl`. Desktop environments usually handle key layout long\nbefore Ghostty receives the key events.\n\nExample:\n\n key-remap = ctrl=super\n key-remap = left_control=right_alt\n\nImportant notes:\n\n* This is a one-way remap. If you remap `ctrl=super`, then the physical\n Ctrl key acts as Super, but the Super key remains Super.\n\n* Remaps are not transitive. If you remap `ctrl=super` and `alt=ctrl`,\n pressing Alt will produce Ctrl, NOT Super.\n\n* This affects both keybind matching and terminal input encoding.\n This does NOT impact keyboard layout or how keys are interpreted\n prior to Ghostty receiving them. For example, `option+a` on macOS\n may still produce `å` even if `option` is remapped to `ctrl`.\n\n* Generic modifiers (e.g. `ctrl`) match both left and right physical keys.\n Use sided names (e.g. `left_ctrl`) to remap only one side.\n\nThere are other edge case scenarios that may not behave as expected\nbut are working as intended the way this feature is designed:\n\n* On macOS, bindings in the main menu will trigger before any remapping\n is done. This is because macOS itself handles menu activation and\n this happens before Ghostty receives the key event. To workaround\n this, you should unbind the menu items and rebind them using your\n desired modifier.\n\nThis configuration can be repeated to specify multiple remaps.", + "defaults": [ + "" + ] + }, + { + "key": "window-padding-x", + "zigType": "WindowPadding", + "kind": "padding", + "doc": "Horizontal window padding. This applies padding between the terminal cells\nand the left and right window borders. The value is in points, meaning that\nit will be scaled appropriately for screen DPI.\n\nIf this value is set too large, the screen will render nothing, because the\ngrid will be completely squished by the padding. It is up to you as the user\nto pick a reasonable value. If you pick an unreasonable value, a warning\nwill appear in the logs.\n\nChanging this configuration at runtime will only affect new terminals, i.e.\nnew windows, tabs, etc.\n\nTo set a different left and right padding, specify two numerical values\nseparated by a comma. For example, `window-padding-x = 2,4` will set the\nleft padding to 2 and the right padding to 4. If you want to set both\npaddings to the same value, you can use a single value. For example,\n`window-padding-x = 2` will set both paddings to 2.", + "defaults": [ + "2" + ] + }, + { + "key": "window-padding-y", + "zigType": "WindowPadding", + "kind": "padding", + "doc": "Vertical window padding. This applies padding between the terminal cells and\nthe top and bottom window borders. The value is in points, meaning that it\nwill be scaled appropriately for screen DPI.\n\nIf this value is set too large, the screen will render nothing, because the\ngrid will be completely squished by the padding. It is up to you as the user\nto pick a reasonable value. If you pick an unreasonable value, a warning\nwill appear in the logs.\n\nChanging this configuration at runtime will only affect new terminals,\ni.e. new windows, tabs, etc.\n\nTo set a different top and bottom padding, specify two numerical values\nseparated by a comma. For example, `window-padding-y = 2,4` will set the\ntop padding to 2 and the bottom padding to 4. If you want to set both\npaddings to the same value, you can use a single value. For example,\n`window-padding-y = 2` will set both paddings to 2.", + "defaults": [ + "2" + ] + }, + { + "key": "window-padding-balance", + "zigType": "bool", + "kind": "bool", + "doc": "The viewport dimensions are usually not perfectly divisible by the cell\nsize. In this case, some extra padding on the end of a column and the bottom\nof the final row may exist. If this is `true`, then this extra padding\nis automatically balanced between all four edges to minimize imbalance on\none side. If this is `false`, the top left grid cell will always hug the\nedge with zero padding other than what may be specified with the other\n`window-padding` options.\n\nIf other `window-padding` fields are set and this is `true`, this will still\napply. The other padding is applied first and may affect how many grid cells\nactually exist, and this is applied last in order to balance the padding\ngiven a certain viewport size and grid cell size.", + "defaults": [ + "false" + ] + }, + { + "key": "window-padding-color", + "zigType": "WindowPaddingColor", + "kind": "enum", + "values": [ + "background", + "extend", + "extend-always" + ], + "doc": "The color of the padding area of the window. Valid values are:\n\n* `background` - The background color specified in `background`.\n* `extend` - Extend the background color of the nearest grid cell.\n* `extend-always` - Same as \"extend\" but always extends without applying\n any of the heuristics that disable extending noted below.\n\nThe \"extend\" value will be disabled in certain scenarios. On primary\nscreen applications (e.g. not something like Neovim), the color will not\nbe extended vertically if any of the following are true:\n\n* The nearest row has any cells that have the default background color.\n The thinking is that in this case, the default background color looks\n fine as a padding color.\n* The nearest row is a prompt row (requires shell integration). The\n thinking here is that prompts often contain powerline glyphs that\n do not look good extended.\n* The nearest row contains a perfect fit powerline character. These\n don't look good extended.", + "defaults": [ + "background" + ] + }, + { + "key": "window-vsync", + "zigType": "bool", + "kind": "bool", + "doc": "Synchronize rendering with the screen refresh rate. If true, this will\nminimize tearing and align redraws with the screen but may cause input\nlatency. If false, this will maximize redraw frequency but may cause tearing,\nand under heavy load may use more CPU and power.\n\nThis defaults to true because out-of-sync rendering on macOS can\ncause kernel panics (macOS 14.4+) and performance issues for external\ndisplays over some hardware such as DisplayLink. If you want to minimize\ninput latency, set this to false with the known aforementioned risks.\n\nChanging this value at runtime will only affect new terminals.\n\nThis setting is only supported currently on macOS.", + "defaults": [ + "true" + ] + }, + { + "key": "window-inherit-working-directory", + "zigType": "bool", + "kind": "bool", + "doc": "If true, new windows will inherit the working directory of the\npreviously focused window. If no window was previously focused, the default\nworking directory will be used (the `working-directory` option).", + "defaults": [ + "true" + ] + }, + { + "key": "tab-inherit-working-directory", + "zigType": "bool", + "kind": "bool", + "doc": "If true, new tabs will inherit the working directory of the\npreviously focused tab. If no tab was previously focused, the default\nworking directory will be used (the `working-directory` option).", + "defaults": [ + "true" + ] + }, + { + "key": "split-inherit-working-directory", + "zigType": "bool", + "kind": "bool", + "doc": "If true, new split panes will inherit the working directory of the\npreviously focused split. If no split was previously focused, the default\nworking directory will be used (the `working-directory` option).", + "defaults": [ + "true" + ] + }, + { + "key": "window-inherit-font-size", + "zigType": "bool", + "kind": "bool", + "doc": "If true, new windows and tabs will inherit the font size of the previously\nfocused window. If no window was previously focused, the default font size\nwill be used. If this is false, the default font size specified in the\nconfiguration `font-size` will be used.", + "defaults": [ + "true" + ] + }, + { + "key": "window-decoration", + "zigType": "WindowDecoration", + "kind": "enum", + "values": [ + "auto", + "client", + "server", + "none" + ], + "doc": "Configure a preference for window decorations. This setting specifies\na _preference_; the actual OS, desktop environment, window manager, etc.\nmay override this preference. Ghostty will do its best to respect this\npreference but it may not always be possible.\n\nValid values:\n\n * `none`\n\n All window decorations will be disabled. Titlebar, borders, etc. will\n not be shown. On macOS, this will also disable tabs (enforced by the\n system).\n\n * `auto`\n\n Automatically decide to use either client-side or server-side\n decorations based on the detected preferences of the current OS and\n desktop environment. This option usually makes Ghostty look the most\n \"native\" for your desktop.\n\n * `client`\n\n Prefer client-side decorations.\n\n Available since: 1.1.0\n\n * `server`\n\n Prefer server-side decorations. This is only relevant on Linux with GTK,\n either on X11, or Wayland on a compositor that supports the\n `org_kde_kwin_server_decoration` protocol (e.g. KDE Plasma, but almost\n any non-GNOME desktop supports this protocol).\n\n If `server` is set but the environment doesn't support server-side\n decorations, client-side decorations will be used instead.\n\n Available since: 1.1.0\n\nThe default value is `auto`.\n\nFor the sake of backwards compatibility and convenience, this setting also\naccepts boolean true and false values. If set to `true`, this is equivalent\nto `auto`. If set to `false`, this is equivalent to `none`.\nThis is convenient for users who live primarily on systems that don't\ndifferentiate between client and server-side decorations (e.g. macOS and\nWindows).\n\nThe \"toggle_window_decorations\" keybind action can be used to create\na keybinding to toggle this setting at runtime.\n\nmacOS: To hide the titlebar without removing the native window borders\n or rounded corners, use `macos-titlebar-style = hidden` instead.", + "defaults": [ + "auto" + ] + }, + { + "key": "window-title-font-family", + "zigType": "?[:0]const u8", + "kind": "font", + "doc": "The font that will be used for the application's window and tab titles.\n\nIf this setting is left unset, the system default font will be used.\n\nNote: any font available on the system may be used, this font is not\nrequired to be a fixed-width font.\n\nAvailable since: 1.0.0 on macOS, 1.1.0 on GTK", + "defaults": [ + "" + ] + }, + { + "key": "window-subtitle", + "zigType": "WindowSubtitle", + "kind": "enum", + "values": [ + "false", + "working-directory" + ], + "doc": "The text that will be displayed in the subtitle of the window. Valid values:\n\n * `false` - Disable the subtitle.\n * `working-directory` - Set the subtitle to the working directory of the\n surface.\n\nThis feature is only supported on GTK.\n\nAvailable since: 1.1.0", + "defaults": [ + "false" + ] + }, + { + "key": "window-theme", + "zigType": "WindowTheme", + "kind": "enum", + "values": [ + "auto", + "system", + "light", + "dark", + "ghostty" + ], + "doc": "The theme to use for the windows. Valid values:\n\n * `auto` - Determine the theme based on the configured terminal\n background color. This has no effect if the \"theme\" configuration\n has separate light and dark themes. In that case, the behavior\n of \"auto\" is equivalent to \"system\".\n * `system` - Use the system theme.\n * `light` - Use the light theme regardless of system theme.\n * `dark` - Use the dark theme regardless of system theme.\n * `ghostty` - Use the background and foreground colors specified in the\n Ghostty configuration. This is only supported on Linux builds.\n\nOn macOS, if `macos-titlebar-style` is `tabs` or `transparent`, the window theme will be\nautomatically set based on the luminosity of the terminal background color.\nThis only applies to terminal windows. This setting will still apply to\nnon-terminal windows within Ghostty.\n\nThis is currently only supported on macOS and Linux.", + "defaults": [ + "auto" + ] + }, + { + "key": "window-colorspace", + "zigType": "WindowColorspace", + "kind": "enum", + "values": [ + "srgb", + "display-p3" + ], + "doc": "The color space to use when interpreting terminal colors. \"Terminal colors\"\nrefers to colors specified in your configuration and colors produced by\ndirect-color SGR sequences.\n\nValid values:\n\n * `srgb` - Interpret colors in the sRGB color space. This is the default.\n * `display-p3` - Interpret colors in the Display P3 color space.\n\nThis setting is currently only supported on macOS.", + "defaults": [ + "srgb" + ] + }, + { + "key": "window-height", + "zigType": "u32", + "kind": "int", + "min": 0, + "max": 4294967295, + "doc": "The initial window size. This size is in terminal grid cells by default.\nBoth values must be set to take effect. If only one value is set, it is\nignored.\n\nWe don't currently support specifying a size in pixels but a future change\ncan enable that. If this isn't specified, the app runtime will determine\nsome default size.\n\nNote that the window manager may put limits on the size or override the\nsize. For example, a tiling window manager may force the window to be a\ncertain size to fit within the grid. There is nothing Ghostty will do about\nthis, but it will make an effort.\n\nSizes larger than the screen size will be clamped to the screen size.\nThis can be used to create a maximized-by-default window size.\n\nThis will not affect new tabs, splits, or other nested terminal elements.\nThis only affects the initial window size of any new window. Changing this\nvalue will not affect the size of the window after it has been created. This\nis only used for the initial size.\n\nBUG: On Linux with GTK, the calculated window size will not properly take\ninto account window decorations. As a result, the grid dimensions will not\nexactly match this configuration. If window decorations are disabled (see\n`window-decoration`), then this will work as expected.\n\nWindows smaller than 10 wide by 4 high are not allowed.", + "defaults": [ + "0" + ] + }, + { + "key": "window-width", + "zigType": "u32", + "kind": "int", + "min": 0, + "max": 4294967295, + "doc": "The initial window size. This size is in terminal grid cells by default.\nBoth values must be set to take effect. If only one value is set, it is\nignored.\n\nWe don't currently support specifying a size in pixels but a future change\ncan enable that. If this isn't specified, the app runtime will determine\nsome default size.\n\nNote that the window manager may put limits on the size or override the\nsize. For example, a tiling window manager may force the window to be a\ncertain size to fit within the grid. There is nothing Ghostty will do about\nthis, but it will make an effort.\n\nSizes larger than the screen size will be clamped to the screen size.\nThis can be used to create a maximized-by-default window size.\n\nThis will not affect new tabs, splits, or other nested terminal elements.\nThis only affects the initial window size of any new window. Changing this\nvalue will not affect the size of the window after it has been created. This\nis only used for the initial size.\n\nBUG: On Linux with GTK, the calculated window size will not properly take\ninto account window decorations. As a result, the grid dimensions will not\nexactly match this configuration. If window decorations are disabled (see\n`window-decoration`), then this will work as expected.\n\nWindows smaller than 10 wide by 4 high are not allowed.", + "defaults": [ + "0" + ] + }, + { + "key": "window-position-x", + "zigType": "?i16", + "kind": "int", + "min": -32768, + "max": 32767, + "doc": "The starting window position. This position is in pixels and is relative\nto the top-left corner of the primary monitor. Both values must be set to take\neffect. If only one value is set, it is ignored.\n\nNote that the window manager may put limits on the position or override\nthe position. For example, a tiling window manager may force the window\nto be a certain position to fit within the grid. There is nothing Ghostty\nwill do about this, but it will make an effort.\n\nAlso note that negative values are also up to the operating system and\nwindow manager. Some window managers may not allow windows to be placed\noff-screen.\n\nInvalid positions are runtime-specific, but generally the positions are\nclamped to the nearest valid position.\n\nOn macOS, the window position is relative to the top-left corner of\nthe visible screen area. This means that if the menu bar is visible, the\nwindow will be placed below the menu bar.\n\nNote: this is only supported on macOS. The GTK runtime does not support\nsetting the window position, as windows are only allowed position\nthemselves in X11 and not Wayland.", + "defaults": [ + "" + ] + }, + { + "key": "window-position-y", + "zigType": "?i16", + "kind": "int", + "min": -32768, + "max": 32767, + "doc": "The starting window position. This position is in pixels and is relative\nto the top-left corner of the primary monitor. Both values must be set to take\neffect. If only one value is set, it is ignored.\n\nNote that the window manager may put limits on the position or override\nthe position. For example, a tiling window manager may force the window\nto be a certain position to fit within the grid. There is nothing Ghostty\nwill do about this, but it will make an effort.\n\nAlso note that negative values are also up to the operating system and\nwindow manager. Some window managers may not allow windows to be placed\noff-screen.\n\nInvalid positions are runtime-specific, but generally the positions are\nclamped to the nearest valid position.\n\nOn macOS, the window position is relative to the top-left corner of\nthe visible screen area. This means that if the menu bar is visible, the\nwindow will be placed below the menu bar.\n\nNote: this is only supported on macOS. The GTK runtime does not support\nsetting the window position, as windows are only allowed position\nthemselves in X11 and not Wayland.", + "defaults": [ + "" + ] + }, + { + "key": "window-save-state", + "zigType": "WindowSaveState", + "kind": "enum", + "values": [ + "default", + "never", + "always" + ], + "doc": "Whether to enable saving and restoring window state. Window state includes\ntheir position, size, tabs, splits, etc. Some window state requires shell\nintegration, such as preserving working directories. See `shell-integration`\nfor more information.\n\nThere are three valid values for this configuration:\n\n * `default` will use the default system behavior. On macOS, this\n will only save state if the application is forcibly terminated\n or if it is configured systemwide via Settings.app.\n\n * `never` will never save window state.\n\n * `always` will always save window state whenever Ghostty is exited.\n\nIf you change this value to `never` while Ghostty is not running, the next\nGhostty launch will NOT restore the window state.\n\nIf you change this value to `default` while Ghostty is not running and the\nprevious exit saved state, the next Ghostty launch will still restore the\nwindow state. This is because Ghostty cannot know if the previous exit was\ndue to a forced save or not (macOS doesn't provide this information).\n\nIf you change this value so that window state is saved while Ghostty is not\nrunning, the previous window state will not be restored because Ghostty only\nsaves state on exit if this is enabled.\n\nThe default value is `default`.\n\nThis is currently only supported on macOS. This has no effect on Linux.", + "defaults": [ + "default" + ] + }, + { + "key": "window-step-resize", + "zigType": "bool", + "kind": "bool", + "doc": "Resize the window in discrete increments of the focused surface's cell size.\nIf this is disabled, surfaces are resized in pixel increments. Currently\nonly supported on macOS.", + "defaults": [ + "false" + ] + }, + { + "key": "window-new-tab-position", + "zigType": "WindowNewTabPosition", + "kind": "enum", + "values": [ + "current", + "end" + ], + "doc": "The position where new tabs are created. Valid values:\n\n * `current` - Insert the new tab after the currently focused tab,\n or at the end if there are no focused tabs.\n\n * `end` - Insert the new tab at the end of the tab list.", + "defaults": [ + "current" + ] + }, + { + "key": "window-show-tab-bar", + "zigType": "WindowShowTabBar", + "kind": "enum", + "values": [ + "always", + "auto", + "never" + ], + "doc": "Whether to show the tab bar.\n\nValid values:\n\n - `always`\n\n Always display the tab bar, even when there's only one tab.\n\n Available since: 1.2.0\n\n - `auto` *(default)*\n\n Automatically show and hide the tab bar. The tab bar is only\n shown when there are two or more tabs present.\n\n - `never`\n\n Never show the tab bar. Tabs are only accessible via the tab\n overview or by keybind actions.\n\nCurrently only supported on Linux (GTK).", + "defaults": [ + "auto" + ] + }, + { + "key": "window-titlebar-background", + "zigType": "?Color", + "kind": "color", + "doc": "Background color for the window titlebar. This only takes effect if\nwindow-theme is set to ghostty. Currently only supported in the GTK app\nruntime.\n\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "" + ] + }, + { + "key": "window-titlebar-foreground", + "zigType": "?Color", + "kind": "color", + "doc": "Foreground color for the window titlebar. This only takes effect if\nwindow-theme is set to ghostty. Currently only supported in the GTK app\nruntime.\n\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "" + ] + }, + { + "key": "resize-overlay", + "zigType": "ResizeOverlay", + "kind": "enum", + "values": [ + "always", + "never", + "after-first" + ], + "doc": "This controls when resize overlays are shown. Resize overlays are a\ntransient popup that shows the size of the terminal while the surfaces are\nbeing resized. The possible options are:\n\n * `always` - Always show resize overlays.\n * `never` - Never show resize overlays.\n * `after-first` - The resize overlay will not appear when the surface\n is first created, but will show up if the surface is\n subsequently resized.\n\nThe default is `after-first`.", + "defaults": [ + "after-first" + ] + }, + { + "key": "resize-overlay-position", + "zigType": "ResizeOverlayPosition", + "kind": "enum", + "values": [ + "center", + "top-left", + "top-center", + "top-right", + "bottom-left", + "bottom-center", + "bottom-right" + ], + "doc": "If resize overlays are enabled, this controls the position of the overlay.\nThe possible options are:\n\n * `center`\n * `top-left`\n * `top-center`\n * `top-right`\n * `bottom-left`\n * `bottom-center`\n * `bottom-right`\n\nThe default is `center`.", + "defaults": [ + "center" + ] + }, + { + "key": "resize-overlay-duration", + "zigType": "Duration", + "kind": "duration", + "doc": "If resize overlays are enabled, this controls how long the overlay is\nvisible on the screen before it is hidden. The default is ¾ of a second or\n750 ms.\n\nThe duration is specified as a series of numbers followed by time units.\nWhitespace is allowed between numbers and units. Each number and unit will\nbe added together to form the total duration.\n\nThe allowed time units are as follows:\n\n * `y` - 365 SI days, or 8760 hours, or 31536000 seconds. No adjustments\n are made for leap years or leap seconds.\n * `d` - one SI day, or 86400 seconds.\n * `h` - one hour, or 3600 seconds.\n * `m` - one minute, or 60 seconds.\n * `s` - one second.\n * `ms` - one millisecond, or 0.001 second.\n * `us` or `µs` - one microsecond, or 0.000001 second.\n * `ns` - one nanosecond, or 0.000000001 second.\n\nExamples:\n * `1h30m`\n * `45s`\n\nUnits can be repeated and will be added together. This means that\n`1h1h` is equivalent to `2h`. This is confusing and should be avoided.\nA future update may disallow this.\n\nThe maximum value is `584y 49w 23h 34m 33s 709ms 551µs 615ns`. Any\nvalue larger than this will be clamped to the maximum value.\n\nAvailable since 1.0.0", + "defaults": [ + "750ms" + ] + }, + { + "key": "focus-follows-mouse", + "zigType": "bool", + "kind": "bool", + "doc": "If true, when there are multiple split panes, the mouse selects the pane\nthat is focused. This only applies to the currently focused window; e.g.\nmousing over a split in an unfocused window will not focus that split\nand bring the window to front.\n\nDefault is false.", + "defaults": [ + "false" + ] + }, + { + "key": "clipboard-read", + "zigType": "ClipboardAccess", + "kind": "enum", + "values": [ + "allow", + "deny", + "ask" + ], + "doc": "Whether to allow programs running in the terminal to read/write to the\nsystem clipboard (OSC 52, for googling). The default is to allow clipboard\nreading after prompting the user and allow writing unconditionally.\n\nValid values are:\n\n * `ask`\n * `allow`\n * `deny`", + "defaults": [ + "ask" + ] + }, + { + "key": "clipboard-write", + "zigType": "ClipboardAccess", + "kind": "enum", + "values": [ + "allow", + "deny", + "ask" + ], + "doc": "Whether to allow programs running in the terminal to read/write to the\nsystem clipboard (OSC 52, for googling). The default is to allow clipboard\nreading after prompting the user and allow writing unconditionally.\n\nValid values are:\n\n * `ask`\n * `allow`\n * `deny`", + "defaults": [ + "allow" + ] + }, + { + "key": "clipboard-trim-trailing-spaces", + "zigType": "bool", + "kind": "bool", + "doc": "Trims trailing whitespace on data that is copied to the clipboard. This does\nnot affect data sent to the clipboard via `clipboard-write`. This only\napplies to trailing whitespace on lines that have other characters.\nCompletely blank lines always have their whitespace trimmed.", + "defaults": [ + "true" + ] + }, + { + "key": "clipboard-paste-protection", + "zigType": "bool", + "kind": "bool", + "doc": "Require confirmation before pasting text that appears unsafe. This helps\nprevent a \"copy/paste attack\" where a user may accidentally execute unsafe\ncommands by pasting text with newlines.", + "defaults": [ + "true" + ] + }, + { + "key": "clipboard-paste-bracketed-safe", + "zigType": "bool", + "kind": "bool", + "doc": "If true, bracketed pastes will be considered safe. By default, bracketed\npastes are considered safe. \"Bracketed\" pastes are pastes while the running\nprogram has bracketed paste mode enabled (a setting set by the running\nprogram, not the terminal emulator).", + "defaults": [ + "true" + ] + }, + { + "key": "title-report", + "zigType": "bool", + "kind": "bool", + "doc": "Enables or disabled title reporting (CSI 21 t). This escape sequence\nallows the running program to query the terminal title. This is a common\nsecurity issue and is disabled by default.\n\nWarning: This can expose sensitive information at best and enable\narbitrary code execution at worst (with a maliciously crafted title\nand a minor amount of user interaction).\n\nAvailable since: 1.0.1", + "defaults": [ + "false" + ] + }, + { + "key": "image-storage-limit", + "zigType": "u32", + "kind": "int", + "min": 0, + "max": 4294967295, + "doc": "The total amount of bytes that can be used for image data (e.g. the Kitty\nimage protocol) per terminal screen. The maximum value is 4,294,967,295\n(4GiB). The default is 320MB. If this is set to zero, then all image\nprotocols will be disabled.\n\nThis value is separate for primary and alternate screens so the effective\nlimit per surface is double.", + "defaults": [ + "320000000" + ] + }, + { + "key": "copy-on-select", + "zigType": "CopyOnSelect", + "kind": "enum", + "values": [ + "false", + "true", + "clipboard" + ], + "doc": "Whether to automatically copy selected text to the clipboard. `true`\nwill prefer to copy to the selection clipboard, otherwise it will copy to\nthe system clipboard.\n\nThe value `clipboard` will always copy text to the selection clipboard\nas well as the system clipboard.\n\nMiddle-click paste will always use the selection clipboard. Middle-click\npaste is always enabled even if this is `false`.\n\nThe default value is true on Linux and macOS.", + "defaults": [ + "true" + ] + }, + { + "key": "right-click-action", + "zigType": "RightClickAction", + "kind": "enum", + "values": [ + "ignore", + "paste", + "copy", + "copy-or-paste", + "context-menu" + ], + "doc": "The action to take when the user right-clicks on the terminal surface.\n\nValid values:\n * `context-menu` - Show the context menu.\n * `paste` - Paste the contents of the clipboard.\n * `copy` - Copy the selected text to the clipboard.\n * `copy-or-paste` - If there is a selection, copy the selected text to\n the clipboard; otherwise, paste the contents of the clipboard.\n * `ignore` - Do nothing, ignore the right-click.\n\nThe default value is `context-menu`.", + "defaults": [ + "context-menu" + ] + }, + { + "key": "click-repeat-interval", + "zigType": "u32", + "kind": "int", + "min": 0, + "max": 4294967295, + "doc": "The time in milliseconds between clicks to consider a click a repeat\n(double, triple, etc.) or an entirely new single click. A value of zero will\nuse a platform-specific default. The default on macOS is determined by the\nOS settings. On every other platform it is 500ms.", + "defaults": [ + "0" + ] + }, + { + "key": "config-file", + "zigType": "RepeatablePath", + "kind": "path", + "repeatable": true, + "hint": "prefix with ? to make the file optional", + "doc": "Additional configuration files to read. This configuration can be repeated\nto read multiple configuration files. Configuration files themselves can\nload more configuration files. Paths are relative to the file containing the\n`config-file` directive. For command-line arguments, paths are relative to\nthe current working directory.\n\nPrepend a ? character to the file path to suppress errors if the file does\nnot exist. If you want to include a file that begins with a literal ?\ncharacter, surround the file path in double quotes (\").\n\nCycles are not allowed. If a cycle is detected, an error will be logged and\nthe configuration file will be ignored.\n\nConfiguration files are loaded after the configuration they're defined\nwithin in the order they're defined. **THIS IS A VERY SUBTLE BUT IMPORTANT\nPOINT.** To put it another way: configuration files do not take effect\nuntil after the entire configuration is loaded. For example, in the\nconfiguration below:\n\n```\nconfig-file = \"foo\"\na = 1\n```\n\nIf \"foo\" contains `a = 2`, the final value of `a` will be 2, because\n`foo` is loaded after the configuration file that configures the\nnested `config-file` value.", + "defaults": [ + "" + ] + }, + { + "key": "config-default-files", + "zigType": "bool", + "kind": "bool", + "doc": "When this is true, the default configuration file paths will be loaded.\nThe default configuration file paths are currently only the XDG\nconfig path ($XDG_CONFIG_HOME/ghostty/config.ghostty).\n\nIf this is false, the default configuration paths will not be loaded.\nThis is targeted directly at using Ghostty from the CLI in a way\nthat minimizes external effects.\n\nThis is a CLI-only configuration. Setting this in a configuration file\nwill have no effect. It is not an error, but it will not do anything.\nThis configuration can only be set via CLI arguments.", + "defaults": [ + "true" + ] + }, + { + "key": "confirm-close-surface", + "zigType": "ConfirmCloseSurface", + "kind": "enum", + "values": [ + "false", + "true", + "always" + ], + "doc": "Confirms that a surface should be closed before closing it.\n\nThis defaults to `true`. If set to `false`, surfaces will close without\nany confirmation. This can also be set to `always`, which will always\nconfirm closing a surface, even if shell integration says a process isn't\nrunning.", + "defaults": [ + "true" + ] + }, + { + "key": "quit-after-last-window-closed", + "zigType": "bool", + "kind": "bool", + "doc": "Whether or not to quit after the last surface is closed.\n\nThis defaults to `false` on macOS since that is standard behavior for\na macOS application. On Linux, this defaults to `true` since that is\ngenerally expected behavior.\n\nOn Linux, if this is `true`, Ghostty can delay quitting fully until a\nconfigurable amount of time has passed after the last window is closed.\nSee the documentation of `quit-after-last-window-closed-delay`.", + "defaults": [ + "false" + ] + }, + { + "key": "quit-after-last-window-closed-delay", + "zigType": "?Duration", + "kind": "duration", + "doc": "Controls how long Ghostty will stay running after the last open surface has\nbeen closed. This only has an effect if `quit-after-last-window-closed` is\nalso set to `true`.\n\nThe minimum value for this configuration is `1s`. Any values lower than\nthis will be clamped to `1s`.\n\nThe duration is specified as a series of numbers followed by time units.\nWhitespace is allowed between numbers and units. Each number and unit will\nbe added together to form the total duration.\n\nThe allowed time units are as follows:\n\n * `y` - 365 SI days, or 8760 hours, or 31536000 seconds. No adjustments\n are made for leap years or leap seconds.\n * `d` - one SI day, or 86400 seconds.\n * `h` - one hour, or 3600 seconds.\n * `m` - one minute, or 60 seconds.\n * `s` - one second.\n * `ms` - one millisecond, or 0.001 second.\n * `us` or `µs` - one microsecond, or 0.000001 second.\n * `ns` - one nanosecond, or 0.000000001 second.\n\nExamples:\n * `1h30m`\n * `45s`\n\nUnits can be repeated and will be added together. This means that\n`1h1h` is equivalent to `2h`. This is confusing and should be avoided.\nA future update may disallow this.\n\nThe maximum value is `584y 49w 23h 34m 33s 709ms 551µs 615ns`. Any\nvalue larger than this will be clamped to the maximum value.\n\nBy default `quit-after-last-window-closed-delay` is unset and\nGhostty will quit immediately after the last window is closed if\n`quit-after-last-window-closed` is `true`.\n\nOnly implemented on Linux.", + "defaults": [ + "" + ] + }, + { + "key": "initial-window", + "zigType": "bool", + "kind": "bool", + "doc": "This controls whether an initial window is created when Ghostty\nis run. Note that if `quit-after-last-window-closed` is `true` and\n`quit-after-last-window-closed-delay` is set, setting `initial-window` to\n`false` will mean that Ghostty will quit after the configured delay if no\nwindow is ever created. Only implemented on Linux and macOS.", + "defaults": [ + "true" + ] + }, + { + "key": "undo-timeout", + "zigType": "Duration", + "kind": "duration", + "doc": "The duration that undo operations remain available. After this\ntime, the operation will be removed from the undo stack and\ncannot be undone.\n\nThe default value is 5 seconds.\n\nThis timeout applies per operation, meaning that if you perform\nmultiple operations, each operation will have its own timeout.\nNew operations do not reset the timeout of previous operations.\n\nA timeout of zero will effectively disable undo operations. It is\nnot possible to set an infinite timeout, but you can set a very\nlarge timeout to effectively disable the timeout (on the order of years).\nThis is highly discouraged, as it will cause the undo stack to grow\nindefinitely, memory usage to grow unbounded, and terminal sessions\nto never actually quit.\n\nThe duration is specified as a series of numbers followed by time units.\nWhitespace is allowed between numbers and units. Each number and unit will\nbe added together to form the total duration.\n\nThe allowed time units are as follows:\n\n * `y` - 365 SI days, or 8760 hours, or 31536000 seconds. No adjustments\n are made for leap years or leap seconds.\n * `d` - one SI day, or 86400 seconds.\n * `h` - one hour, or 3600 seconds.\n * `m` - one minute, or 60 seconds.\n * `s` - one second.\n * `ms` - one millisecond, or 0.001 second.\n * `us` or `µs` - one microsecond, or 0.000001 second.\n * `ns` - one nanosecond, or 0.000000001 second.\n\nExamples:\n * `1h30m`\n * `45s`\n\nUnits can be repeated and will be added together. This means that\n`1h1h` is equivalent to `2h`. This is confusing and should be avoided.\nA future update may disallow this.\n\nThis configuration is only supported on macOS. Linux doesn't\nsupport undo operations at all so this configuration has no\neffect.\n\nAvailable since: 1.2.0", + "defaults": [ + "5s" + ] + }, + { + "key": "quick-terminal-position", + "zigType": "QuickTerminalPosition", + "kind": "enum", + "values": [ + "top", + "bottom", + "left", + "right", + "center" + ], + "doc": "The position of the \"quick\" terminal window. To learn more about the\nquick terminal, see the documentation for the `toggle_quick_terminal`\nbinding action.\n\nValid values are:\n\n * `top` - Terminal appears at the top of the screen.\n * `bottom` - Terminal appears at the bottom of the screen.\n * `left` - Terminal appears at the left of the screen.\n * `right` - Terminal appears at the right of the screen.\n * `center` - Terminal appears at the center of the screen.\n\nOn macOS, changing this configuration requires restarting Ghostty\ncompletely.\n\nNote: There is no default keybind for toggling the quick terminal.\nTo enable this feature, bind the `toggle_quick_terminal` action to a key.", + "defaults": [ + "top" + ] + }, + { + "key": "gtk-quick-terminal-layer", + "zigType": "QuickTerminalLayer", + "kind": "enum", + "values": [ + "overlay", + "top", + "bottom", + "background" + ], + "doc": "The size of the quick terminal.\n\nThe size can be specified either as a percentage of the screen dimensions\n(height/width), or as an absolute size in pixels. Percentage values are\nsuffixed with `%` (e.g. `20%`) while pixel values are suffixed with `px`\n(e.g. `300px`). A bare value without a suffix is a config error.\n\nWhen only one size is specified, the size parameter affects the size of\nthe quick terminal on its *primary axis*, which depends on its position:\nheight for quick terminals placed on the top or bottom, and width for left\nor right. The primary axis of a centered quick terminal depends on the\nmonitor's orientation: height when on a landscape monitor, and width when\non a portrait monitor.\n\nThe *secondary axis* would be maximized for non-center positioned\nquick terminals unless another size parameter is specified, separated\nfrom the first by a comma (`,`). Percentage and pixel sizes can be mixed\ntogether: for instance, a size of `50%,500px` for a top-positioned quick\nterminal would be half a screen tall, and 500 pixels wide.\n\nAvailable since: 1.2.0\nThe layer of the quick terminal window. The higher the layer,\nthe more windows the quick terminal may conceal.\n\nValid values are:\n\n * `overlay`\n\n The quick terminal appears in front of all windows.\n\n * `top` (default)\n\n The quick terminal appears in front of normal windows but behind\n fullscreen overlays like lock screens.\n\n * `bottom`\n\n The quick terminal appears behind normal windows but in front of\n wallpapers and other windows in the background layer.\n\n * `background`\n\n The quick terminal appears behind all windows.\n\nGTK Wayland only.\n\nAvailable since: 1.2.0", + "defaults": [ + "top" + ] + }, + { + "key": "gtk-quick-terminal-namespace", + "zigType": "[:0]const u8", + "kind": "text", + "doc": "The namespace for the quick terminal window.\n\nThis is an identifier that is used by the Wayland compositor and/or\nscripts to determine the type of layer surfaces and to possibly apply\nunique effects.\n\nGTK Wayland only.\n\nAvailable since: 1.2.0", + "defaults": [ + "ghostty-quick-terminal" + ] + }, + { + "key": "quick-terminal-screen", + "zigType": "QuickTerminalScreen", + "kind": "enum", + "values": [ + "main", + "mouse", + "macos-menu-bar" + ], + "doc": "The screen where the quick terminal should show up.\n\nValid values are:\n\n * `main` - The screen that the operating system recommends as the main\n screen. On macOS, this is the screen that is currently receiving\n keyboard input. This screen is defined by the operating system and\n not chosen by Ghostty.\n\n * `mouse` - The screen that the mouse is currently hovered over.\n\n * `macos-menu-bar` - The screen that contains the macOS menu bar as\n set in the display settings on macOS. This is a bit confusing because\n every screen on macOS has a menu bar, but this is the screen that\n contains the primary menu bar.\n\nThe default value is `main` because this is the recommended screen\nby the operating system.\n\nOnly implemented on macOS.", + "defaults": [ + "main" + ] + }, + { + "key": "quick-terminal-animation-duration", + "zigType": "f64", + "kind": "float", + "doc": "Duration (in seconds) of the quick terminal enter and exit animation.\nSet it to 0 to disable animation completely. This can be changed at\nruntime.\n\nOnly implemented on macOS.", + "defaults": [ + "0.2" + ] + }, + { + "key": "quick-terminal-autohide", + "zigType": "bool", + "kind": "bool", + "doc": "Automatically hide the quick terminal when focus shifts to another window.\nSet it to false for the quick terminal to remain open even when it loses focus.\n\nDefaults to true on macOS and on false on Linux/BSD. This is because global\nshortcuts on Linux require system configuration and are considerably less\naccessible than on macOS, meaning that it is more preferable to keep the\nquick terminal open until the user has completed their task.\nThis default may change in the future.", + "defaults": [ + "true" + ] + }, + { + "key": "quick-terminal-space-behavior", + "zigType": "QuickTerminalSpaceBehavior", + "kind": "enum", + "values": [ + "remain", + "move" + ], + "doc": "This configuration option determines the behavior of the quick terminal\nwhen switching between macOS spaces. macOS spaces are virtual desktops\nthat can be manually created or are automatically created when an\napplication is in full-screen mode.\n\nValid values are:\n\n * `move` - When switching to another space, the quick terminal will\n also moved to the current space.\n\n * `remain` - The quick terminal will stay only in the space where it\n was originally opened and will not follow when switching to another\n space.\n\nThe default value is `move`.\n\nOnly implemented on macOS.\nOn Linux the behavior is always equivalent to `move`.\n\nAvailable since: 1.1.0", + "defaults": [ + "move" + ] + }, + { + "key": "quick-terminal-keyboard-interactivity", + "zigType": "QuickTerminalKeyboardInteractivity", + "kind": "enum", + "values": [ + "none", + "on-demand", + "exclusive" + ], + "doc": "Determines under which circumstances that the quick terminal should receive\nkeyboard input. See the corresponding [Wayland documentation](https://wayland.app/protocols/wlr-layer-shell-unstable-v1#zwlr_layer_surface_v1:enum:keyboard_interactivity)\nfor a more detailed explanation of the behavior of each option.\n\n\u003e [!NOTE]\n\u003e The exact behavior of each option may differ significantly across\n\u003e compositors -- experiment with them on your system to find one that\n\u003e suits your liking!\n\nValid values are:\n\n * `none`\n\n The quick terminal will not receive any keyboard input.\n\n * `on-demand` (default)\n\n The quick terminal would only receive keyboard input when it is focused.\n\n * `exclusive`\n\n The quick terminal will always receive keyboard input, even when another\n window is currently focused.\n\nOnly has an effect on Linux Wayland.\nOn macOS the behavior is always equivalent to `on-demand`.\n\nAvailable since: 1.2.0", + "defaults": [ + "on-demand" + ] + }, + { + "key": "shell-integration", + "zigType": "ShellIntegration", + "kind": "enum", + "values": [ + "none", + "detect", + "bash", + "elvish", + "fish", + "nushell", + "zsh" + ], + "doc": "Whether to enable shell integration auto-injection or not. Shell integration\ngreatly enhances the terminal experience by enabling a number of features:\n\n * Working directory reporting so new tabs, splits inherit the\n previous terminal's working directory.\n\n * Prompt marking that enables the \"jump_to_prompt\" keybinding.\n\n * If you're sitting at a prompt, closing a terminal will not ask\n for confirmation.\n\n * Resizing the window with a complex prompt usually paints much\n better.\n\nAllowable values are:\n\n * `none` - Do not do any automatic injection. You can still manually\n configure your shell to enable the integration.\n\n * `detect` - Detect the shell based on the filename.\n\n * `bash`, `elvish`, `fish`, `nushell`, `zsh` - Use this specific shell injection scheme.\n\nThe default value is `detect`.", + "defaults": [ + "detect" + ] + }, + { + "key": "shell-integration-features", + "zigType": "ShellIntegrationFeatures", + "kind": "flags", + "flags": [ + "cursor", + "sudo", + "title", + "ssh-env", + "ssh-terminfo", + "path" + ], + "doc": "Shell integration features to enable. These require our shell integration\nto be loaded, either automatically via shell-integration or manually.\n\nThe format of this is a list of features to enable separated by commas. If\nyou prefix a feature with `no-` then it is disabled. If you omit a feature,\nits default value is used, so you must explicitly disable features you don't\nwant. You can also use `true` or `false` to turn all features on or off.\n\nExample: `cursor`, `no-cursor`, `sudo`, `no-sudo`, `title`, `no-title`\n\nAvailable features:\n\n * `cursor` - Set the cursor to a bar at the prompt.\n\n * `sudo` - Set sudo wrapper to preserve terminfo.\n\n * `title` - Set the window title via shell integration.\n\n * `ssh-env` - Enable SSH environment variable compatibility. Automatically\n converts TERM from `xterm-ghostty` to `xterm-256color` when connecting to\n remote hosts and propagates COLORTERM, TERM_PROGRAM, and TERM_PROGRAM_VERSION.\n Whether or not these variables will be accepted by the remote host(s) will\n depend on whether or not the variables are allowed in their sshd_config.\n (Available since: 1.2.0)\n\n * `ssh-terminfo` - Enable automatic terminfo installation on remote hosts.\n Attempts to install Ghostty's terminfo entry using `infocmp` and `tic` when\n connecting to hosts that lack it. Requires `infocmp` to be available locally\n and `tic` to be available on remote hosts. Once terminfo is installed on a\n remote host, it will be automatically \"cached\" to avoid repeat installations.\n If desired, the `+ssh-cache` CLI action can be used to manage the installation\n cache manually using various arguments.\n (Available since: 1.2.0)\n\n * `path` - Add Ghostty's binary directory to PATH. This ensures the `ghostty`\n command is available in the shell even if shell init scripts reset PATH.\n This is particularly useful on macOS where PATH is often overridden by\n system scripts. The directory is only added if not already present.\n\nSSH features work independently and can be combined for optimal experience:\nwhen both `ssh-env` and `ssh-terminfo` are enabled, Ghostty will install its\nterminfo on remote hosts and use `xterm-ghostty` as TERM, falling back to\n`xterm-256color` with environment variables if terminfo installation fails.", + "defaults": [ + "cursor,no-sudo,title,no-ssh-env,no-ssh-terminfo,path" + ] + }, + { + "key": "command-palette-entry", + "zigType": "RepeatableCommand", + "kind": "text", + "repeatable": true, + "hint": "title:NAME,action:ACTION[,description:TEXT]", + "doc": "Custom entries into the command palette.\n\nEach entry requires the title, the corresponding action, and an optional\ndescription. Each field should be prefixed with the field name, a colon\n(`:`), and then the specified value. The syntax for actions is identical\nto the one for keybind actions. Whitespace in between fields is ignored.\n\nIf you need to embed commas or any other special characters in the values,\nenclose the value in double quotes and it will be interpreted as a Zig\nstring literal. This is also useful for including whitespace at the\nbeginning or the end of a value. See the\n[Zig documentation](https://ziglang.org/documentation/master/#Escape-Sequences)\nfor more information on string literals. Note that multiline string literals\nare not supported.\n\nDouble quotes can not be used around the field names.\n\n```ini\ncommand-palette-entry = title:Reset Font Style, action:csi:0m\ncommand-palette-entry = title:Crash on Main Thread,description:Causes a crash on the main (UI) thread.,action:crash:main\ncommand-palette-entry = title:Focus Split: Right,description:\"Focus the split to the right, if it exists.\",action:goto_split:right\ncommand-palette-entry = title:\"Ghostty\",description:\"Add a little Ghostty to your terminal.\",action:\"text:\\xf0\\x9f\\x91\\xbb\"\n```\n\nBy default, the command palette is preloaded with most actions that might\nbe useful in an interactive setting yet do not have easily accessible or\nmemorizable shortcuts. The default entries can be cleared by setting this\nsetting to an empty value:\n\n```ini\ncommand-palette-entry =\n```\n\nAvailable since: 1.2.0", + "defaults": [ + "title:\"Change Tab Title\\xe2\\x80\\xa6\",description:\"Prompt for a new title for the current tab.\",action:\"prompt_tab_title\"", + "title:\"Change Terminal Title\\xe2\\x80\\xa6\",description:\"Prompt for a new title for the current terminal.\",action:\"prompt_surface_title\"", + "title:\"Check for Updates\",description:\"Check for updates to the application.\",action:\"check_for_updates\"", + "title:\"Clear Screen\",description:\"Clear the screen and scrollback.\",action:\"clear_screen\"", + "title:\"Close All Windows\",description:\"Close all windows.\",action:\"close_all_windows\"", + "title:\"Close Other Tabs\",description:\"Close all tabs in this window except the current one.\",action:\"close_tab:other\"", + "title:\"Close Tab\",description:\"Close the current tab.\",action:\"close_tab:this\"", + "title:\"Close Tabs to the Right\",description:\"Close all tabs to the right of the current one.\",action:\"close_tab:right\"", + "title:\"Close Terminal\",description:\"Close the current terminal.\",action:\"close_surface\"", + "title:\"Close Window\",description:\"Close the current window.\",action:\"close_window\"", + "title:\"Copy Screen as ANSI Sequences to Temporary File and Copy Path\",description:\"Copy the screen contents as ANSI escape sequences to a temporary file and copy the path to the clipboard.\",action:\"write_screen_file:copy,vt\"", + "title:\"Copy Screen as ANSI Sequences to Temporary File and Open\",description:\"Copy the screen contents as ANSI escape sequences to a temporary file and open it.\",action:\"write_screen_file:open,vt\"", + "title:\"Copy Screen as ANSI Sequences to Temporary File and Paste Path\",description:\"Copy the screen contents as ANSI escape sequences to a temporary file and paste the path to the file.\",action:\"write_screen_file:paste,vt\"", + "title:\"Copy Screen as HTML to Temporary File and Copy Path\",description:\"Copy the screen contents as HTML to a temporary file and copy the path to the clipboard.\",action:\"write_screen_file:copy,html\"", + "title:\"Copy Screen as HTML to Temporary File and Open\",description:\"Copy the screen contents as HTML to a temporary file and open it.\",action:\"write_screen_file:open,html\"", + "title:\"Copy Screen as HTML to Temporary File and Paste Path\",description:\"Copy the screen contents as HTML to a temporary file and paste the path to the file.\",action:\"write_screen_file:paste,html\"", + "title:\"Copy Screen to Temporary File and Copy Path\",description:\"Copy the screen contents to a temporary file and copy the path to the clipboard.\",action:\"write_screen_file:copy,plain\"", + "title:\"Copy Screen to Temporary File and Open\",description:\"Copy the screen contents to a temporary file and open it.\",action:\"write_screen_file:open,plain\"", + "title:\"Copy Screen to Temporary File and Paste Path\",description:\"Copy the screen contents to a temporary file and paste the path to the file.\",action:\"write_screen_file:paste,plain\"", + "title:\"Copy Selection as ANSI Sequences to Clipboard\",description:\"Copy the selected text as ANSI escape sequences to the clipboard.\",action:\"copy_to_clipboard:vt\"", + "title:\"Copy Selection as ANSI Sequences to Temporary File and Copy Path\",description:\"Copy the selection contents as ANSI escape sequences to a temporary file and copy the path to the clipboard.\",action:\"write_selection_file:copy,vt\"", + "title:\"Copy Selection as ANSI Sequences to Temporary File and Open\",description:\"Copy the selection contents as ANSI escape sequences to a temporary file and open it.\",action:\"write_selection_file:open,vt\"", + "title:\"Copy Selection as ANSI Sequences to Temporary File and Paste Path\",description:\"Copy the selection contents as ANSI escape sequences to a temporary file and paste the path to the file.\",action:\"write_selection_file:paste,vt\"", + "title:\"Copy Selection as HTML to Clipboard\",description:\"Copy the selected text as HTML to the clipboard.\",action:\"copy_to_clipboard:html\"", + "title:\"Copy Selection as HTML to Temporary File and Copy Path\",description:\"Copy the selection contents as HTML to a temporary file and copy the path to the clipboard.\",action:\"write_selection_file:copy,html\"", + "title:\"Copy Selection as HTML to Temporary File and Open\",description:\"Copy the selection contents as HTML to a temporary file and open it.\",action:\"write_selection_file:open,html\"", + "title:\"Copy Selection as HTML to Temporary File and Paste Path\",description:\"Copy the selection contents as HTML to a temporary file and paste the path to the file.\",action:\"write_selection_file:paste,html\"", + "title:\"Copy Selection as Plain Text to Clipboard\",description:\"Copy the selected text as plain text to the clipboard.\",action:\"copy_to_clipboard:plain\"", + "title:\"Copy Selection to Temporary File and Copy Path\",description:\"Copy the selection contents to a temporary file and copy the path to the clipboard.\",action:\"write_selection_file:copy,plain\"", + "title:\"Copy Selection to Temporary File and Open\",description:\"Copy the selection contents to a temporary file and open it.\",action:\"write_selection_file:open,plain\"", + "title:\"Copy Selection to Temporary File and Paste Path\",description:\"Copy the selection contents to a temporary file and paste the path to the file.\",action:\"write_selection_file:paste,plain\"", + "title:\"Copy Terminal Title to Clipboard\",description:\"Copy the terminal title to the clipboard. If the terminal title is not set this has no effect.\",action:\"copy_title_to_clipboard\"", + "title:\"Copy to Clipboard\",description:\"Copy the selected text to the clipboard in both plain and styled formats.\",action:\"copy_to_clipboard:mixed\"", + "title:\"Copy URL to Clipboard\",description:\"Copy the URL under the cursor to the clipboard.\",action:\"copy_url_to_clipboard\"", + "title:\"Decrease Font Size\",description:\"Decrease the font size by 1 point.\",action:\"decrease_font_size:1\"", + "title:\"End Search\",description:\"End the current search if any and hide any GUI elements.\",action:\"end_search\"", + "title:\"Equalize Splits\",description:\"Equalize the size of all splits.\",action:\"equalize_splits\"", + "title:\"Focus Split: Down\",description:\"Focus the split below, if it exists.\",action:\"goto_split:down\"", + "title:\"Focus Split: Left\",description:\"Focus the split to the left, if it exists.\",action:\"goto_split:left\"", + "title:\"Focus Split: Next\",description:\"Focus the next split, if any.\",action:\"goto_split:next\"", + "title:\"Focus Split: Previous\",description:\"Focus the previous split, if any.\",action:\"goto_split:previous\"", + "title:\"Focus Split: Right\",description:\"Focus the split to the right, if it exists.\",action:\"goto_split:right\"", + "title:\"Focus Split: Up\",description:\"Focus the split above, if it exists.\",action:\"goto_split:up\"", + "title:\"Focus Window: Next\",description:\"Focus the next window, if any.\",action:\"goto_window:next\"", + "title:\"Focus Window: Previous\",description:\"Focus the previous window, if any.\",action:\"goto_window:previous\"", + "title:\"Ghostty\",description:\"Put a little Ghostty in your terminal.\",action:\"text:\\xf0\\x9f\\x91\\xbb\"", + "title:\"Increase Font Size\",description:\"Increase the font size by 1 point.\",action:\"increase_font_size:1\"", + "title:\"Move Tab Left\",description:\"Move the current tab to the left.\",action:\"move_tab:-1\"", + "title:\"Move Tab Right\",description:\"Move the current tab to the right.\",action:\"move_tab:1\"", + "title:\"New Tab\",description:\"Open a new tab.\",action:\"new_tab\"", + "title:\"New Window\",description:\"Open a new window.\",action:\"new_window\"", + "title:\"Next Search Result\",description:\"Navigate to the next search result, if any.\",action:\"navigate_search:next\"", + "title:\"Open Config\",description:\"Open the config file.\",action:\"open_config\"", + "title:\"Paste from Clipboard\",description:\"Paste the contents of the main clipboard.\",action:\"paste_from_clipboard\"", + "title:\"Paste from Selection\",description:\"Paste the contents of the selection clipboard.\",action:\"paste_from_selection\"", + "title:\"Previous Search Result\",description:\"Navigate to the previous search result, if any.\",action:\"navigate_search:previous\"", + "title:\"Quit\",description:\"Quit the application.\",action:\"quit\"", + "title:\"Redo\",description:\"Redo the last undone action.\",action:\"redo\"", + "title:\"Reload Config\",description:\"Reload the config file.\",action:\"reload_config\"", + "title:\"Reset Font Size\",description:\"Reset the font size to the default.\",action:\"reset_font_size\"", + "title:\"Reset Terminal\",description:\"Reset the terminal to a clean state.\",action:\"reset\"", + "title:\"Reset Window Size\",description:\"Reset the window size to the default.\",action:\"reset_window_size\"", + "title:\"Scroll Page Down\",description:\"Scroll the screen down by a page.\",action:\"scroll_page_down\"", + "title:\"Scroll Page Up\",description:\"Scroll the screen up by a page.\",action:\"scroll_page_up\"", + "title:\"Scroll to Bottom\",description:\"Scroll to the bottom of the screen.\",action:\"scroll_to_bottom\"", + "title:\"Scroll to Selection\",description:\"Scroll to the selected text.\",action:\"scroll_to_selection\"", + "title:\"Scroll to Top\",description:\"Scroll to the top of the screen.\",action:\"scroll_to_top\"", + "title:\"Search Selection\",description:\"Start a search for the current text selection.\",action:\"search_selection\"", + "title:\"Select All\",description:\"Select all text on the screen.\",action:\"select_all\"", + "title:\"Show On-Screen Keyboard\",description:\"Show the on-screen keyboard if present.\",action:\"show_on_screen_keyboard\"", + "title:\"Show the GTK Inspector\",description:\"Show the GTK inspector.\",action:\"show_gtk_inspector\"", + "title:\"Split Down\",description:\"Split the terminal down.\",action:\"new_split:down\"", + "title:\"Split Left\",description:\"Split the terminal to the left.\",action:\"new_split:left\"", + "title:\"Split Right\",description:\"Split the terminal to the right.\",action:\"new_split:right\"", + "title:\"Split Up\",description:\"Split the terminal up.\",action:\"new_split:up\"", + "title:\"Start Search\",description:\"Start a search if one isn't already active.\",action:\"start_search\"", + "title:\"Toggle Background Opacity\",description:\"Toggle the background opacity of a window that started transparent.\",action:\"toggle_background_opacity\"", + "title:\"Toggle Float on Top\",description:\"Toggle the float on top state of the current window.\",action:\"toggle_window_float_on_top\"", + "title:\"Toggle Fullscreen\",description:\"Toggle the fullscreen state of the current window.\",action:\"toggle_fullscreen\"", + "title:\"Toggle Inspector\",description:\"Toggle the inspector.\",action:\"inspector:toggle\"", + "title:\"Toggle Maximize\",description:\"Toggle the maximized state of the current window.\",action:\"toggle_maximize\"", + "title:\"Toggle Mouse Reporting\",description:\"Toggle whether mouse events are reported to terminal applications.\",action:\"toggle_mouse_reporting\"", + "title:\"Toggle Read-Only Mode\",description:\"Toggle read-only mode for the current surface.\",action:\"toggle_readonly\"", + "title:\"Toggle Secure Input\",description:\"Toggle secure input mode.\",action:\"toggle_secure_input\"", + "title:\"Toggle Split Zoom\",description:\"Toggle the zoom state of the current split.\",action:\"toggle_split_zoom\"", + "title:\"Toggle Tab Overview\",description:\"Toggle the tab overview.\",action:\"toggle_tab_overview\"", + "title:\"Toggle Window Decorations\",description:\"Toggle the window decorations.\",action:\"toggle_window_decorations\"", + "title:\"Undo\",description:\"Undo the last action.\",action:\"undo\"" + ] + }, + { + "key": "osc-color-report-format", + "zigType": "OSCColorReportFormat", + "kind": "enum", + "values": [ + "none", + "8-bit", + "16-bit" + ], + "doc": "Sets the reporting format for OSC sequences that request color information.\nGhostty currently supports OSC 10 (foreground), OSC 11 (background), and\nOSC 4 (256 color palette) queries, and by default the reported values\nare scaled-up RGB values, where each component are 16 bits. This is how\nmost terminals report these values. However, some legacy applications may\nrequire 8-bit, unscaled, components. We also support turning off reporting\naltogether. The components are lowercase hex values.\n\nAllowable values are:\n\n * `none` - OSC 4/10/11 queries receive no reply\n\n * `8-bit` - Color components are return unscaled, e.g. `rr/gg/bb`\n\n * `16-bit` - Color components are returned scaled, e.g. `rrrr/gggg/bbbb`\n\nThe default value is `16-bit`.", + "defaults": [ + "16-bit" + ] + }, + { + "key": "vt-kam-allowed", + "zigType": "bool", + "kind": "bool", + "doc": "If true, allows the \"KAM\" mode (ANSI mode 2) to be used within\nthe terminal. KAM disables keyboard input at the request of the\napplication. This is not a common feature and is not recommended\nto be enabled. This will not be documented further because\nif you know you need KAM, you know. If you don't know if you\nneed KAM, you don't need it.", + "defaults": [ + "false" + ] + }, + { + "key": "custom-shader", + "zigType": "RepeatablePath", + "kind": "path", + "repeatable": true, + "hint": "prefix with ? to make the file optional", + "doc": "Custom shaders to run after the default shaders. This is a file path\nto a GLSL-syntax shader for all platforms.\n\nWarning: Invalid shaders can cause Ghostty to become unusable such as by\ncausing the window to be completely black. If this happens, you can\nunset this configuration to disable the shader.\n\nCustom shader support is based on and compatible with the Shadertoy shaders.\nShaders should specify a `mainImage` function and the available uniforms\nlargely match Shadertoy, with some caveats and Ghostty-specific extensions.\n\nThe uniform values available to shaders are as follows:\n\n * `sampler2D iChannel0` - Input texture.\n\n A texture containing the current terminal screen. If multiple custom\n shaders are specified, the output of previous shaders is written to\n this texture, to allow combining multiple effects.\n\n * `vec3 iResolution` - Output texture size, `[width, height, 1]` (in px).\n\n * `float iTime` - Time in seconds since first frame was rendered.\n\n * `float iTimeDelta` - Time in seconds since previous frame was rendered.\n\n * `float iFrameRate` - Average framerate. (NOT CURRENTLY SUPPORTED)\n\n * `int iFrame` - Number of frames that have been rendered so far.\n\n * `float iChannelTime[4]` - Current time for video or sound input. (N/A)\n\n * `vec3 iChannelResolution[4]` - Resolutions of the 4 input samplers.\n\n Currently only `iChannel0` exists, and `iChannelResolution[0]` is\n identical to `iResolution`.\n\n * `vec4 iMouse` - Mouse input info. (NOT CURRENTLY SUPPORTED)\n\n * `vec4 iDate` - Date/time info. (NOT CURRENTLY SUPPORTED)\n\n * `float iSampleRate` - Sample rate for audio. (N/A)\n\nGhostty-specific extensions:\n\n * `vec4 iCurrentCursor` - Info about the terminal cursor.\n\n - `iCurrentCursor.xy` is the -X, +Y corner of the current cursor.\n - `iCurrentCursor.zw` is the width and height of the current cursor.\n\n * `vec4 iPreviousCursor` - Info about the previous terminal cursor.\n\n * `vec4 iCurrentCursorColor` - Color of the terminal cursor.\n\n * `vec4 iPreviousCursorColor` - Color of the previous terminal cursor.\n\n * `vec4 iCurrentCursorStyle` - Style of the terminal cursor\n\n Macros simplified use are defined for the various cursor styles:\n\n - `CURSORSTYLE_BLOCK` or `0`\n - `CURSORSTYLE_BLOCK_HOLLOW` or `1`\n - `CURSORSTYLE_BAR` or `2`\n - `CURSORSTYLE_UNDERLINE` or `3`\n - `CURSORSTYLE_LOCK` or `4`\n\n * `vec4 iPreviousCursorStyle` - Style of the previous terminal cursor\n\n * `vec4 iCursorVisible` - Visibility of the terminal cursor.\n\n * `float iTimeCursorChange` - Timestamp of terminal cursor change.\n\n When the terminal cursor changes position or color, this is set to\n the same time as the `iTime` uniform, allowing you to compute the\n time since the change by subtracting this from `iTime`.\n\n * `float iTimeFocus` - Timestamp when the surface last gained iFocus.\n\n When the surface gains focus, this is set to the current value of\n `iTime`, similar to how `iTimeCursorChange` works. This allows you\n to compute the time since focus was gained or lost by calculating\n `iTime - iTimeFocus`. Use this to create animations that restart\n when the terminal regains focus.\n\n * `int iFocus` - Current focus state of the surface.\n\n Set to 1.0 when the surface is focused, 0.0 when unfocused. This\n allows shaders to detect unfocused state and avoid animation artifacts\n from large time deltas caused by infrequent \"deceptive frames\"\n (e.g., modifier key presses, link hover events in unfocused split panes).\n Check `iFocus \u003e 0` to determine if the surface is currently focused.\n\n * `vec3 iPalette[256]` - The 256-color terminal palette.\n\n RGB values for all 256 colors in the terminal palette, normalized\n to [0.0, 1.0]. Index 0-15 are the ANSI colors, 16-231 are the 6x6x6\n color cube, and 232-255 are the grayscale colors.\n\n * `vec3 iBackgroundColor` - Terminal background color (RGB).\n\n * `vec3 iForegroundColor` - Terminal foreground color (RGB).\n\n * `vec3 iCursorColor` - Terminal cursor color (RGB).\n\n * `vec3 iCursorText` - Terminal cursor text color (RGB).\n\n * `vec3 iSelectionBackgroundColor` - Selection background color (RGB).\n\n * `vec3 iSelectionForegroundColor` - Selection foreground color (RGB).\n\nIf the shader fails to compile, the shader will be ignored. Any errors\nrelated to shader compilation will not show up as configuration errors\nand only show up in the log, since shader compilation happens after\nconfiguration loading on the dedicated render thread. For interactive\ndevelopment, use [shadertoy.com](https://shadertoy.com).\n\nThis can be repeated multiple times to load multiple shaders. The shaders\nwill be run in the order they are specified.\n\nThis can be changed at runtime and will affect all open terminals.", + "defaults": [ + "" + ] + }, + { + "key": "custom-shader-animation", + "zigType": "CustomShaderAnimation", + "kind": "enum", + "values": [ + "false", + "true", + "always" + ], + "doc": "If `true` (default), the focused terminal surface will run an animation\nloop when custom shaders are used. This uses slightly more CPU (generally\nless than 10%) but allows the shader to animate. This only runs if there\nare custom shaders and the terminal is focused.\n\nIf this is set to `false`, the terminal and custom shader will only render\nwhen the terminal is updated. This is more efficient but the shader will\nnot animate.\n\nThis can also be set to `always`, which will always run the animation\nloop regardless of whether the terminal is focused or not. The animation\nloop will still only run when custom shaders are used. Note that this\nwill use more CPU per terminal surface and can become quite expensive\ndepending on the shader and your terminal usage.\n\nThis can be changed at runtime and will affect all open terminals.", + "defaults": [ + "true" + ] + }, + { + "key": "bell-features", + "zigType": "BellFeatures", + "kind": "flags", + "flags": [ + "system", + "audio", + "attention", + "title", + "border" + ], + "doc": "Bell features to enable if bell support is available in your runtime. Not\nall features are available on all runtimes. The format of this is a list of\nfeatures to enable separated by commas. If you prefix a feature with `no-`\nthen it is disabled. If you omit a feature, its default value is used.\n\nValid values are:\n\n * `system`\n\n Instruct the system to notify the user using built-in system functions.\n This could result in an audiovisual effect, a notification, or something\n else entirely. Changing these effects require altering system settings:\n for instance under the \"Sound \u003e Alert Sound\" setting in GNOME,\n or the \"Accessibility \u003e System Bell\" settings in KDE Plasma.\n\n On macOS, this plays the system alert sound.\n\n * `audio`\n\n Play a custom sound. (Available since 1.3.0 on macOS)\n\n * `attention` *(enabled by default)*\n\n Request the user's attention when Ghostty is unfocused, until it has\n received focus again. On macOS, this will bounce the app icon in the\n dock once. On Linux, the behavior depends on the desktop environment\n and/or the window manager/compositor:\n\n - On KDE, the background of the desktop icon in the task bar would be\n highlighted;\n\n - On GNOME, you may receive a notification that, when clicked, would\n bring the Ghostty window into focus;\n\n - On Sway, the window may be decorated with a distinctly colored border;\n\n - On other systems this may have no effect at all.\n\n * `title` *(enabled by default)*\n\n Prepend a bell emoji (🔔) to the title of the alerted surface until the\n terminal is re-focused or interacted with (such as on keyboard input).\n\n * `border`\n\n Display a border around the alerted surface until the terminal is\n re-focused or interacted with (such as on keyboard input).\n\n Available since: 1.2.0 on GTK, 1.2.1 on macOS\n\nExample: `audio`, `no-audio`, `system`, `no-system`\n\nAvailable since: 1.2.0", + "defaults": [ + "no-system,no-audio,attention,title,no-border" + ] + }, + { + "key": "bell-audio-path", + "zigType": "?Path", + "kind": "path", + "doc": "If `audio` is an enabled bell feature, this is a path to an audio file. If\nthe path is not absolute, it is considered relative to the directory of the\nconfiguration file that it is referenced from, or from the current working\ndirectory if this is used as a CLI flag. The path may be prefixed with `~/`\nto reference the user's home directory.\n\nAvailable since: 1.2.0 on GTK, 1.3.0 on macOS.", + "defaults": [ + "" + ] + }, + { + "key": "bell-audio-volume", + "zigType": "f64", + "kind": "float", + "min": 0, + "max": 1, + "doc": "If `audio` is an enabled bell feature, this is the volume to play the audio\nfile at (relative to the system volume). This is a floating point number\nranging from 0.0 (silence) to 1.0 (as loud as possible). The default is 0.5.\n\nAvailable since: 1.2.0 on GTK, 1.3.0 on macOS.", + "defaults": [ + "0.5" + ] + }, + { + "key": "app-notifications", + "zigType": "AppNotifications", + "kind": "flags", + "flags": [ + "clipboard-copy", + "config-reload" + ], + "doc": "Control the in-app notifications that Ghostty shows.\n\nOn Linux (GTK), in-app notifications show up as toasts. Toasts appear\noverlaid on top of the terminal window. They are used to show information\nthat is not critical but may be important.\n\nPossible notifications are:\n\n - `clipboard-copy` (default: true) - Show a notification when text is copied\n to the clipboard.\n - `config-reload` (default: true) - Show a notification when\n the configuration is reloaded.\n\nTo specify a notification to enable, specify the name of the notification.\nTo specify a notification to disable, prefix the name with `no-`. For\nexample, to disable `clipboard-copy`, set this configuration to\n`no-clipboard-copy`. To enable it, set this configuration to `clipboard-copy`.\n\nMultiple notifications can be enabled or disabled by separating them\nwith a comma.\n\nA value of \"false\" will disable all notifications. A value of \"true\" will\nenable all notifications.\n\nThis configuration only applies to GTK.\n\nAvailable since: 1.1.0", + "defaults": [ + "clipboard-copy,config-reload" + ] + }, + { + "key": "macos-non-native-fullscreen", + "zigType": "NonNativeFullscreen", + "kind": "enum", + "values": [ + "false", + "true", + "visible-menu", + "padded-notch" + ], + "doc": "If anything other than false, fullscreen mode on macOS will not use the\nnative fullscreen, but make the window fullscreen without animations and\nusing a new space. It's faster than the native fullscreen mode since it\ndoesn't use animations.\n\nImportant: tabs DO NOT WORK in this mode. Non-native fullscreen removes\nthe titlebar and macOS native tabs require the titlebar. If you use tabs,\nyou should not use this mode.\n\nIf you fullscreen a window with tabs, the currently focused tab will\nbecome fullscreen while the others will remain in a separate window in\nthe background. You can switch to that window using normal window-switching\nkeybindings such as command+tilde. When you exit fullscreen, the window\nwill return to the tabbed state it was in before.\n\nAllowable values are:\n\n * `true` - Use non-native macOS fullscreen, hide the menu bar\n * `false` - Use native macOS fullscreen\n * `visible-menu` - Use non-native macOS fullscreen, keep the menu bar\n visible\n * `padded-notch` - Use non-native macOS fullscreen, hide the menu bar,\n but ensure the window is not obscured by the notch on applicable\n devices. The area around the notch will remain transparent currently,\n but in the future we may fill it with the window background color.\n\nChanging this option at runtime works, but will only apply to the next\ntime the window is made fullscreen. If a window is already fullscreen,\nit will retain the previous setting until fullscreen is exited.", + "defaults": [ + "false" + ] + }, + { + "key": "macos-window-buttons", + "zigType": "MacWindowButtons", + "kind": "enum", + "values": [ + "visible", + "hidden" + ], + "doc": "Whether the window buttons in the macOS titlebar are visible. The window\nbuttons are the colored buttons in the upper left corner of most macOS apps,\nalso known as the traffic lights, that allow you to close, miniaturize, and\nzoom the window.\n\nThis setting has no effect when `window-decoration = none` or\n`macos-titlebar-style = hidden`, as the window buttons are always hidden in\nthese modes.\n\nValid values are:\n\n * `visible` - Show the window buttons.\n * `hidden` - Hide the window buttons.\n\nThe default value is `visible`.\n\nChanging this option at runtime only applies to new windows.\n\nAvailable since: 1.2.0", + "defaults": [ + "visible" + ] + }, + { + "key": "macos-titlebar-style", + "zigType": "MacTitlebarStyle", + "kind": "enum", + "values": [ + "native", + "transparent", + "tabs", + "hidden" + ], + "doc": "The style of the macOS titlebar. Available values are: \"native\",\n\"transparent\", \"tabs\", and \"hidden\".\n\nThe \"native\" style uses the native macOS titlebar with zero customization.\nThe titlebar will match your window theme (see `window-theme`).\n\nThe \"transparent\" style is the same as \"native\" but the titlebar will\nbe transparent and allow your window background color to come through.\nThis makes a more seamless window appearance but looks a little less\ntypical for a macOS application and may not work well with all themes.\n\nThe \"transparent\" style will also update in real-time to dynamic\nchanges to the window background color, e.g. via OSC 11. To make this\nmore aesthetically pleasing, this only happens if the terminal is\na window, tab, or split that borders the top of the window. This\navoids a disjointed appearance where the titlebar color changes\nbut all the topmost terminals don't match.\n\nThe \"tabs\" style is a completely custom titlebar that integrates the\ntab bar into the titlebar. This titlebar always matches the background\ncolor of the terminal. There are some limitations to this style:\nOn macOS 13 and below, saved window state will not restore tabs correctly.\nmacOS 14 does not have this issue and any other macOS version has not\nbeen tested.\n\nThe \"hidden\" style hides the titlebar. Unlike `window-decoration = none`,\nhowever, it does not remove the frame from the window or cause it to have\nsquared corners. Changing to or from this option at run-time may affect\nexisting windows in buggy ways.\n\nWhen \"hidden\", the top titlebar area can no longer be used for dragging\nthe window. To drag the window, you can use option+click on the resizable\nareas of the frame to drag the window. This is a standard macOS behavior\nand not something Ghostty enables.\n\nThe default value is \"transparent\". This is an opinionated choice\nbut its one I think is the most aesthetically pleasing and works in\nmost cases.\n\nChanging this option at runtime only applies to new windows.", + "defaults": [ + "transparent" + ] + }, + { + "key": "macos-titlebar-proxy-icon", + "zigType": "MacTitlebarProxyIcon", + "kind": "enum", + "values": [ + "visible", + "hidden" + ], + "doc": "Whether the proxy icon in the macOS titlebar is visible. The proxy icon\nis the icon that represents the folder of the current working directory.\nYou can see this very clearly in the macOS built-in Terminal.app\ntitlebar.\n\nThe proxy icon is only visible with the native macOS titlebar style.\n\nValid values are:\n\n * `visible` - Show the proxy icon.\n * `hidden` - Hide the proxy icon.\n\nThe default value is `visible`.\n\nThis setting can be changed at runtime and will affect all currently\nopen windows but only after their working directory changes again.\nTherefore, to make this work after changing the setting, you must\nusually `cd` to a different directory, open a different file in an\neditor, etc.", + "defaults": [ + "visible" + ] + }, + { + "key": "macos-dock-drop-behavior", + "zigType": "MacOSDockDropBehavior", + "kind": "enum", + "values": [ + "new-tab", + "new-window" + ], + "doc": "Controls the windowing behavior when dropping a file or folder\nonto the Ghostty icon in the macOS dock.\n\nValid values are:\n\n * `new-tab` - Create a new tab in the current window, or open\n a new window if none exist.\n * `new-window` - Create a new window unconditionally.\n\nThe default value is `new-tab`.\n\nThis setting is only supported on macOS and has no effect on other\nplatforms.", + "defaults": [ + "new-tab" + ] + }, + { + "key": "macos-option-as-alt", + "zigType": "?inputpkg.OptionAsAlt", + "kind": "enum", + "values": [ + "false", + "true", + "left", + "right" + ], + "doc": "macOS doesn't have a distinct \"alt\" key and instead has the \"option\"\nkey which behaves slightly differently. On macOS by default, the\noption key plus a character will sometimes produce a Unicode character.\nFor example, on US standard layouts option-b produces \"∫\". This may be\nundesirable if you want to use \"option\" as an \"alt\" key for keybindings\nin terminal programs or shells.\n\nThis configuration lets you change the behavior so that option is treated\nas alt.\n\nThe default behavior (unset) will depend on your active keyboard\nlayout. If your keyboard layout is one of the keyboard layouts listed\nbelow, then the default value is \"true\". Otherwise, the default\nvalue is \"false\". Keyboard layouts with a default value of \"true\" are:\n\n - U.S. Standard\n - U.S. International\n\nNote that if an *Option*-sequence doesn't produce a printable character, it\nwill be treated as *Alt* regardless of this setting. (e.g. `alt+ctrl+a`).\n\nExplicit values that can be set:\n\nIf `true`, the *Option* key will be treated as *Alt*. This makes terminal\nsequences expecting *Alt* to work properly, but will break Unicode input\nsequences on macOS if you use them via the *Alt* key.\n\nYou may set this to `false` to restore the macOS *Alt* key unicode\nsequences but this will break terminal sequences expecting *Alt* to work.\n\nThe values `left` or `right` enable this for the left or right *Option*\nkey, respectively.", + "defaults": [ + "" + ] + }, + { + "key": "macos-window-shadow", + "zigType": "bool", + "kind": "bool", + "doc": "Whether to enable the macOS window shadow. The default value is true.\nWith some window managers and window transparency settings, you may\nfind false more visually appealing.", + "defaults": [ + "true" + ] + }, + { + "key": "macos-hidden", + "zigType": "MacHidden", + "kind": "enum", + "values": [ + "never", + "always" + ], + "doc": "If true, the macOS icon in the dock and app switcher will be hidden. This is\nmainly intended for those primarily using the quick-terminal mode.\n\nNote that setting this to true means that keyboard layout changes\nwill no longer be automatic.\n\nControl whether macOS app is excluded from the dock and app switcher,\na \"hidden\" state. This is mainly intended for those primarily using\nquick-terminal mode, but is a general configuration for any use\ncase.\n\nAvailable values:\n\n * `never` - The macOS app is never hidden.\n * `always` - The macOS app is always hidden.\n\nNote: When the macOS application is hidden, keyboard layout changes\nwill no longer be automatic. This is a limitation of macOS.\n\nAvailable since: 1.2.0", + "defaults": [ + "never" + ] + }, + { + "key": "macos-auto-secure-input", + "zigType": "bool", + "kind": "bool", + "doc": "If true, Ghostty on macOS will automatically enable the \"Secure Input\"\nfeature when it detects that a password prompt is being displayed.\n\n\"Secure Input\" is a macOS security feature that prevents applications from\nreading keyboard events. This can always be enabled manually using the\n`Ghostty \u003e Secure Keyboard Entry` menu item.\n\nNote that automatic password prompt detection is based on heuristics\nand may not always work as expected. Specifically, it does not work\nover SSH connections, but there may be other cases where it also\ndoesn't work.\n\nA reason to disable this feature is if you find that it is interfering\nwith legitimate accessibility software (or software that uses the\naccessibility APIs), since secure input prevents any application from\nreading keyboard events.", + "defaults": [ + "true" + ] + }, + { + "key": "macos-secure-input-indication", + "zigType": "bool", + "kind": "bool", + "doc": "If true, Ghostty will show a graphical indication when secure input is\nenabled. This indication is generally recommended to know when secure input\nis enabled.\n\nNormally, secure input is only active when a password prompt is displayed\nor it is manually (and typically temporarily) enabled. However, if you\nalways have secure input enabled, the indication can be distracting and\nyou may want to disable it.", + "defaults": [ + "true" + ] + }, + { + "key": "macos-applescript", + "zigType": "bool", + "kind": "bool", + "doc": "If true, Ghostty exposes and handles the built-in AppleScript dictionary\non macOS.\n\nIf false, all AppleScript interactions are disabled. This includes\nAppleScript commands and AppleScript object lookup for windows, tabs,\nand terminals.\n\nThe default is true.", + "defaults": [ + "true" + ] + }, + { + "key": "macos-icon", + "zigType": "MacAppIcon", + "kind": "enum", + "values": [ + "official", + "blueprint", + "chalkboard", + "microchip", + "glass", + "holographic", + "paper", + "retro", + "xray", + "custom", + "custom-style" + ], + "doc": "Customize the macOS app icon.\n\nThis only affects the icon that appears in the dock, application\nswitcher, etc. This does not affect the icon in Finder because\nthat is controlled by a hardcoded value in the signed application\nbundle and can't be changed at runtime. For more details on what\nexactly is affected, see the `NSApplication.icon` Apple documentation;\nthat is the API that is being used to set the icon.\n\nValid values:\n\n * `official` - Use the official Ghostty icon.\n * `blueprint`, `chalkboard`, `microchip`, `glass`, `holographic`,\n `paper`, `retro`, `xray` - Official variants of the Ghostty icon\n hand-created by artists (no AI).\n * `custom` - Use a completely custom icon. The location must be specified\n using the additional `macos-custom-icon` configuration\n * `custom-style` - Use the official Ghostty icon but with custom\n styles applied to various layers. The custom styles must be\n specified using the additional `macos-icon`-prefixed configurations.\n The `macos-icon-ghost-color` and `macos-icon-screen-color`\n configurations are required for this style.\n\nWARNING: The `custom-style` option is _experimental_. We may change\nthe format of the custom styles in the future. We're still finalizing\nthe exact layers and customization options that will be available.\n\nOther caveats:\n\n * The icon in the update dialog will always be the official icon.\n This is because the update dialog is managed through a\n separate framework and cannot be customized without significant\n effort.", + "defaults": [ + "official" + ] + }, + { + "key": "macos-custom-icon", + "zigType": "?[:0]const u8", + "kind": "path", + "doc": "The absolute path to the custom icon file.\nSupported formats include PNG, JPEG, and ICNS.\n\nDefaults to `~/.config/ghostty/Ghostty.icns`", + "defaults": [ + "" + ] + }, + { + "key": "macos-icon-frame", + "zigType": "MacAppIconFrame", + "kind": "enum", + "values": [ + "aluminum", + "beige", + "plastic", + "chrome" + ], + "doc": "The material to use for the frame of the macOS app icon.\n\nValid values:\n\n * `aluminum` - A brushed aluminum frame. This is the default.\n * `beige` - A classic 90's computer beige frame.\n * `plastic` - A glossy, dark plastic frame.\n * `chrome` - A shiny chrome frame.\n\nNote: This configuration is required when `macos-icon` is set to\n`custom-style`.", + "defaults": [ + "aluminum" + ] + }, + { + "key": "macos-icon-ghost-color", + "zigType": "?Color", + "kind": "color", + "doc": "The color of the ghost in the macOS app icon.\n\nNote: This configuration is required when `macos-icon` is set to\n`custom-style`.\n\nSpecified as either hex (`#RRGGBB` or `RRGGBB`) or a named X11 color.", + "defaults": [ + "" + ] + }, + { + "key": "macos-icon-screen-color", + "zigType": "?ColorList", + "kind": "colorlist", + "doc": "The color of the screen in the macOS app icon.\n\nThe screen is a linear gradient so you can specify multiple colors\nthat make up the gradient. Up to 64 comma-separated colors may be\nspecified as either hex (`#RRGGBB` or `RRGGBB`) or as named X11\ncolors. The first color is the bottom of the gradient and the last\ncolor is the top of the gradient.\n\nNote: This configuration is required when `macos-icon` is set to\n`custom-style`.", + "defaults": [ + "" + ] + }, + { + "key": "macos-shortcuts", + "zigType": "MacShortcuts", + "kind": "enum", + "values": [ + "allow", + "deny", + "ask" + ], + "doc": "Whether macOS Shortcuts are allowed to control Ghostty.\n\nGhostty exposes a number of actions that allow Shortcuts to\ncontrol and interact with Ghostty. This includes creating new\nterminals, sending text to terminals, running commands, invoking\nany keybind action, etc.\n\nThis is a powerful feature but can be a security risk if a malicious\nshortcut is able to be installed and executed. Therefore, this\nconfiguration allows you to disable this feature.\n\nValid values are:\n\n* `ask` - Ask the user whether for permission. Ghostty will remember\n this choice and never ask again. This is similar to other macOS\n permissions such as microphone access, camera access, etc.\n\n* `allow` - Allow Shortcuts to control Ghostty without asking.\n\n* `deny` - Deny Shortcuts from controlling Ghostty.\n\nAvailable since: 1.2.0", + "defaults": [ + "ask" + ] + }, + { + "key": "linux-cgroup", + "zigType": "LinuxCgroup", + "kind": "enum", + "values": [ + "never", + "always", + "single-instance" + ], + "doc": "Put every surface (tab, split, window) into a transient `systemd` scope.\n\nThis allows per-surface resource management. For example, if a shell program\nis using too much memory, only that shell will be killed by the oom monitor\ninstead of the entire Ghostty process. Similarly, if a shell program is\nusing too much CPU, only that surface will be CPU-throttled.\n\nThis will cause startup times to be slower (a hundred milliseconds or so),\nso the default value is \"single-instance.\" In single-instance mode, only\none instance of Ghostty is running (see gtk-single-instance) so the startup\ntime is a one-time cost. Additionally, single instance Ghostty is much\nmore likely to have many windows, tabs, etc. so cgroup isolation is a\nbig benefit.\n\nThis feature requires `systemd`. If `systemd` is unavailable, cgroup\ninitialization will fail. By default, this will not prevent Ghostty from\nworking (see `linux-cgroup-hard-fail`).\n\nChanging this value and reloading the config will not affect existing\nsurfaces.\n\nValid values are:\n\n * `never` - Never use cgroups.\n * `always` - Always use cgroups.\n * `single-instance` - Enable cgroups only for Ghostty instances launched\n as single-instance applications (see gtk-single-instance).", + "defaults": [ + "never" + ] + }, + { + "key": "linux-cgroup-memory-limit", + "zigType": "?u64", + "kind": "int", + "min": 0, + "doc": "Memory limit for any individual terminal process (tab, split, window,\netc.) in bytes. If this is unset then no memory limit will be set.\n\nNote that this sets the `MemoryHigh` setting on the transient `systemd`\nscope, which is a soft limit. You should configure something like\n`systemd-oom` to handle killing processes that have too much memory\npressure.\n\nChanging this value and reloading the config will not affect existing\nsurfaces.\n\nSee the `systemd.resource-control` manual page for more information:\nhttps://www.freedesktop.org/software/systemd/man/latest/systemd.resource-control.html", + "defaults": [ + "" + ] + }, + { + "key": "linux-cgroup-processes-limit", + "zigType": "?u64", + "kind": "int", + "min": 0, + "doc": "Number of processes limit for any individual terminal process (tab, split,\nwindow, etc.). If this is unset then no limit will be set.\n\nNote that this sets the `TasksMax` setting on the transient `systemd` scope,\nwhich is a hard limit.\n\nChanging this value and reloading the config will not affect existing\nsurfaces.\n\nSee the `systemd.resource-control` manual page for more information:\nhttps://www.freedesktop.org/software/systemd/man/latest/systemd.resource-control.html", + "defaults": [ + "" + ] + }, + { + "key": "linux-cgroup-hard-fail", + "zigType": "bool", + "kind": "bool", + "doc": "If this is false, then creating a transient `systemd` scope (for\n`linux-cgroup`) will be allowed to fail and the failure is ignored. This is\nuseful if you view cgroup isolation as a \"nice to have\" and not a critical\nresource management feature, because surface creation will not fail if\n`systemd` APIs fail.\n\nIf this is true, then any transient `systemd` scope creation failure will\ncause surface creation to fail.\n\nChanging this value and reloading the config will not affect existing\nsurfaces.", + "defaults": [ + "false" + ] + }, + { + "key": "gtk-opengl-debug", + "zigType": "bool", + "kind": "bool", + "doc": "Enable or disable GTK's OpenGL debugging logs. The default is `true` for\ndebug builds, `false` for all others.\n\nAvailable since: 1.1.0", + "defaults": [ + "false" + ] + }, + { + "key": "gtk-single-instance", + "zigType": "GtkSingleInstance", + "kind": "enum", + "values": [ + "false", + "true", + "detect" + ], + "doc": "If `true`, the Ghostty GTK application will run in single-instance mode:\neach new `ghostty` process launched will result in a new window if there is\nalready a running process.\n\nIf `false`, each new ghostty process will launch a separate application.\n\nIf `detect`, Ghostty will assume true (single instance) unless one of\nthe following scenarios is found:\n\n1. TERM_PROGRAM environment variable is a non-empty value. In this\ncase, we assume Ghostty is being launched from a graphical terminal\nsession and you want a dedicated instance.\n\n2. Any CLI arguments exist. In this case, we assume you are passing\ncustom Ghostty configuration. Single instance mode inherits the\nconfiguration from when it was launched, so we must disable single\ninstance to load the new configuration.\n\nIf either of these scenarios is producing a false positive, you can\nset this configuration explicitly to the behavior you want.\n\nThe pre-1.2 option `desktop` has been deprecated. Please replace\nthis with `detect`.\n\nThe default value is `detect`.\n\nNote that debug builds of Ghostty have a separate single-instance ID\nso you can test single instance without conflicting with release builds.", + "defaults": [ + "detect" + ] + }, + { + "key": "gtk-titlebar", + "zigType": "bool", + "kind": "bool", + "doc": "When enabled, the full GTK titlebar is displayed instead of your window\nmanager's simple titlebar. The behavior of this option will vary with your\nwindow manager.\n\nThis option does nothing when `window-decoration` is none or when running\nunder macOS.", + "defaults": [ + "true" + ] + }, + { + "key": "gtk-tabs-location", + "zigType": "GtkTabsLocation", + "kind": "enum", + "values": [ + "top", + "bottom" + ], + "doc": "Determines the side of the screen that the GTK tab bar will stick to.\nTop, bottom, and hidden are supported. The default is top.\n\nWhen `hidden` is set, a tab button displaying the number of tabs will appear\nin the title bar. It has the ability to open a tab overview for displaying\ntabs. Alternatively, you can use the `toggle_tab_overview` action in a\nkeybind if your window doesn't have a title bar, or you can switch tabs\nwith keybinds.", + "defaults": [ + "top" + ] + }, + { + "key": "gtk-titlebar-hide-when-maximized", + "zigType": "bool", + "kind": "bool", + "doc": "If this is `true`, the titlebar will be hidden when the window is maximized,\nand shown when the titlebar is unmaximized. GTK only.\n\nAvailable since: 1.1.0", + "defaults": [ + "false" + ] + }, + { + "key": "gtk-toolbar-style", + "zigType": "GtkToolbarStyle", + "kind": "enum", + "values": [ + "flat", + "raised", + "raised-border" + ], + "doc": "Determines the appearance of the top and bottom bars tab bar.\n\nValid values are:\n\n * `flat` - Top and bottom bars are flat with the terminal window.\n * `raised` - Top and bottom bars cast a shadow on the terminal area.\n * `raised-border` - Similar to `raised` but the shadow is replaced with a\n more subtle border.", + "defaults": [ + "raised" + ] + }, + { + "key": "gtk-titlebar-style", + "zigType": "GtkTitlebarStyle", + "kind": "enum", + "values": [ + "native", + "tabs" + ], + "doc": "The style of the GTK titlebar. Available values are `native` and `tabs`.\n\nThe `native` titlebar style is a traditional titlebar with a title, a few\nbuttons and window controls. A separate tab bar will show up below the\ntitlebar if you have multiple tabs open in the window.\n\nThe `tabs` titlebar merges the tab bar and the traditional titlebar.\nThis frees up vertical space on your screen if you use multiple tabs. One\nlimitation of the `tabs` titlebar is that you cannot drag the titlebar\nby the titles any longer (as they are tab titles now). Other areas of the\n`tabs` title bar can be used to drag the window around.\n\nThe default style is `native`.", + "defaults": [ + "native" + ] + }, + { + "key": "gtk-wide-tabs", + "zigType": "bool", + "kind": "bool", + "doc": "If `true` (default), then the Ghostty GTK tabs will be \"wide.\" Wide tabs\nare the new typical Gnome style where tabs fill their available space.\nIf you set this to `false` then tabs will only take up space they need,\nwhich is the old style.", + "defaults": [ + "true" + ] + }, + { + "key": "gtk-custom-css", + "zigType": "RepeatablePath", + "kind": "path", + "repeatable": true, + "hint": "prefix with ? to make the file optional", + "doc": "Custom CSS files to be loaded.\n\nGTK CSS documentation can be found at the following links:\n\n * https://docs.gtk.org/gtk4/css-overview.html - An overview of GTK CSS.\n * https://docs.gtk.org/gtk4/css-properties.html - A comprehensive list\n of supported CSS properties.\n\nLaunch Ghostty with `env GTK_DEBUG=interactive ghostty` to tweak Ghostty's\nCSS in real time using the GTK Inspector. Errors in your CSS files would\nalso be reported in the terminal you started Ghostty from. See\nhttps://developer.gnome.org/documentation/tools/inspector.html for more\ninformation about the GTK Inspector.\n\nThis configuration can be repeated multiple times to load multiple files.\nPrepend a ? character to the file path to suppress errors if the file does\nnot exist. If you want to include a file that begins with a literal ?\ncharacter, surround the file path in double quotes (\").\nThe file size limit for a single stylesheet is 5MiB.\n\nAvailable since: 1.1.0", + "defaults": [ + "" + ] + }, + { + "key": "desktop-notifications", + "zigType": "bool", + "kind": "bool", + "doc": "If `true` (default), applications running in the terminal can show desktop\nnotifications using certain escape sequences such as OSC 9 or OSC 777.", + "defaults": [ + "true" + ] + }, + { + "key": "progress-style", + "zigType": "bool", + "kind": "bool", + "doc": "If `true` (default), applications running in the terminal can show\ngraphical progress bars using the ConEmu OSC 9;4 escape sequence.\nIf `false`, progress bar sequences are silently ignored.", + "defaults": [ + "true" + ] + }, + { + "key": "bold-color", + "zigType": "?BoldColor", + "kind": "color", + "values": [ + "bright" + ], + "doc": "Modifies the color used for bold text in the terminal.\n\nThis can be set to a specific color, using the same format as\n`background` or `foreground` (e.g. `#RRGGBB` but other formats\nare also supported; see the aforementioned documentation). If a\nspecific color is set, this color will always be used for the default\nbold text color. It will set the rest of the bold colors to `bright`.\n\nThis can also be set to `bright`, which uses the bright color palette\nfor bold text. For example, if the text is red, then the bold will\nuse the bright red color. The terminal palette is set with `palette`\nbut can also be overridden by the terminal application itself using\nescape sequences such as OSC 4. (Since Ghostty 1.2.0, the previous\nconfiguration `bold-is-bright` is deprecated and replaced by this\nusage).\n\nAvailable since Ghostty 1.2.0.", + "defaults": [ + "" + ] + }, + { + "key": "faint-opacity", + "zigType": "f64", + "kind": "float", + "min": 0, + "max": 1, + "doc": "The opacity level (opposite of transparency) of the faint text. A value of\n1 is fully opaque and a value of 0 is fully transparent. A value less than 0\nor greater than 1 will be clamped to the nearest valid value.\n\nAvailable since Ghostty 1.2.0.", + "defaults": [ + "0.5" + ] + }, + { + "key": "term", + "zigType": "[]const u8", + "kind": "text", + "doc": "This will be used to set the `TERM` environment variable.\nHACK: We set this with an `xterm` prefix because vim uses that to enable key\nprotocols (specifically this will enable `modifyOtherKeys`), among other\nfeatures. An option exists in vim to modify this: `:set\nkeyprotocol=ghostty:kitty`, however a bug in the implementation prevents it\nfrom working properly. https://github.com/vim/vim/pull/13211 fixes this.", + "defaults": [ + "xterm-ghostty" + ] + }, + { + "key": "enquiry-response", + "zigType": "[]const u8", + "kind": "text", + "doc": "String to send when we receive `ENQ` (`0x05`) from the command that we are\nrunning. Defaults to an empty string if not set.", + "defaults": [ + "" + ] + }, + { + "key": "async-backend", + "zigType": "AsyncBackend", + "kind": "enum", + "values": [ + "auto", + "epoll", + "io_uring" + ], + "doc": "Configures the low-level API to use for async IO, eventing, etc.\n\nMost users should leave this set to `auto`. This will automatically detect\nscenarios where APIs may not be available (for example `io_uring` on\ncertain hardened kernels) and fall back to a different API. However, if\nyou want to force a specific backend for any reason, you can set this\nhere.\n\nBased on various benchmarks, we haven't found a statistically significant\ndifference between the backends with regards to memory, CPU, or latency.\nThe choice of backend is more about compatibility and features.\n\nAvailable options:\n\n * `auto` - Automatically choose the best backend for the platform\n based on available options.\n * `epoll` - Use the `epoll` API\n * `io_uring` - Use the `io_uring` API\n\nIf the selected backend is not available on the platform, Ghostty will\nfall back to an automatically chosen backend that is available.\n\nChanging this value requires a full application restart to take effect.\n\nThis is only supported on Linux, since this is the only platform\nwhere we have multiple options. On macOS, we always use `kqueue`.\n\nAvailable since: 1.2.0", + "defaults": [ + "auto" + ] + }, + { + "key": "auto-update", + "zigType": "?AutoUpdate", + "kind": "enum", + "values": [ + "off", + "check", + "download" + ], + "doc": "Control the auto-update functionality of Ghostty. This is only supported\non macOS currently, since Linux builds are distributed via package\nmanagers that are not centrally controlled by Ghostty.\n\nChecking or downloading an update does not send any information to\nthe project beyond standard network information mandated by the\nunderlying protocols. To put it another way: Ghostty doesn't explicitly\nadd any tracking to the update process. The update process works by\ndownloading information about the latest version and comparing it\nclient-side to the current version.\n\nValid values are:\n\n * `off` - Disable auto-updates.\n * `check` - Check for updates and notify the user if an update is\n available, but do not automatically download or install the update.\n * `download` - Check for updates, automatically download the update,\n notify the user, but do not automatically install the update.\n\nIf unset, we defer to Sparkle's default behavior, which respects the\npreference stored in the standard user defaults (`defaults(1)`).\n\nChanging this value at runtime works after a small delay.", + "defaults": [ + "" + ] + }, + { + "key": "auto-update-channel", + "zigType": "?build_config.ReleaseChannel", + "kind": "enum", + "values": [ + "stable", + "tip" + ], + "doc": "The release channel to use for auto-updates.\n\nThe default value of this matches the release channel of the currently\nrunning Ghostty version. If you download a pre-release version of Ghostty\nthen this will be set to `tip` and you will receive pre-release updates.\nIf you download a stable version of Ghostty then this will be set to\n`stable` and you will receive stable updates.\n\nValid values are:\n\n * `stable` - Stable, tagged releases such as \"1.0.0\".\n * `tip` - Pre-release versions generated from each commit to the\n main branch. This is the version that was in use during private\n beta testing by thousands of people. It is generally stable but\n will likely have more bugs than the stable channel.\n\nChanging this configuration requires a full restart of\nGhostty to take effect.\n\nThis only works on macOS since only macOS has an auto-update feature.", + "defaults": [ + "" + ] + }, + { + "key": "quick-terminal-size", + "zigType": "QuickTerminalSize", + "kind": "text", + "hint": "e.g. 50%, 400px or 50%,500px", + "doc": "The size of the quick terminal.\n\nThe size can be specified either as a percentage of the screen dimensions\n(height/width), or as an absolute size in pixels. Percentage values are\nsuffixed with `%` (e.g. `20%`) while pixel values are suffixed with `px`\n(e.g. `300px`). A bare value without a suffix is a config error.\n\nWhen only one size is specified, the size parameter affects the size of\nthe quick terminal on its *primary axis*, which depends on its position:\nheight for quick terminals placed on the top or bottom, and width for left\nor right. The primary axis of a centered quick terminal depends on the\nmonitor's orientation: height when on a landscape monitor, and width when\non a portrait monitor.\n\nThe *secondary axis* would be maximized for non-center positioned\nquick terminals unless another size parameter is specified, separated\nfrom the first by a comma (`,`). Percentage and pixel sizes can be mixed\ntogether: for instance, a size of `50%,500px` for a top-positioned quick\nterminal would be half a screen tall, and 500 pixels wide.\n\nAvailable since: 1.2.0", + "notListed": true + } + ] +} diff --git a/internal/schema/schema_test.go b/internal/schema/schema_test.go new file mode 100644 index 0000000..4d1d882 --- /dev/null +++ b/internal/schema/schema_test.go @@ -0,0 +1,176 @@ +package schema + +import ( + "strings" + "testing" +) + +func TestEmbeddedSchema(t *testing.T) { + s, err := Embedded() + if err != nil { + t.Fatal(err) + } + if len(s.Options) < 150 { + t.Fatalf("only %d options in embedded schema", len(s.Options)) + } + for _, o := range s.Options { + if o.Kind == "" { + t.Errorf("%s has no kind", o.Key) + } + if o.Category == "" { + t.Errorf("%s has no category", o.Key) + } + if (o.Kind == KindEnum || o.Kind == KindChoice) && len(o.Values) == 0 { + t.Errorf("%s has no values", o.Key) + } + if o.Kind == KindEnum && o.Default() != "" && !contains(o.Values, o.Default()) { + t.Errorf("%s: default %q is not a valid value", o.Key, o.Default()) + } + if !o.Repeatable && o.Default() != "" { + if err := o.Validate(o.Default()); err != nil { + t.Errorf("%s: default %q does not validate: %v", o.Key, o.Default(), err) + } + } + } + for _, key := range []string{"font-family", "keybind", "palette", "theme", "cursor-style", "shell-integration-features"} { + if s.Lookup(key) == nil { + t.Errorf("missing %s", key) + } + } +} + +func TestParseDocs(t *testing.T) { + out := `# Font families. +# +# Can be repeated. +font-family = + +font-family-bold = +# The palette. +palette = 0=#000000 +palette = 1=#ff0000 +selection-word-chars = '" +` + got := ParseDocs(out) + if len(got) != 4 { + t.Fatalf("got %d entries", len(got)) + } + if got[0].Doc != "Font families.\n\nCan be repeated." { + t.Errorf("doc = %q", got[0].Doc) + } + if got[1].Doc != got[0].Doc { + t.Errorf("font-family-bold should share the font-family docs") + } + if len(got[2].Defaults) != 2 { + t.Errorf("palette defaults = %v", got[2].Defaults) + } + if got[3].Defaults[0] != " \t'\"" { + t.Errorf("leading whitespace must be kept, got %q", got[3].Defaults[0]) + } +} + +func TestValidate(t *testing.T) { + opt := func(k Kind) *Option { + return &Option{Kind: k, Values: []string{"cell-foreground"}, Flags: []string{"cursor", "sudo"}} + } + cases := []struct { + kind Kind + value string + ok bool + }{ + {KindBool, "true", true}, + {KindBool, "yes", false}, + {KindColor, "#1e1e2e", true}, + {KindColor, "fff", true}, + {KindColor, "dark slate gray", true}, + {KindColor, "cell-foreground", true}, + {KindColor, "#12345", false}, + {KindMetric, "-10%", true}, + {KindMetric, "2", true}, + {KindMetric, "1.5", false}, + {KindDuration, "750ms", true}, + {KindDuration, "1h 30m", true}, + {KindDuration, "0", true}, + {KindDuration, "5", false}, + {KindPadding, "2,4", true}, + {KindPadding, "a", false}, + {KindFlags, "no-cursor,sudo", true}, + {KindFlags, "false", true}, + {KindFlags, "bogus", false}, + {KindKeybind, "ctrl+==reset_font_size", true}, + {KindKeybind, "clear", true}, + {KindKeybind, "ctrl+a", false}, + {KindPalette, "4=#89b4fa", true}, + {KindPalette, "256=#000000", false}, + {KindFloat, "0.5", true}, + {KindFloat, "x", false}, + } + for _, c := range cases { + err := opt(c.kind).Validate(c.value) + if (err == nil) != c.ok { + t.Errorf("%s %q: err = %v, want ok=%v", c.kind, c.value, err, c.ok) + } + } +} + +func TestFlags(t *testing.T) { + o := &Option{Kind: KindFlags, Flags: []string{"cursor", "sudo", "title"}, Defaults: []string{"cursor,no-sudo,title"}} + st := o.ParseFlags("no-cursor") + if st["cursor"] || st["sudo"] || !st["title"] { + t.Fatalf("state = %v", st) + } + if got := o.FormatFlags(st); got != "no-cursor,no-sudo,title" { + t.Fatalf("format = %q", got) + } +} + +func TestSplitKeybind(t *testing.T) { + cases := map[string][2]string{ + "ctrl+a=new_tab": {"ctrl+a", "new_tab"}, + "==text:=": {"=", "text:="}, + "ctrl+==text:=hello": {"ctrl+=", "text:=hello"}, + "super+shift+,=reload": {"super+shift+,", "reload"}, + "ctrl+a>n=new_window": {"ctrl+a>n", "new_window"}, + "§=goto_split:next": {"§", "goto_split:next"}, + } + for in, want := range cases { + tr, ac := SplitKeybind(in) + if tr != want[0] || ac != want[1] { + t.Errorf("SplitKeybind(%q) = %q, %q", in, tr, ac) + } + } +} + +func TestCategoriesCoverEverything(t *testing.T) { + s, _ := Embedded() + cats := s.Categories() + total := 0 + for _, c := range cats { + total += len(s.InCategory(c)) + } + if total != len(s.Options) { + t.Fatalf("categories hold %d of %d options", total, len(s.Options)) + } + if !strings.Contains(strings.Join(cats, ","), CatFonts) { + t.Fatal("missing Fonts category") + } +} + +func TestPlatformDetection(t *testing.T) { + s, _ := Embedded() + want := map[string]string{ + "keybind": "", + "fullscreen": "", + "window-theme": "", + "window-step-resize": "macOS", + "undo-timeout": "macOS", + "window-subtitle": "Linux", + "macos-icon": "macOS", + "gtk-wide-tabs": "Linux", + } + for key, p := range want { + if o := s.Lookup(key); o == nil || o.Platform != p { + t.Errorf("%s: platform = %q, want %q", key, o.Platform, p) + } + } +} diff --git a/internal/schema/validate.go b/internal/schema/validate.go new file mode 100644 index 0000000..63e6a17 --- /dev/null +++ b/internal/schema/validate.go @@ -0,0 +1,197 @@ +package schema + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" + + "ghosttyconf/internal/colors" + "ghosttyconf/internal/keybind" +) + +var ( + reMetric = regexp.MustCompile(`^[+-]?\d+$|^[+-]?\d+(\.\d+)?%$`) + reDuration = regexp.MustCompile(`^(\s*\d+\s*(y|w|d|h|m|s|ms|µs|us|ns)\s*)+$`) + rePadding = regexp.MustCompile(`^\d+(\s*,\s*\d+)?$`) + rePalette = regexp.MustCompile(`^\s*(\d{1,3})\s*=\s*(.+?)\s*$`) +) + +// Unquote strips one pair of surrounding double quotes, as Ghostty does +// when reading a config file. +func Unquote(s string) string { + if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' { + return s[1 : len(s)-1] + } + return s +} + +// Validate checks a single (raw, possibly quoted) value for the option. For +// repeatable options it validates one list entry. +func (o *Option) Validate(raw string) error { + v := strings.TrimSpace(Unquote(raw)) + if v == "" { + // An empty value resets the option to its default; always allowed. + return nil + } + switch o.Kind { + case KindBool: + if v != "true" && v != "false" { + return errors.New(`expected "true" or "false"`) + } + case KindEnum: + if !contains(o.Values, v) { + return fmt.Errorf("expected one of: %s", strings.Join(o.Values, ", ")) + } + case KindFlags: + return o.validateFlags(v) + case KindInt: + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return errors.New("expected a whole number") + } + return o.checkRange(float64(n)) + case KindFloat: + f, err := strconv.ParseFloat(v, 64) + if err != nil { + return errors.New("expected a number") + } + return o.checkRange(f) + case KindColor: + if contains(o.Values, v) || colors.Valid(v) { + return nil + } + return errors.New("expected a color like #1e1e2e, 1e1e2e, #fff or an X11 name like \"dark slate gray\"") + case KindColorList: + for _, part := range strings.Split(v, ",") { + if !colors.Valid(part) { + return fmt.Errorf("%q is not a valid color", strings.TrimSpace(part)) + } + } + case KindMetric: + if !reMetric.MatchString(v) { + return errors.New("expected an integer (e.g. 2, -1) or a percentage (e.g. 10%, -5%)") + } + case KindDuration: + if v != "0" && !reDuration.MatchString(v) { + return errors.New("expected a duration such as 750ms, 5s, 2m or 1h30m") + } + case KindPadding: + if !rePadding.MatchString(v) { + return errors.New("expected one or two non-negative integers, e.g. 4 or 4,8") + } + case KindKeybind: + if v == "clear" { + return nil + } + trigger, action := SplitKeybind(v) + if trigger == "" || action == "" { + return errors.New("expected trigger=action, e.g. ctrl+shift+t=new_tab (or \"clear\")") + } + case KindPalette: + m := rePalette.FindStringSubmatch(v) + if m == nil { + return errors.New("expected N=COLOR, e.g. 4=#89b4fa") + } + if n, _ := strconv.Atoi(m[1]); n > 255 { + return errors.New("palette index must be between 0 and 255") + } + if !colors.Valid(m[2]) { + return fmt.Errorf("%q is not a valid color", m[2]) + } + } + return nil +} + +func (o *Option) validateFlags(v string) error { + if v == "true" || v == "false" { + return nil + } + for _, part := range strings.Split(v, ",") { + name := strings.TrimPrefix(strings.TrimSpace(part), "no-") + if !contains(o.Flags, name) { + return fmt.Errorf("unknown flag %q (valid: %s)", name, strings.Join(o.Flags, ", ")) + } + } + return nil +} + +func (o *Option) checkRange(f float64) error { + if o.Min != nil && f < *o.Min { + return fmt.Errorf("must be at least %s", num(*o.Min)) + } + if o.Max != nil && f > *o.Max { + return fmt.Errorf("must be at most %s", num(*o.Max)) + } + return nil +} + +// ParseFlags returns the state of every flag for a flags value, starting +// from the option's default the same way Ghostty does. +func (o *Option) ParseFlags(value string) map[string]bool { + state := make(map[string]bool, len(o.Flags)) + apply := func(v string) { + v = strings.TrimSpace(Unquote(v)) + if v == "true" || v == "false" { + for _, f := range o.Flags { + state[f] = v == "true" + } + return + } + for _, part := range strings.Split(v, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + on := !strings.HasPrefix(part, "no-") + state[strings.TrimPrefix(part, "no-")] = on + } + } + apply(o.Default()) + if value != "" { + apply(value) + } + return state +} + +// FormatFlags renders flag states in Ghostty's explicit form, +// e.g. "cursor,no-sudo,title". +func (o *Option) FormatFlags(state map[string]bool) string { + parts := make([]string, len(o.Flags)) + for i, f := range o.Flags { + if state[f] { + parts[i] = f + } else { + parts[i] = "no-" + f + } + } + return strings.Join(parts, ",") +} + +// SplitKeybind splits "trigger=action" exactly like Ghostty does. +func SplitKeybind(v string) (trigger, action string) { + return keybind.Split(v) +} + +// SplitPalette splits a palette entry into its index and color. +func SplitPalette(v string) (index int, color string, ok bool) { + m := rePalette.FindStringSubmatch(Unquote(v)) + if m == nil { + return 0, "", false + } + n, err := strconv.Atoi(m[1]) + if err != nil || n > 255 { + return 0, "", false + } + return n, m[2], true +} + +func contains(list []string, v string) bool { + for _, s := range list { + if s == v { + return true + } + } + return false +} diff --git a/internal/ui/app.go b/internal/ui/app.go new file mode 100644 index 0000000..d75fa13 --- /dev/null +++ b/internal/ui/app.go @@ -0,0 +1,966 @@ +// Package ui implements the terminal user interface. +package ui + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "sort" + "strings" + + "github.com/charmbracelet/bubbles/textinput" + "github.com/charmbracelet/bubbles/viewport" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "ghosttyconf/internal/config" + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/schema" +) + +const ( + catSet = "Set in Config" + catAll = "All Options" +) + +type pane int + +const ( + paneCats pane = iota + paneOpts +) + +// Messages delivering data loaded in the background. +type itemsMsg struct { + source string // "themes" or "fonts" + items []string + err error +} + +type actionsMsg struct { + items []ghostty.Action + err error +} + +// reloadMsg reports the result of asking Ghostty to reload its config. +type reloadMsg struct { + saved string // status text describing the save + err error +} + +type undoEntry struct { + file *config.File + key string +} + +type rect struct{ x, y, w, h int } + +func (r rect) contains(x, y int) bool { + return x >= r.x && x < r.x+r.w && y >= r.y && y < r.y+r.h +} + +// App is the Bubble Tea model of the editor. +type App struct { + sch *schema.Schema + gh *ghostty.Ghostty + file *config.File + saved *config.File + undo []undoEntry + rev int // incremented on every change to file + backup bool // a .bak copy was written this session + unknown map[string]*schema.Option + osName string + + width, height int + focus pane + cats []string + catIdx int + catTop int + opts []*schema.Option + optIdx int + optTop int + + search textinput.Model + searching bool + query string + hideForeign bool + + doc viewport.Model + docFor string + + editor editor + editOpt *schema.Option + + dlg *dialog + status string + statusStyle lipgloss.Style + quitAfterSave bool + autoReload bool + + // Screen regions from the last render, for mouse handling. + catRect, optRect, docRect rect + optListY int + + themes []string + themesErr error + themesLoaded bool + fonts []string + fontsErr error + fontsLoaded bool + actions []ghostty.Action + actionsLoaded bool + themeCache map[string]*ghostty.Theme +} + +// New creates the editor for file. gh may be nil when Ghostty is not +// installed; validation, themes, fonts and actions are then unavailable. +func New(sch *schema.Schema, gh *ghostty.Ghostty, file *config.File) *App { + a := &App{ + sch: sch, + gh: gh, + file: file, + saved: file.Clone(), + unknown: map[string]*schema.Option{}, + themeCache: map[string]*ghostty.Theme{}, + doc: viewport.New(0, 0), + focus: paneOpts, + autoReload: true, + } + switch runtime.GOOS { + case "darwin": + a.osName = "macOS" + case "linux", "freebsd": + a.osName = "Linux" + } + a.search = textinput.New() + a.search.Prompt = "/ " + a.search.PromptStyle = stAccent + a.search.Placeholder = "search options and documentation" + a.search.PlaceholderStyle = stDim + + a.cats = append([]string{catSet, catAll}, sch.Categories()...) + if len(file.Keys()) == 0 { + a.catIdx = 2 // nothing set yet: start with the first real category + } + a.rebuild() + if gh == nil { + a.setStatus("Running without the ghostty binary: built-in docs only; validation, themes, fonts and actions are unavailable.", stChanged) + } + return a +} + +// SetAutoReload controls whether Ghostty is asked to reload its config +// after every save (on by default). +func (a *App) SetAutoReload(on bool) { a.autoReload = on } + +func (a *App) Init() tea.Cmd { + if a.gh == nil { + return nil + } + gh := a.gh + return tea.Batch( + func() tea.Msg { t, err := gh.Themes(); return itemsMsg{"themes", t, err} }, + func() tea.Msg { f, err := gh.Fonts(); return itemsMsg{"fonts", f, err} }, + func() tea.Msg { ac, err := gh.Actions(); return actionsMsg{ac, err} }, + ) +} + +func (a *App) setStatus(s string, st lipgloss.Style) { + a.status, a.statusStyle = s, st +} + +func (a *App) dirty() bool { return !a.file.Equal(a.saved) } + +// option returns the schema entry for key, synthesizing one for keys in the +// config file that Ghostty does not know. +func (a *App) option(key string) *schema.Option { + if o := a.sch.Lookup(key); o != nil { + return o + } + if o := a.unknown[key]; o != nil { + return o + } + o := &schema.Option{ + Key: key, + Kind: schema.KindText, + Repeatable: len(a.file.GetAll(key)) > 1, + Category: catSet, + Doc: "This key is not a known Ghostty " + a.sch.GhosttyVersion + " option. " + + "It may be misspelled or belong to a different Ghostty version. " + + "Ghostty will report it as an error; press r to remove it.", + } + a.unknown[key] = o + return o +} + +func (a *App) selected() *schema.Option { + if a.optIdx >= 0 && a.optIdx < len(a.opts) { + return a.opts[a.optIdx] + } + return nil +} + +func (a *App) visible(o *schema.Option) bool { + return !a.hideForeign || o.Platform == "" || a.osName == "" || o.Platform == a.osName +} + +// categoryOptions returns the options listed under a category. +func (a *App) categoryOptions(cat string) []*schema.Option { + var list []*schema.Option + switch cat { + case catSet: + for _, k := range a.file.Keys() { + list = append(list, a.option(k)) + } + return list // always show everything that is set + case catAll: + list = append(list, a.sch.Options...) + sort.Slice(list, func(i, j int) bool { return list[i].Key < list[j].Key }) + default: + list = a.sch.InCategory(cat) + } + var out []*schema.Option + for _, o := range list { + if a.visible(o) { + out = append(out, o) + } + } + return out +} + +// searchOptions ranks options by how well they match the query: key +// matches first, then documentation matches. +func (a *App) searchOptions(q string) []*schema.Option { + terms := strings.Fields(strings.ToLower(q)) + var byKey, byDoc []*schema.Option + for _, o := range a.sch.Options { + if !a.visible(o) { + continue + } + key, doc := o.Key, strings.ToLower(o.Doc) + inKey, inAny := true, true + for _, t := range terms { + if !strings.Contains(key, t) { + inKey = false + if !strings.Contains(doc, t) { + inAny = false + } + } + } + switch { + case inKey: + byKey = append(byKey, o) + case inAny: + byDoc = append(byDoc, o) + } + } + return append(byKey, byDoc...) +} + +// rebuild recomputes the visible option list, keeping the selection. +func (a *App) rebuild() { + var keep string + if o := a.selected(); o != nil { + keep = o.Key + } + if a.query != "" { + a.opts = a.searchOptions(a.query) + } else { + a.opts = a.categoryOptions(a.cats[a.catIdx]) + } + a.optIdx = min(a.optIdx, max(0, len(a.opts)-1)) + for i, o := range a.opts { + if o.Key == keep { + a.optIdx = i + break + } + } +} + +func (a *App) selectCategory(i int) { + if i == a.catIdx && a.query == "" { + return + } + a.catIdx = i + a.clearSearch() + a.optIdx, a.optTop = 0, 0 + a.opts = nil + a.rebuild() +} + +func (a *App) clearSearch() { + a.query = "" + a.searching = false + a.search.SetValue("") + a.search.Blur() +} + +// --------------------------------------------------------------------------- +// Update + +func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + a.width, a.height = msg.Width, msg.Height + return a, nil + case itemsMsg: + switch msg.source { + case "themes": + a.themes, a.themesErr, a.themesLoaded = msg.items, msg.err, true + case "fonts": + a.fonts, a.fontsErr, a.fontsLoaded = msg.items, msg.err, true + } + case actionsMsg: + a.actions, a.actionsLoaded = msg.items, true + case reloadMsg: + switch { + case msg.err == nil: + a.setStatus(msg.saved+" Ghostty reloaded the configuration.", stOK) + case errors.Is(msg.err, ghostty.ErrNotRunning): + a.setStatus(msg.saved+" Ghostty is not running; it will use the new config on its next start.", stOK) + default: + a.setStatus(msg.saved+" Automatic reload failed: "+msg.err.Error()+". Reload with "+reloadShortcut()+".", stChanged) + } + return a, nil + case tea.MouseMsg: + return a, a.handleMouse(msg) + case tea.KeyMsg: + if msg.String() == "ctrl+c" && !a.capturing() { + if a.dlg != nil && a.dlg.quit { + return a, tea.Quit + } + return a, a.quit() + } + if a.dlg != nil { + return a, a.dlg.update(a, msg) + } + if a.editor != nil { + return a, a.updateEditor(msg) + } + return a, a.updateBrowse(msg) + } + if a.editor != nil { + return a, a.updateEditor(msg) + } + return a, nil +} + +// capturing reports whether the editor records raw key presses, in which +// case no key may be interpreted by the application. +func (a *App) capturing() bool { + c, ok := a.editor.(interface{ capturing() bool }) + return ok && c.capturing() +} + +func (a *App) updateEditor(msg tea.Msg) tea.Cmd { + if km, ok := msg.(tea.KeyMsg); ok && !a.capturing() { + switch km.String() { + case "shift+down": + a.doc.ScrollDown(3) + return nil + case "shift+up": + a.doc.ScrollUp(3) + return nil + } + } + cmd, res := a.editor.Update(msg) + if res != nil { + o := a.editOpt + a.editor, a.editOpt = nil, nil + a.apply(o, res) + } + return cmd +} + +func (a *App) updateBrowse(km tea.KeyMsg) tea.Cmd { + key := km.String() + if a.searching { + switch key { + case "esc": + a.clearSearch() + a.rebuild() + case "enter", "down", "tab": + a.searching = false + a.search.Blur() + a.focus = paneOpts + default: + var cmd tea.Cmd + a.search, cmd = a.search.Update(km) + if v := a.search.Value(); v != a.query { + a.query = v + a.optIdx, a.optTop = 0, 0 + a.rebuild() + } + return cmd + } + return nil + } + + a.status = "" + switch key { + case "q": + return a.quit() + case "?", "f1": + a.dlg = helpDialog() + return nil + case "/", "ctrl+f": + // Every search starts fresh, like "/" in less or vim. + a.search.SetValue("") + if a.query != "" { + a.query = "" + a.rebuild() + } + a.searching = true + a.focus = paneOpts + return a.search.Focus() + case "ctrl+s": + return a.save(false, false) + case "u", "ctrl+z": + a.undoLast() + return nil + case "c": + a.dlg = a.changesDialog() + return nil + case "b": + if o := a.sch.Lookup("keybind"); o != nil { + return a.edit(o) + } + return nil + case "p": + a.hideForeign = !a.hideForeign + if a.hideForeign { + a.setStatus("Hiding options that do not apply to "+a.osName+".", stDim) + } else { + a.setStatus("Showing options for all platforms.", stDim) + } + a.rebuild() + return nil + case "tab": + if a.focus == paneCats { + a.focus = paneOpts + } else { + a.focus = paneCats + } + return nil + case "esc": + if a.query != "" { + a.clearSearch() + a.rebuild() + } + return nil + case "ctrl+d", "shift+down": + a.doc.ScrollDown(max(3, a.doc.Height/2)) + return nil + case "ctrl+u", "shift+up": + a.doc.ScrollUp(max(3, a.doc.Height/2)) + return nil + } + + if a.focus == paneCats { + if c, moved := moveCursor(key, a.catIdx, len(a.cats), 5); moved { + a.selectCategory(c) + return nil + } + switch key { + case "right", "l", "enter": + a.focus = paneOpts + } + return nil + } + + if c, moved := moveCursor(key, a.optIdx, len(a.opts), max(1, a.optRect.h-3)); moved { + a.optIdx = c + return nil + } + o := a.selected() + switch key { + case "left", "h": + a.focus = paneCats + case "enter", "e", "right", "l": + if o != nil { + if key == "right" || key == "l" { + // Only open editors that are not instant toggles. + if o.Kind == schema.KindBool && !o.Repeatable { + return nil + } + } + return a.edit(o) + } + case " ": + if o != nil { + a.quickToggle(o) + } + case "+", "=", "-", "_": + if o != nil && !o.Repeatable { + delta := 1 + if key == "-" || key == "_" { + delta = -1 + } + a.step(o, delta) + } + case "r", "delete", "backspace", "d": + if o != nil { + a.apply(o, &result{}) + } + } + return nil +} + +// edit opens the editor for o. Booleans are toggled directly. +func (a *App) edit(o *schema.Option) tea.Cmd { + if o.Kind == schema.KindBool && !o.Repeatable { + a.quickToggle(o) + return nil + } + values := a.file.GetAll(o.Key) + current, _ := a.file.Get(o.Key) + switch { + case o.Kind == schema.KindKeybind: + a.editor = newKeybindManager(o, values, a.actions, func(v string) editor { + return a.valueEditor(o, v) + }) + case o.Kind == schema.KindPalette: + pe := newPaletteEditor(o, values) + if th := a.currentTheme(); th != nil { + pe.useTheme(th) + } + a.editor = pe + case o.Repeatable: + a.editor = newListEditor(o, values, func(v string) editor { + e := a.valueEditor(o, v) + if t, ok := e.(*textEditor); ok { + t.item = true + } + return e + }) + default: + a.editor = a.valueEditor(o, current) + } + a.editOpt = o + a.docFor = "" // force docs to re-render for the editor layout + return nil +} + +func (a *App) valueEditor(o *schema.Option, current string) editor { + switch o.Kind { + case schema.KindBool, schema.KindEnum, schema.KindChoice: + return newChoiceEditor(o, current) + case schema.KindFlags: + return newFlagsEditor(o, current) + case schema.KindTheme: + p := newPickerEditor(o, "themes", current) + p.preview = a.loadTheme + var overrides []string + for _, k := range []string{"background", "foreground", "cursor-color", "cursor-text", "selection-background", "selection-foreground", "palette"} { + if a.file.Has(k) { + overrides = append(overrides, k) + } + } + if len(overrides) > 0 { + p.note = "Your config also sets " + strings.Join(overrides, ", ") + ", which take precedence over the theme." + } + if a.themesLoaded { + p.setItems(a.themes, a.themesErr) + } else if a.gh == nil { + p.setItems(nil, fmt.Errorf("ghostty not found")) + } + return p + case schema.KindFont: + p := newPickerEditor(o, "fonts", current) + if a.fontsLoaded { + p.setItems(a.fonts, a.fontsErr) + } else if a.gh == nil { + p.setItems(nil, fmt.Errorf("ghostty not found")) + } + return p + case schema.KindKeybind: + return newKeybindEditor(current, a.actions) + default: + return newTextEditor(o, current) + } +} + +func (a *App) loadTheme(name string) *ghostty.Theme { + if a.gh == nil { + return nil + } + if t, ok := a.themeCache[name]; ok { + return t + } + t, err := a.gh.LoadTheme(name) + if err != nil { + t = nil + } + a.themeCache[name] = t + return t +} + +// currentTheme loads the theme set in the config (the dark variant for +// "light:A,dark:B"), or nil. +func (a *App) currentTheme() *ghostty.Theme { + v, ok := a.file.Get("theme") + if !ok { + return nil + } + v = schema.Unquote(v) + name := v + if strings.Contains(v, ":") && !strings.HasPrefix(v, "/") { + for _, part := range strings.Split(v, ",") { + mode, n, found := strings.Cut(strings.TrimSpace(part), ":") + if found && (mode == "dark" || name == v) { + name = strings.TrimSpace(n) + } + } + } + return a.loadTheme(name) +} + +// quickToggle flips booleans and cycles through enum values in place. +func (a *App) quickToggle(o *schema.Option) { + if o.Repeatable { + return + } + cur, ok := a.file.Get(o.Key) + if !ok { + cur = o.Default() + } + cur = schema.Unquote(cur) + var values []string + switch o.Kind { + case schema.KindBool: + values = []string{"false", "true"} + if cur == "" { + cur = "false" + } + case schema.KindEnum: + values = o.Values + default: + a.setStatus("Space toggles booleans and cycles choices; press enter to edit "+o.Key+".", stDim) + return + } + next := values[0] + for i, v := range values { + if v == cur { + next = values[(i+1)%len(values)] + break + } + } + a.apply(o, valuesResult(next)) +} + +func (a *App) step(o *schema.Option, delta int) { + switch o.Kind { + case schema.KindInt, schema.KindFloat, schema.KindMetric: + default: + return + } + cur, _ := a.file.Get(o.Key) + v, ok := stepValue(o, cur, delta) + if !ok { + return + } + if err := o.Validate(v); err != nil { + a.setStatus(err.Error(), stError) + return + } + a.apply(o, valuesResult(v)) +} + +// apply writes an editor result into the in-memory config. +func (a *App) apply(o *schema.Option, res *result) { + if res == nil || res.cancel { + return + } + before := a.file.Clone() + switch { + case res.values == nil: + a.file.Unset(o.Key) + case o.Repeatable: + a.file.SetAll(o.Key, res.values) + default: + a.file.Set(o.Key, res.values[0]) + } + if a.file.Equal(before) { + return + } + a.rev++ + a.undo = append(a.undo, undoEntry{file: before, key: o.Key}) + if len(a.undo) > 500 { + a.undo = a.undo[1:] + } + switch { + case res.values == nil: + a.setStatus("Reset "+o.Key+" to its default.", stChanged) + case o.Repeatable: + a.setStatus(fmt.Sprintf("Updated %s (%d entr%s).", o.Key, len(res.values), plural(len(res.values), "y", "ies")), stChanged) + default: + a.setStatus("Set "+o.Key+" = "+res.values[0], stChanged) + } + a.rebuild() +} + +func (a *App) undoLast() { + if len(a.undo) == 0 { + a.setStatus("Nothing to undo.", stDim) + return + } + last := a.undo[len(a.undo)-1] + a.undo = a.undo[:len(a.undo)-1] + a.file = last.file + a.rev++ + a.setStatus("Undid change to "+last.key+".", stChanged) + a.rebuild() +} + +// --------------------------------------------------------------------------- +// Saving and quitting + +func (a *App) save(skipDiskCheck, skipValidation bool) tea.Cmd { + if !a.dirty() { + a.setStatus("No changes to save.", stDim) + if a.quitAfterSave { + return tea.Quit + } + return nil + } + if !skipDiskCheck && a.file.ChangedOnDisk() { + a.dlg = &dialog{ + title: "File changed on disk", + lines: []string{ + "The config file was modified outside the editor since it was loaded:", + "", + a.file.Path, + "", + "Saving will overwrite those changes.", + }, + keys: []dialogKey{{"o", "Overwrite"}, {"esc", "Cancel"}}, + onKey: func(k string) tea.Cmd { + if k == "o" { + return a.save(true, skipValidation) + } + a.quitAfterSave = false + return nil + }, + warn: true, + } + return nil + } + if !skipValidation && a.gh != nil { + if errs := a.validate(); len(errs) > 0 { + lines := []string{"Ghostty reported problems with the new configuration:", ""} + for _, e := range errs { + lines = append(lines, stError.Render("• ")+e) + } + lines = append(lines, "", "Ghostty ignores invalid lines and uses defaults instead.") + a.dlg = &dialog{ + title: "Validation failed", + lines: lines, + keys: []dialogKey{{"s", "Save anyway"}, {"esc", "Back to editing"}}, + onKey: func(k string) tea.Cmd { + if k == "s" { + return a.save(true, true) + } + a.quitAfterSave = false + return nil + }, + warn: true, + } + return nil + } + } + makeBackup := !a.backup && a.file.Exists + if err := a.file.Save(makeBackup); err != nil { + a.setStatus("Save failed: "+err.Error(), stError) + a.quitAfterSave = false + return nil + } + a.backup = a.backup || makeBackup + a.saved = a.file.Clone() + msg := "Saved." + if makeBackup { + msg += " Backup: " + filepath.Base(a.file.Path) + ".bak." + } + if a.autoReload { + a.setStatus(msg+" Reloading Ghostty…", stOK) + reload := func() tea.Msg { return reloadMsg{saved: msg, err: ghostty.Reload()} } + if a.quitAfterSave { + return tea.Sequence(reload, tea.Quit) + } + return reload + } + a.setStatus(msg+" Reload Ghostty's config with "+reloadShortcut()+" to apply.", stOK) + if a.quitAfterSave { + return tea.Quit + } + return nil +} + +// validate checks the pending config with `ghostty +validate-config`. +func (a *App) validate() []string { + tmp, err := a.file.WriteTemp() + if err != nil { + return []string{"could not write temporary file: " + err.Error()} + } + defer os.Remove(tmp) + errs, err := a.gh.Validate(tmp) + if err != nil { + return nil // validation unavailable; do not block saving + } + var out []string + for _, e := range errs { + out = append(out, e.String()) + } + return out +} + +func (a *App) quit() tea.Cmd { + if !a.dirty() { + return tea.Quit + } + n := len(a.changedKeys()) + a.dlg = &dialog{ + title: "Unsaved changes", + lines: []string{fmt.Sprintf("You have unsaved changes to %d option(s).", n)}, + keys: []dialogKey{{"s", "Save and quit"}, {"d", "Discard and quit"}, {"esc", "Cancel"}}, + onKey: func(k string) tea.Cmd { + switch k { + case "s": + a.quitAfterSave = true + return a.save(false, false) + case "d": + return tea.Quit + } + return nil + }, + quit: true, + } + return nil +} + +// changedKeys lists keys whose values differ from the saved file. +func (a *App) changedKeys() []string { + seen := map[string]bool{} + var keys []string + for _, k := range append(a.saved.Keys(), a.file.Keys()...) { + if seen[k] { + continue + } + seen[k] = true + if !equalStrings(a.saved.GetAll(k), a.file.GetAll(k)) { + keys = append(keys, k) + } + } + return keys +} + +func (a *App) changesDialog() *dialog { + keys := a.changedKeys() + var lines []string + if len(keys) == 0 { + lines = append(lines, "No unsaved changes.") + } + for _, k := range keys { + lines = append(lines, stBold.Render(k)) + for _, c := range config.Diff(a.saved.GetAll(k), a.file.GetAll(k)) { + if c.Removed { + lines = append(lines, stError.Render(" - "+config.FormatLine(k, c.Value))) + } else { + lines = append(lines, stOK.Render(" + "+config.FormatLine(k, c.Value))) + } + } + } + return &dialog{ + title: fmt.Sprintf("Unsaved changes (%d)", len(keys)), + lines: lines, + keys: []dialogKey{{"esc", "Close"}}, + } +} + +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func reloadShortcut() string { + if runtime.GOOS == "darwin" { + return "⌘⇧," + } + return "ctrl+shift+," +} + +func shortPath(p string) string { + if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home+string(os.PathSeparator)) { + return "~" + p[len(home):] + } + return p +} + +// --------------------------------------------------------------------------- +// Mouse + +func (a *App) handleMouse(m tea.MouseMsg) tea.Cmd { + if a.dlg != nil || a.capturing() { + return nil + } + wheel := 0 + switch m.Button { + case tea.MouseButtonWheelUp: + wheel = -1 + case tea.MouseButtonWheelDown: + wheel = 1 + } + if wheel != 0 { + switch { + case a.docRect.contains(m.X, m.Y): + if wheel > 0 { + a.doc.ScrollDown(3) + } else { + a.doc.ScrollUp(3) + } + case a.editor != nil: + if _, isText := a.editor.(*textEditor); isText { + return nil // up/down would change numeric values + } + key := tea.KeyMsg{Type: tea.KeyDown} + if wheel < 0 { + key = tea.KeyMsg{Type: tea.KeyUp} + } + return a.updateEditor(key) + case a.optRect.contains(m.X, m.Y): + a.optIdx = min(max(0, a.optIdx+wheel), max(0, len(a.opts)-1)) + case a.catRect.contains(m.X, m.Y): + a.selectCategory(min(max(0, a.catIdx+wheel), len(a.cats)-1)) + } + return nil + } + if a.editor != nil || m.Action != tea.MouseActionPress || m.Button != tea.MouseButtonLeft { + return nil + } + switch { + case a.catRect.contains(m.X, m.Y): + a.focus = paneCats + row := m.Y - a.catRect.y - 1 + a.catTop + if i := a.catRowIndex(row); i >= 0 { + a.selectCategory(i) + } + case a.optRect.contains(m.X, m.Y): + a.focus = paneOpts + i := m.Y - a.optListY + a.optTop + if m.Y >= a.optListY && i >= 0 && i < len(a.opts) { + if i == a.optIdx { + return a.edit(a.opts[i]) + } + a.optIdx = i + } + } + return nil +} diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go new file mode 100644 index 0000000..b545d6e --- /dev/null +++ b/internal/ui/app_test.go @@ -0,0 +1,220 @@ +package ui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/config" + "ghosttyconf/internal/schema" +) + +func newTestApp(t *testing.T, content string) *App { + t.Helper() + sch, err := schema.Embedded() + if err != nil { + t.Fatal(err) + } + f := &config.File{Path: "/tmp/ghosttyconf-test/config.ghostty", Lines: config.Parse([]byte(content))} + a := New(sch, nil, f) + a.Update(tea.WindowSizeMsg{Width: 160, Height: 45}) + return a +} + +func press(a *App, keys ...string) { + for _, k := range keys { + var msg tea.KeyMsg + switch k { + case "enter": + msg = tea.KeyMsg{Type: tea.KeyEnter} + case "esc": + msg = tea.KeyMsg{Type: tea.KeyEsc} + case "down": + msg = tea.KeyMsg{Type: tea.KeyDown} + case "up": + msg = tea.KeyMsg{Type: tea.KeyUp} + case "tab": + msg = tea.KeyMsg{Type: tea.KeyTab} + case "shift+tab": + msg = tea.KeyMsg{Type: tea.KeyShiftTab} + case "space": + msg = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}} + default: + msg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)} + } + a.Update(msg) + } +} + +// TestEveryEditorRenders opens the editor of every option at several +// terminal sizes to catch panics and layout bugs. +func TestEveryEditorRenders(t *testing.T) { + a := newTestApp(t, "font-family = Hack\nkeybind = ctrl+a=new_tab\npalette = 1=#ff0000\n") + sizes := [][2]int{{160, 45}, {100, 30}, {60, 16}, {40, 12}} + for _, o := range a.sch.Options { + for _, sz := range sizes { + a.Update(tea.WindowSizeMsg{Width: sz[0], Height: sz[1]}) + a.edit(o) + if a.editor == nil && o.Kind != schema.KindBool { + t.Fatalf("%s: no editor opened", o.Key) + } + _ = a.View() + press(a, "down", "down") + _ = a.View() + for i := 0; i < 3 && a.editor != nil; i++ { + press(a, "esc") + } + if a.editor != nil { + t.Fatalf("%s: editor did not close on esc", o.Key) + } + _ = a.View() + } + } +} + +func TestEditEnumAndUndo(t *testing.T) { + a := newTestApp(t, "# keep me\ncursor-style = block\n") + press(a, "/") + for _, r := range "cursor-style" { + press(a, string(r)) + } + press(a, "enter") + if o := a.selected(); o == nil || o.Key != "cursor-style" { + t.Fatalf("selected = %v", o) + } + press(a, "enter", "down", "enter") // block -> bar + if v, _ := a.file.Get("cursor-style"); v != "bar" { + t.Fatalf("cursor-style = %q", v) + } + if !a.dirty() { + t.Fatal("expected unsaved changes") + } + press(a, "u") + if v, _ := a.file.Get("cursor-style"); v != "block" { + t.Fatalf("after undo cursor-style = %q", v) + } + if a.dirty() { + t.Fatal("undo should restore the saved state") + } + if !strings.HasPrefix(string(a.file.Bytes()), "# keep me\n") { + t.Fatal("comment lost") + } +} + +func TestToggleStepAndReset(t *testing.T) { + a := newTestApp(t, "font-size = 13\n") + a.selectCategory(0) // Set in Config + press(a, "+", "+") + if v, _ := a.file.Get("font-size"); v != "14" { + t.Fatalf("font-size = %q", v) + } + press(a, "r") + if a.file.Has("font-size") { + t.Fatal("font-size should have been removed") + } +} + +func TestKeybindListAdd(t *testing.T) { + a := newTestApp(t, "") + a.edit(a.sch.Lookup("keybind")) + press(a, "a") + for _, r := range "ctrl+shift+t" { + press(a, string(r)) + } + press(a, "tab") + for _, r := range "new_tab" { + press(a, string(r)) + } + press(a, "enter", "esc") + if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+shift+t=new_tab" { + t.Fatalf("keybind = %v", got) + } +} + +func TestKeybindManagerChangeDefault(t *testing.T) { + a := newTestApp(t, "") + o := a.sch.Lookup("keybind") + a.edit(o) + m, ok := a.editor.(*keybindManager) + if !ok { + t.Fatalf("editor is %T", a.editor) + } + // Find the built-in super+d binding and move it to super+shift+d. + press(a, "/") + for _, r := range "super+d" { + press(a, string(r)) + } + press(a, "enter") + b := m.selected() + if b == nil || b.Trigger != "super+d" { + t.Fatalf("selected = %+v", b) + } + press(a, "enter") // change + press(a, "shift+tab") // trigger field + a.Update(tea.KeyMsg{Type: tea.KeyCtrlU}) // clear it + for _, r := range "super+shift+d" { + press(a, string(r)) + } + press(a, "enter", "esc") + got := strings.Join(a.file.GetAll("keybind"), " | ") + if got != "super+d=unbind | super+shift+d="+b.Action { + t.Fatalf("keybind = %s", got) + } +} + +func TestKeybindManagerUnbindRestore(t *testing.T) { + a := newTestApp(t, "") + a.edit(a.sch.Lookup("keybind")) + m := a.editor.(*keybindManager) + b := *m.selected() + press(a, "d") + if v := m.set.Values(); len(v) != 1 || !strings.HasSuffix(v[0], "=unbind") { + t.Fatalf("after unbind: %v", v) + } + press(a, "r") + if v := m.set.Values(); len(v) != 0 { + t.Fatalf("after restore: %v", v) + } + press(a, "esc") + if a.file.Has("keybind") { + t.Fatalf("no change expected, got %v (binding %s)", a.file.GetAll("keybind"), b.Trigger) + } +} + +func TestKeybindRecording(t *testing.T) { + a := newTestApp(t, "") + a.edit(a.sch.Lookup("keybind")) + press(a, "a") + a.Update(tea.KeyMsg{Type: tea.KeyCtrlR}) + if !a.capturing() { + t.Fatal("not recording") + } + // ctrl+c must be recorded, not quit the program. + _, cmd := a.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + if a.dlg != nil || cmd != nil && a.capturing() == false { + t.Fatal("ctrl+c was not captured") + } + press(a, "enter") + if a.capturing() { + t.Fatal("still recording") + } + for _, r := range "copy_to_clipboard" { + press(a, string(r)) + } + press(a, "enter", "esc") + if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+c=copy_to_clipboard" { + t.Fatalf("keybind = %v", got) + } +} + +func TestUnknownKeyIsListed(t *testing.T) { + a := newTestApp(t, "bogus-key = 1\n") + a.selectCategory(0) + if len(a.opts) != 1 || a.opts[0].Key != "bogus-key" { + t.Fatalf("opts = %v", a.opts) + } + if !strings.Contains(a.View(), "bogus-key") { + t.Fatal("unknown key not rendered") + } +} diff --git a/internal/ui/dialogs.go b/internal/ui/dialogs.go new file mode 100644 index 0000000..8a7e7d3 --- /dev/null +++ b/internal/ui/dialogs.go @@ -0,0 +1,154 @@ +package ui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" +) + +type dialogKey struct{ key, label string } + +// dialog is a modal box drawn over the main view. +type dialog struct { + title string + lines []string + keys []dialogKey + onKey func(key string) tea.Cmd + scroll int + warn bool + quit bool // the unsaved-changes prompt: a second ctrl+c quits + height int // visible body lines in the last render +} + +func (d *dialog) update(a *App, km tea.KeyMsg) tea.Cmd { + key := km.String() + switch key { + case "up", "k": + d.scroll = max(0, d.scroll-1) + return nil + case "down", "j": + d.scroll = min(d.scroll+1, max(0, len(d.lines)-d.height)) + return nil + case "pgup": + d.scroll = max(0, d.scroll-d.height) + return nil + case "pgdown", " ": + d.scroll = min(d.scroll+d.height, max(0, len(d.lines)-d.height)) + return nil + } + for _, k := range d.keys { + if k.key == key { + a.dlg = nil + if d.onKey != nil { + return d.onKey(key) + } + return nil + } + } + if key == "esc" || key == "q" || key == "enter" { + a.dlg = nil + if d.onKey != nil { + return d.onKey("esc") + } + } + return nil +} + +func (d *dialog) view(width, height int) string { + var keys []string + for _, k := range d.keys { + keys = append(keys, stKey.Render(k.key)+" "+k.label) + } + hint := strings.Join(keys, " ") + + // Size the box to its content, within the screen. + want := max(40, ansi.StringWidth(hint)+18, ansi.StringWidth(d.title)+8) + for _, l := range d.lines { + want = max(want, ansi.StringWidth(l)+4) + } + w := min(width-4, 84, want) + inner := w - 4 + var body []string + for _, l := range d.lines { + if l == "" { + body = append(body, "") + continue + } + body = append(body, strings.Split(ansi.Wrap(l, inner, ""), "\n")...) + } + maxBody := max(3, height-8) + d.height = min(len(body), maxBody) + d.scroll = min(d.scroll, max(0, len(body)-d.height)) + visible := body[d.scroll : d.scroll+d.height] + + if len(body) > d.height { + hint += stDim.Render(" ↑↓ scroll") + } + + lines := []string{""} + for _, l := range visible { + lines = append(lines, " "+l) + } + lines = append(lines, "", " "+hint) + content := strings.Join(lines, "\n") + color := colAccent + if d.warn { + color = colChanged + } + return framed(d.title, content, w, len(lines)+2, color) +} + +func helpDialog() *dialog { + k := func(key, desc string) string { return stKey.Render(fit(key, 16)) + desc } + return &dialog{ + title: "Help", + lines: []string{ + stBold.Render("Browsing"), + k("↑↓ / j k", "move"), + k("← → / tab", "switch between categories and options"), + k("enter", "edit the selected option (booleans toggle)"), + k("space", "toggle a boolean / cycle through choices"), + k("+ / -", "increase / decrease numbers"), + k("r / del", "reset to the default (removes the line from the file)"), + k("/", "search option names and documentation"), + k("b", "open the key binding editor"), + k("shift+↑↓", "scroll the documentation (also ctrl+u / ctrl+d)"), + k("p", "hide options for other platforms"), + k("u / ctrl+z", "undo the last change"), + k("c", "show unsaved changes"), + k("ctrl+s", "validate with Ghostty, save and reload Ghostty's config"), + k("q / ctrl+c", "quit"), + "", + stBold.Render("Editors"), + k("enter", "apply the value"), + k("esc", "cancel (in list editors: done)"), + k("↑↓", "choose; in number fields: increase / decrease"), + k("tab", "complete the highlighted theme, font or action"), + "", + stBold.Render("Key bindings") + stDim.Render(" (b, or enter on keybind)"), + k("enter", "change the selected binding (also built-in ones)"), + k("a", "add a binding"), + k("d", "unbind: the key no longer does anything in Ghostty"), + k("r", "restore Ghostty's default for this key"), + k("ctrl+r", "in the binding form: record the key combination"), + k("/ c s", "filter · show changes only · sort by action or key"), + k("R", "edit the raw keybind entries"), + "", + stBold.Render("List editors") + stDim.Render(" (font-family, env, config-file, …)"), + k("a", "add an entry"), + k("enter / e", "edit the entry; on a built-in default: copy it"), + k("r", "edit the entry as raw text"), + k("d", "delete the entry"), + k("J / K", "move the entry down / up"), + k("v", "show or hide Ghostty's built-in defaults"), + "", + stBold.Render("Markers"), + stSet.Render("●") + " set in your config " + stChanged.Render("●") + " changed, not saved " + stChanged.Render("○") + " removed, not saved", + "", + "Comments, blank lines and the order of untouched lines in your config file are kept. " + + "Before the first save a backup is written to .bak.", + }, + keys: []dialogKey{{"esc", "Close"}}, + } +} diff --git a/internal/ui/docs.go b/internal/ui/docs.go new file mode 100644 index 0000000..2f9e727 --- /dev/null +++ b/internal/ui/docs.go @@ -0,0 +1,117 @@ +package ui + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// renderDoc reflows Ghostty's option documentation (lightly formatted +// Markdown) to width: paragraphs are re-wrapped, list items get a hanging +// indent, indented code examples are kept verbatim and `code` spans are +// highlighted. +func renderDoc(doc string, width int) string { + if width < 10 { + width = 10 + } + var out []string + var para []string + prefix, hang := "", "" + + flush := func() { + if len(para) == 0 { + return + } + text := strings.Join(para, " ") + wrapped := strings.Split(ansi.Wrap(text, width-ansi.StringWidth(prefix), ""), "\n") + inCode := false + for i, l := range wrapped { + p := hang + if i == 0 { + p = prefix + } + var styled string + styled, inCode = styleInline(l, inCode) + out = append(out, p+styled) + } + para, prefix, hang = nil, "", "" + } + + inBullet := false + bulletIndent := 0 + for _, line := range strings.Split(doc, "\n") { + trimmed := strings.TrimSpace(line) + indent := len(line) - len(strings.TrimLeft(line, " ")) + switch { + case trimmed == "": + flush() + inBullet = false + out = append(out, "") + case isBullet(trimmed): + flush() + inBullet = true + bulletIndent = indent + 2 + lead := strings.Repeat(" ", min(indent, 4)) + prefix = lead + "• " + hang = lead + " " + para = append(para, strings.TrimSpace(trimmed[2:])) + case inBullet && indent >= bulletIndent: + para = append(para, trimmed) + case indent >= 4 || strings.HasPrefix(line, "\t"): + flush() + inBullet = false + out = append(out, stCode.Render(ansi.Truncate(" "+trimmed, width, "…"))) + default: + if inBullet { + flush() + inBullet = false + } + para = append(para, trimmed) + } + } + flush() + + // Collapse repeated blank lines. + var res []string + for i, l := range out { + if l == "" && (i == 0 || out[i-1] == "") { + continue + } + res = append(res, l) + } + return strings.TrimRight(strings.Join(res, "\n"), "\n") +} + +func isBullet(s string) bool { + return strings.HasPrefix(s, "* ") || strings.HasPrefix(s, "- ") +} + +// styleInline highlights `code` spans. inCode carries an open span across +// wrapped lines. +func styleInline(line string, inCode bool) (string, bool) { + if !strings.Contains(line, "`") && !inCode { + return line, false + } + var b, seg strings.Builder + emit := func() { + if seg.Len() == 0 { + return + } + if inCode { + b.WriteString(stCode.Render(seg.String())) + } else { + b.WriteString(seg.String()) + } + seg.Reset() + } + for _, r := range line { + if r == '`' { + emit() + inCode = !inCode + continue + } + seg.WriteRune(r) + } + emit() + return b.String(), inCode +} diff --git a/internal/ui/editors.go b/internal/ui/editors.go new file mode 100644 index 0000000..c32f3f3 --- /dev/null +++ b/internal/ui/editors.go @@ -0,0 +1,435 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/bubbles/cursor" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + "ghosttyconf/internal/schema" +) + +// result is what an editor produces when it closes. +type result struct { + cancel bool + // values are the new raw values. nil (without cancel) removes the + // option from the config file, restoring the default. + values []string +} + +func cancelled() *result { return &result{cancel: true} } +func valuesResult(v ...string) *result { return &result{values: v} } + +// editor edits the value of one option (or one entry of a list option). +type editor interface { + Update(msg tea.Msg) (tea.Cmd, *result) + View(width, height int) string + Help() string +} + +func newInput(value, placeholder string) textinput.Model { + ti := textinput.New() + ti.Prompt = "› " + ti.PromptStyle = stAccent + ti.Placeholder = placeholder + ti.PlaceholderStyle = stDim + ti.Cursor.SetMode(cursor.CursorStatic) + ti.SetValue(value) + ti.CursorEnd() + ti.Focus() + return ti +} + +// scrollWindow returns the first visible row so that cursor stays visible. +func scrollWindow(cursor, top, height, n int) int { + if height <= 0 { + return 0 + } + if cursor < top { + top = cursor + } + if cursor >= top+height { + top = cursor - height + 1 + } + if top > n-height { + top = max(0, n-height) + } + return max(0, top) +} + +// moveCursor applies common list navigation keys. +func moveCursor(key string, cursor, n, page int) (int, bool) { + if n == 0 { + return 0, false + } + switch key { + case "up", "k", "ctrl+p": + cursor-- + case "down", "j", "ctrl+n": + cursor++ + case "pgup": + cursor -= page + case "pgdown": + cursor += page + case "home", "g": + cursor = 0 + case "end", "G": + cursor = n - 1 + default: + return cursor, false + } + return min(max(cursor, 0), n-1), true +} + +// --------------------------------------------------------------------------- +// Choice editor: booleans, enums and enums with a custom value. + +type choiceItem struct { + value string + label string + custom bool +} + +type choiceEditor struct { + opt *schema.Option + items []choiceItem + cursor int + top int + height int + current string + text *textEditor // active while typing a custom value +} + +func newChoiceEditor(o *schema.Option, current string) *choiceEditor { + e := &choiceEditor{opt: o, current: schema.Unquote(current)} + values := o.Values + if o.Kind == schema.KindBool { + values = []string{"true", "false"} + } + for _, v := range values { + e.items = append(e.items, choiceItem{value: v, label: v}) + } + if o.Kind == schema.KindChoice { + label := "Custom value…" + if e.current != "" && !contains(values, e.current) { + label = "Custom value: " + e.current + } + e.items = append(e.items, choiceItem{label: label, custom: true}) + } + e.cursor = 0 + effective := e.current + if effective == "" { + effective = o.Default() + } + for i, it := range e.items { + if it.value == effective || (it.custom && effective != "" && !contains(values, effective)) { + e.cursor = i + break + } + } + return e +} + +func (e *choiceEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if e.text != nil { + cmd, res := e.text.Update(msg) + if res != nil { + e.text = nil + if res.cancel { + return nil, nil + } + return nil, res + } + return cmd, nil + } + km, ok := msg.(tea.KeyMsg) + if !ok { + return nil, nil + } + key := km.String() + if c, moved := moveCursor(key, e.cursor, len(e.items), max(1, e.height-1)); moved { + e.cursor = c + return nil, nil + } + switch key { + case "esc", "q": + return nil, cancelled() + case "enter", " ": + it := e.items[e.cursor] + if it.custom { + v := "" + if !contains(e.opt.Values, e.current) { + v = e.current + } + e.text = newTextEditor(e.opt, v) + return nil, nil + } + return nil, valuesResult(it.value) + } + return nil, nil +} + +func (e *choiceEditor) View(width, height int) string { + if e.text != nil { + return e.text.View(width, height) + } + e.height = height + e.top = scrollWindow(e.cursor, e.top, height, len(e.items)) + var lines []string + def := e.opt.Default() + for i := e.top; i < len(e.items) && len(lines) < height; i++ { + it := e.items[i] + sel := i == e.cursor + labelSt := lipgloss.NewStyle() + if sel { + labelSt = stBold + } + segs := []seg{cursorSeg(sel), styled(fit(it.label, 28), labelSt), plain(" ")} + if !it.custom && it.value == e.current { + segs = append(segs, styled("● current ", stSet)) + } + if !it.custom && it.value == def { + segs = append(segs, styled("default", stDim)) + } + lines = append(lines, renderRow(segs, width, sel)) + } + return strings.Join(lines, "\n") +} + +func (e *choiceEditor) Help() string { + if e.text != nil { + return e.text.Help() + } + return "↑↓ choose · enter select · esc cancel" +} + +// --------------------------------------------------------------------------- +// Flags editor: packed structs such as shell-integration-features. + +type flagsEditor struct { + opt *schema.Option + state map[string]bool + def map[string]bool + cursor int +} + +func newFlagsEditor(o *schema.Option, current string) *flagsEditor { + return &flagsEditor{opt: o, state: o.ParseFlags(current), def: o.ParseFlags("")} +} + +func (e *flagsEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + km, ok := msg.(tea.KeyMsg) + if !ok { + return nil, nil + } + key := km.String() + if c, moved := moveCursor(key, e.cursor, len(e.opt.Flags), 5); moved { + e.cursor = c + return nil, nil + } + switch key { + case "esc", "q": + return nil, cancelled() + case " ", "x": + f := e.opt.Flags[e.cursor] + e.state[f] = !e.state[f] + case "a": + for _, f := range e.opt.Flags { + e.state[f] = true + } + case "n": + for _, f := range e.opt.Flags { + e.state[f] = false + } + case "d": + for _, f := range e.opt.Flags { + e.state[f] = e.def[f] + } + case "enter": + return nil, valuesResult(e.opt.FormatFlags(e.state)) + } + return nil, nil +} + +func (e *flagsEditor) View(width, height int) string { + var lines []string + for i, f := range e.opt.Flags { + box := styled("[ ]", stDim) + if e.state[f] { + box = styled("[✓]", stSet) + } + segs := []seg{cursorSeg(i == e.cursor), box, plain(" " + fit(f, 22) + " ")} + if e.state[f] != e.def[f] { + segs = append(segs, styled("changed from default", stChanged)) + } + lines = append(lines, renderRow(segs, width, i == e.cursor)) + } + lines = append(lines, "", stDim.Render("Result: ")+stCode.Render(e.opt.FormatFlags(e.state))) + return strings.Join(lines, "\n") +} + +func (e *flagsEditor) Help() string { + return "↑↓ move · space toggle · a all · n none · d defaults · enter apply · esc cancel" +} + +// --------------------------------------------------------------------------- +// Text editor with validation, used for numbers, colors, durations, paths +// and free text. + +type textEditor struct { + opt *schema.Option + input textinput.Model + err string + // item is set when editing one entry of a list option: an empty value + // then means "remove this entry" rather than "reset to default". + item bool +} + +func newTextEditor(o *schema.Option, value string) *textEditor { + placeholder := o.Default() + if placeholder == "" { + placeholder = o.Hint + } + return &textEditor{opt: o, input: newInput(value, placeholder)} +} + +func (e *textEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if km, ok := msg.(tea.KeyMsg); ok { + switch km.String() { + case "esc": + return nil, cancelled() + case "enter": + v := strings.TrimSpace(e.input.Value()) + if v == "" { + return nil, &result{} + } + if err := e.opt.Validate(v); err != nil { + e.err = err.Error() + return nil, nil + } + return nil, valuesResult(v) + case "up", "down": + if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric { + delta := 1 + if km.String() == "down" { + delta = -1 + } + if v, ok := stepValue(e.opt, e.input.Value(), delta); ok { + e.input.SetValue(v) + e.input.CursorEnd() + } + return nil, nil + } + } + } + var cmd tea.Cmd + e.input, cmd = e.input.Update(msg) + e.err = "" + return cmd, nil +} + +func (e *textEditor) View(width, height int) string { + e.input.Width = max(10, width-4) + var lines []string + lines = append(lines, e.input.View(), "") + + v := strings.TrimSpace(e.input.Value()) + switch { + case e.err != "": + lines = append(lines, stError.Render("✗ "+e.err)) + case v == "" && e.item: + lines = append(lines, stDim.Render("Empty: the entry will be removed.")) + case v == "": + lines = append(lines, stDim.Render("Empty: the option will be reset to its default.")) + default: + if err := e.opt.Validate(v); err != nil { + lines = append(lines, stError.Render("✗ "+err.Error())) + } else { + lines = append(lines, stOK.Render("✓ valid")) + } + } + + if e.opt.Kind == schema.KindColor || e.opt.Kind == schema.KindPalette || e.opt.Kind == schema.KindColorList { + var sw []string + for _, part := range strings.Split(v, ",") { + if s := swatch(part); s != "" { + sw = append(sw, s+s+s) + } + } + if len(sw) > 0 { + lines = append(lines, "", strings.Join(sw, " ")+" "+stDim.Render("preview")) + } + } + if e.opt.Hint != "" { + lines = append(lines, "", stDim.Render("Format: ")+e.opt.Hint) + } + if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric { + lines = append(lines, "", stDim.Render("Use ↑/↓ to increase or decrease the value.")) + } + return strings.Join(lines, "\n") +} + +func (e *textEditor) Help() string { + return "type to edit · enter apply · esc cancel" +} + +// stepValue increments or decrements numeric values, keeping a percentage +// suffix for metric modifiers. +func stepValue(o *schema.Option, value string, delta int) (string, bool) { + v := strings.TrimSpace(schema.Unquote(value)) + if v == "" { + v = o.Default() + } + pct := strings.HasSuffix(v, "%") + v = strings.TrimSuffix(v, "%") + if v == "" { + v = "0" + } + var f float64 + if _, err := fmt.Sscanf(v, "%g", &f); err != nil { + return "", false + } + step := 1.0 + if o.Kind == schema.KindFloat { + switch { + case o.Max != nil && *o.Max <= 1: + step = 0.05 + case f < 1 && f > -1 && o.Key != "font-size": + step = 0.1 + case o.Key == "font-size": + step = 0.5 + } + } + f += float64(delta) * step + if o.Min != nil && f < *o.Min { + f = *o.Min + } + if o.Max != nil && f > *o.Max { + f = *o.Max + } + var s string + if o.Kind == schema.KindFloat { + s = strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), ".") + if s == "" || s == "-" { + s = "0" + } + } else { + s = fmt.Sprintf("%d", int64(f)) + } + if pct { + s += "%" + } + return s, true +} + +func contains(list []string, v string) bool { + for _, s := range list { + if s == v { + return true + } + } + return false +} diff --git a/internal/ui/keybind.go b/internal/ui/keybind.go new file mode 100644 index 0000000..09dd2b8 --- /dev/null +++ b/internal/ui/keybind.go @@ -0,0 +1,342 @@ +package ui + +import ( + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/keybind" + "ghosttyconf/internal/schema" +) + +const triggerPlaceholder = "e.g. super+shift+t, ctrl+a>n, global:ctrl+backquote" + +// keybindEditor edits a single "trigger=action" binding with a separate +// field for each half, key recording for the trigger and completion for +// action names. +type keybindEditor struct { + trigger textinput.Model + action textinput.Model + focus int // 0 = trigger, 1 = action + actions []ghostty.Action + matches []ghostty.Action + cursor int + top int + err string + + // conflict describes an existing binding of a trigger ("" if none). + conflict func(trigger string) string + + recording bool + recorded []string + beforeRecord string + kittyReply bool // the terminal confirmed the kitty keyboard protocol +} + +func newKeybindEditor(value string, actions []ghostty.Action) *keybindEditor { + t, a := schema.SplitKeybind(schema.Unquote(value)) + e := &keybindEditor{ + trigger: newInput(t, triggerPlaceholder), + action: newInput(a, "e.g. new_tab, goto_split:right, text:\\x15"), + actions: actions, + } + e.trigger.Prompt = "Trigger › " + e.action.Prompt = "Action › " + if t != "" { + e.focus = 1 + e.trigger.Blur() + } else { + e.action.Blur() + } + e.refilter() + return e +} + +// capturing reports whether all keys must go to this editor (recording). +func (e *keybindEditor) capturing() bool { return e.recording } + +func (e *keybindEditor) refilter() { + name := strings.ToLower(keybind.ActionName(e.action.Value())) + var prefix, rest []ghostty.Action + for _, a := range e.actions { + switch { + case strings.HasPrefix(a.Name, name): + prefix = append(prefix, a) + case strings.Contains(a.Name, name) || (name != "" && strings.Contains(strings.ToLower(a.Summary), name)): + rest = append(rest, a) + } + } + e.matches = append(prefix, rest...) + e.cursor, e.top = 0, 0 + for i, a := range e.matches { + if a.Name == name { + e.cursor = i + break + } + } +} + +func (e *keybindEditor) setFocus(f int) { + e.focus = f + if f == 0 { + e.trigger.Focus() + e.action.Blur() + } else { + e.action.Focus() + e.trigger.Blur() + } +} + +func (e *keybindEditor) startRecording() tea.Cmd { + e.setFocus(0) + e.recording = true + e.recorded = nil + e.beforeRecord = e.trigger.Value() + e.trigger.SetValue("") + e.trigger.Placeholder = "waiting for keys…" + e.err = "" + return enableKeyCapture() +} + +func (e *keybindEditor) stopRecording(keep bool) tea.Cmd { + e.recording = false + e.trigger.Placeholder = triggerPlaceholder + if !keep || len(e.recorded) == 0 { + e.trigger.SetValue(e.beforeRecord) + } else { + e.trigger.SetValue(strings.Join(e.recorded, ">")) + e.setFocus(1) + } + e.trigger.CursorEnd() + return disableKeyCapture() +} + +// updateRecording handles input while recording: every key combination is +// appended to the trigger; plain Enter finishes, plain Esc cancels and plain +// Backspace removes the last combination. +func (e *keybindEditor) updateRecording(msg tea.Msg) tea.Cmd { + var combo keybind.Combo + var ok bool + if raw, isRaw := rawSequence(msg); isRaw { + if keybind.IsKittyReply(raw) { + e.kittyReply = true + return nil + } + combo, ok = keybind.DecodeCSI(raw) + } else if km, isKey := msg.(tea.KeyMsg); isKey { + combo, ok = keybind.DecodeKeyName(km.String()) + } else { + return nil + } + if !ok || combo.Modifier { + return nil + } + if combo.Plain() { + switch combo.Key { + case "enter": + return e.stopRecording(true) + case "escape": + return e.stopRecording(false) + case "backspace": + if len(e.recorded) > 0 { + e.recorded = e.recorded[:len(e.recorded)-1] + } + e.trigger.SetValue(strings.Join(e.recorded, ">")) + return nil + } + } + e.recorded = append(e.recorded, combo.String()) + e.trigger.SetValue(strings.Join(e.recorded, ">")) + return nil +} + +func (e *keybindEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if e.recording { + return e.updateRecording(msg), nil + } + if km, ok := msg.(tea.KeyMsg); ok { + key := km.String() + switch key { + case "esc": + return nil, cancelled() + case "ctrl+r": + return e.startRecording(), nil + case "enter": + t := strings.TrimSpace(e.trigger.Value()) + a := strings.TrimSpace(e.action.Value()) + if t == "" && a == "" { + return nil, &result{} + } + if t == "clear" && a == "" { + return nil, valuesResult("clear") + } + if t == "" { + e.err = "the trigger is empty" + e.setFocus(0) + return nil, nil + } + if a == "" { + e.err = "the action is empty" + e.setFocus(1) + return nil, nil + } + return nil, valuesResult(t + "=" + a) + case "shift+tab": + e.setFocus(0) + return nil, nil + case "tab": + if e.focus == 0 { + e.setFocus(1) + return nil, nil + } + if len(e.matches) > 0 { + name := e.matches[e.cursor].Name + _, param, hasParam := strings.Cut(e.action.Value(), ":") + v := name + if hasParam { + v += ":" + param + } + e.action.SetValue(v) + e.action.CursorEnd() + e.refilter() + } + return nil, nil + case "up", "down", "pgup", "pgdown": + if e.focus == 1 { + if key == "up" && e.cursor == 0 { + e.setFocus(0) + return nil, nil + } + e.cursor, _ = moveCursor(key, e.cursor, len(e.matches), 5) + return nil, nil + } + if key == "down" { + e.setFocus(1) + } + return nil, nil + } + } + var cmd tea.Cmd + if e.focus == 0 { + e.trigger, cmd = e.trigger.Update(msg) + } else { + before := e.action.Value() + e.action, cmd = e.action.Update(msg) + if e.action.Value() != before { + e.refilter() + } + } + e.err = "" + return cmd, nil +} + +// triggerStatus validates the trigger and reports conflicts. +func (e *keybindEditor) triggerStatus() []string { + t := strings.TrimSpace(e.trigger.Value()) + if t == "" || t == "clear" { + return nil + } + if _, err := keybind.Normalize(t); err != nil { + return []string{stError.Render("✗ " + err.Error())} + } + if e.conflict != nil { + if c := e.conflict(t); c != "" { + return []string{stChanged.Render("⚠ " + c)} + } + } + return []string{stOK.Render("✓ trigger is free")} +} + +func (e *keybindEditor) actionStatus() []string { + name := keybind.ActionName(e.action.Value()) + if name == "" || len(e.actions) == 0 { + return nil + } + for _, a := range e.actions { + if a.Name == name { + return nil + } + } + return []string{stChanged.Render("⚠ unknown action " + name)} +} + +func (e *keybindEditor) View(width, height int) string { + e.trigger.Width = max(10, width-14) + e.action.Width = max(10, width-14) + + var lines []string + if e.recording { + lines = append(lines, + stRecording.Render(" ● REC ")+" "+stBold.Render("Press the key combination now."), + "", + e.trigger.View(), + "", + stDim.Render("enter finish · esc cancel · backspace remove last key"), + stDim.Render("Press several combinations in a row to record a sequence (ctrl+a>n)."), + "", + stDim.Render("Keys that Ghostty or macOS already use (e.g. a current Ghostty"), + stDim.Render("shortcut) never reach this program: type those instead."), + ) + if !e.kittyReply { + lines = append(lines, "", stChanged.Render("The terminal did not confirm the kitty keyboard protocol;"), + stChanged.Render("super/cmd combinations may not be recorded.")) + } + return strings.Join(lines, "\n") + } + + lines = append(lines, e.trigger.View()) + lines = append(lines, e.triggerStatus()...) + lines = append(lines, e.action.View()) + lines = append(lines, e.actionStatus()...) + lines = append(lines, "") + if e.err != "" { + lines = append(lines, stError.Render("✗ "+e.err), "") + } + if e.focus == 0 { + lines = append(lines, + stKey.Render("ctrl+r")+" record the keys instead of typing them", + "", + stDim.Render("Modifiers: ")+"super (cmd), ctrl, alt (opt), shift", + stDim.Render("Keys: ")+"a, 1, ,, arrow_up, page_down, enter, f1, backquote, …", + stDim.Render("Sequences: ")+"ctrl+a>n (press ctrl+a, then n)", + stDim.Render("Prefixes: ")+"global:, all:, unconsumed:, performable:", + ) + return strings.Join(lines, "\n") + } + if len(e.actions) == 0 { + lines = append(lines, stDim.Render("Action list unavailable (ghostty binary not found).")) + return strings.Join(lines, "\n") + } + lines = append(lines, stDim.Render("Actions (tab to complete, add :param where needed):")) + listH := min(8, max(3, height-len(lines)-6)) + e.top = scrollWindow(e.cursor, e.top, listH, len(e.matches)) + for i := e.top; i < len(e.matches) && i < e.top+listH; i++ { + a := e.matches[i] + segs := []seg{cursorSeg(i == e.cursor), plain(fit(a.Name, 30) + " "), styled(a.Summary, stDim)} + lines = append(lines, renderRow(segs, width, i == e.cursor)) + } + if len(e.matches) == 0 { + lines = append(lines, stDim.Render(" no matching action")) + } + if len(e.matches) > 0 { + doc := e.matches[e.cursor].Doc + if rest := height - len(lines) - 1; rest > 2 { + lines = append(lines, "") + docLines := strings.Split(renderDoc(doc, width), "\n") + if len(docLines) > rest { + docLines = docLines[:rest] + } + lines = append(lines, docLines...) + } + } + return strings.Join(lines, "\n") +} + +func (e *keybindEditor) Help() string { + if e.recording { + return "recording: press keys · enter finish · esc cancel" + } + return "ctrl+r record keys · tab next field / complete · ↑↓ choose action · enter save · esc cancel" +} diff --git a/internal/ui/keybinds.go b/internal/ui/keybinds.go new file mode 100644 index 0000000..b7a3509 --- /dev/null +++ b/internal/ui/keybinds.go @@ -0,0 +1,472 @@ +package ui + +import ( + "fmt" + "sort" + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/keybind" + "ghosttyconf/internal/schema" +) + +// keybindManager shows the effective key bindings — Ghostty's defaults +// merged with the user's keybind entries — and lets the user change, +// unbind, restore and add bindings. Edits are translated into the minimal +// set of keybind entries. +type keybindManager struct { + opt *schema.Option + set *keybind.Set + original []string + defaults []string + actions []ghostty.Action + summaries map[string]string + + rows []keybind.Binding + cursor int + top int + height int + filter textinput.Model + filtering bool + changesOnly bool + byTrigger bool + msg string + msgStyle lipgloss.Style + + child editor + childFor *keybind.Binding // binding being edited; nil when adding + childRaw bool // child is the raw entry list + newItem func(string) editor +} + +func newKeybindManager(o *schema.Option, values []string, actions []ghostty.Action, newItem func(string) editor) *keybindManager { + m := &keybindManager{ + opt: o, + original: append([]string(nil), values...), + defaults: o.DefaultList(), + actions: actions, + summaries: map[string]string{}, + newItem: newItem, + filter: newInput("", "filter by key, action or description"), + } + m.filter.Prompt = "/ " + m.filter.Blur() + for _, a := range actions { + m.summaries[a.Name] = a.Summary + } + m.set = keybind.NewSet(m.defaults, values) + m.refresh("") + return m +} + +func (m *keybindManager) capturing() bool { + c, ok := m.child.(interface{ capturing() bool }) + return ok && c.capturing() +} + +// refresh recomputes the visible rows and keeps the cursor on norm (or on +// the current row when norm is empty). +func (m *keybindManager) refresh(norm string) { + if norm == "" && m.cursor < len(m.rows) { + norm = m.rows[m.cursor].Norm + } + query := strings.TrimSpace(m.filter.Value()) + terms := strings.Fields(strings.ToLower(query)) + // A query that is a valid trigger ("cmd+d") also finds that exact + // binding, whatever spelling it uses. + exact, err := keybind.Normalize(query) + if err != nil || query == "" { + exact = "" + } + var rows []keybind.Binding + for _, b := range m.set.Bindings() { + if m.changesOnly && b.Source == keybind.Default && !b.InConfig { + continue + } + if exact != "" && b.Norm == exact { + rows = append(rows, b) + continue + } + hay := strings.ToLower(b.Trigger + " " + b.Action + " " + b.Source.String() + " " + m.summaries[keybind.ActionName(b.Action)]) + ok := true + for _, t := range terms { + if !strings.Contains(hay, t) { + ok = false + break + } + } + if ok { + rows = append(rows, b) + } + } + sort.SliceStable(rows, func(i, j int) bool { + a, b := rows[i], rows[j] + if (a.Norm == exact) != (b.Norm == exact) { + return a.Norm == exact + } + if m.byTrigger { + return a.Norm < b.Norm + } + if a.Action != b.Action { + return a.Action < b.Action + } + return a.Norm < b.Norm + }) + m.rows = rows + m.cursor = min(m.cursor, max(0, len(rows)-1)) + for i, b := range rows { + if b.Norm == norm { + m.cursor = i + break + } + } +} + +func (m *keybindManager) selected() *keybind.Binding { + if m.cursor < len(m.rows) { + b := m.rows[m.cursor] + return &b + } + return nil +} + +func (m *keybindManager) changed() bool { + return !equalStrings(m.set.Values(), m.original) +} + +func (m *keybindManager) setMsg(s string, st lipgloss.Style) { m.msg, m.msgStyle = s, st } + +func (m *keybindManager) openEditor(b *keybind.Binding) { + value := "" + if b != nil { + value = b.Trigger + "=" + b.Action + } + e := newKeybindEditor(value, m.actions) + if b == nil { + e.setFocus(0) + } + e.conflict = func(trigger string) string { + n, err := keybind.Normalize(trigger) + if err != nil || (b != nil && n == b.Norm) { + return "" + } + if cur, ok := m.set.Lookup(n); ok { + return fmt.Sprintf("already bound to %s (%s); saving replaces that binding", cur.Action, cur.Source) + } + return "" + } + m.child, m.childFor, m.childRaw = e, b, false +} + +func (m *keybindManager) Update(msg tea.Msg) (tea.Cmd, *result) { + if m.child != nil { + cmd, res := m.child.Update(msg) + if res != nil { + m.finishChild(res) + } + return cmd, nil + } + km, ok := msg.(tea.KeyMsg) + if !ok { + return nil, nil + } + key := km.String() + + if m.filtering { + switch key { + case "esc": + m.filter.SetValue("") + m.filtering = false + m.filter.Blur() + m.refresh("") + case "enter", "down", "tab": + m.filtering = false + m.filter.Blur() + default: + var cmd tea.Cmd + before := m.filter.Value() + m.filter, cmd = m.filter.Update(km) + if m.filter.Value() != before { + m.cursor, m.top = 0, 0 + m.refresh("") + } + return cmd, nil + } + return nil, nil + } + + if c, moved := moveCursor(key, m.cursor, len(m.rows), max(1, m.height-1)); moved { + m.cursor = c + return nil, nil + } + m.msg = "" + b := m.selected() + switch key { + case "esc", "q": + if m.filter.Value() != "" && key == "esc" { + m.filter.SetValue("") + m.refresh("") + return nil, nil + } + if !m.changed() { + return nil, cancelled() + } + v := m.set.Values() + if len(v) == 0 { + return nil, &result{} + } + return nil, valuesResult(v...) + case "/": + m.filtering = true + return m.filter.Focus(), nil + case "enter", "e": + if b != nil { + m.openEditor(b) + } + case "a", "n", "+", "insert": + m.openEditor(nil) + case "d", "x", "delete", "backspace": + if b == nil { + break + } + if b.Source == keybind.Unbound { + m.setMsg(b.Trigger+" is already unbound. Press r to restore it.", stDim) + break + } + m.set.Unbind(*b) + m.setMsg("Unbound "+b.Trigger+".", stChanged) + m.refresh(b.Norm) + case "r": + if b == nil { + break + } + m.set.Restore(*b) + if b.Default != "" { + m.setMsg("Restored "+b.Trigger+" → "+b.Default+".", stChanged) + } else { + m.setMsg("Removed "+b.Trigger+" (it has no default binding).", stChanged) + } + m.refresh(b.Norm) + case "c": + m.changesOnly = !m.changesOnly + m.refresh("") + case "s": + m.byTrigger = !m.byTrigger + m.refresh("") + case "R": + le := newListEditor(m.opt, m.set.Values(), m.newItem) + m.child, m.childFor, m.childRaw = le, nil, true + } + return nil, nil +} + +func (m *keybindManager) finishChild(res *result) { + defer func() { m.child, m.childFor, m.childRaw = nil, nil, false }() + if res.cancel { + return + } + if m.childRaw { + m.set = keybind.NewSet(m.defaults, res.values) + m.refresh("") + m.setMsg("Updated the raw keybind entries.", stChanged) + return + } + if len(res.values) == 0 { + return + } + v := res.values[0] + if v == "clear" { + m.set = keybind.NewSet(m.defaults, append(m.set.Values(), "clear")) + m.refresh("") + m.setMsg("Added keybind = clear: all built-in bindings are removed.", stChanged) + return + } + if err := m.set.Change(m.childFor, v); err != nil { + m.setMsg("Not changed: "+err.Error(), stError) + return + } + trigger, action := keybind.Split(v) + norm := keybind.NormalizeLoose(trigger) + if m.changesOnly || m.filter.Value() != "" { + // Make sure the edited binding stays visible. + m.changesOnly = false + m.filter.SetValue("") + } + m.refresh(norm) + m.setMsg("Bound "+trigger+" → "+action+".", stChanged) +} + +func (m *keybindManager) View(width, height int) string { + if m.child != nil { + title := "New binding" + switch { + case m.childRaw: + title = "Raw keybind entries" + case m.childFor != nil: + title = "Change " + m.childFor.Trigger + if m.childFor.Source == keybind.Default { + title += stDim.Render(" (built-in binding)") + } + } + return stBold.Render(title) + "\n\n" + m.child.View(width, height-2) + } + + var lines []string + counts := map[keybind.Source]int{} + for _, b := range m.set.Bindings() { + counts[b.Source]++ + } + summary := fmt.Sprintf("%d active · %s · %s · %s", + counts[keybind.Default]+counts[keybind.Changed]+counts[keybind.Custom], + stChanged.Render(fmt.Sprintf("%d changed", counts[keybind.Changed])), + stSet.Render(fmt.Sprintf("%d custom", counts[keybind.Custom])), + stError.Render(fmt.Sprintf("%d unbound", counts[keybind.Unbound]))) + view := "all" + if m.changesOnly { + view = "changes only" + } + sortBy := "action" + if m.byTrigger { + sortBy = "key" + } + lines = append(lines, summary+stDim.Render(fmt.Sprintf(" showing %s, sorted by %s", view, sortBy))) + if m.set.HasClear() { + lines = append(lines, stChanged.Render("Your config contains keybind = clear: built-in bindings before it are removed.")) + } + if m.filtering || m.filter.Value() != "" { + m.filter.Width = max(10, width-4) + lines = append(lines, m.filter.View()) + } + lines = append(lines, "") + + trigW := 12 + for _, b := range m.rows { + trigW = max(trigW, ansi.StringWidth(b.Trigger)) + } + trigW = min(trigW+2, width*40/100) + srcW := 9 + actW := max(10, width-trigW-srcW-3) + lines = append(lines, stDim.Render(" "+fit("Key", trigW)+fit("Action", actW)+" Source")) + + detailH := 3 + listH := max(3, height-len(lines)-detailH-1) + m.height = listH + m.top = scrollWindow(m.cursor, m.top, listH, len(m.rows)) + if len(m.rows) == 0 { + lines = append(lines, stDim.Render(" No bindings match.")) + } + for i := m.top; i < len(m.rows) && i < m.top+listH; i++ { + lines = append(lines, renderRow(m.rowSegs(m.rows[i], i == m.cursor, trigW, actW), width, i == m.cursor)) + } + for len(lines) < height-detailH { + lines = append(lines, "") + } + lines = append(lines, m.detail(width)...) + return strings.Join(lines, "\n") +} + +func (m *keybindManager) rowSegs(b keybind.Binding, selected bool, trigW, actW int) []seg { + action := b.Action + if len(b.Chain) > 0 { + action += " + " + strings.Join(b.Chain, " + ") + } + actSt := lipgloss.NewStyle() + var src seg + switch b.Source { + case keybind.Default: + src = styled("default", stDim) + actSt = stDim + if b.InConfig { + actSt = lipgloss.NewStyle() + } + case keybind.Changed: + src = styled("changed", stChanged) + case keybind.Custom: + src = styled("custom", stSet) + case keybind.Unbound: + src = styled("unbound", stError) + actSt = stDim.Strikethrough(true) + } + return []seg{ + cursorSeg(selected), + styled(fit(b.Trigger, trigW), stKey), + styled(fit(action, actW), actSt), + plain(" "), + src, + } +} + +func (m *keybindManager) detail(width int) []string { + b := m.selected() + var lines []string + if m.msg != "" { + lines = append(lines, m.msgStyle.Render(ansi.Truncate(m.msg, width, "…"))) + } else { + lines = append(lines, "") + } + if b == nil { + return append(lines, "", "") + } + var info string + switch b.Source { + case keybind.Default: + info = "Ghostty's built-in binding." + case keybind.Changed: + info = "Changed in your config. Ghostty's default: " + b.Default + " (press r to restore)." + case keybind.Custom: + info = "Added in your config." + case keybind.Unbound: + info = "Removed in your config. Press r to restore " + b.Default + "." + } + sum := m.summaries[keybind.ActionName(b.Action)] + lines = append(lines, + stDim.Render(ansi.Truncate(info, width, "…")), + ansi.Truncate(stKey.Render(keybind.ActionName(b.Action))+" "+sum, width, "…")) + return lines +} + +// docFor shows the documentation of the selected binding's action and all +// keys bound to it. +func (m *keybindManager) docFor() (id, title, body string, ok bool) { + b := m.selected() + if m.child != nil || b == nil { + return "", "", "", false + } + name := keybind.ActionName(b.Action) + var doc string + for _, a := range m.actions { + if a.Name == name { + doc = a.Doc + break + } + } + if doc == "" { + doc = "No documentation available for this action." + } + var keys []string + for _, other := range m.set.Bindings() { + if keybind.ActionName(other.Action) == name && other.Source != keybind.Unbound { + keys = append(keys, "* `"+other.Trigger+"` → `"+other.Action+"` ("+other.Source.String()+")") + } + } + body = doc + if len(keys) > 0 { + body += "\n\nKeys bound to " + name + ":\n\n" + strings.Join(keys, "\n") + } + return fmt.Sprintf("action:%s#%d", name, len(m.set.Values())) + strings.Join(m.set.Values(), "\x00"), name, body, true +} + +func (m *keybindManager) Help() string { + if m.child != nil { + return m.child.Help() + } + if m.filtering { + return "type to filter · enter/↓ results · esc clear" + } + return "enter change · a add · d unbind · r restore · / filter · c changes only · s sort · R raw · esc done" +} diff --git a/internal/ui/listedit.go b/internal/ui/listedit.go new file mode 100644 index 0000000..7662455 --- /dev/null +++ b/internal/ui/listedit.go @@ -0,0 +1,243 @@ +package ui + +import ( + "fmt" + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/schema" +) + +// listEditor edits repeatable options (font-family, keybind, env, …). The +// entries from the config file can be added, edited, removed and +// reordered; Ghostty's built-in default entries are shown read-only and can +// be copied as a starting point. +type listEditor struct { + opt *schema.Option + items []string + defaults []string + showDefaults bool + cursor int + top int + height int + changed bool + + child editor + childIndex int // index being edited, or -1 for a new entry + childTitle string + newItem func(value string) editor +} + +func newListEditor(o *schema.Option, items []string, newItem func(string) editor) *listEditor { + return &listEditor{ + opt: o, + items: append([]string(nil), items...), + defaults: o.DefaultList(), + newItem: newItem, + } +} + +func (e *listEditor) capturing() bool { + c, ok := e.child.(interface{ capturing() bool }) + return ok && c.capturing() +} + +func (e *listEditor) rows() int { + n := len(e.items) + if e.showDefaults { + n += len(e.defaults) + } + return n +} + +func (e *listEditor) onDefault() (string, bool) { + if e.cursor >= len(e.items) { + return e.defaults[e.cursor-len(e.items)], true + } + return "", false +} + +func (e *listEditor) startChild(index int, value, title string, raw bool) { + e.childIndex = index + e.childTitle = title + if raw { + t := newTextEditor(e.opt, value) + t.item = true + e.child = t + } else { + e.child = e.newItem(value) + } +} + +func (e *listEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if e.child != nil { + cmd, res := e.child.Update(msg) + if res != nil { + e.finishChild(res) + } + return cmd, nil + } + km, ok := msg.(tea.KeyMsg) + if !ok { + return nil, nil + } + key := km.String() + if c, moved := moveCursor(key, e.cursor, e.rows(), max(1, e.height-1)); moved { + e.cursor = c + return nil, nil + } + def, isDefault := "", false + if e.rows() > 0 { + def, isDefault = e.onDefault() + } + switch key { + case "esc", "q": + if !e.changed { + return nil, cancelled() + } + if len(e.items) == 0 { + return nil, &result{} + } + return nil, valuesResult(e.items...) + case "a", "n", "insert", "+": + e.startChild(-1, "", "New entry", false) + case "enter", "e": + switch { + case e.rows() == 0: + e.startChild(-1, "", "New entry", false) + case isDefault: + e.startChild(-1, def, "New entry (copied from default)", false) + default: + e.startChild(e.cursor, e.items[e.cursor], "Edit entry", false) + } + case "r": + if e.rows() > 0 && !isDefault { + e.startChild(e.cursor, e.items[e.cursor], "Edit entry (raw text)", true) + } + case "d", "x", "delete", "backspace": + if e.rows() == 0 { + break + } + if isDefault { + if e.opt.Kind == schema.KindKeybind { + trigger, _ := schema.SplitKeybind(def) + e.items = append(e.items, trigger+"=unbind") + e.changed = true + e.cursor = len(e.items) - 1 + } + break + } + e.items = append(e.items[:e.cursor], e.items[e.cursor+1:]...) + e.changed = true + e.cursor = min(e.cursor, max(0, e.rows()-1)) + case "K", "shift+up": + if !isDefault && e.cursor > 0 && e.cursor < len(e.items) { + e.items[e.cursor-1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor-1] + e.cursor-- + e.changed = true + } + case "J", "shift+down": + if !isDefault && e.cursor < len(e.items)-1 { + e.items[e.cursor+1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor+1] + e.cursor++ + e.changed = true + } + case "v": + if len(e.defaults) > 0 { + e.showDefaults = !e.showDefaults + e.cursor = min(e.cursor, max(0, e.rows()-1)) + } + } + return nil, nil +} + +func (e *listEditor) finishChild(res *result) { + defer func() { e.child = nil }() + if res.cancel { + return + } + value := "" + if len(res.values) > 0 { + value = res.values[0] + } + switch { + case e.childIndex < 0 && value == "": + return + case e.childIndex < 0: + e.items = append(e.items, value) + e.cursor = len(e.items) - 1 + case value == "": + e.items = append(e.items[:e.childIndex], e.items[e.childIndex+1:]...) + e.cursor = min(e.childIndex, max(0, e.rows()-1)) + default: + e.items[e.childIndex] = value + } + e.changed = true +} + +func (e *listEditor) View(width, height int) string { + if e.child != nil { + title := stBold.Render(e.childTitle) + return title + "\n\n" + e.child.View(width, height-2) + } + var lines []string + if len(e.items) == 0 { + lines = append(lines, stDim.Render("No entries in your config. Press a to add one.")) + } + e.height = height - 2 + listH := e.height + e.top = scrollWindow(e.cursor, e.top, listH, e.rows()) + for i := e.top; i < e.rows() && len(lines) < listH; i++ { + isDefault := i >= len(e.items) + var v string + if isDefault { + if i == len(e.items) { + if len(lines) > 0 { + lines = append(lines, "") + } + lines = append(lines, stDim.Render(fmt.Sprintf("Built-in defaults (%d, read-only):", len(e.defaults)))) + } + v = e.defaults[i-len(e.items)] + } else { + v = e.items[i] + } + segs := append([]seg{cursorSeg(i == e.cursor)}, e.itemSegs(v, isDefault)...) + lines = append(lines, renderRow(segs, width, i == e.cursor)) + } + if len(e.defaults) > 0 && !e.showDefaults { + lines = append(lines, "", stDim.Render(fmt.Sprintf("Ghostty has %d built-in default entries. Press v to show them.", len(e.defaults)))) + } + if e.changed { + lines = append(lines, "", stChanged.Render("Modified. Press esc to keep the changes.")) + } + return strings.Join(lines, "\n") +} + +func (e *listEditor) itemSegs(v string, isDefault bool) []seg { + if isDefault { + return []seg{styled(v, stDim)} + } + switch e.opt.Kind { + case schema.KindKeybind: + trigger, action := schema.SplitKeybind(v) + if action == "" { + return []seg{plain(v)} + } + return []seg{styled(trigger, stKey), styled(" → ", stDim), plain(action)} + case schema.KindColor: + return []seg{rawSeg(swatch(v)), plain(" " + v)} + } + return []seg{plain(v)} +} + +func (e *listEditor) Help() string { + if e.child != nil { + return e.child.Help() + } + h := "a add · enter edit · r raw · d delete · J/K move · esc done" + if len(e.defaults) > 0 { + h += " · v defaults" + } + return h +} diff --git a/internal/ui/palette.go b/internal/ui/palette.go new file mode 100644 index 0000000..625a891 --- /dev/null +++ b/internal/ui/palette.go @@ -0,0 +1,161 @@ +package ui + +import ( + "fmt" + "sort" + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/schema" +) + +// paletteEditor shows all 256 palette colors and edits individual +// overrides (written as "palette = N=COLOR"). +type paletteEditor struct { + opt *schema.Option + defaults [256]string + overrides map[int]string + extra []string // entries that could not be parsed; kept as is + cursor int + top int + height int + changed bool + child *textEditor + colorOpt *schema.Option + theme string // theme providing the defaults of colors 0-15 +} + +// useTheme takes the base colors from the configured theme, since those +// are what an override replaces. +func (e *paletteEditor) useTheme(t *ghostty.Theme) { + for i, c := range t.Palette { + if c != "" { + e.defaults[i] = c + e.theme = t.Name + } + } +} + +func newPaletteEditor(o *schema.Option, entries []string) *paletteEditor { + e := &paletteEditor{ + opt: o, + overrides: map[int]string{}, + colorOpt: &schema.Option{Key: "palette", Kind: schema.KindColor}, + } + for _, d := range o.DefaultList() { + if i, c, ok := schema.SplitPalette(d); ok { + e.defaults[i] = c + } + } + for _, v := range entries { + if i, c, ok := schema.SplitPalette(v); ok { + e.overrides[i] = c + } else { + e.extra = append(e.extra, v) + } + } + return e +} + +func (e *paletteEditor) values() []string { + idx := make([]int, 0, len(e.overrides)) + for i := range e.overrides { + idx = append(idx, i) + } + sort.Ints(idx) + var out []string + for _, i := range idx { + out = append(out, fmt.Sprintf("%d=%s", i, e.overrides[i])) + } + return append(out, e.extra...) +} + +func (e *paletteEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if e.child != nil { + cmd, res := e.child.Update(msg) + if res != nil { + if !res.cancel { + if len(res.values) == 0 { + delete(e.overrides, e.cursor) + } else { + e.overrides[e.cursor] = res.values[0] + } + e.changed = true + } + e.child = nil + } + return cmd, nil + } + km, ok := msg.(tea.KeyMsg) + if !ok { + return nil, nil + } + key := km.String() + if c, moved := moveCursor(key, e.cursor, 256, max(1, e.height-1)); moved { + e.cursor = c + return nil, nil + } + switch key { + case "esc", "q": + if !e.changed { + return nil, cancelled() + } + v := e.values() + if len(v) == 0 { + return nil, &result{} + } + return nil, valuesResult(v...) + case "enter", "e": + cur := e.overrides[e.cursor] + e.child = newTextEditor(e.colorOpt, cur) + e.child.item = true + e.child.input.Placeholder = e.defaults[e.cursor] + case "d", "x", "delete", "backspace": + if _, ok := e.overrides[e.cursor]; ok { + delete(e.overrides, e.cursor) + e.changed = true + } + } + return nil, nil +} + +func (e *paletteEditor) View(width, height int) string { + if e.child != nil { + head := stBold.Render(fmt.Sprintf("Palette color %d", e.cursor)) + if d := e.defaults[e.cursor]; d != "" { + head += stDim.Render(" default ") + swatch(d) + " " + d + } + return head + "\n\n" + e.child.View(width, height-2) + } + var lines []string + lines = append(lines, stDim.Render(fmt.Sprintf("%d of 256 colors overridden. 0–7 normal, 8–15 bright, 16–255 extended.", len(e.overrides)))) + if e.theme != "" { + lines = append(lines, stDim.Render("Colors 0–15 default to the theme "+e.theme+".")) + } + lines = append(lines, "") + e.height = height - len(lines) + e.top = scrollWindow(e.cursor, e.top, e.height, 256) + for i := e.top; i < 256 && i < e.top+e.height; i++ { + value, set := e.overrides[i] + if !set { + value = e.defaults[i] + } + segs := []seg{cursorSeg(i == e.cursor), plain(fmt.Sprintf("%3d ", i)), rawSeg(swatch(value)), plain(" ")} + if set { + segs = append(segs, styled("● "+value, stSet), styled(" (default "+e.defaults[i]+")", stDim)) + } else { + segs = append(segs, styled(" "+value, stDim)) + } + lines = append(lines, renderRow(segs, width, i == e.cursor)) + } + return strings.Join(lines, "\n") +} + +func (e *paletteEditor) Help() string { + if e.child != nil { + return e.child.Help() + } + return "↑↓ move · enter edit · d reset color · esc done" +} diff --git a/internal/ui/picker.go b/internal/ui/picker.go new file mode 100644 index 0000000..6927190 --- /dev/null +++ b/internal/ui/picker.go @@ -0,0 +1,222 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "ghosttyconf/internal/colors" + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/schema" +) + +// pickerEditor selects a value from a long, filterable list (themes, font +// families). Any typed value can be used as well. +type pickerEditor struct { + opt *schema.Option + source string // "themes" or "fonts" + all []string + loading bool + loadErr error + filter textinput.Model + matches []string + cursor int + top int + height int + current string + preview func(name string) *ghostty.Theme + note string +} + +func newPickerEditor(o *schema.Option, source, current string) *pickerEditor { + p := &pickerEditor{ + opt: o, + source: source, + current: schema.Unquote(current), + loading: true, + filter: newInput("", "type to filter, or enter any value"), + } + p.filter.Prompt = "Search: " + return p +} + +// setItems delivers the asynchronously loaded list. +func (p *pickerEditor) setItems(items []string, err error) { + p.all, p.loadErr, p.loading = items, err, false + p.refilter() + for i, m := range p.matches { + if m == p.current { + p.cursor = i + break + } + } +} + +func (p *pickerEditor) refilter() { + q := strings.ToLower(strings.TrimSpace(p.filter.Value())) + terms := strings.Fields(q) + var prefix, rest []string + for _, it := range p.all { + l := strings.ToLower(it) + ok := true + for _, t := range terms { + if !strings.Contains(l, t) { + ok = false + break + } + } + if !ok { + continue + } + if q != "" && strings.HasPrefix(l, q) { + prefix = append(prefix, it) + } else { + rest = append(rest, it) + } + } + p.matches = append(prefix, rest...) + p.cursor = 0 + p.top = 0 +} + +func (p *pickerEditor) Update(msg tea.Msg) (tea.Cmd, *result) { + if km, ok := msg.(tea.KeyMsg); ok { + key := km.String() + switch key { + case "esc": + return nil, cancelled() + case "enter": + if len(p.matches) > 0 { + return nil, valuesResult(p.matches[p.cursor]) + } + v := strings.TrimSpace(p.filter.Value()) + if v == "" { + return nil, &result{} + } + return nil, valuesResult(v) + case "tab": + if len(p.matches) > 0 { + p.filter.SetValue(p.matches[p.cursor]) + p.filter.CursorEnd() + p.refilter() + } + return nil, nil + case "up", "down", "pgup", "pgdown", "ctrl+p", "ctrl+n": + p.cursor, _ = moveCursor(key, p.cursor, len(p.matches), max(1, p.height-1)) + return nil, nil + } + } + before := p.filter.Value() + var cmd tea.Cmd + p.filter, cmd = p.filter.Update(msg) + if p.filter.Value() != before { + p.refilter() + } + return cmd, nil +} + +func (p *pickerEditor) View(width, height int) string { + p.filter.Width = max(10, width-12) + var lines []string + count := "" + if !p.loading { + count = stDim.Render(fmt.Sprintf("%d of %d", len(p.matches), len(p.all))) + } + lines = append(lines, p.filter.View(), count) + if p.note != "" { + var note []string + for _, l := range strings.Split(ansi.Wrap(p.note, width, ""), "\n") { + note = append(note, stChanged.Render(l)) + } + lines = append(lines[:1], append(note, lines[1:]...)...) + } + + var previewLines []string + if p.preview != nil && len(p.matches) > 0 && height >= 16 { + if t := p.preview(p.matches[p.cursor]); t != nil { + previewLines = strings.Split(renderThemePreview(t, width), "\n") + } + } + listH := height - len(lines) - len(previewLines) + if len(previewLines) > 0 { + listH-- + } + p.height = listH + + switch { + case p.loading: + lines = append(lines, stDim.Render("Loading "+p.source+"…")) + case p.loadErr != nil: + lines = append(lines, stError.Render("Could not load "+p.source+": "+p.loadErr.Error()), + stDim.Render("Type a value and press enter.")) + case len(p.matches) == 0: + lines = append(lines, stDim.Render("No matches. Press enter to use the typed value.")) + default: + p.top = scrollWindow(p.cursor, p.top, listH, len(p.matches)) + for i := p.top; i < len(p.matches) && i < p.top+listH; i++ { + m := p.matches[i] + segs := []seg{cursorSeg(i == p.cursor), plain(m)} + if m == p.current { + segs = append(segs, styled(" ● current", stSet)) + } + lines = append(lines, renderRow(segs, width, i == p.cursor)) + } + } + if len(previewLines) > 0 { + for len(lines) < height-len(previewLines) { + lines = append(lines, "") + } + lines = append(lines, previewLines...) + } + return strings.Join(lines, "\n") +} + +func (p *pickerEditor) Help() string { + return "type to filter · ↑↓ choose · tab complete · enter select · esc cancel" +} + +// renderThemePreview draws a small terminal mock-up using a theme's colors. +func renderThemePreview(t *ghostty.Theme, width int) string { + bg, fg := t.Background, t.Foreground + if !colors.Valid(bg) { + bg = "#000000" + } + if !colors.Valid(fg) { + fg = "#ffffff" + } + hexOf := func(v, fallback string) lipgloss.Color { + if h, ok := colors.Hex(v); ok { + return lipgloss.Color(h) + } + return lipgloss.Color(fallback) + } + base := lipgloss.NewStyle().Background(hexOf(bg, "#000000")).Foreground(hexOf(fg, "#ffffff")) + col := func(i int) lipgloss.Style { return base.Foreground(hexOf(t.Palette[i], fg)) } + w := min(width, 48) + row := func(parts ...string) string { + s := strings.Join(parts, "") + return s + base.Render(strings.Repeat(" ", max(0, w-lipglossWidth(s)))) + } + var lines []string + lines = append(lines, + row(base.Render(" ")), + row(base.Render(" "), col(2).Bold(true).Render("user@host"), base.Render(" "), col(4).Render("~/src"), base.Render(" $ "), base.Render("ls --color")), + row(base.Render(" "), col(4).Bold(true).Render("docs"), base.Render(" "), col(2).Render("build.sh"), base.Render(" "), col(1).Render("error.log"), base.Render(" "), col(3).Render("notes.md")), + row(base.Render(" "), col(5).Render("import"), base.Render(" os "), col(6).Render("# comment"), base.Render(" "), col(8).Render("dimmed")), + ) + var normal, bright strings.Builder + normal.WriteString(base.Render(" ")) + bright.WriteString(base.Render(" ")) + for i := 0; i < 8; i++ { + normal.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i], bg)).Render(" ") + base.Render(" ")) + bright.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i+8], bg)).Render(" ") + base.Render(" ")) + } + lines = append(lines, row(base.Render(" ")), row(normal.String()), row(bright.String()), row(base.Render(" "))) + return strings.Join(lines, "\n") +} + +func lipglossWidth(s string) int { return lipgloss.Width(s) } diff --git a/internal/ui/styles.go b/internal/ui/styles.go new file mode 100644 index 0000000..5068ef6 --- /dev/null +++ b/internal/ui/styles.go @@ -0,0 +1,184 @@ +package ui + +import ( + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "ghosttyconf/internal/colors" +) + +// The UI uses the 16 ANSI colors so it follows the user's terminal theme. +var ( + colAccent = lipgloss.Color("12") + colBorder = lipgloss.Color("8") + colDim = lipgloss.Color("8") + colSet = lipgloss.Color("2") + colChanged = lipgloss.Color("3") + colError = lipgloss.Color("1") + colCode = lipgloss.Color("6") + colSelected = lipgloss.AdaptiveColor{Light: "254", Dark: "237"} + + stTitle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colAccent).Padding(0, 1) + stHeader = lipgloss.NewStyle().Foreground(colDim) + stDim = lipgloss.NewStyle().Foreground(colDim) + stBold = lipgloss.NewStyle().Bold(true) + stAccent = lipgloss.NewStyle().Foreground(colAccent) + stSet = lipgloss.NewStyle().Foreground(colSet) + stChanged = lipgloss.NewStyle().Foreground(colChanged) + stError = lipgloss.NewStyle().Foreground(colError) + stOK = lipgloss.NewStyle().Foreground(colSet) + stCode = lipgloss.NewStyle().Foreground(colCode) + stSelected = lipgloss.NewStyle().Background(colSelected) + stKey = lipgloss.NewStyle().Foreground(colAccent).Bold(true) + stLabel = lipgloss.NewStyle().Foreground(colDim).Width(9) + + stRecording = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colError) +) + +// swatch renders a small color sample, or "" if value is not a color. +func swatch(value string) string { + h, ok := colors.Hex(value) + if !ok { + return "" + } + return lipgloss.NewStyle().Background(lipgloss.Color(h)).Render(" ") +} + +// fit truncates or pads s to exactly width cells. +func fit(s string, width int) string { + if width <= 0 { + return "" + } + if w := ansi.StringWidth(s); w > width { + return ansi.Truncate(s, width, "…") + } else if w < width { + return s + strings.Repeat(" ", width-w) + } + return s +} + +// panel draws a rounded box with a title in the top border. The content is +// clipped to the inner area. +func panel(title, content string, width, height int, focused bool) string { + if focused { + return framed(title, content, width, height, colAccent) + } + return framed(title, content, width, height, colBorder) +} + +// framed is panel with an explicit border color. +func framed(title, content string, width, height int, color lipgloss.TerminalColor) string { + if width < 4 || height < 2 { + return "" + } + border := lipgloss.NewStyle().Foreground(color) + titleSt := stDim + if color != colBorder { + titleSt = lipgloss.NewStyle().Foreground(color).Bold(true) + } + inner := width - 2 + var b strings.Builder + + t := "" + if title != "" { + t = ansi.Truncate(" "+title+" ", inner-2, "… ") + } + dashes := max(0, inner-1-ansi.StringWidth(t)) + b.WriteString(border.Render("╭─") + titleSt.Render(t) + border.Render(strings.Repeat("─", dashes)+"╮") + "\n") + + lines := strings.Split(content, "\n") + for i := 0; i < height-2; i++ { + line := "" + if i < len(lines) { + line = lines[i] + } + b.WriteString(border.Render("│") + fit(line, inner) + "\x1b[0m" + border.Render("│") + "\n") + } + b.WriteString(border.Render("╰" + strings.Repeat("─", inner) + "╯")) + return b.String() +} + +// overlay draws box centered on top of base. +func overlay(base, box string, width, height int) string { + baseLines := strings.Split(base, "\n") + for len(baseLines) < height { + baseLines = append(baseLines, "") + } + boxLines := strings.Split(box, "\n") + bw := 0 + for _, l := range boxLines { + if w := ansi.StringWidth(l); w > bw { + bw = w + } + } + x := max(0, (width-bw)/2) + y := max(0, (height-len(boxLines))/2) + for i, l := range boxLines { + row := y + i + if row >= len(baseLines) { + break + } + bl := baseLines[row] + left := fit(ansi.Truncate(bl, x, ""), x) + right := ansi.TruncateLeft(bl, x+bw, "") + baseLines[row] = left + "\x1b[0m" + fit(l, bw) + "\x1b[0m" + right + } + return strings.Join(baseLines, "\n") +} + +// seg is a styled piece of a list row. +type seg struct { + text string + st lipgloss.Style + raw bool // pre-rendered (e.g. a swatch); keeps its own background +} + +func plain(s string) seg { return seg{text: s, st: lipgloss.NewStyle()} } +func styled(s string, st lipgloss.Style) seg { return seg{text: s, st: st} } +func rawSeg(s string) seg { return seg{text: s, raw: true} } + +// renderRow joins segments into a row of exactly width cells. Selected rows +// get a background on every segment, so nested styles do not interrupt the +// highlight. +func renderRow(segs []seg, width int, selected bool) string { + var b strings.Builder + used := 0 + for _, s := range segs { + if used >= width { + break + } + w := ansi.StringWidth(s.text) + text := s.text + if used+w > width { + text = ansi.Truncate(text, width-used, "…") + w = ansi.StringWidth(text) + } + switch { + case s.raw: + b.WriteString(text) + case selected: + b.WriteString(s.st.Background(colSelected).Render(text)) + default: + b.WriteString(s.st.Render(text)) + } + used += w + } + if used < width { + pad := strings.Repeat(" ", width-used) + if selected { + pad = stSelected.Render(pad) + } + b.WriteString(pad) + } + return b.String() +} + +// cursorSeg is the "▸ " marker in front of the selected row. +func cursorSeg(selected bool) seg { + if selected { + return styled("▸ ", stAccent) + } + return plain(" ") +} diff --git a/internal/ui/term.go b/internal/ui/term.go new file mode 100644 index 0000000..7d4509c --- /dev/null +++ b/internal/ui/term.go @@ -0,0 +1,68 @@ +package ui + +import ( + "os" + "reflect" + "sync" + + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/keybind" +) + +// rawSequence extracts the bytes of an escape sequence Bubble Tea did not +// recognize. Bubble Tea v1 reports those as an unexported []byte message +// type, which is where kitty keyboard protocol key events end up. +func rawSequence(msg tea.Msg) ([]byte, bool) { + if msg == nil { + return nil, false + } + t := reflect.TypeOf(msg) + if t.Kind() != reflect.Slice || t.Elem().Kind() != reflect.Uint8 || + t.PkgPath() != "github.com/charmbracelet/bubbletea" { + return nil, false + } + return reflect.ValueOf(msg).Bytes(), true +} + +var ( + kittyMu sync.Mutex + kittyActive bool +) + +func writeTerminal(s string) { + _, _ = os.Stdout.WriteString(s) +} + +// enableKeyCapture switches the terminal to the kitty keyboard protocol so +// that every key (including cmd/super combinations) can be recorded. +func enableKeyCapture() tea.Cmd { + return func() tea.Msg { + kittyMu.Lock() + defer kittyMu.Unlock() + if !kittyActive { + writeTerminal(keybind.PushKitty + keybind.QueryKitty) + kittyActive = true + } + return nil + } +} + +// disableKeyCapture restores the previous keyboard mode. +func disableKeyCapture() tea.Cmd { + return func() tea.Msg { + RestoreTerminal() + return nil + } +} + +// RestoreTerminal undoes enableKeyCapture. It is safe to call at any time +// and is called on exit in case the program stops while recording. +func RestoreTerminal() { + kittyMu.Lock() + defer kittyMu.Unlock() + if kittyActive { + writeTerminal(keybind.PopKitty) + kittyActive = false + } +} diff --git a/internal/ui/term_test.go b/internal/ui/term_test.go new file mode 100644 index 0000000..cf49c3f --- /dev/null +++ b/internal/ui/term_test.go @@ -0,0 +1,51 @@ +package ui + +import ( + "io" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +// rawProbe stops at the first message rawSequence accepts. +type rawProbe struct{ got []byte } + +func (p *rawProbe) Init() tea.Cmd { return nil } +func (p *rawProbe) View() string { return "" } + +func (p *rawProbe) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if b, ok := rawSequence(msg); ok { + p.got = b + return p, tea.Quit + } + return p, nil +} + +// TestRawSequenceFromBubbleTea feeds a kitty keyboard protocol key event +// through Bubble Tea's input parser. It breaks if a Bubble Tea upgrade +// changes how unknown escape sequences are delivered. +func TestRawSequenceFromBubbleTea(t *testing.T) { + const seq = "\x1b[92;9u" // super+\ + p := &rawProbe{} + prog := tea.NewProgram(p, tea.WithInput(strings.NewReader(seq)), tea.WithOutput(io.Discard), + tea.WithoutRenderer(), tea.WithoutSignals()) + done := make(chan error, 1) + go func() { + _, err := prog.Run() + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + prog.Kill() + t.Fatal("Bubble Tea did not deliver the sequence") + } + if string(p.got) != seq { + t.Fatalf("rawSequence = %q, want %q", p.got, seq) + } +} diff --git a/internal/ui/view.go b/internal/ui/view.go new file mode 100644 index 0000000..ee0ee1b --- /dev/null +++ b/internal/ui/view.go @@ -0,0 +1,488 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + + "ghosttyconf/internal/keybind" + "ghosttyconf/internal/schema" +) + +func (a *App) View() string { + if a.width < 40 || a.height < 12 { + return "Terminal too small for the Ghostty config editor (min. 40×12)." + } + bodyH := a.height - 3 + var body string + if a.editor != nil { + body = a.viewEditor(a.width, bodyH) + } else { + body = a.viewBrowse(a.width, bodyH) + } + out := a.viewHeader() + "\n" + body + "\n" + a.viewFooter() + if a.dlg != nil { + out = overlay(out, a.dlg.view(a.width, a.height), a.width, a.height) + } + return out +} + +func (a *App) viewHeader() string { + title := stTitle.Render("Ghostty Config Editor") + " " + right := stHeader.Render(fmt.Sprintf(" %s · %d options ", a.sch.Source, len(a.sch.Options))) + if lipgloss.Width(title)+lipgloss.Width(right)+20 > a.width { + right = "" + } + path := shortPath(a.file.Path) + if !a.file.Exists { + path += " (new file)" + } + pathW := a.width - lipgloss.Width(title) - lipgloss.Width(right) + if ansi.StringWidth(path) > pathW { + // Keep the end of the path, which is the informative part. + path = "…" + ansi.TruncateLeft(path, ansi.StringWidth(path)-pathW+1, "") + } + return title + fit(stHeader.Render(path), pathW) + right +} + +func (a *App) viewFooter() string { + right := "" + if n := len(a.changedKeys()); n > 0 { + right = stChanged.Render(fmt.Sprintf("● %d unsaved ", n)) + } + status := a.statusStyle.Render(a.status) + statusW := a.width - lipgloss.Width(right) - 1 + line1 := " " + fit(status, statusW) + right + + var help string + switch { + case a.editor != nil: + help = a.editor.Help() + " · shift+↑↓ scroll docs" + case a.searching: + help = "type to search keys and docs · enter/↓ go to results · esc clear" + case a.focus == paneCats: + help = "↑↓ category · → options · / search · b keybindings · c changes · ctrl+s save · ? help · q quit" + default: + help = "↑↓ move · enter edit · space toggle · +/- adjust · r reset · u undo · / search · ctrl+s save · ? help · q quit" + } + return line1 + "\n" + stDim.Render(fit(" "+help, a.width)) +} + +// --------------------------------------------------------------------------- +// Browse screen + +func (a *App) viewBrowse(w, h int) string { + catW := 26 + if w < 90 { + catW = 20 + } + rightW := w - catW + a.catRect = rect{0, 1, catW, h} + cats := panel("Categories", a.renderCats(catW-2, h-2), catW, h, a.focus == paneCats && !a.searching) + + optTitle := a.cats[a.catIdx] + if a.query != "" || a.searching { + optTitle = fmt.Sprintf("Search (%d)", len(a.opts)) + } else { + optTitle = fmt.Sprintf("%s (%d)", optTitle, len(a.opts)) + } + + if rightW >= 120 { + optW := rightW * 52 / 100 + docW := rightW - optW + a.optRect = rect{catW, 1, optW, h} + a.docRect = rect{catW + optW, 1, docW, h} + opts := panel(optTitle, a.renderOpts(optW-2, h-2), optW, h, a.focus == paneOpts) + content := a.renderDocs(a.selected(), docW-4, h-2) + docs := panel(a.docTitle(), content, docW, h, false) + return lipgloss.JoinHorizontal(lipgloss.Top, cats, opts, docs) + } + optH := max(7, h*55/100) + docH := h - optH + a.optRect = rect{catW, 1, rightW, optH} + a.docRect = rect{catW, 1 + optH, rightW, docH} + opts := panel(optTitle, a.renderOpts(rightW-2, optH-2), rightW, optH, a.focus == paneOpts) + content := a.renderDocs(a.selected(), rightW-4, docH-2) + docs := panel(a.docTitle(), content, rightW, docH, false) + return lipgloss.JoinHorizontal(lipgloss.Top, cats, lipgloss.JoinVertical(lipgloss.Left, opts, docs)) +} + +// catRows returns the rendered category rows; -1 marks the separator. +func (a *App) catRows() []int { + rows := []int{0, 1, -1} + for i := 2; i < len(a.cats); i++ { + rows = append(rows, i) + } + return rows +} + +func (a *App) catRowIndex(row int) int { + rows := a.catRows() + if row < 0 || row >= len(rows) { + return -1 + } + return rows[row] +} + +func (a *App) renderCats(w, h int) string { + rows := a.catRows() + sel := 0 + for i, r := range rows { + if r == a.catIdx { + sel = i + } + } + a.catTop = scrollWindow(sel, a.catTop, h, len(rows)) + var lines []string + for i := a.catTop; i < len(rows) && len(lines) < h; i++ { + ci := rows[i] + if ci < 0 { + lines = append(lines, stDim.Render(strings.Repeat("─", w))) + continue + } + name := a.cats[ci] + n := len(a.categoryOptions(name)) + count := fmt.Sprintf("%d", n) + selected := ci == a.catIdx && a.query == "" + nameSt := lipgloss.NewStyle() + if ci == 0 && n > 0 { + nameSt = stSet + } + if selected && a.focus == paneCats { + nameSt = nameSt.Bold(true) + } + nameW := w - 2 - len(count) - 1 + segs := []seg{cursorSeg(selected), styled(fit(name, nameW), nameSt), plain(" "), styled(count, stDim)} + lines = append(lines, renderRow(segs, w, selected && a.focus == paneCats)) + } + return strings.Join(lines, "\n") +} + +func (a *App) renderOpts(w, h int) string { + var lines []string + listY := a.optRect.y + 1 + if a.searching || a.query != "" { + a.search.Width = max(10, w-4) + lines = append(lines, a.search.View(), "") + h -= 2 + listY += 2 + } + a.optListY = listY + if len(a.opts) == 0 { + msg := "No options." + switch { + case a.query != "": + msg = "No options match your search." + case a.cats[a.catIdx] == catSet: + msg = "Your config file does not set any options yet." + } + lines = append(lines, stDim.Render(" "+msg)) + return strings.Join(lines, "\n") + } + keyW := 0 + for _, o := range a.opts { + keyW = max(keyW, len(o.Key)) + } + keyW = min(keyW+1, w*55/100) + valW := w - keyW - 4 + + a.optTop = scrollWindow(a.optIdx, a.optTop, h, len(a.opts)) + for i := a.optTop; i < len(a.opts) && i < a.optTop+h; i++ { + o := a.opts[i] + selected := i == a.optIdx + keySt := lipgloss.NewStyle() + switch { + case a.unknown[o.Key] == o: + keySt = stError + case o.Platform != "" && a.osName != "" && o.Platform != a.osName: + keySt = stDim + } + if selected && a.focus == paneOpts { + keySt = keySt.Bold(true) + } + segs := []seg{cursorSeg(selected), a.marker(o), styled(fit(o.Key, keyW), keySt), plain(" ")} + segs = append(segs, a.valueSegs(o, valW)...) + lines = append(lines, renderRow(segs, w, selected && a.focus == paneOpts)) + } + return strings.Join(lines, "\n") +} + +// marker shows whether an option is set in the file and whether it has +// unsaved changes. +func (a *App) marker(o *schema.Option) seg { + now := a.file.GetAll(o.Key) + changed := !equalStrings(now, a.saved.GetAll(o.Key)) + switch { + case changed && len(now) == 0: + return styled("○ ", stChanged) + case changed: + return styled("● ", stChanged) + case len(now) > 0: + return styled("● ", stSet) + } + return plain(" ") +} + +// valueSegs summarizes the current value for the option list. +func (a *App) valueSegs(o *schema.Option, w int) []seg { + vals := a.file.GetAll(o.Key) + set := len(vals) > 0 + switch { + case o.Kind == schema.KindKeybind: + counts := map[keybind.Source]int{} + for _, b := range keybind.NewSet(o.DefaultList(), vals).Bindings() { + counts[b.Source]++ + } + var parts []seg + add := func(n int, label string, st lipgloss.Style) { + if n == 0 { + return + } + if len(parts) > 0 { + parts = append(parts, styled(" · ", stDim)) + } + parts = append(parts, styled(fmt.Sprintf("%d %s", n, label), st)) + } + add(counts[keybind.Changed], "changed", stChanged) + add(counts[keybind.Custom], "custom", stSet) + add(counts[keybind.Unbound], "unbound", stError) + if len(parts) == 0 { + return []seg{styled(fmt.Sprintf("%d built-in bindings", counts[keybind.Default]), stDim)} + } + return parts + case o.Kind == schema.KindPalette: + if set { + return []seg{plain(fmt.Sprintf("%d color(s) overridden", len(vals)))} + } + return []seg{styled("default palette", stDim)} + case o.Repeatable: + if set { + s := vals[0] + if o.Kind == schema.KindKeybind { + s = keybindSummary(vals[0]) + } + if len(vals) > 1 { + return []seg{plain(ansi.Truncate(s, max(5, w-10), "…")), styled(fmt.Sprintf(" +%d more", len(vals)-1), stDim)} + } + return []seg{plain(s)} + } + defs := o.DefaultList() + switch len(defs) { + case 0: + return []seg{styled("—", stDim)} + case 1: + return []seg{styled(defs[0], stDim)} + } + return []seg{styled(fmt.Sprintf("%d built-in entries", len(defs)), stDim)} + } + v := o.Default() + st := stDim + if set { + v, st = vals[len(vals)-1], lipgloss.NewStyle() + if o.Validate(v) != nil { + st = stError + } + } + if v == "" { + return []seg{styled("—", stDim)} + } + v = strings.ReplaceAll(v, "\t", "\\t") + if o.Kind == schema.KindColor || o.Kind == schema.KindColorList { + if sw := swatch(strings.Split(v, ",")[0]); sw != "" { + return []seg{rawSeg(sw), plain(" "), styled(v, st)} + } + } + return []seg{styled(v, st)} +} + +func keybindSummary(v string) string { + t, act := schema.SplitKeybind(v) + if act == "" { + return v + } + return t + " → " + act +} + +// renderDocs renders the documentation panel content for o into a.doc and +// returns the visible part. +func (a *App) renderDocs(o *schema.Option, w, h int) string { + if o == nil { + return "" + } + a.doc.Width, a.doc.Height = w, h + id := o.Key + var content func() string + // Editors can show documentation of their own (e.g. of the selected + // keybind action) instead of the option's. + if dp, ok := a.editor.(interface { + docFor() (id, title, body string, ok bool) + }); ok { + if did, title, body, ok := dp.docFor(); ok { + id = did + content = func() string { return stAccent.Bold(true).Render(title) + "\n\n" + renderDoc(body, w) } + } + } + if content == nil { + content = func() string { return a.docContent(o, w) } + } + key := fmt.Sprintf("%s|%d|%d", id, w, a.rev) + if a.editor != nil { + key += "|edit" + } + if key != a.docFor { + if !strings.HasPrefix(a.docFor, id+"|") { + a.doc.GotoTop() + } + a.docFor = key + a.doc.SetContent(content()) + } + lines := strings.Split(a.doc.View(), "\n") + for i := range lines { + lines[i] = " " + lines[i] + } + return strings.Join(lines, "\n") +} + +// docTitle is the documentation panel title, with a scroll position when +// the text does not fit. Call it after renderDocs. +func (a *App) docTitle() string { + if a.doc.TotalLineCount() <= a.doc.Height { + return "Documentation" + } + return fmt.Sprintf("Documentation · %d%% · shift+↑↓ scroll", int(a.doc.ScrollPercent()*100)) +} + +func (a *App) docContent(o *schema.Option, w int) string { + var b strings.Builder + b.WriteString(stAccent.Bold(true).Render(o.Key) + "\n\n") + row := func(label, value string) { + b.WriteString(stLabel.Render(label) + " " + ansi.Wrap(value, max(10, w-10), "") + "\n") + } + if a.editor == nil { + row("Type", o.TypeLabel()) + vals := a.file.GetAll(o.Key) + switch { + case o.Repeatable: + defs := o.DefaultList() + if len(defs) > 0 { + row("Default", fmt.Sprintf("%d built-in entries", len(defs))) + } else { + row("Default", "none") + } + if len(vals) == 0 { + row("Value", stDim.Render("not set")) + } else { + row("Value", fmt.Sprintf("%d entr%s in your config", len(vals), plural(len(vals), "y", "ies"))) + for i, v := range vals { + if i == 8 { + b.WriteString(stDim.Render(fmt.Sprintf(" … and %d more", len(vals)-8)) + "\n") + break + } + b.WriteString(" " + ansi.Truncate(v, max(10, w-10), "…") + "\n") + } + } + default: + def := o.Default() + if def == "" { + def = stDim.Render("(unset)") + } else if sw := swatch(def); sw != "" && o.Kind == schema.KindColor { + def = sw + " " + def + } + row("Default", strings.ReplaceAll(def, "\t", "\\t")) + if len(vals) == 0 { + row("Value", stDim.Render("not set (uses default)")) + } else { + v := vals[len(vals)-1] + if sw := swatch(v); sw != "" && o.Kind == schema.KindColor { + v = sw + " " + v + } + row("Value", v+" "+stSet.Render("● set in config")) + if err := o.Validate(vals[len(vals)-1]); err != nil { + b.WriteString(stError.Render(" ✗ invalid: "+err.Error()) + "\n") + } + if len(vals) > 1 { + b.WriteString(stChanged.Render(fmt.Sprintf(" set %d times; the last one wins", len(vals))) + "\n") + } + } + } + if o.Platform != "" { + row("Platform", o.Platform+" only") + } + row("Category", o.Category) + b.WriteString("\n") + } + if o.Doc == "" { + b.WriteString(stDim.Render("No documentation available.")) + } else { + b.WriteString(renderDoc(o.Doc, w)) + } + return b.String() +} + +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + +// --------------------------------------------------------------------------- +// Editor screen + +func (a *App) viewEditor(w, h int) string { + o := a.editOpt + title := "Edit " + o.Key + if w >= 110 { + edW := w * 55 / 100 + docW := w - edW + a.optRect = rect{0, 1, edW, h} + a.docRect = rect{edW, 1, docW, h} + left := panel(title, a.renderEditor(edW-4, h-2), edW, h, true) + content := a.renderDocs(o, docW-4, h-2) + right := panel(a.docTitle(), content, docW, h, false) + return lipgloss.JoinHorizontal(lipgloss.Top, left, right) + } + edH := max(10, h*62/100) + switch a.editor.(type) { + case *keybindManager, *listEditor, *paletteEditor: + edH = max(10, h*75/100) // long lists need the room + } + docH := h - edH + a.optRect = rect{0, 1, w, edH} + a.docRect = rect{0, 1 + edH, w, docH} + top := panel(title, a.renderEditor(w-4, edH-2), w, edH, true) + if docH < 3 { + return top + } + content := a.renderDocs(o, w-4, docH-2) + bottom := panel(a.docTitle(), content, w, docH, false) + return lipgloss.JoinVertical(lipgloss.Left, top, bottom) +} + +func (a *App) renderEditor(w, h int) string { + o := a.editOpt + var head []string + head = append(head, stLabel.Render("Type")+" "+ansi.Truncate(o.TypeLabel(), max(10, w-10), "…")) + if !o.Repeatable { + def := o.Default() + if def == "" { + def = stDim.Render("(unset)") + } + cur, ok := a.file.Get(o.Key) + if !ok { + cur = stDim.Render("not set") + } + head = append(head, + stLabel.Render("Default")+" "+ansi.Truncate(strings.ReplaceAll(def, "\t", "\\t"), max(10, w-10), "…"), + stLabel.Render("Current")+" "+ansi.Truncate(cur, max(10, w-10), "…")) + } + head = append(head, "") + body := a.editor.View(w, h-len(head)) + lines := append(head, strings.Split(body, "\n")...) + for i := range lines { + lines[i] = " " + lines[i] + } + return strings.Join(lines, "\n") +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..de23bb8 --- /dev/null +++ b/main.go @@ -0,0 +1,86 @@ +// Command ghosttyconf is a terminal editor for the Ghostty configuration. +package main + +import ( + "flag" + "fmt" + "os" + "path/filepath" + + tea "github.com/charmbracelet/bubbletea" + + "ghosttyconf/internal/config" + "ghosttyconf/internal/ghostty" + "ghosttyconf/internal/schema" + "ghosttyconf/internal/ui" +) + +func main() { + configPath := flag.String("config", "", "config file to edit (default: Ghostty's default config file)") + ghosttyBin := flag.String("ghostty", "", "path to the ghostty binary (default: search $PATH and /Applications)") + offline := flag.Bool("offline", false, "do not run ghostty; use the built-in option list") + printPath := flag.Bool("print-path", false, "print the config file that would be edited and exit") + noReload := flag.Bool("no-reload", false, "do not ask Ghostty to reload its configuration after saving") + flag.Usage = func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] [config-file]\n\n", filepath.Base(os.Args[0])) + fmt.Fprintln(flag.CommandLine.Output(), "A terminal editor for the Ghostty configuration. Flags:") + flag.PrintDefaults() + } + flag.Parse() + if flag.NArg() > 1 { + flag.Usage() + os.Exit(2) + } + if flag.NArg() == 1 { + *configPath = flag.Arg(0) + } + + path := *configPath + if path == "" { + path = ghostty.DefaultConfigPath() + } + if abs, err := filepath.Abs(path); err == nil { + path = abs + } + if *printPath { + fmt.Println(path) + return + } + + if err := run(path, *ghosttyBin, *offline, !*noReload); err != nil { + fmt.Fprintln(os.Stderr, "ghosttyconf:", err) + os.Exit(1) + } +} + +func run(path, ghosttyBin string, offline, autoReload bool) error { + sch, err := schema.Embedded() + if err != nil { + return err + } + + var gh *ghostty.Ghostty + if !offline { + gh, err = ghostty.Find(ghosttyBin) + if err != nil && ghosttyBin != "" { + return err + } + if gh != nil { + if docs, err := gh.DefaultsWithDocs(); err == nil { + sch.Refresh(docs, gh.Version) + } + } + } + + file, err := config.Load(path) + if err != nil { + return fmt.Errorf("read config: %w", err) + } + + app := ui.New(sch, gh, file) + app.SetAutoReload(autoReload) + p := tea.NewProgram(app, tea.WithAltScreen(), tea.WithMouseCellMotion()) + defer ui.RestoreTerminal() + _, err = p.Run() + return err +} diff --git a/tools/genschema/main.go b/tools/genschema/main.go new file mode 100644 index 0000000..ce8a913 --- /dev/null +++ b/tools/genschema/main.go @@ -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} + } +} diff --git a/tools/screenshots.sh b/tools/screenshots.sh new file mode 100755 index 0000000..5e80d1f --- /dev/null +++ b/tools/screenshots.sh @@ -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 diff --git a/tools/termsvg/main.go b/tools/termsvg/main.go new file mode 100644 index 0000000..340009c --- /dev/null +++ b/tools/termsvg/main.go @@ -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, ``+"\n", + f(totalW), f(totalH), f(totalW), f(totalH)) + b.WriteString(`` + + `` + + `` + "\n") + fmt.Fprintf(&b, ``+"\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, ``+"\n", f(winW), f(winH), th.bg.hex()) + fmt.Fprintf(&b, ``, f(winW), f(titleH), bar.hex()) + fmt.Fprintf(&b, ``+"\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, ``, f(20+float64(i)*20), f(titleH/2), c) + } + b.WriteString("\n") + if title != "" { + fmt.Fprintf(&b, `%s`+"\n", + f(winW/2), f(titleH/2+4.5), mix(th.fg, bar, 0.3).hex(), esc(title)) + } + + fmt.Fprintf(&b, ``+"\n", f(padding), f(titleH+padding)) + backgrounds(&b, rows, th) + shapes(&b, rows, th) + text(&b, rows, th) + b.WriteString("\n\n\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, ``+"\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, ``+"\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, ``+"\n", p.String(), c) + } + if p, ok := heavy[c]; ok { + fmt.Fprintf(b, ``+"\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, ``+"\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, `%s`+"\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("\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("&", "&", "<", "<", ">", ">", `"`, """).Replace(s) +}