Commit Graph

15576 Commits

Author SHA1 Message Date
Alessandro De Blasis
dc3db7b99f build: normalize line endings to LF across all platforms
Add explicit file-type rules to .gitattributes so text files are stored
and checked out with LF line endings regardless of platform. This
prevents issues where Windows git (or CI actions/checkout) converts
LF to CRLF, breaking comptime parsers that split embedded files by
'\n' and end up with trailing '\r' in parsed tokens.

Key changes:
- Source code (*.zig, *.c, *.h, etc.): always LF
- Config/build files (*.zon, *.nix, *.md, etc.): always LF
- Text data files (*.txt): always LF (for embedded file parsing)
- Windows resource files (*.rc, *.manifest): preserve as-is
  (native Windows tooling expects CRLF)
- Binary files: explicitly marked as binary

Removed the legacy rgb.txt -text rule since *.txt now handles it
uniformly with code-level CRLF handling as defense-in-depth.
2026-03-27 06:13:23 -07:00
Alessandro De Blasis
650b9d470a font: handle CRLF line endings in octants.txt parsing
Trim trailing \r when splitting octants.txt by \n at comptime. On
Windows, git may convert LF to CRLF on checkout, leaving \r at the
end of each line. Without trimming, the parser tries to use \r as
a struct field name in @field(), causing a compile error.

