FwrapAnsi
Bun

function

wrapAnsi

function wrapAnsi(
input: string,
columns: number,
options?: WrapAnsiOptions
): string;

Wrap a string to fit within the specified column width, preserving ANSI escape codes.

This function is designed to be compatible with the popular "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
// j

Referenced types

interface WrapAnsiOptions

  • ambiguousIsNarrow?: boolean

    When it's ambiguous and true, count ambiguous width characters as 1 character wide. If false, count them as 2 characters wide.

  • hard?: boolean

    If true, break words in the middle if they don't fit on a line. If false, only break at word boundaries.

  • trim?: boolean

    If true, trim leading and trailing whitespace from each line. If false, preserve whitespace.

  • wordWrap?: boolean

    If true, wrap at word boundaries when possible. If false, don't perform word wrapping (only wrap at explicit newlines).