Skip to main content

ghostty_key_encoder_encode

Function ghostty_key_encoder_encode 

Source
pub unsafe extern "C" fn ghostty_key_encoder_encode(
    encoder: GhosttyKeyEncoder_ptr,
    event: GhosttyKeyEvent_ptr,
    out_buf: *mut c_char,
    out_buf_size: usize,
    out_len: *mut usize,
) -> GhosttyResult
Expand description

Encode a key event into a terminal escape sequence.

Converts a key event into the appropriate terminal escape sequence based on the encoder’s current options. The sequence is written to the provided buffer.

Not all key events produce output. For example, unmodified modifier keys typically don’t generate escape sequences. Check the out_len parameter to determine if any data was written.

If the output buffer is too small, this function returns GHOSTTY_OUT_OF_SPACE and out_len will contain the required buffer size. The caller can then allocate a larger buffer and call the function again.

@param encoder The encoder handle, must not be NULL @param event The key event to encode, must not be NULL @param out_buf Buffer to write the encoded sequence to @param out_buf_size Size of the output buffer in bytes @param out_len Pointer to store the number of bytes written (may be NULL) @return GHOSTTY_SUCCESS on success, GHOSTTY_OUT_OF_SPACE if buffer too small, or other error code

§Example: Calculate required buffer size

@code{.c} // Query the required size with a NULL buffer (always returns OUT_OF_SPACE) size_t required = 0; GhosttyResult result = ghostty_key_encoder_encode(encoder, event, NULL, 0, &required); assert(result == GHOSTTY_OUT_OF_SPACE);

// Allocate buffer of required size char *buf = malloc(required);

// Encode with properly sized buffer size_t written = 0; result = ghostty_key_encoder_encode(encoder, event, buf, required, &written); assert(result == GHOSTTY_SUCCESS);

// Use the encoded sequence…

free(buf); @endcode

§Example: Direct encoding with static buffer

@code{.c} // Most escape sequences are short, so a static buffer often suffices char buf[128]; size_t written = 0; GhosttyResult result = ghostty_key_encoder_encode(encoder, event, buf, sizeof(buf), &written);

if (result == GHOSTTY_SUCCESS) { // Write the encoded sequence to the terminal write(pty_fd, buf, written); } else if (result == GHOSTTY_OUT_OF_SPACE) { // Buffer too small, written contains required size char *dynamic_buf = malloc(written); result = ghostty_key_encoder_encode(encoder, event, dynamic_buf, written, &written); assert(result == GHOSTTY_SUCCESS); write(pty_fd, dynamic_buf, written); free(dynamic_buf); } @endcode

@ingroup key