pad_to_width

Function pad_to_width 

Source
pub fn pad_to_width(
    text: &str,
    target_width: usize,
    align_right: bool,
) -> String
Expand description

Pad text to target display width while respecting ANSI codes and wide Unicode characters.

Uses display width (terminal columns) instead of character count. Correctly handles:

  • Wide characters (CJK, emoji): 2 display width
  • Normal characters (ASCII, Cyrillic): 1 display width
  • Zero-width characters (combining marks): 0 display width
  • ANSI escape sequences: 0 display width (filtered out)

§Arguments

  • text - Input text potentially containing ANSI escape sequences
  • target_width - Desired display width in terminal columns
  • align_right - If true, pad on the left; if false, pad on the right

§Returns

Padded string with correct display width for terminal alignment.

§Examples

use strs_tools::ansi::pad_to_width;

// Left-aligned (pad right)
assert_eq!( pad_to_width( "hi", 5, false ), "hi   " );

// Right-aligned (pad left)
assert_eq!( pad_to_width( "hi", 5, true ), "   hi" );

// With ANSI codes - padding doesn't count escape sequences
assert_eq!(
  pad_to_width( "\x1b[31mhi\x1b[0m", 5, false ),
  "\x1b[31mhi\x1b[0m   "
);

// CJK characters (wide, 2 display width per char)
let padded = pad_to_width( "日本語", 10, false );  // 3 chars, 6 display width
// Result: "日本語    " (6 + 4 spaces = 10 display width)

§Fix(issue-003)

Root cause: Previous implementation mixed character-count-based padding with Rust’s display-width-based formatting ({:<N}), causing misalignment with wide Unicode characters (CJK, emoji).

Pitfall: Always use display width for terminal alignment, not char count. Display width ≠ char count ≠ byte count for Unicode. CJK/emoji have display width = 2, not 1.