How to clear terminal?

I’m looking to make a terminal application as a learning exercise for zig.
Currently, trying to figure out how to clear the terminal either partially or fully.
Is there a zig way to do this; or should I be looking at using C code and zig’s inter-op?

Depending on what you’re looking for. If you use a library like
ncurses, it should provide a function to clear terminal. On the other
hand, printing “\x1B[2J\x1B[H” (clear the entire screen and move the
cursor to top left
)
should do the job, but it should not be used if you are just
to provide dialogs.

2 Likes

The idea of using escape codes completely slipped by.
Thanks

I make GitHub - nektro/zig-ansi: ANSI utilities for CLI usage in Zig. that can assist in the construction of the escape codes

1 Like
//ansi escape codes
const esc = "\x1B";
const csi = esc ++ "[";

const cursor_show = csi ++ "?25h"; //h=high
const cursor_hide = csi ++ "?25l"; //l=low
const cursor_home = csi ++ "1;1H"; //1,1

const color_fg = "38;5;";
const color_bg = "48;5;";
const color_fg_def = csi ++ color_fg ++ "15m"; // white
const color_bg_def = csi ++ color_bg ++ "0m"; // black
const color_def = color_bg_def ++ color_fg_def;

const screen_clear = csi ++ "2J";
const screen_buf_on = csi ++ "?1049h"; //h=high
const screen_buf_off = csi ++ "?1049l"; //l=low

const nl = "\n";

const term_on = screen_buf_on ++ cursor_hide ++ cursor_home ++ screen_clear ++ color_def;
const term_off = screen_buf_off ++ cursor_show ++ nl;

emit term_on at the beginning, term_off when you’re done.

plunder at will from DOOM-fire-zig/main.zig at master · const-void/DOOM-fire-zig · GitHub !

Unfortunately terminal applications can get a bit complicated because terminals can differ in their behavior and the escape codes they support.

There are two projects, “termcap” and “terminfo” depending on which distro you use that will keep track of all the terminals you have installed and common ones that could connect, even remote ones. Terminal libraries like “ncurses” will use the TERM environment variable to identify the current terminal and grab it’s capabilities/behavior from these databases. It then provides a higher level API that will adapt what it emits depending on the information from this terminal database.

Maybe more than you wanted to know, but there it is :slight_smile:

4 Likes