ascii-chat 0.6.0
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
ansi.c File Reference

ANSI escape sequence utilities. More...

Go to the source code of this file.

Functions

char * ansi_strip_escapes (const char *input, size_t input_len)
 Strip all ANSI escape sequences from a string.
 

Detailed Description

ANSI escape sequence utilities.

Definition in file ansi.c.

Function Documentation

◆ ansi_strip_escapes()

char * ansi_strip_escapes ( const char *  input,
size_t  input_len 
)

Strip all ANSI escape sequences from a string.

Removes all ANSI CSI sequences (ESC [ ... final_byte) from the input, leaving only printable text. Useful for creating plain text output from colorized ASCII art.

Parameters
inputInput string containing ANSI escape sequences
input_lenLength of input string
Returns
Newly allocated string with escapes removed (caller must free), or NULL on error

Definition at line 13 of file ansi.c.

13 {
14 if (!input || input_len == 0) {
15 return NULL;
16 }
17
18 // Output will be at most input_len (stripping only removes chars)
19 outbuf_t ob = {0};
20 ob_reserve(&ob, input_len);
21
22 size_t i = 0;
23 while (i < input_len) {
24 // Check for ESC character (start of ANSI sequence)
25 if (input[i] == '\x1b' && i + 1 < input_len && input[i + 1] == '[') {
26 // Skip ESC[
27 i += 2;
28
29 // Skip parameter bytes (digits, semicolons, and intermediate bytes)
30 while (i < input_len) {
31 char c = input[i];
32 // Parameter bytes: 0x30-0x3F (digits, semicolon, etc.)
33 // Intermediate bytes: 0x20-0x2F (space, !, ", etc.)
34 if ((c >= 0x30 && c <= 0x3F) || (c >= 0x20 && c <= 0x2F)) {
35 i++;
36 } else {
37 break;
38 }
39 }
40
41 // Skip final byte (0x40-0x7E: @, A-Z, [, \, ], ^, _, `, a-z, {, |, }, ~)
42 if (i < input_len) {
43 char final = input[i];
44 if (final >= 0x40 && final <= 0x7E) {
45 i++;
46 }
47 }
48 } else {
49 // Regular character - copy to output
50 ob_putc(&ob, input[i]);
51 i++;
52 }
53 }
54
55 ob_term(&ob);
56 return ob.buf;
57}
void ob_term(outbuf_t *ob)
Append null terminator to buffer.
void ob_putc(outbuf_t *ob, char c)
Append a character to buffer.
void ob_reserve(outbuf_t *ob, size_t need)
Reserve buffer space for upcoming writes.
Dynamic output buffer (auto-expanding)
char * buf
Buffer pointer (allocated, owned by caller, must be freed)

References outbuf_t::buf, ob_putc(), ob_reserve(), and ob_term().