Skip to content

Commit ac6a6ff

Browse files
committed
Fix display of colors when wrapping text
When colored text wraps to the next line, the color was only applied until the end of the line, the text continued on the following line was reset to default color. This reapplies the currently used color at the beginning of each wrapped line, unless it has been properly reset.
1 parent 11cef6b commit ac6a6ff

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/Colors.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ class Colors
3131
const C_LIGHTGRAY = 'lightgray';
3232
const C_WHITE = 'white';
3333

34+
// Regex pattern to match color codes
35+
const C_CODE_REGEX = "/(\33\[[0-9;]+m)/";
36+
3437
/** @var array known color names */
3538
protected $colors = array(
3639
self::C_RESET => "\33[0m",

src/TableFormatter.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ protected function substr($string, $start = 0, $length = null)
293293
protected function wordwrap($str, $width = 75, $break = "\n", $cut = false)
294294
{
295295
$lines = explode($break, $str);
296+
$color_reset = $this->colors->getColorCode(Colors::C_RESET);
296297
foreach ($lines as &$line) {
297298
$line = rtrim($line);
298299
if ($this->strlen($line) <= $width) {
@@ -301,18 +302,30 @@ protected function wordwrap($str, $width = 75, $break = "\n", $cut = false)
301302
$words = explode(' ', $line);
302303
$line = '';
303304
$actual = '';
305+
$color = '';
304306
foreach ($words as $word) {
307+
if (preg_match_all(Colors::C_CODE_REGEX, $word, $color_codes) ) {
308+
# Word contains color codes
309+
foreach ($color_codes[0] as $code) {
310+
if ($code == $color_reset) {
311+
$color = '';
312+
} else {
313+
# Remember color so we can reapply it after a line break
314+
$color = $code;
315+
}
316+
}
317+
}
305318
if ($this->strlen($actual . $word) <= $width) {
306319
$actual .= $word . ' ';
307320
} else {
308321
if ($actual != '') {
309322
$line .= rtrim($actual) . $break;
310323
}
311-
$actual = $word;
324+
$actual = $color . $word;
312325
if ($cut) {
313326
while ($this->strlen($actual) > $width) {
314327
$line .= $this->substr($actual, 0, $width) . $break;
315-
$actual = $this->substr($actual, $width);
328+
$actual = $color . $this->substr($actual, $width);
316329
}
317330
}
318331
$actual .= ' ';
@@ -322,4 +335,4 @@ protected function wordwrap($str, $width = 75, $break = "\n", $cut = false)
322335
}
323336
return implode($break, $lines);
324337
}
325-
}
338+
}

0 commit comments

Comments
 (0)