function phutil_console_wrap()

in src/console/format.php [102:191]


function phutil_console_wrap($text, $indent = 0, $with_prefix = true) {
  $lines = array();

  $width = (78 - $indent);
  $esc = chr(27);

  $break_pos = null;
  $len_after_break = 0;
  $line_len = 0;

  $line = array();
  $lines = array();

  $vector = phutil_utf8v($text);
  $vector_len = count($vector);
  for ($ii = 0; $ii < $vector_len; $ii++) {
    $chr = $vector[$ii];

    // If this is an ANSI escape sequence for a color code, just consume it
    // without counting it toward the character limit. This prevents lines
    // with bold/color on them from wrapping too early.
    if ($chr == $esc) {
      for ($ii; $ii < $vector_len; $ii++) {
        $line[] = $vector[$ii];
        if ($vector[$ii] == 'm') {
          break;
        }
      }
      continue;
    }

    $line[] = $chr;

    ++$line_len;
    ++$len_after_break;

    if ($line_len > $width) {
      if ($break_pos !== null) {
        $slice = array_slice($line, 0, $break_pos);
        while (count($slice) && end($slice) == ' ') {
          array_pop($slice);
        }
        $slice[] = "\n";
        $lines[] = $slice;
        $line = array_slice($line, $break_pos);

        $line_len = $len_after_break;
        $len_after_break = 0;
        $break_pos = null;
      }
    }

    if ($chr == ' ') {
      $break_pos = count($line);
      $len_after_break = 0;
    }

    if ($chr == "\n") {
      $lines[] = $line;
      $line = array();

      $len_after_break = 0;
      $line_len = 0;
      $break_pos = null;
    }
  }

  if ($line) {
    if ($line) {
      $lines[] = $line;
    }
  }

  $pre = null;
  if ($indent) {
    $pre = str_repeat(' ', $indent);
  }

  foreach ($lines as $idx => $line) {
    if ($idx == 0 && !$with_prefix) {
      $prefix = null;
    } else {
      $prefix = $pre;
    }

    $lines[$idx] = $prefix.implode('', $line);
  }

  return implode('', $lines);
}