#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11143680 use warnings; use 5.010; use Term::ANSIColor qw(color :constants); sub ta_wrap { my ($text, $width, $optionsref) = @_; tr/\n\t/ /, s/ +/ /g for $text; # replace newlines and tabs my %pads = (flindent => '', slindent => '', %{ $optionsref // {} } ); $text = $pads{flindent} . $text; my $out = ''; my $carryover = ''; while( $text =~ s/^(.+)(?: +|$)(??{ $width < length join '', split m{\e[[\d;]*m}, $1 and '(*FAIL)' })// ) { $out .= "$1\e[m\n"; $carryover .= join '', $1 =~ /\e[[\d;]*m/g; $carryover =~ s/^.*\e\[0?m//; # clear up to and including last RESET $text =~ /./ and $text = "$pads{slindent}$carryover$text"; } return $out; } sub show { my $line = shift; my $wrapped = ta_wrap($line, 30, {flindent => q[ ] x 5, slindent => q[ ] x 5 } ); say "BEFORE:"; say $line; say "AFTER:"; say $wrapped; } show "Marley was " . BOLD . color('green') . "dead, " . RESET . "to begin with."; show "Marley was " . color('green') . "dead, " . RESET . "to begin with."; show "Marley was " . BOLD . "dead, " . RESET . "to begin with."; show "Marley was " . UNDERLINE . color('green') . "dead, to begin with. " . RESET . "There is no doubt..."; show "Marley was " . UNDERLINE . "dead, to begin with. " . RESET . "There is no doubt..."; show "Marley was dead, to begin with. There is no doubt...";