function
wrapAnsi
input: string,
columns: number,
): string;
Wrap a string to fit within the specified column width, preserving ANSI escape codes.
Designed to be compatible with the wrap-ansi npm package.
Features:
- Preserves ANSI escape codes (colors, styles) across line breaks
- Supports SGR codes (colors, bold, italic, etc.) and OSC 8 hyperlinks
- Respects Unicode display widths (full-width characters, emoji)
- Word wrapping at word boundaries (configurable)
@param input
The string to wrap
@param columns
The maximum column width
@param options
Wrapping options
@returns
The wrapped string
import { wrapAnsi } from "bun";
console.log(wrapAnsi("hello world", 5));
// Output:
// hello
// world
// Preserves ANSI colors across line breaks
console.log(wrapAnsi("\u001b[31mhello world\u001b[0m", 5));
// Output:
// \u001b[31mhello\u001b[0m
// \u001b[31mworld\u001b[0m
// Hard wrap long words
console.log(wrapAnsi("abcdefghij", 3, { hard: true }));
// Output:
// abc
// def
// ghi
// jReferenced types
interface WrapAnsiOptions
- ambiguousIsNarrow?: boolean
If
true, count ambiguous-width characters as 1 character wide. Iffalse, count them as 2 characters wide. - hard?: boolean
If
true, break words in the middle if they don't fit on a line. Iffalse, only break at word boundaries. - trim?: boolean
If
true, trim leading and trailing whitespace from each line. Iffalse, preserve whitespace. - wordWrap?: boolean
If
true, wrap at word boundaries when possible. Iffalse, break every line at exactly the column width (characters are split wherever the limit falls, ignoring word boundaries).