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.
This commit is contained in:
Mitchell Hashimoto
2026-03-26 11:26:56 -07:00
parent 6ebbd4785b
commit 11574c35a2
6 changed files with 165 additions and 6 deletions

View File

@@ -1,7 +1,7 @@
# Example: `ghostty-vt` Paste Safety Check
# Example: `ghostty-vt` Paste Utilities
This contains a simple example of how to use the `ghostty-vt` paste
utilities to check if paste data is safe.
utilities to check if paste data is safe and encode it for terminal input.
This uses a `build.zig` and `Zig` to build the C program so that we
can reuse a lot of our build logic and depend directly on our source

View File

@@ -3,7 +3,7 @@
#include <ghostty/vt.h>
//! [paste-safety]
void basic_example() {
void safety_example() {
const char* safe_data = "hello world";
const char* unsafe_data = "rm -rf /\n";
@@ -17,8 +17,26 @@ void basic_example() {
}
//! [paste-safety]
//! [paste-encode]
void encode_example() {
// The input buffer is modified in place (unsafe bytes are stripped).
char data[] = "hello\nworld";
char buf[64];
size_t written = 0;
GhosttyResult result = ghostty_paste_encode(
data, strlen(data), true, buf, sizeof(buf), &written);
if (result == GHOSTTY_SUCCESS) {
printf("Encoded %zu bytes: ", written);
fwrite(buf, 1, written, stdout);
printf("\n");
}
}
//! [paste-encode]
int main() {
basic_example();
safety_example();
// Test unsafe paste data with bracketed paste end sequence
const char *unsafe_escape = "evil\x1b[201~code";
@@ -32,5 +50,7 @@ int main() {
printf("Empty data is safe\n");
}
encode_example();
return 0;
}