Follows the same pattern used in x11_color.zig for rgb.txt parsing.
2026-03-27 06:11:20 -07:00
Alessandro De Blasis
fead488d23 ci: add full test suite for Windows
Add test-windows job running zig build -Dapp-runtime=none test on
windows-2025. Added to required checks.
2026-03-27 06:11:20 -07:00
Mitchell Hashimoto
fa9265636b macOS: fix search bar losing focus unexpectedly (#11872)
A regression caused by 3ee8ef4f65.

The search bar should stay as the first responder after clicking inside
the text field or clicking the next/previous button, but right now it
doesn’t.
2026-03-27 06:00:27 -07:00
Mitchell Hashimoto
6057f8d2b7 terminal: redo trailing state capture in OSC parser (#11873)
Trailing state capture now is encapsulated in a struct `Capture` and all
parsers access the data via `p.capture.trailing()` rather than directly
from the writer.

This is primarily to prep for the OSC parser to be able to capture the
entire sequence (not just the trailing part) so we can setup libghostty
for fallback handlers so libghostty implementers can have custom OSC
behaviors.

But, it has the benefit of making our OSC parser much cleaner too.

I'm doing some benchmarks now...
2026-03-26 14:04:49 -07:00
Mitchell Hashimoto
7801e97127 terminal: redo trailing state capture in OSC parser
Trailing state capture now is encapsulated in a struct `Capture` and all
parsers access the data via `p.capture.trailing()` rather than directly
from the writer.

This is primarily to prep for the OSC parser to be able to capture the
entire sequence (not just the trailing part) so we can setup libghostty
for fallback handlers so libghostty implementers can have custom OSC
behaviors.

But, it has the benefit of making our OSC parser much cleaner too.
2026-03-26 13:57:42 -07:00
Lukas
ad0c5fbec3 macOS: fix regression caused by 3ee8ef4f65 2026-03-26 19:58:18 +01:00
Lukas
95ee878904 macOS: add test case for search bar focus change 2026-03-26 19:58:18 +01:00
Mitchell Hashimoto
7df353a619 libghostty: expose paste encode to C API (#11871)
Add ghostty_paste_encode() which encodes paste data for writing to the
terminal pty. It strips unsafe control bytes, wraps in bracketed paste
sequences when requested, and replaces newlines with carriage returns
for unbracketed mode. The input buffer is modified in place and the
encoded result is written to a caller-provided output buffer, following
the same buffer/out_written pattern as the other encode functions like
ghostty_size_report_encode.

Update the c-vt-paste example with an encode_example() demonstrating the
new function and add corresponding @snippet references in the header
documentation.

Extracted this from #11870 since I can't figure out why that build is
failing.
2026-03-26 11:35:20 -07:00
Mitchell Hashimoto
11574c35a2 libghostty: expose paste encode to C API
Add ghostty_paste_encode() which encodes paste data for writing to
the terminal pty. It strips unsafe control bytes, wraps in bracketed
paste sequences when requested, and replaces newlines with carriage
returns for unbracketed mode. The input buffer is modified in place
and the encoded result is written to a caller-provided output buffer,
following the same buffer/out_written pattern as the other encode
functions like ghostty_size_report_encode.

Update the c-vt-paste example with an encode_example() demonstrating
the new function and add corresponding @snippet references in the
header documentation.
2026-03-26 11:28:23 -07:00
Mitchell Hashimoto
6ebbd4785b libghostty: expose terminal default colors via C API (#11868)
Add set/get support for foreground, background, cursor, and palette
default colors through ghostty_terminal_set and ghostty_terminal_get.

Four new set options (COLOR_FOREGROUND, COLOR_BACKGROUND, COLOR_CURSOR,
COLOR_PALETTE) write directly to the terminal color defaults. Passing
NULL clears the value for RGB colors or resets the palette to the
built-in default. All set operations mark the palette dirty flag for the
renderer.

Eight new get data types retrieve either the effective color (override
or default, via DynamicRGB.get) or the default color only (ignoring any
OSC overrides). Effective getters for RGB colors return the new NO_VALUE
result code when no color is configured. The palette getters return the
current or original palette respectively.

Adds the GHOSTTY_NO_VALUE result code for cases where a queried value is
simply not configured, distinct from GHOSTTY_INVALID_VALUE which
indicates a caller error.

## Example

```c
#include <ghostty/vt.h>
#include <stdio.h>

int main() {
  GhosttyTerminal terminal = NULL;
  GhosttyTerminalOptions opts = { .cols = 80, .rows = 24, .max_scrollback = 0 };
  ghostty_terminal_new(NULL, &terminal, opts);

  // Set default colors
  GhosttyColorRgb fg = { .r = 0xDD, .g = 0xDD, .b = 0xDD };
  GhosttyColorRgb bg = { .r = 0x1E, .g = 0x1E, .b = 0x2E };
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND, &fg);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND, &bg);

  // Read back the effective foreground
  GhosttyColorRgb color;
  if (ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND, &color)
      == GHOSTTY_SUCCESS) {
    printf("fg: #%02X%02X%02X\n", color.r, color.g, color.b);  // #DDDDDD
  }

  // After an OSC 10 override from a program inside the terminal:
  ghostty_terminal_vt_write(terminal, (const uint8_t*)"\x1B]10;rgb:FF/00/00\x1B\\", 20);

  // Effective returns the override, default returns the original
  ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND, &color);
  printf("effective: #%02X%02X%02X\n", color.r, color.g, color.b);  // #FF0000

  ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_COLOR_FOREGROUND_DEFAULT, &color);
  printf("default:   #%02X%02X%02X\n", color.r, color.g, color.b);  // #DDDDDD

  ghostty_terminal_free(terminal);
  return 0;
}
```

A full working example is in `example/c-vt-colors/`.
2026-03-26 10:00:04 -07:00
Mitchell Hashimoto
945920a186 vt: expose terminal default colors via C API
Add set/get support for foreground, background, cursor, and palette
default colors through ghostty_terminal_set and ghostty_terminal_get.

Four new set options (COLOR_FOREGROUND, COLOR_BACKGROUND, COLOR_CURSOR,
COLOR_PALETTE) write directly to the terminal color defaults. Passing
NULL clears the value for RGB colors or resets the palette to the
built-in default. All set operations mark the palette dirty flag for
the renderer.

Eight new get data types retrieve either the effective color (override
or default, via DynamicRGB.get) or the default color only (ignoring
any OSC overrides). Effective getters for RGB colors return the new
NO_VALUE result code when no color is configured. The palette getters
return the current or original palette respectively.

Adds the GHOSTTY_NO_VALUE result code for cases where a queried value
is simply not configured, distinct from GHOSTTY_INVALID_VALUE which
indicates a caller error.
2026-03-26 09:51:30 -07:00
Mitchell Hashimoto
0752320d3b ci: use namespace runners for windows jobs (#11864)
Switch the two Windows CI jobs (build-examples-cmake-windows and
build-libghostty-vt-windows) from GitHub-hosted windows-2025 runners to
namespace-profile-ghostty-windows runners.
2026-03-26 07:28:23 -07:00
Mitchell Hashimoto
4ffde268c5 ci: use namespace runners for windows jobs
Switch the two Windows CI jobs (build-examples-cmake-windows and
build-libghostty-vt-windows) from GitHub-hosted windows-2025 runners
to namespace-profile-ghostty-windows runners.
2026-03-26 07:19:45 -07:00
Mitchell Hashimoto
4e2b227b6a Add libghostty-vt source tarball (2.8 MB vs. 38 MB for Ghostty GUI) (#11863)
This makes it so that `zig build dist -Demit-lib-vt` produces a
`libghostty-vt-<version>.tar.gz` source tarball that only contains what
is needed to build and test libghostty-vt (it cannot build Ghostty GUI
on macOS or Linux). `distcheck` has been updated to also verify cmake
works.

The source tarball goes from 38 MB to 2.8 MB for libghostty.

I also updated CI to build and test this, and also contains an assertion
that our tarball is always less than 5 MB so we can be aware if/when we
blow it up.

The `release-tip` job was also updated to add the libghostty-vt tarball
to our tip release on GH.
2026-03-26 07:15:01 -07:00
Mitchell Hashimoto
96c414521a build: add cmake build verification to lib-vt distcheck
Run cmake configure and build on the extracted lib-vt tarball as
part of distcheck to ensure the CMake wrapper works from the
stripped archive. Keep dist/cmake/ and dist/libghostty-vt/ in the
archive since the CMake build needs them.
2026-03-26 07:04:15 -07:00
Mitchell Hashimoto
bfa3055309 ci: add distcheck for lib-vt source tarball
Add a build-dist-lib-vt job that runs distcheck with
-Demit-lib-vt=true and verifies the resulting tarball stays under
5 MB. Also downsize the build-dist runner from -md to -sm.
2026-03-26 07:00:14 -07:00
Mitchell Hashimoto
7ae1e32ecb ci: add libghostty-vt source tarball to tip release
Add a source-tarball-lib-vt job that builds the stripped lib-vt
dist tarball and publishes it as libghostty-vt-source.tar.gz to
the tip release. Also downsize the source-tarball runner from -md
to -sm since it does not need the extra resources.
2026-03-26 06:57:56 -07:00
Mitchell Hashimoto
7a59e966b8 build: strip large files from lib-vt dist tarball
When emit_lib_vt is set, the dist tarball is now named
ghostty-vt-<version>.tar.gz and excludes large files that are
unnecessary for building libghostty-vt. This reduces the archive
from ~36MB to ~2.8MB by excluding images, macOS app resources,
font assets, fuzz test corpus, crash testdata, and vendored
libraries not used by lib-vt.

GTK resources and frame data generation are also skipped since
lib-vt does not need them, which removes the GTK build-time
dependency. The distcheck step runs test-lib-vt instead of the
full test suite for lib-vt archives.
2026-03-26 06:56:30 -07:00
Mitchell Hashimoto
b839561e5d ci: update to Xcode 26.3 (#11853)
**WARNING:** We CANNOT upgrade to Xcode 26.4 with Zig 0.15 because:
https://codeberg.org/ziglang/zig/issues/31658

We have to wait and see if Zig will backport that or if we just have to
roll forward to Zig 0.16 when it comes out. At the time of this commit,
no released Zig version has the fix for that issue.
2026-03-25 20:07:57 -07:00
Mitchell Hashimoto
312ba7ac80 ci: update to Xcode 26.3
**WARNING:** We CANNOT upgrade to Xcode 26.4 with Zig 0.15 because:
https://codeberg.org/ziglang/zig/issues/31658

We have to wait and see if Zig will backport that or if we just have to
roll forward to Zig 0.16 when it comes out. At the time of this commit,
no released Zig version has the fix for that issue.
2026-03-25 19:46:50 -07:00
ghostty-vouch[bot]
efc0e4118a Update VOUCHED list (#11847)
Triggered by [discussion
comment](https://github.com/ghostty-org/ghostty/discussions/11669#discussioncomment-16318770)
from @jcollie.

Vouch: @brianc442

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-25 22:58:46 +00:00
Mitchell Hashimoto
2655aa47d3 build: fix libghostty shared lib install for Windows (#11840)
## Summary

- On Windows, install the shared lib as `ghostty.dll` and the static lib
as `ghostty-static.lib` instead of `libghostty.so` and `libghostty.a`
- The `-static` suffix on the static lib avoids collision with the
import lib that the DLL produces (same pattern as
`ghostty-vt-static.lib`)
- Guard `bundle_ubsan_rt` in `GhosttyLib.zig` `initStatic` for Windows,
since Zig's ubsan emits `/exclude-symbols` linker directives that are
incompatible with the MSVC linker (LNK4229). Matches the existing
pattern in `GhosttyLibVt.zig`

Also includes a cherry-pick of PR #11782 (backslash path handling) to
keep the Windows test suite fully passing on this branch.

## Discussion

- Is this better? This is me starting to question Claude's
training/output.

```zig
// Zig's ubsan emits /exclude-symbols linker directives that
// are incompatible with the MSVC linker (LNK4229).
lib.bundle_ubsan_rt = deps.config.target.result.os.tag != .windows;
```

More concise, still preserves the comment. Not sure which is preferred
here. The set-then-override matches `GhosttyLibVt.zig` exactly, but the
boolean is maybe cleaner? Open to either. Curious about your preference.

## Test results

Tested before/after on all three platforms:

| | Windows | Linux | Mac |
|---|---|---|---|
| **BEFORE** (upstream/main) | FAIL (pre-existing, fixed by PR 11782) |
PASS | PASS |
| **AFTER** (this branch) | PASS - 51/51 steps, 2604/2657 tests, 53
skipped | PASS | PASS |

No regressions on any platform.

## What I Learnt

- Zig's build system automatically generates an import `.lib` alongside
a `.dll` on Windows, so the static lib needs a distinct name to avoid
collision.
- The ubsan runtime emits MSVC-incompatible linker directives
2026-03-25 13:02:37 -07:00
Mitchell Hashimoto
d8e8697bad build: make sure CMake can clean up after libghostty-vt (#11845)
Fixes `cmake --build build --target clean`

Currently:

```
[1/1] Cleaning all built files...
FAILED: clean
ninja  -t clean
Cleaning... ninja: error: remove(_deps/ghostty-src/zig-out/lib): Directory not empty
ninja: error: remove(/...ghostling/build/_deps/ghostty-src/zig-out/lib): Directory not empty
33 files.
ninja: build stopped: subcommand failed.
```
2026-03-25 13:00:42 -07:00
Alessandro De Blasis
c5bb97bcbd build: fix libghostty shared lib install for Windows
On Windows, install as ghostty.dll + ghostty-static.lib instead of
libghostty.so + libghostty.a, following Windows naming conventions.
Guard ubsan_rt bundling in initStatic for MSVC compatibility.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 20:31:56 +01:00
ghostty-vouch[bot]
26ba9bf579 Update VOUCHED list (#11844)
Triggered by [discussion
comment](https://github.com/ghostty-org/ghostty/discussions/11843#discussioncomment-16314609)
from @jcollie.

Vouch: @paaloeye

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-25 18:48:33 +00:00
Paal Øye-Strømme
62aeabdc85 build: make sure CMake can clean up after libghostty-vt 2026-03-25 19:11:33 +01:00
Jeffrey C. Ollie
d5b6857673 windows: handle backslash paths in config value parsing (#11782)
# What

CommaSplitter treats backslash as an escape character, which breaks
Windows paths like
C:\Users\foo since \U is not a valid escape. On Windows, treat backslash
as a literal character
outside of quoted strings. Inside quotes, escape sequences still work as
before.

Also fix Theme.parseCLI to not mistake the colon in a Windows drive
letter (C:\...) for a
light/dark theme pair separator.

# How

The platform behavior is controlled by a single comptime constant at the
top of CommaSplitter:

const escape_outside_quotes = builtin.os.tag != .windows;

The next() function checks this constant to decide whether backslash
triggers escape parsing
outside quoted strings. All behavior lives in one place.

For Theme, skip colon detection at index 1 on Windows so drive letters
are not mistaken for pair
separators.

Escape-specific tests are skipped on Windows with SkipZigTest.
Windows-specific tests are added
separately to cover paths, literal backslash, and
escapes-still-work-inside-quotes.

# Note

There are other places in config parsing that use colon as a delimiter
without accounting for
Windows drive letters (command.zig prefix parsing, keybind parsing).
Those are separate from this
 PR.

# Verified

- zig build test-lib-vt passes on Windows (exit 0)
- No impact on Linux/macOS (the constant is true there, all existing
behavior unchanged)

# What I Learnt

- Platform behavior should live in a single constant or struct, not
scattered across if-else
branches in every test. The escape_outside_quotes constant mirrors the
pattern upstream uses with
PageAlloc = switch(builtin.os.tag) but for a simpler boolean case.
- Use error.SkipZigTest for tests that cannot run on a platform, never
silent returns. This way
the test runner reports them as skipped, not silently passed.
- When fixing a pattern (colon as delimiter), grep the whole codebase
for similar issues even if
you are not fixing them all in one PR. Note them for future work.
2026-03-25 13:07:45 -05:00
Mitchell Hashimoto
a8e65e829a libghostty: refactor lib calls into centralized terminal/lib.zig to prep for Zig to call C (#11831)
This parameterizes all our calling conventions on our C API based on
whether we're building the C lib or Zig lib. If we're building the C
lib, it's C calling convention, else Zig. This lets the Zig module call
the C API via `terminal.c_api.<func>`.

Zig is perfectly capable of calling C ABI but we actually modify our
struct layouts depending on calling conv so you can't actually use the
API prior to this. This fixes that all up.

**Why would you want to do this?** The C API has some different
semantics and stricter care about things like ABI compatibility (in how
it changes structs and so on). It actually might be a more API-stable
API to rely on even from Zig.
2026-03-25 08:48:52 -07:00
Mitchell Hashimoto
ad861d0821 zsh: fix trailing '%' in PS1/PS2 combining with marks (#11832)
When PS1 ends with a bare '%' (e.g. `%3~ %`), concatenating our 133;B
mark (`%{...%}`) directly after it causes zsh's prompt expansion to
interpret the '%' + '{' result as a '%{' escape sequence. This swallows
the 133;B mark and produces a visible '{' in the prompt.

Work around this by doubling a trailing '%' into '%%' before appending
marks, so it expands to a literal '%' and won't merge with the `%{`
token.
2026-03-25 08:47:39 -07:00
Mitchell Hashimoto
ac85a2f3d6 terminal: always use C ABI for now 2026-03-25 08:41:50 -07:00
Jon Parise
43f3dc5f13 zsh: fix trailing '%' in PS1/PS2 combining with marks
When PS1 ends with a bare '%' (e.g. `%3~ %`), concatenating our 133;B
mark (`%{...%}`) directly after it causes zsh's prompt expansion to
interpret the '%' + '{' result as a '%{' escape sequence. This swallows
the 133;B mark and produces a visible '{' in the prompt.

Work around this by doubling a trailing '%' into '%%' before appending
marks, so it expands to a literal '%' and won't merge with the `%{`
token.
2026-03-25 10:58:06 -04:00
Mitchell Hashimoto
3c9c3a4f54 terminal/c: use lib.alloc instead of direct lib/allocator.zig import
Each C API file independently imported ../../lib/allocator.zig as
lib_alloc. Now that terminal/lib.zig re-exports the allocator module
as lib.alloc, use that instead. This removes the redundant import
and keeps all lib dependencies flowing through the single lib.zig
entry point.
2026-03-25 07:31:21 -07:00
Mitchell Hashimoto
2f2f003aa5 terminal/c: use lib.calling_conv to allow Zig calling conv 2026-03-25 07:28:22 -07:00
Mitchell Hashimoto
f50aa90ced terminal: add lib.zig to centralize lib target and re-exports
Previously every file in the terminal package independently imported
build_options and ../lib/main.zig, then computed the same
lib_target constant. This was repetitive and meant each file needed
both imports just to get the target.

Introduce src/terminal/lib.zig which computes the target once and
re-exports the commonly used lib types (Enum, TaggedUnion, Struct,
String, checkGhosttyHEnum, structSizedFieldFits). All terminal
package files now import lib.zig and use lib.target instead of the
local lib_target constant, removing the per-file boilerplate.
2026-03-25 07:25:16 -07:00
Mitchell Hashimoto
bebca84668 vt: handle pixel sizes and size reports in ghostty_terminal_resize (#11818)
The resize function now requires cell_width_px and cell_height_px
parameters and handles the full resize sequence: computing and setting
width_px/height_px on the terminal, clearing synchronized output mode so
changes display immediately, and encoding a mode 2048 in-band size
report via the write_pty callback when that mode is enabled.

A valid width/height px is critical for some applications and protocols
and some applications rely directly on in-band size reports, so this
change is necessary to support those use cases.

I do wonder if for the Zig API we should be doing this in
`terminal.resize` or somewhere else, because as it stands this has to
all be manually done on the Zig side.
2026-03-24 14:30:14 -07:00
Mitchell Hashimoto
c12f62c82d vt: handle pixel sizes and size reports in ghostty_terminal_resize
The resize function now requires cell_width_px and cell_height_px
parameters and handles the full resize sequence: computing and
setting width_px/height_px on the terminal, clearing synchronized output mode 
so changes display immediately, and encoding a mode 2048 in-band size report
via the write_pty callback when that mode is enabled.

A valid width/height px is critical for some applications and protocols
and some applications rely directly on in-band size reports, so this
change is necessary to support those use cases.
2026-03-24 14:23:42 -07:00
Mitchell Hashimoto
f452087eac vt: add total_rows and scrollback_rows to terminal get API (#11817)
Add total_rows and scrollback_rows as new TerminalData variants
queryable through the existing ghostty_terminal_get interface, using the
cached O(1) total_rows field from PageList rather than introducing
standalone functions.
2026-03-24 14:14:15 -07:00
Mitchell Hashimoto
2c16c9e40c vt: add total_rows and scrollback_rows to terminal get API
Add total_rows and scrollback_rows as new TerminalData variants
queryable through the existing ghostty_terminal_get interface,
using the cached O(1) total_rows field from PageList rather than
introducing standalone functions.
2026-03-24 14:05:55 -07:00
Mitchell Hashimoto
a062c16e13 libghostty: pass pointer options directly to terminal_set (#11816)
Previously ghostty_terminal_set required all values to be passed as
pointers to the value, even when the value itself was already a pointer
(userdata, function pointer callbacks). This forced callers into awkward
patterns like compound literals or intermediate variables just to take
the address of a pointer.

Now pointer-typed options (userdata and all callbacks) are passed
directly as the value parameter. Only non-pointer types like
GhosttyString still require a pointer to the value. This simplifies
InType to return the actual stored type for each option and lets
setTyped work with those types directly.
2026-03-24 13:59:31 -07:00
Mitchell Hashimoto
6e34bc686c vt: pass pointer options directly to terminal_set
Previously ghostty_terminal_set required all values to be passed as
pointers to the value, even when the value itself was already a
pointer (userdata, function pointer callbacks). This forced callers
into awkward patterns like compound literals or intermediate
variables just to take the address of a pointer.

Now pointer-typed options (userdata and all callbacks) are passed
directly as the value parameter. Only non-pointer types like
GhosttyString still require a pointer to the value. This
simplifies InType to return the actual stored type for each option
and lets setTyped work with those types directly.
2026-03-24 13:52:49 -07:00
Mitchell Hashimoto
82f7527b30 vt: expose title and pwd in C API (#11815)
Add title and pwd as both gettable data keys
(GHOSTTY_TERMINAL_DATA_TITLE/PWD) and settable options
(GHOSTTY_TERMINAL_OPT_TITLE/PWD) in the C terminal API. Getting returns
a borrowed GhosttyString; setting copies the data into the terminal via
setTitle/setPwd.

The underlying Terminal.setTitle/setPwd now append a null sentinel so
that getTitle/getPwd can return sentinel-terminated slices ([:0]const
u8), which is useful for downstream consumers that need C strings.

Change ghostty_terminal_set to return GhosttyResult instead of void so
that the new title/pwd options can report allocation failures. Existing
option-setting calls cannot fail so the return value is
backwards-compatible for callers that discard it.
2026-03-24 13:17:43 -07:00
Mitchell Hashimoto
8f1ac0bd4e vt: expose title and pwd in C API
Add title and pwd as both gettable data keys
(GHOSTTY_TERMINAL_DATA_TITLE/PWD) and settable options
(GHOSTTY_TERMINAL_OPT_TITLE/PWD) in the C terminal API. Getting
returns a borrowed GhosttyString; setting copies the data into the
terminal via setTitle/setPwd.

The underlying Terminal.setTitle/setPwd now append a null sentinel so
that getTitle/getPwd can return sentinel-terminated slices ([:0]const
u8), which is useful for downstream consumers that need C strings.

Change ghostty_terminal_set to return GhosttyResult instead of void
so that the new title/pwd options can report allocation failures.
Existing option-setting calls cannot fail so the return value is
backwards-compatible for callers that discard it.
2026-03-24 13:13:29 -07:00
Mitchell Hashimoto
f21455b7e7 build: refactor checkGhosttyHEnum to use @hasDecl for Windows compatibility (#11813)
### This is it! This one (and the other stacked PRs) and #11782 should
finally give a clean test run on Windows!


## Summary

- Increase `@setEvalBranchQuota` from 1M to 10M (too much? how much is
too much?) in `checkGhosttyHEnum` (src/lib/enum.zig)
- Fixes the only remaining test failure on Windows MSVC: `ghostty.h
MouseShape`

## Context
This one was fun! Claude started blabbering, diminishing returns it
said. It couldn't figure out. So I called Dario and it worked.
Nah, much easier than that.

On MSVC, the translate-c output for `ghostty.h` is ~360KB with ~2173
declarations (vs ~112KB / ~1502 on Linux/Mac) because `<sys/types.h>`
and `<BaseTsd.h>` pull in Windows SDK headers. The `checkGhosttyHEnum`
function uses a nested `inline for` (enum fields x declarations) with
comptime string comparisons. For MouseShape (34 variants), this
generates roughly 34 x 2173 x ~20 = ~1.5M comptime branches, exceeding
the 1M quota.

The failure was confusing because it presented as a runtime error
("ghostty.h is missing value for GHOSTTY_MOUSE_SHAPE_DEFAULT") rather
than a compile error. The constants exist in the translate-c output and
the test compiles, but the comptime loop silently stops matching when it
hits the branch limit, so `set.remove` is never called and the set
reports all entries as missing at runtime.

## How we found it
The translate-c output clearly had all 34 GHOSTTY_MOUSE_SHAPE_*
constants, yet the test reported all of them as missing. I asked Claude
to list 5 hypotheses (decl truncation, branch quota, string comparison
bug, declaration ordering, field access failure) and to write 7 targeted
POC tests in enum.zig to isolate each step of `checkGhosttyHEnum`:

1. POC1-2: Module access and declaration count (both passed)
2. POC3: `@hasDecl` for the constant (passed)
3. POC4: Direct field value access (passed)
4. POC5: `inline for` over decls with string comparison - **compile
error: "evaluation exceeded 1000 backwards branches"**
5. POC6: Same but with 10M quota (passed)
6. POC7: Full `checkGhosttyHEnum` clone with 10M quota - **passed,
confirming the fix**

POC5 was the key: the default 1000 branch limit for test code confirmed
the comptime budget mechanism. The existing 1M quota in
`checkGhosttyHEnum` was enough for Linux/Mac (1502 declarations) but not
for MSVC (2173 declarations) with larger enums.

## Stack
Stacked on 016-windows/fix-libcxx-msvc.

## Test plan

### Cross-platform results (`zig build test` / `zig build
-Dapp-runtime=none test` on Windows)

| | Windows | Linux | Mac |
|---|---|---|---|
| **BEFORE** (016, ce9930051) | FAIL - 49/51, 2630/2654, 1 test failed,
23 skipped | PASS - 86/86, 2655/2678, 23 skipped | PASS - 160/160,
2655/2662, 7 skipped |
| **AFTER** (017, 68378a0bb) | FAIL - 49/51, 2631/2654, 23 skipped |
PASS - 86/86, 2655/2678, 23 skipped | PASS - 160/160, 2655/2662, 7
skipped |

### Windows: what changed (2630 -> 2631 tests, MouseShape fixed)

**Fixed by this PR:**
- `ghostty.h MouseShape` test - was failing because comptime branch
quota exhaustion silently prevented the inline for loop from matching
any constants

**Remaining failure (pre-existing, unrelated):**
- `config.Config.test.clone can then change conditional state` -
segfaults (exit code 3) on Windows. We investigated this and it looked
familiar.. cherry-picking the `CommaSplitter `fix from PR #11782
resolved it! The backslash path handling in `CommaSplitter `breaks theme
path parsing on Windows, which is exactly what that PR addresses. So
once that lands, we should be in a good place... ready to ship to
Windows users! (just kidding)

### Linux/macOS: no regressions
Identical pass counts and test results before and after.

## What I Learnt
- Comptime branch quota exhaustion in Zig does not always surface as a
clean compile error. When it happens inside an `inline for` loop with
`comptime` string comparisons that gate runtime code (like
`set.remove`), the effect is that matching code is silently not
generated. The test compiles and runs, but the runtime behavior is wrong
because the matching branches were never emitted. This makes the failure
look like a data issue (missing declarations) rather than a compile
budget issue.
- When debugging comptime issues, writing small isolated POC tests that
exercise each step of the failing function independently is very
effective. It took 7 targeted tests to pinpoint the exact failure point.
- Cross-platform translate-c outputs can vary significantly in size. On
MSVC, system headers are much larger than on Linux/Mac, which affects
comptime budgets for any code that iterates over translated module
declarations.
2026-03-24 12:56:21 -07:00
Mitchell Hashimoto
d5bd331c91 libghostty: C API for terminal "effects" for processing output and side effects (#11814)
This adds the terminal effects callback system to the libghostty-vt C
API.

Previously, `ghostty_terminal_vt_write()` silently ignored VT sequences
that produce side effects or require responses (bell, title changes,
device status queries, etc.). With this change, embedders can register
callbacks via `ghostty_terminal_set()` to handle these sequences.

This has already existed in the Zig API.

## Effects

| Option | Callback Type | Trigger |
|--------|--------------|---------|
| `GHOSTTY_TERMINAL_OPT_WRITE_PTY` | `GhosttyTerminalWritePtyFn` | Query
responses written back to the pty |
| `GHOSTTY_TERMINAL_OPT_BELL` | `GhosttyTerminalBellFn` | BEL character
(0x07) |
| `GHOSTTY_TERMINAL_OPT_TITLE_CHANGED` | `GhosttyTerminalTitleChangedFn`
| Title change via OSC 0 / OSC 2 |
| `GHOSTTY_TERMINAL_OPT_ENQUIRY` | `GhosttyTerminalEnquiryFn` | ENQ
character (0x05) |
| `GHOSTTY_TERMINAL_OPT_XTVERSION` | `GhosttyTerminalXtversionFn` |
XTVERSION query (CSI > q) |
| `GHOSTTY_TERMINAL_OPT_SIZE` | `GhosttyTerminalSizeFn` | XTWINOPS size
query (CSI 14/16/18 t) |
| `GHOSTTY_TERMINAL_OPT_COLOR_SCHEME` | `GhosttyTerminalColorSchemeFn` |
Color scheme query (CSI ? 996 n) |
| `GHOSTTY_TERMINAL_OPT_DEVICE_ATTRIBUTES` |
`GhosttyTerminalDeviceAttributesFn` | Device attributes query (CSI c / >
c / = c) |

## Example

```c
#include <stdio.h>
#include <string.h>
#include <ghostty/vt.h>

void on_write_pty(GhosttyTerminal terminal, void* userdata,
                  const uint8_t* data, size_t len) {
  (void)terminal; (void)userdata;
  printf("  write_pty (%zu bytes): ", len);
  fwrite(data, 1, len, stdout);
  printf("\n");
}

void on_bell(GhosttyTerminal terminal, void* userdata) {
  (void)terminal;
  int* count = (int*)userdata;
  (*count)++;
  printf("  bell! (count=%d)\n", *count);
}

int main() {
  GhosttyTerminal terminal = NULL;
  GhosttyTerminalOptions opts = { .cols = 80, .rows = 24, .max_scrollback = 0 };
  if (ghostty_terminal_new(NULL, &terminal, opts) != GHOSTTY_SUCCESS)
    return 1;

  // Attach userdata and callbacks
  int bell_count = 0;
  void* ud = &bell_count;
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_USERDATA, &ud);

  GhosttyTerminalWritePtyFn write_fn = on_write_pty;
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY, &write_fn);

  GhosttyTerminalBellFn bell_fn = on_bell;
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_BELL, &bell_fn);

  // BEL triggers the bell callback
  const uint8_t bel = 0x07;
  ghostty_terminal_vt_write(terminal, &bel, 1);

  // DECRQM triggers write_pty with the mode response
  const char* decrqm = "\x1B[?7$p";
  ghostty_terminal_vt_write(terminal, (const uint8_t*)decrqm, strlen(decrqm));

  ghostty_terminal_free(terminal);
  return 0;
}
```
2026-03-24 12:55:17 -07:00
Alessandro De Blasis
81e21e4d0a build: refactor checkGhosttyHEnum to use @hasDecl instead of nested inline for
Replace the O(N×M) nested inline for loop with direct @hasDecl lookups.
The old approach iterated over all translate-c declarations for each enum
field, which required a 10M comptime branch quota on MSVC (2173 decls ×
138 fields × ~20 branches). The new approach constructs the expected
declaration name and checks directly, reducing to O(N) and needing only
100K quota on all platforms.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 20:12:57 +01:00
Mitchell Hashimoto
d2c6a3c775 vt: store DA1 feature buffer in wrapper struct
The DA1 trampoline was converting C feature codes into a local
stack buffer and returning a slice pointing into it. This is
unsound because the slice outlives the stack frame once the
trampoline returns, leaving reportDeviceAttributes reading
invalid memory.

Move the scratch buffer into the wrapper effects struct so that
its lifetime extends beyond the trampoline call, keeping the
returned slice valid for the caller.
2026-03-24 12:07:26 -07:00
Mitchell Hashimoto
e36b745314 fmt 2026-03-24 11:48:27 -07:00
Mitchell Hashimoto
4128e6a38c vt: add effects documentation section with example
Add a comprehensive "Effects" section to the terminal module
documentation in terminal.h explaining the callback system that
lets embedding applications react to terminal-initiated events
(bell, title changes, pty writes, device queries, etc.). The
section includes a reference table of all available effects and
their triggers, plus @snippet references to the new example.

Add c-vt-effects example project demonstrating how to register
write_pty, bell, and title_changed callbacks, attach userdata,
and feed VT data that triggers each effect.
2026-03-24 11:46:02 -07:00
Mitchell Hashimoto
bbfe1c2787 vt: use struct literal for handler effects assignment
Assign handler.effects as a struct literal instead of setting fields
individually. This lets the compiler catch missing fields if new
effects are added to the Effects struct.

Also sort the callback function typedefs in vt/terminal.h
alphabetically (Bell, ColorScheme, DeviceAttributes, Enquiry, Size,
TitleChanged, WritePty, Xtversion).
2026-03-24 11:36:38 -07:00