AnsiUtils 1.0.3
dotnet add package AnsiUtils --version 1.0.3
NuGet\Install-Package AnsiUtils -Version 1.0.3
<PackageReference Include="AnsiUtils" Version="1.0.3" />
<PackageVersion Include="AnsiUtils" Version="1.0.3" />
<PackageReference Include="AnsiUtils" />
paket add AnsiUtils --version 1.0.3
#r "nuget: AnsiUtils, 1.0.3"
#:package AnsiUtils@1.0.3
#addin nuget:?package=AnsiUtils&version=1.0.3
#tool nuget:?package=AnsiUtils&version=1.0.3
AnsiUtils
A lightweight .NET library for working with ANSI console colors and text manipulations. The library provides extension methods for colorizing console text and handling string operations that respect ANSI escape sequences.
Features
- Easy-to-use extension methods for adding colors and styles to console text
- Support for standard ANSI colors (foreground and background)
- Support for bright ANSI colors (foreground and background)
- RGB color support for terminals that support it
- Grayscale color support (24 levels)
- String manipulation functions that respect ANSI codes (substring, padding, centering, etc.)
- Text wrapping and columnar formatting with ANSI code preservation
- Advanced text formatting utilities via AnsiText class:
- ANSI-aware table formatting for objects and dictionaries
- Customizable progress bars with color support
- Bordered boxes in multiple styles (Single, Double, Rounded, ASCII)
- Formatted lists with bullets, numbers, checkboxes, and custom markers
- Horizontal separators and dividers with label positioning
- Spinner frames for console animations
- Status indicators with colored icons
- Global and per-call color customization
Installation
dotnet add package AnsiUtils
Usage Examples
Basic Colors and Styles
using System;
using AnsiUtils;
// Initialize ANSI support
AnsiConsole.Initialize();
// Use extension methods for simple colors
Console.WriteLine("This is ".Red() + "colored".Green() + " text!".Blue());
// Mix colors with styles
Console.WriteLine("Bold Red".Red().Bold());
Console.WriteLine("Underlined Cyan".Cyan().Underline());
Console.WriteLine("Blinking Yellow".Yellow().Blink());
Console.WriteLine("Inverse Magenta".Magenta().Inverse());
// Background colors
Console.WriteLine("White on Blue".White().OnBlue());
// Bright colors
Console.WriteLine("Bright Green".BrightGreen());
Console.WriteLine("Bright Red on Bright Blue".BrightRed().OnBrightBlue());
// Restore original Console.Out when done (optional)
AnsiConsole.Restore();
RGB Colors
using AnsiUtils;
// RGB colors for terminals that support it
Console.WriteLine("Custom RGB Color".Rgb(135, 206, 235));
Console.WriteLine("Text on RGB background".BgRgb(255, 192, 203));
ANSI-Aware String Operations
using AnsiUtils;
string coloredText = "This is [red]colored[normal] text with [blue]blue[normal] parts";
// Get length ignoring ANSI codes
int length = coloredText.AnsiLength(); // Returns 35 instead of 59
// Substring that preserves ANSI codes
string part = coloredText.AnsiSubstring(8, 15); // Returns "is [red]colored[normal] text"
// Find text ignoring ANSI codes
int pos = coloredText.AnsiIndexOf("blue"); // Finds "blue" at the correct position
// Padding and alignment
string centered = coloredText.AnsiCenter(50);
string leftPad = coloredText.AnsiPadLeft(50);
string rightPad = coloredText.AnsiPadRight(50);
Text Formatting
using AnsiUtils;
// Format text in columns
var items = new List<string> {
"Item 1".Red(),
"Item 2".Green(),
"Item 3".Blue(),
"Item 4".Yellow()
};
var columns = items.Columnize(2, 40);
foreach (var line in columns)
{
Console.WriteLine(line);
}
// Wrap text
string longText = "This is a [red]very long text[normal] that needs to be wrapped to multiple lines";
var wrappedLines = longText.WrapText(40);
foreach (var line in wrappedLines)
{
Console.WriteLine(line);
}
Advanced Text Formatting with AnsiText
The AnsiText
class provides a comprehensive set of static methods for creating formatted console UI elements with full ANSI color support and customizable styling.
Table Formatting
Format collections of objects as aligned tables with ANSI-aware column sizing:
using AnsiUtils;
// Format a list of objects as a table
var users = new List<User> {
new User { Name = "Alice", Age = 30, City = "New York" },
new User { Name = "Bob", Age = 25, City = "Los Angeles" }
};
var columns = new List<string> { "Name", "Age", "City" };
var table = AnsiText.FormatTable(users, columns, maxWidth: 80);
foreach (var row in table)
{
Console.WriteLine(row);
}
// Format dictionaries as key-value tables
var config = new Dictionary<string, string> {
{ "Server", "production.example.com" },
{ "Port", "8080" },
{ "Status", "[green]Online[normal]" }
};
var dictTable = AnsiText.FormatDictionary(config, maxWidth: 60);
foreach (var row in dictTable)
{
Console.WriteLine(row);
}
Progress Bars
Create customizable progress bars with color support:
// Basic progress bar
var progress = AnsiText.CreateProgressBar(75.0);
Console.WriteLine(progress); // [green]██████████████████████████████[normal][gray]░░░░░░░░░░[normal] 75.0%
// Customized progress bar
var customProgress = AnsiText.CreateProgressBar(
percentage: 50.0,
width: 30,
fillChar: '■',
emptyChar: '□',
label: "Loading",
showPercentage: true,
fillColor: "[bright][blue]",
emptyColor: "[dim][gray]"
);
Console.WriteLine(customProgress);
Bordered Boxes
Create bordered text boxes in various styles:
// Simple box
var box = AnsiText.CreateBox("Hello, World!", "Greeting", AnsiText.BoxStyle.Single);
foreach (var line in box)
{
Console.WriteLine(line);
}
// Different box styles
var roundedBox = AnsiText.CreateBox("Content", "Title", AnsiText.BoxStyle.Rounded);
var doubleBox = AnsiText.CreateBox("Content", "Title", AnsiText.BoxStyle.Double);
var asciiBox = AnsiText.CreateBox("Content", "Title", AnsiText.BoxStyle.Ascii);
// Custom colored box
var coloredBox = AnsiText.CreateBox("Important", "Alert",
AnsiText.BoxStyle.Single, frameColor: "[bright][red]");
Lists and Bullets
Format lists with various bullet styles:
var items = new[] { "First item", "Second item", "Third item" };
// Bullet list
var bullets = AnsiText.FormatList(items, AnsiText.ListStyle.Bullets);
// Numbered list
var numbered = AnsiText.FormatList(items, AnsiText.ListStyle.Numbers);
// Checkbox list
var checkboxes = AnsiText.FormatList(items, AnsiText.ListStyle.Checkboxes);
// Custom bullets with color
var custom = AnsiText.FormatList(items, AnsiText.ListStyle.Custom,
customBullet: "★", bulletColor: "[yellow]");
foreach (var line in bullets)
{
Console.WriteLine(line);
}
Separators and Dividers
Create horizontal separators with optional labels:
// Simple separator
var separator = AnsiText.CreateSeparator(50);
Console.WriteLine(separator); // ──────────────────────────────────────────────────
// Centered label
var centered = AnsiText.CreateSeparator(40, '─', "SECTION 1", AnsiText.SeparatorStyle.Centered);
Console.WriteLine(centered); // ───────── SECTION 1 ──────────
// Left and right aligned
var leftSep = AnsiText.CreateSeparator(30, '=', "START", AnsiText.SeparatorStyle.LeftAligned);
var rightSep = AnsiText.CreateSeparator(30, '=', "END", AnsiText.SeparatorStyle.RightAligned);
Spinners and Status Indicators
Create spinner frames and status indicators:
// Spinner frames (for animations)
var spinner1 = AnsiText.CreateSpinner(0, AnsiText.SpinnerStyle.Classic); // |
var spinner2 = AnsiText.CreateSpinner(1, AnsiText.SpinnerStyle.Unicode); // ⠋
var spinner3 = AnsiText.CreateSpinner(2, AnsiText.SpinnerStyle.Braille); // ⣻
// Status indicators
var success = AnsiText.CreateStatusIndicator(AnsiText.StatusType.Success, "Operation completed");
var error = AnsiText.CreateStatusIndicator(AnsiText.StatusType.Error, "Failed to connect");
var warning = AnsiText.CreateStatusIndicator(AnsiText.StatusType.Warning, "Low disk space");
Console.WriteLine(success); // [green]✓[normal] Operation completed
Console.WriteLine(error); // [red]✗[normal] Failed to connect
Console.WriteLine(warning); // [yellow]⚠[normal] Low disk space
Color Customization
All AnsiText methods support color customization through optional parameters and global defaults:
// Customize global defaults
AnsiText.DefaultProgressFillColor = "[bright][green]";
AnsiText.DefaultProgressEmptyColor = "[dim][gray]";
AnsiText.DefaultBoxFrameColor = "[blue]";
AnsiText.DefaultSeparatorColor = "[cyan]";
AnsiText.DefaultSuccessColor = "[bright][green]";
// Use full ANSI tag strings for complex styling
var styledProgress = AnsiText.CreateProgressBar(60.0,
fillColor: "[bright][bgblue][white]",
emptyColor: "[dim][bggray][black]");
// Override colors per method call
var coloredBox = AnsiText.CreateBox("Alert", "Warning",
frameColor: "[bright][yellow][blink]");
Combining Elements
Create rich console interfaces by combining multiple AnsiText utilities:
// Header with separator
Console.WriteLine(AnsiText.CreateSeparator(60, '═', "SYSTEM STATUS", AnsiText.SeparatorStyle.Centered));
// Status indicators
Console.WriteLine(AnsiText.CreateStatusIndicator(AnsiText.StatusType.Success, "Database: Connected"));
Console.WriteLine(AnsiText.CreateStatusIndicator(AnsiText.StatusType.Warning, "Memory: 85% used"));
Console.WriteLine(AnsiText.CreateStatusIndicator(AnsiText.StatusType.Error, "Disk: Full"));
// Progress section
Console.WriteLine("\n" + AnsiText.CreateSeparator(60, '─', "PROGRESS"));
Console.WriteLine(AnsiText.CreateProgressBar(75.0, label: "Upload"));
Console.WriteLine(AnsiText.CreateProgressBar(45.0, label: "Processing"));
// Configuration table
var config = new Dictionary<string, string> {
{ "Version", "2.1.0" },
{ "Environment", "[green]Production[normal]" },
{ "Uptime", "15 days" }
};
Console.WriteLine("\n" + AnsiText.CreateSeparator(60, '─', "CONFIG"));
foreach (var row in AnsiText.FormatDictionary(config))
{
Console.WriteLine(row);
}
Controlling ANSI Code Processing
You can control which types of ANSI codes are processed using the Options
property:
// Enable only standard colors and backgrounds, disable bright colors
AnsiConsole.Options = AnsiConsole.CodeOptions.Colors | AnsiConsole.CodeOptions.Backgrounds;
// Enable all features
AnsiConsole.Options = AnsiConsole.CodeOptions.All;
// Disable all ANSI processing
AnsiConsole.Options = AnsiConsole.CodeOptions.Ignore;
Cursor Movement and Screen Control
In addition to color formatting, AnsiUtils provides cursor movement and screen control functionality:
Using Tags in Text
// Clear the screen and position cursor at home (1,1)
Console.WriteLine("[clearscreen][home]Hello, world!");
// Position cursor at row 5, column 10
Console.WriteLine("[pos:5:10]This text starts at position 5,10");
// Move cursor up 2 lines
Console.WriteLine("[up:2]This appears 2 lines above");
// Clear the current line
Console.WriteLine("[clearline]");
// Add delays between text
Console.WriteLine("This will pause[delay:500] for half a second");
Using Direct Methods
// Clear screen and position cursor
AnsiConsole.ClearScreen();
AnsiConsole.CursorPosition(5, 10);
// Write some text
Console.WriteLine("Hello at position 5,10");
// Move cursor
AnsiConsole.CursorUp(2);
Console.WriteLine("This appears 2 lines above");
// Clear the current line
AnsiConsole.ClearLine();
// Add a delay
AnsiConsole.Delay(500); // 500ms delay
Available Cursor Tags
Tag | Description |
---|---|
[home] |
Move cursor to position 1,1 |
[pos] |
Move cursor to position 1,1 |
[pos:row:col] |
Move cursor to specific row and column |
[up] |
Move cursor up 1 line |
[up:n] |
Move cursor up n lines |
[down] |
Move cursor down 1 line |
[down:n] |
Move cursor down n lines |
[left] |
Move cursor left 1 column |
[left:n] |
Move cursor left n columns |
[right] |
Move cursor right 1 column |
[right:n] |
Move cursor right n columns |
[nextline] |
Move to beginning of next line |
[nextline:n] |
Move to beginning of nth next line |
[prevline] |
Move to beginning of previous line |
[prevline:n] |
Move to beginning of nth previous line |
[column] |
Move to column 1 of current line |
[column:n] |
Move to column n of current line |
Screen & Line Control Tags
Tag | Description |
---|---|
[clearscreen] |
Clear entire screen |
[clearscreenforward] |
Clear from cursor to end of screen |
[clearscreenbackward] |
Clear from cursor to beginning of screen |
[clearline] |
Clear entire line |
[clearlineforward] |
Clear from cursor to end of line |
[clearlinebackward] |
Clear from cursor to beginning of line |
[savecursor] |
Save current cursor position |
[restorecursor] |
Restore saved cursor position |
[hidecursor] |
Hide the cursor |
[showcursor] |
Show the cursor |
Delay Tag
Tag | Description |
---|---|
[delay] |
Pause for 10ms (default) |
[delay:ms] |
Pause for specified milliseconds |
Creating Animations
You can combine cursor movement, delays, and colors to create terminal animations:
// Simple progress bar
Console.WriteLine("[clearscreen][home][blue]Loading:[normal]");
Console.WriteLine("[hidecursor]");
for (int i = 0; i <= 100; i += 5)
{
Console.Write($"[pos:2:1][clearlineforward]");
int blocks = i / 5;
Console.Write($"[green]{new string('█', blocks)}[normal] {i}%");
Console.Write("[delay:100]");
}
Console.WriteLine("\n[showcursor][green]Complete![normal]");
License
This project is licensed under the MIT License - see the LICENSE.txt file for details.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.