When we look at text displayed in a terminal, it might appear simple at first glance. However, terminals are capable of much more than just displaying plain text. They can change text colors, apply styles such as bold or underline, move the cursor to different positions on the screen, and even clear or redraw sections of the display. All of these capabilities are made possible through ANSI escape codes.
ANSI escape codes are special sequences of characters that instruct the terminal to perform specific formatting or control actions. Instead of printing these sequences as visible text, the terminal interprets them as commands that modify how the output is displayed. These commands can change text colors, control cursor movement, clear the screen, or apply formatting styles.
For example, a program can send a sequence to the terminal that tells it to display text in red, and another sequence to reset the text back to the default color. These sequences typically begin with a special escape character followed by a set of parameters that define the desired action.
A simple example looks like this:
ESC[31m
This sequence tells the terminal to switch the text color to red. After printing colored text, another sequence can reset the formatting:
ESC[0m
Together, these escape codes allow developers to produce rich terminal output such as colored logs, highlighted messages, and structured terminal layouts.
Many command-line tools rely heavily on ANSI escape codes to improve readability and user experience. For instance, system monitoring tools, interactive dashboards, and modern terminal applications use these codes to render colored tables, progress bars, and dynamic updates within the terminal window.
In Java applications, developers can work with ANSI escape codes directly or use libraries such as Jansi, which provides a convenient way to generate ANSI-formatted output across different operating systems.
In this post, we will explore what ANSI escape codes are, how escape sequences are structured, and how they are used to format text, clear the screen, and control cursor movement in terminal applications. By understanding these concepts, you will gain deeper insight into how terminals interpret formatting commands and how developers create interactive and visually structured terminal output.
1. What are ANSI Escape Codes
ANSI escape codes are special sequences of characters used to control the formatting and behavior of text displayed in a terminal.
Instead of displaying these sequences as normal text, the terminal interprets them as commands that modify how text appears or how the cursor behaves. These commands can be used to:
· change text color
· apply styles like bold or underline
· move the cursor to a specific position
· clear parts of the screen
· update the display dynamically
The term ANSI comes from the American National Standards Institute, which defined standards for terminal control sequences. These escape codes became widely adopted across operating systems and terminal programs.
Today, most terminal emulators support ANSI escape codes, allowing applications to produce colorful and interactive terminal output.
For example, a command-line tool might use ANSI codes to:
· highlight errors in red
· display success messages in green
· show warnings in yellow
These visual cues make terminal output easier to read and understand.
HelloAnsi.java
public class HelloAnsi { public static void main(String[] args) { // ANSI escape codes String RESET = "\u001B[0m"; String RED = "\u001B[31m"; String GREEN = "\u001B[32m"; String YELLOW = "\u001B[33m"; String BOLD = "\u001B[1m"; System.out.println("Normal Text"); System.out.println(RED + "Error: Something went wrong" + RESET); System.out.println(GREEN + "Success: Operation completed" + RESET); System.out.println(YELLOW + "Warning: Check your input" + RESET); System.out.println(BOLD + "Bold Text Example" + RESET); } }
Compile and run the Application.
2. Structure of Escape Sequences
ANSI escape sequences follow a specific structure.
They begin with an escape character, followed by parameters that define the action the terminal should perform.
A typical ANSI escape sequence looks like this:
ESC [ parameters command
Where:
· ESC is the escape character
· [ indicates the start of a control sequence
· parameters specify the formatting or action
· command defines what operation should be executed
In most programming languages, the escape character is written as: \033 or \u001B.
Example
\u001B[31m
This sequence instructs the terminal to change the text color to red. The letter m at the end indicates a text formatting command.
3. Formatting Text
One of the most common uses of ANSI escape codes is text formatting.
These codes allow developers to modify the appearance of text by applying styles such as:
· colors
· bold
· underline
· background colors
Example formatting codes:
|
Code |
Meaning |
|
30 |
Black |
|
31 |
Red |
|
32 |
Green |
|
33 |
Yellow |
|
34 |
Blue |
|
1 |
Bold |
|
4 |
Underline |
|
0 |
Reset formatting |
For example, the code ESC[31m changes the text color to red.
Many CLI tools rely on color formatting to improve readability.
For example:
· errors displayed in red
· success messages displayed in green
· warnings displayed in yellow
4. Clearing the Screen
ANSI escape codes can also be used to clear the terminal screen. This is useful for applications that continuously update the display, such as system monitors or dashboards.
The common escape sequence used to clear the screen is: ESC[2J
This command instructs the terminal to clear all characters from the screen.
Sometimes applications also move the cursor back to the top-left corner after clearing the screen using ESC[H code.
This combination is frequently used in interactive terminal applications to refresh the display.
For example, a monitoring application might:
· clear the screen
· print updated metrics
· repeat the process every second
This creates the effect of a live updating dashboard.
AnsiDemo.java
public class AnsiDemo { // ANSI Escape Codes private static final String RESET = "\u001B[0m"; private static final String RED = "\u001B[31m"; private static final String GREEN = "\u001B[32m"; private static final String YELLOW = "\u001B[33m"; private static final String BOLD = "\u001B[1m"; // Clear screen and move cursor to top private static final String CLEAR_SCREEN = "\u001B[2J"; private static final String CURSOR_HOME = "\u001B[H"; public static void main(String[] args) throws InterruptedException { System.out.println(BOLD + "ANSI Escape Code Demo" + RESET); System.out.println(); System.out.println(RED + "Error: Something went wrong" + RESET); System.out.println(GREEN + "Success: Operation completed" + RESET); System.out.println(YELLOW + "Warning: Check configuration" + RESET); System.out.println(); System.out.println("Screen will refresh in 3 seconds..."); // Pause so user can see the output Thread.sleep(3000); // Clear screen System.out.print(CLEAR_SCREEN); // Move cursor to top-left System.out.print(CURSOR_HOME); // Simulate refreshed dashboard System.out.println(BOLD + "System Monitor (Demo)" + RESET); System.out.println("----------------------------"); System.out.println(GREEN + "CPU Usage: 32%" + RESET); System.out.println(YELLOW + "Memory Usage: 68%" + RESET); System.out.println(RED + "Disk Usage: 91%" + RESET); System.out.println(); System.out.println("Display refreshed using ANSI escape codes."); } }
Compile and run above application to see the behavior.
5. Moving the Cursor
ANSI escape codes also allow programs to control the cursor position on the screen. Instead of printing text sequentially, applications can move the cursor to a specific location before writing output.
Example cursor movement sequence:
ESC[row;columnH
Example:
ESC[5;10H
This moves the cursor to Row 5 and Column 10.
Once the cursor is moved, any new text will appear at that position. This capability allows developers to build structured layouts such as:
· tables
· dashboards
· menus
· status bars
Many terminal-based applications rely on cursor movement to update only specific parts of the screen rather than redrawing everything.
Example
ESC[31mHello WorldESC[0m
The terminal interprets above statement as:
· switch to red text
· print "Hello World"
· reset formatting
6. Using ANSI Escape Codes in Java with Jansi
In Java applications, ANSI escape codes can be written directly into output strings. However, this approach may not work consistently across all operating systems.
To solve this problem, developers often use libraries such as Jansi, which provide cross-platform support for ANSI formatting.
Example Java code using Jansi:
AnsiExample.java
package com.sample.app; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; public class AnsiExample { public static void main(String[] args) { AnsiConsole.systemInstall(); // Title System.out.println(Ansi.ansi().bold().fgBrightBlue().a("\n==============================") .a("\n SYSTEM DASHBOARD").a("\n==============================\n").reset()); // System Status Section System.out.println(Ansi.ansi().bold().fgBrightYellow().a("System Status").reset()); System.out.println(Ansi.ansi().fgBrightGreen().a("✔ Server Status : RUNNING").reset()); System.out.println(Ansi.ansi().fgBrightGreen().a("✔ Database : CONNECTED").reset()); System.out.println(Ansi.ansi().fgBrightYellow().a("⚠ Cache Usage : 75%").reset()); System.out.println(Ansi.ansi().fgBrightRed().a("✖ Failed Jobs : 2").reset()); // Metrics Section System.out.println(Ansi.ansi().bold().fgBrightYellow().a("\nApplication Metrics").reset()); System.out.println(Ansi.ansi().fgCyan().a("Requests/sec : 145").reset()); System.out.println(Ansi.ansi().fgCyan().a("Active Users : 32").reset()); System.out.println(Ansi.ansi().fgCyan().a("Avg Response : 120 ms").reset()); // Recent Logs Section System.out.println(Ansi.ansi().bold().fgBrightYellow().a("\nRecent Logs").reset()); System.out.println(Ansi.ansi().fgGreen().a("[INFO] Application started").reset()); System.out.println(Ansi.ansi().fgYellow().a("[WARN] High memory usage detected").reset()); System.out.println(Ansi.ansi().fgRed().a("[ERROR] Job execution failed").reset()); System.out.println(Ansi.ansi().fgGreen().a("[INFO] Backup completed successfully").reset()); AnsiConsole.systemUninstall(); } }
Output
7. How Terminals Interpret These Commands
When a program prints an ANSI escape sequence, the terminal does not display the characters literally. Instead, it interprets the sequence as a control instruction.
For example:
ESC[31mHelloESC[0m
The terminal processes this as:
· Change text color to red
· Display the word "Hello"
· Reset formatting
This interpretation happens instantly, allowing applications to produce visually rich terminal output.
In summary, ANSI escape codes allow terminal applications to control how text is displayed and how the screen behaves.
They enable developers to:
· change text colors
· apply formatting styles
· move the cursor
· clear the screen
· create dynamic terminal interfaces
Libraries such as Jansi simplify the use of ANSI escape codes in Java applications by providing a clean and portable way to generate formatted terminal output.
Understanding ANSI escape codes is an essential step toward building interactive terminal applications and Text User Interfaces (TUI).
Previous Next Home


No comments:
Post a Comment