Crate wrap_ansi

Crate wrap_ansi 

Source
Expand description

§🎨 wrap-ansi

Crates.io Documentation License Build Status

A high-performance, Unicode-aware Rust library for intelligently wrapping text while preserving ANSI escape sequences, colors, styles, and hyperlinks.

This library is a faithful Rust port of the popular JavaScript wrap-ansi library, designed for terminal applications, CLI tools, and any software that needs to display formatted text in constrained widths.

§✨ Key Features

FeatureDescription
🎨 ANSI-Aware WrappingPreserves colors, styles, and formatting across line breaks
πŸ”— Hyperlink SupportMaintains clickable OSC 8 hyperlinks when wrapping
🌍 Unicode ReadyCorrectly handles CJK characters, emojis, and combining marks
⚑ High PerformanceOptimized algorithms with pre-compiled regex patterns
πŸ› οΈ Flexible OptionsHard/soft wrapping, trimming, word boundaries control
πŸ”’ Memory SafeBuilt-in protection against DoS attacks with input size limits
πŸ“š Rich APIFluent builder pattern and comprehensive error handling

Β§πŸš€ Quick Start

Add this to your Cargo.toml:

[dependencies]
wrap-ansi = "0.1.0"

Β§Basic Text Wrapping

use wrap_ansi::wrap_ansi;

let text = "The quick brown fox jumps over the lazy dog";
let wrapped = wrap_ansi(text, 20, None);
println!("{}", wrapped);
// Output:
// The quick brown fox
// jumps over the lazy
// dog

Β§ANSI Colors & Styles

use wrap_ansi::wrap_ansi;

// Colors are preserved across line breaks!
let colored = "\u{001B}[31mThis is red text that will be wrapped properly\u{001B}[39m";
let wrapped = wrap_ansi(colored, 15, None);
println!("{}", wrapped);
// Each line will have proper color codes: \u{001B}[31m...\u{001B}[39m

Β§Advanced Configuration

use wrap_ansi::{wrap_ansi, WrapOptions};

// Using the builder pattern for clean configuration
let options = WrapOptions::builder()
    .hard_wrap(true)           // Break long words
    .trim_whitespace(false)    // Preserve whitespace
    .word_wrap(true)           // Respect word boundaries
    .build();

let text = "supercalifragilisticexpialidocious word";
let wrapped = wrap_ansi(text, 10, Some(options));
println!("{}", wrapped);
// Output:
// supercalif
// ragilistic
// expialidoc
// ious word

§🎯 Use Cases

Perfect for:

  • CLI Applications: Format help text, error messages, and output
  • Terminal UIs: Create responsive layouts that adapt to terminal width
  • Documentation Tools: Generate formatted text with preserved styling
  • Log Processing: Wrap log entries while maintaining color coding
  • Code Formatters: Handle syntax-highlighted code with proper wrapping

§🌟 Advanced Features

Β§Wrapping Modes

ModeBehaviorUse Case
Soft Wrap (default)Long words move to next line intactNatural text flow
Hard WrapLong words break at column boundaryStrict width constraints
Character WrapBreak anywhere, ignore word boundariesMonospace layouts

Β§ANSI Sequence Support

βœ… Foreground Colors: Standard (30-37) and bright (90-97) βœ… Background Colors: Standard (40-47) and bright (100-107) βœ… Text Styles: Bold, italic, underline, strikethrough βœ… Color Resets: Proper handling of reset sequences (39, 49) βœ… Hyperlinks: OSC 8 sequences for clickable terminal links βœ… Custom SGR: Support for any Select Graphic Rendition codes

Β§Unicode & Internationalization

use wrap_ansi::{wrap_ansi, WrapOptions};

// CJK characters are properly counted as 2 columns
let chinese = "δ½ ε₯½δΈ–η•ŒοΌŒθΏ™ζ˜―δΈ€δΈͺζ΅‹θ―•";
let wrapped = wrap_ansi(chinese, 8, None);

// Emojis and combining characters work correctly
let emoji = "Hello πŸ‘‹ World 🌍 with emojis";
let options = WrapOptions::builder().hard_wrap(true).build();
let wrapped = wrap_ansi(emoji, 10, Some(options));

Β§πŸ”§ Error Handling

For applications requiring robust error handling:

use wrap_ansi::{wrap_ansi_checked, WrapError};

let text = "Hello, world!";
match wrap_ansi_checked(text, 0, None) {
    Ok(wrapped) => println!("Wrapped: {}", wrapped),
    Err(WrapError::InvalidColumnWidth(width)) => {
        eprintln!("Invalid width: {}", width);
    }
    Err(WrapError::InputTooLarge(size, max)) => {
        eprintln!("Input too large: {} bytes (max: {})", size, max);
    }
    _ => {}
}

Β§πŸ“Š Performance

  • Zero-copy operations where possible
  • Pre-compiled regex patterns for ANSI sequence parsing
  • Efficient string operations with capacity pre-allocation
  • DoS protection with configurable input size limits
  • Minimal allocations through careful memory management

§🀝 Compatibility

  • Rust Edition: 2021+
  • MSRV: 1.70.0
  • Platforms: All platforms supported by Rust
  • Terminal Compatibility: Works with all ANSI-compatible terminals

Β§πŸ“š Examples

Check out the examples directory for more comprehensive usage examples, including:

  • Terminal UI layouts
  • Progress bars with colors
  • Syntax highlighting preservation
  • Interactive CLI applications

StructsΒ§

WrapOptions
πŸŽ›οΈ Configuration options for advanced text wrapping behavior.
WrapOptionsBuilder
πŸ—οΈ Fluent builder for creating WrapOptions with a clean, readable interface.

EnumsΒ§

WrapError
Comprehensive error types for wrap-ansi operations.

FunctionsΒ§

wrap_ansi
🎨 The main text wrapping function with full ANSI escape sequence support.
wrap_ansi_checked
πŸ›‘οΈ Wrap text with comprehensive error handling and input validation.