[![Actions Status](https://github.com/tecolicom/Text-ANSI-Fold/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/tecolicom/Text-ANSI-Fold/actions?workflow=test) [![MetaCPAN Release](https://badge.fury.io/pl/Text-ANSI-Fold.svg)](https://metacpan.org/release/Text-ANSI-Fold)
# NAME

Text::ANSI::Fold - Text folding library supporting ANSI terminal sequence and Asian wide characters with prohibition character handling.

# VERSION

Version 2.43

# SYNOPSIS

    use Text::ANSI::Fold qw(ansi_fold);
    ($folded, $remain) = ansi_fold($text, $width, [ option ]);

    use Text::ANSI::Fold qw(ansi_unfold);
    $joined = ansi_unfold($text);

    use Text::ANSI::Fold;
    my $f = Text::ANSI::Fold->new(width => 80, boundary => 'word');
    $f->configure(ambiguous => 'wide');
    ($folded, $remain) = $f->fold($text);

    use Text::ANSI::Fold;
    while (<>) {
        print join "\n",
            Text::ANSI::Fold->new(width => 40, text => $_)->chops;
    }

    use Text::ANSI::Fold qw(:constants);
    my $fold = Text::ANSI::Fold->new(
        width     => 70,
        boundary  => 'word',
        linebreak => LINEBREAK_ALL,
        runin     => 4,
        runout    => 4,
    );

# DESCRIPTION

[Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold) provides capability to divide a text into two
parts by given width.  Text can include ANSI terminal sequences and
the width is calculated by its visible representation.  If the text is
divided in the middle of colored region, reset sequence is appended to
the former text, and color recover sequence is inserted before the
latter string.

OSC 8 hyperlink sequences are also handled properly.  If the text is
divided in the middle of a hyperlink, the link is closed at the end of
the former text and reopened at the beginning of the latter string.

Other control sequences (CSI), such as cursor movement, are passed
through with no width.  The movement of the cursor is not taken into
account: text written over by moving the cursor back is counted as
it is.

At the folding point, a sequence goes to the next line with the text
after it.  When no visible text follows up to the end of the line, it
stays on the line, even if the line has no room left.

This module also support Unicode Asian full-width and non-spacing
combining characters properly.  Text is divided between grapheme
clusters, so that a character with combining marks or an emoji
sequence stays in one line, as far as the grapheme rules of the perl
in use go; before perl 5.22, a grapheme in a long paragraph may
rarely be split.  Japanese text formatting with head-or-end of line
prohibition character is also supported.  Set the linebreak mode to
enable it.

Since the overhead of ANSI escape sequence handling is not significant
when the data does not include them, this module can be used for
normal text processing with small penalty.

## **ansi\_fold**

Use exported **ansi\_fold** function to fold original text, with number
of visual columns you want to cut off the text.

    ($folded, $remain, $w) = ansi_fold($text, $width);

It returns a pair of strings; first one is folded text, and second is
the rest.

Additional third result is visual width of the folded text.  It is not
always same as given width, and you may want to know how many columns
returned string takes for further processing.

Negative width value is taken as unlimited.  So the string is never
folded, but you can use this to expand tabs and to get visual string
width.

This function returns at least one character in any situation.  If you
provide Asian wide string and just one column as width, it trims off
the first wide character even if it does not fit to given width.

## **ansi\_unfold**

Use exported **ansi\_unfold** function to join the lines of a paragraph
before folding it to another width.

    $joined = ansi_unfold($text);
    $joined = ansi_unfold(\@lines);

Give a string, or a reference to a list of lines.  In a list, each
element is a line, whether it has a newline at the end or not, and an
empty element is an empty line.  The result is a string, which has a
newline at the end only if the last element has it.

Line breaks are turned into a space, but they are removed in the
following places, because Japanese and Chinese are written without
spaces between words.

- Between Japanese or Chinese characters, including halfwidth kana.
- Before and after their punctuation such as `。` and `「`.
- Between them and a symbol of ambiguous width such as `…` and `→`.

Korean is written with spaces, and a line break next to Hangul is
turned into a space, except after the punctuation above.

The spaces and tabs at the beginning of the next line are taken as an
indent, and removed.  Those at the end of a line are taken as a space
of the original text, and turned into a single space.  IDEOGRAPHIC
SPACE (U+3000) is treated as a character.

ANSI sequences around a line break are kept.  A line break without
text on both sides is left as it is, so the text can have empty lines
between paragraphs, and a newline at the end.

These parameters can be given:

- **interscript** => _string_

    Put _string_ in place of a line break between Japanese or Chinese
    characters and Western characters or numerals.  The default is a
    space.  Give an empty string for a text written without a space there.

        $joined = ansi_unfold($text, interscript => '');

    This is the inter-script spacing of CSS, and `\xkanjiskip` of pTeX.
    Only line breaks are concerned: spaces in a line are neither added nor
    removed.

- **newline** => _pattern_

    Give the pattern of a line break.  The default is `qr/\R/`.

        $joined = ansi_unfold($text, newline => qr/\r/);

The result is not always the same as the text before folding.  A word
divided at a symbol, such as `and/or` after `/`, gets a space there,
because it looks the same as two words.  Fold with `boundary =>
'space'` not to divide it.

## **configure**

Default parameter can be set by **configure** class method:

    Text::ANSI::Fold->configure(width => 80, padding => 1);

Then you don't have to pass second argument.

    ($folded, $remain) = ansi_fold($text);

Because second argument is always taken as width, use _undef_ when
using default width with additional parameter:

    ($folded, $remain) = ansi_fold($text, undef, padding => 1);

Some other easy-to-use interfaces are provided by sister module
[Text::ANSI::Fold::Util](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold%3A%3AUtil).

# REGULAR EXPRESSIONS

Import-tag `:regex` gives the regular expressions `$reset_re`,
`$color_re`, `$erase_re`, `$csi_re`, `$osc_re` and `$ctrl_string_re`,
which match the ANSI sequences this module recognizes.  `$ctrl_string_re`
matches all the control strings of ECMA-48: DCS, OSC, SOS, PM and
APC, and `$osc_re` only OSC of them.

# OBJECT INTERFACE

You can create an object to hold parameters, which is effective during
object life time.

## **new**

Use `new` method to make a fold object.

    my $obj = Text::ANSI::Fold->new(
        width => 80,
        boundary => 'word',
    );

This makes an object folding on word boundaries with 80 columns width.

## **fold**

Then you can call `fold` method without parameters because the object
keeps necessary information.

    $obj->fold($text);

## **configure**

Use **configure** method to update parameters:

    $obj->configure(padding => 1);

Additional parameter can be specified on each call, and they precede
saved value.

    $obj->fold($text, width => 40);

# STRING OBJECT INTERFACE

You can use a fold object to hold string inside, and take out folded
strings from it.  Use `text` method to store data in the object, and
`retrieve` or `chops` method to take out folded string from it.

## **text**

A fold object can hold string inside by **text** method.

    $obj->text("text");

Method **text** has an lvalue attribute, so it can be assigned to, as
well as can be a subject of mutating operator such as `s///`.

    $obj->text = "text";

## **retrieve**

Folded string can be taken out by `retrieve` method.  It returns
empty string if nothing remained.

    while ((my $folded = $obj->retrieve) ne '') {
        print $folded;
        print "\n" if $folded !~ /\n\z/;
    }

## **chops**

Method `chops` returns chopped string list.  Because the `text`
method returns the object itself when called with a parameter, you can
use `text` and `chops` in series:

    print join "\n", $obj->text($string)->chops;

Actually, text can be set by `new` or `configure` method through
`text` parameter.  Next program just works.

    use Text::ANSI::Fold;
    while (<>) {
        print join "\n",
            Text::ANSI::Fold->new(width => 40, text => $_)->chops;
    }

## **unfold**

Method `unfold` joins the lines of the string in the object, in the
same way as `ansi_unfold`, and returns the object.  It takes the same
parameters.  Unlike `fold`, it does not take a string.  Use `ansi_unfold`
for that.

    print join "\n", $obj->text($paragraph)->unfold->chops;

## **chops** with multiple width

When using `chops` method, `width` parameter can take array
reference, and chops text into given width list.

    my $fold = Text::ANSI::Fold->new;
    my @list = $fold->text("1223334444")->chops(width => [ 1, 2, 3 ]);
    # return ("1", "22", "333") and keep "4444"

If the width value is 0, it returns empty string.  Negative width
value takes all the rest of stored string.  In the following code, the
fourth width (3) is ignored because the -2 immediately preceding it
consumes all remaining strings.

    my $fold = Text::ANSI::Fold->new;
    my @list = $fold->text("1223334444")->chops(width => [ 1, 0, -2, 3 ]);
    # return ("1", "", "223334444")

The padding operation is performed only on the last non-empty element,
and no elements corresponding to subsequent items are returned.  Also,
of course, padding is not performed for negative widths.

## **chops** with length

Give an array reference by `length` parameter, and it is set to the
visual width of each element returned (not the number of characters).
It is the width that the fold counted, so the strings need not be
measured again.  The padding is not included.

    my @list = $fold->text($text)->chops(length => \my @length);

# OPTIONS

Option parameter can be specified as name-value list for **ansi\_fold**
function as well as **new** and **configure** method.

    ansi_fold($text, $width, boundary => 'word', ...);

    Text::ANSI::Fold->configure(boundary => 'word');

    my $obj = Text::ANSI::Fold->new(boundary => 'word');

    $obj->configure(boundary => 'word');

- **width** => _n_ | _\[ n, m, ... \]_

    Specify folding width by integer.  Negative value means all the rest.

    Array reference can be specified but works only with **chops** method,
    and retunrs empty string for zero width.

- **boundary** => `word` | `space`

    Option **boundary** takes `word` and `space` as a valid value.  These
    prohibit to fold a line in the middle of a word in Latin, Greek,
    Cyrillic and Hangul scripts.  Value `word` means a sequence of
    alpha-numeric characters, and `space` means a sequence of any
    characters other than spaces, wide characters and halfwidth kana.
    No-break spaces are part of the sequence.

    This operation takes place only when enough space will be provided to
    hold the word on next call with same width.

    If the color of text is altered within a word, that position is also
    taken as an boundary.

- **padding** => _bool_

    If **padding** option is given with true value, margin space is filled
    up with space character.  Default is 0.  Next code fills spaces if the
    given text is shorter than 80.

        ansi_fold($text, 80, padding => 1);

    If an ANSI **Erase Line** sequence is found in the string, color status
    at the position is remembered, and padding string is produced in that
    color.

- **padchar** => _char_

    **padchar** option specifies character used to fill up the remainder of
    given width.

        ansi_fold($text, 80, padding => 1, padchar => '_');

- **prefix** => _string_ | _coderef_

    **prefix** string is inserted before remained string if it is not
    empty.  This is convenient to produce indented series of text by
    **chops** interface.

    If the value is reference to subroutine, its result is used as a
    prefix string.

    The **fold** function does not complain if the result of adding a
    prefix string is longer than the original text.  The caller must be
    very careful because of the possibility of an infinite loop, when the
    prefix is as wide as the width or longer, or given by a subroutine.

    A line has at least one character after the prefix, even if it does
    not fit.  A wide character after the prefix may make the line one
    column longer than the width.

- **trim** => _bool_

    If **trim** option is given with true value, spaces at the end of a
    folded line are removed, including those brought there by the run-in
    operation, so that they do not make the line longer than the width.
    Only ASCII spaces are removed; other spaces, such as full-width spaces
    and the no-break space that **splitwide** uses, are kept.  Default is 0.

    Spaces at the end of the original line are left as they are, because
    the line is not folded there.  Colored spaces are also left, because
    their background color may be visible.

- **ambiguous** => `narrow` or `wide`

    Tells how to treat Unicode East Asian ambiguous characters.  Default
    is `narrow` which means single column.  Set `wide` to tell the
    module to treat them as wide character.

- **discard** => \[ `EL`, `OSC`, `CONTROL` \]

    Specify the list reference of control sequence name to be discarded.
    **EL** means Erase Line; **OSC** means Operating System Command, defined
    in ECMA-48.  Erase Line right after RESET sequence is always kept.
    **CONTROL** means all the control strings of ECMA-48: DCS, OSC, SOS,
    PM and APC (see ["CONTROL STRINGS"](#control-strings)).  The text between them, such as
    that of a hyperlink, is kept.

    When OSC is discarded, OSC 8 hyperlink state tracking is also
    disabled.

- **linebreak** => _mode_
- **runin** => _width_
- **runout** => _width_

    These options specify the behavior of line break handling for Asian
    multi byte characters.  Only Japanese is supported currently.

    If the cut-off text start with space or prohibited characters
    (e.g. closing parenthesis), they are ran-in at the end of current line
    as much as possible.

    If the trimmed text end with prohibited characters (e.g. opening
    parenthesis), they are ran-out to the head of next line, if it fits to
    maximum width.

    Default **linebreak** mode is `LINEBREAK_NONE` and can be set one of
    those:

        LINEBREAK_NONE
        LINEBREAK_RUNIN
        LINEBREAK_RUNOUT
        LINEBREAK_ALL

    Import-tag `:constants` can be used to access these constants.

    Option **runin** and **runout** is used to set maximum width of moving
    characters.  Default values are both 2.

- **margin** => _width_

    This option reserves a margin space within the specified width for
    run-in operation.  When margin is specified, the actual folding width
    becomes `width - margin`, and the margin space is used for run-in
    characters.  Any unused margin space is filled with padding characters
    if padding is enabled.

    If margin is 0 (default), run-in may cause the result to exceed the
    specified width.  Set margin equal to or greater than runin value to
    ensure the result always fits within the specified width.

- **splitwide** => _bool_
- **lefthalf** => _char_
- **righthalf** => _char_

    It is sometimes necessary to split a string at the middle of a wide
    character.  In such cases, the string is usually split before that
    point.  If this parameter is true, that wide character is split into
    left-half and right-half character.

    The parameters `lefthalf` and `righthalf` specify the respective
    characters. Their default value is both `NON-BREAK SPACE`.

- **expand** => _bool_
- **tabstop** => _n_
- **tabhead** => _char_
- **tabspace** => _char_

    Enable tab character expansion.

    Default tabstop is 8 and can be set by **tabstop** option.

    Tab character is converted to **tabhead** and following **tabspace**
    characters.  Both are white space by default.

- **tabstyle** => _style_

    Set tab expansion style.  This parameter set both **tabhead** and
    **tabspace** at once according to the given style name.  Each style has
    two values for tabhead and tabspace.

    If two style names are combined, like `symbol,space`, use
    `symbols`'s tabhead and `space`'s tabspace.

    Currently these names are available.

        symbol   => [ "\N{SYMBOL FOR HORIZONTAL TABULATION}",
                      "\N{SYMBOL FOR SPACE}" ],
        shade    => [ "\N{MEDIUM SHADE}",
                      "\N{LIGHT SHADE}" ],
        block    => [ "\N{LOWER ONE QUARTER BLOCK}",
                      "\N{LOWER ONE EIGHTH BLOCK}" ],
        needle   => [ "\N{BOX DRAWINGS HEAVY RIGHT}",
                      "\N{BOX DRAWINGS LIGHT HORIZONTAL}" ],
        dash     => [ "\N{BOX DRAWINGS HEAVY RIGHT}",
                      "\N{BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL}" ],
        triangle => [ "\N{BLACK RIGHT-POINTING SMALL TRIANGLE}",
                      "\N{WHITE RIGHT-POINTING SMALL TRIANGLE}" ],

    Below are styles providing same character for both tabhead and
    tabspace.

        dot          => '.',
        space        => ' ',
        emspace      => "\N{EM SPACE}",
        blank        => "\N{OPEN BOX}",
        middle-dot   => "\N{MIDDLE DOT}",
        arrow        => "\N{RIGHTWARDS ARROW}",
        double-arrow => "\N{RIGHTWARDS DOUBLE ARROW}",
        triple-arrow => "\N{RIGHTWARDS TRIPLE ARROW}",
        white-arrow  => "\N{RIGHTWARDS WHITE ARROW}",
        wave-arrow   => "\N{RIGHTWARDS WAVE ARROW}",
        circle-arrow => "\N{CIRCLED HEAVY WHITE RIGHTWARDS ARROW}",
        curved-arrow => "\N{HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW}",
        shadow-arrow => "\N{HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW}",
        squat-arrow  => "\N{SQUAT BLACK RIGHTWARDS ARROW}",
        squiggle     => "\N{RIGHTWARDS SQUIGGLE ARROW}",
        harpoon      => "\N{RIGHTWARDS HARPOON WITH BARB UPWARDS}",
        cuneiform    => "\N{CUNEIFORM SIGN TAB}",

# EXAMPLE

Next code implements almost fully-equipped fold command for multi byte
text with Japanese prohibited character handling.

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use open IO => 'utf8', ':std';
    
    use Text::ANSI::Fold qw(:constants);
    my $fold = Text::ANSI::Fold->new(
        width     => 70,
        boundary  => 'word',
        linebreak => LINEBREAK_ALL,
        runin     => 4,
        runout    => 4,
    );
    
    $, = "\n";
    while (<>) {
        print $fold->text($_)->chops;
    }

# CONTROL CHARACTERS

Text::ANSI::Fold handles the following line break related codes
specially:

    Newline (\n)
    Form feed (\f)
    Carriage return (\r)
    Null (\0)
    Line separator (U+2028)
    Paragraph separator (U+2029)

These characters are handled as follows:

- NEWLINE (`\n`), CRNL (`\r\n`)
- NULL (`\0`)
- LINE SEPARATOR (`U+2028`)
- PARAGRAPH SEPARATOR (`U+2029`)

    If any of these characters are found, the folding process terminates
    immediately and the portion up to that character is returned as folded
    text.  These character itself is included at the end of the folded
    text.

- CARRIAGE RETURN (`\r`)

    When a carriage return is found, it is added to the folded text and
    the fold width is reset.

- FORM FEED (`\f`)

    If a form feed character is found in the middle of a string,
    processing stops and the string up to the point immediately before is
    returned.  If it is found at the beginning of a string, it is added to
    the folded text and processing continues.

    The beginning is where no text is before it: a form feed after
    nothing but ANSI sequences, as in a form feed with a color, is at the
    beginning, and is kept in the place where it is.

# OSC 8 HYPERLINKS

This module handles OSC 8 hyperlink sequences.  The OSC (Operating
System Command) is defined in ECMA-48, and OSC 8 is an extension for
terminal hyperlinks.

The command string in OSC is defined in ECMA-48 8.3.89 to consist of
characters in the range 00/08-00/13 and 02/00-07/14.  However, this
module extends the definition to accept non-ASCII characters, since
they may appear in URLs even though the OSC 8 specification recommends
URI encoding.  The behavior for non-ASCII is undefined in the spec, but
this module tolerates it for practical compatibility.

The only exception is U+009C (STRING TERMINATOR), which is excluded
because it terminates the OSC sequence.

# CONTROL STRINGS

DCS (DEVICE CONTROL STRING), SOS (START OF STRING), PM (PRIVACY
MESSAGE) and APC (APPLICATION PROGRAM COMMAND) are, with OSC, the
control strings of ECMA-48, and are taken as OSC is: the opening
delimiter, the string and the terminator are kept together, have no
width, and are never divided.  Images are sent to terminals this way:
Sixel by DCS, and the kitty graphics protocol by APC.  A Sixel image
takes room on the screen, which this module does not know.

The string is of the characters OSC takes, and ends with STRING
TERMINATOR or BEL, as OSC does.  The 8-bit forms of the delimiters
are taken at the start of a text only, as those of OSC and CSI are.

# SEE ALSO

- [https://github.com/tecolicom/ANSI-Tools](https://github.com/tecolicom/ANSI-Tools)

    Collection of ANSI related tools.

- [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold)
- [https://github.com/tecolicom/Text-ANSI-Fold](https://github.com/tecolicom/Text-ANSI-Fold)

    Distribution and repository.

- [App::ansifold](https://metacpan.org/pod/App%3A%3Aansifold)

    Command line utility using [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold).

- [Text::ANSI::Fold::Util](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold%3A%3AUtil)

    Collection of utilities using [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold) module.

- [Text::ANSI::Tabs](https://metacpan.org/pod/Text%3A%3AANSI%3A%3ATabs)

    [Text::Tabs](https://metacpan.org/pod/Text%3A%3ATabs) compatible tab expand/unexpand module using
    [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold) as a backend processor.

- [App::sdif](https://metacpan.org/pod/App%3A%3Asdif)

    [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold) was originally implemented in **sdif** command for
    long time, which provide side-by-side view for diff output.  It is
    necessary to process output from **cdif** command which highlight diff
    output using ANSI escape sequences.

- [Text::ANSI::Util](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AUtil), [Text::ANSI::WideUtil](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AWideUtil)

    These modules provide a rich set of functions to handle string
    contains ANSI color terminal sequences.  In contrast,
    [Text::ANSI::Fold](https://metacpan.org/pod/Text%3A%3AANSI%3A%3AFold) provides simple folding mechanism with minimum
    overhead.  Also **sdif** need to process other than SGR (Select Graphic
    Rendition) color sequence, and non-spacing combining characters, those
    are not supported by these modules.

- [https://en.wikipedia.org/wiki/ANSI\_escape\_code](https://en.wikipedia.org/wiki/ANSI_escape_code)

    ANSI escape code definition.

- [https://www.w3.org/TR/jlreq/](https://www.w3.org/TR/jlreq/)

    Requirements for Japanese Text Layout,
    W3C Working Group Note 11 August 2020

- [ECMA-48](https://www.ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf)

    ECMA-48: Control Functions for Coded Character Sets

# AUTHOR

Kazumasa Utashiro

# LICENSE

Copyright ©︎ 2018-2026 Kazumasa Utashiro.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
