Reflow text width while maintaining certain formatting
        characteristics like double newlines and indented statements.
7425
def _fill_text(self, text, width=None, indent=None):
        
        assert isinstance(text, str)
        if indent is None:
            indent = NBSP * self._current_indent
        assert isinstance(indent, str)
        paragraphs = []
        line_buf = []
        pre = ''
        for fragment in text.splitlines():
            pre_indent = self.leadingws.match(fragment)
            if not fragment or pre_indent:
                if line_buf:
                    line = ' '.join(line_buf)
                    paragraphs.append((pre, self.whitespace.sub(' ', line)))
                if not fragment:
                    paragraphs.append(('', ''))
                else:
                    pre = pre_indent.group()
                    fragment = self.leadingws.sub('', fragment)
                    paragraphs.append((pre, fragment))
                line_buf = []
                pre = ''
            else:
                line_buf.append(fragment)
        if line_buf:
            line = ' '.join(line_buf)
            paragraphs.append((pre, self.whitespace.sub(' ', line)))
        indent = VTMLBuffer(indent)
        nl = VTMLBuffer('\n')
        if width is None:
            width = self._width - len(indent)
        lines = []
        for pre, paragraph in paragraphs:
            pwidth = width - len(pre)
            lines.append(nl.join((indent + pre + x)
                         for x in vtmlrender(paragraph).wrap(pwidth)))
        return nl.join(lines)
518615
def underline(self, text, indent=4):
        """"""
        length = len(text)
        indentation = (' ' * indent)
        return indentation + text + '\n' + indentation + ('-' * length)
295110
def _indent(text, amount):
    
    indentation = amount * ' '
    return indentation + ('\n' + indentation).join(text.split('\n'))
1372141
private void wrapText() {
	if (getFont() == null || text == null) {
	  return;
	}
	FontMetrics fm = getFontMetrics(getFont());

	StringBuilder tempText = new StringBuilder();
	StringBuilder finalText = new StringBuilder("<html>");
	finalText.append("<STYLE type='text/css'>BODY { text-align: ");
	finalText.append(align.name().toLowerCase());
	finalText.append("}</STYLE><BODY>");

	ArrayList<String> words = new ArrayList<String>();
	text = text.replaceAll("\n", "<BR>");
	String split[] = text.split("<BR>");
	for (int i = 0; i < split.length; i++) {
	  if (split[i].length() > 0) {
		String split2[] = split[i].split("[ \\t\\x0B\\f\\r]+");
		for (int j = 0; j < split2.length; j++) {
		  if (split2[j].length() > 0) {
			words.add(split2[j]);
		  }
		}
	  }

	  if (i < split.length - 1) {
		words.add("<BR>");
	  }
	}

	for (String word : words) {
	  if (word.equals("<BR>")) {
		finalText.append("<BR>");
		tempText.setLength(0);
	  } else {
		tempText.append(" ");
		tempText.append(word);

		int tempWidth =
			SwingUtilities.computeStringWidth(fm, tempText.toString().trim());
		if ((wrapWidth > 0 && tempWidth > wrapWidth)) {

		  int wordSize = SwingUtilities.computeStringWidth(fm, word);
		  if (wordSize >= wrapWidth) {
			finalText.append("...");
			break;
		  }

		  finalText.append("<BR>");
		  tempText.setLength(0);
		  tempText.append(word);
		}

		if (tempText.length() > 0) {
		  finalText.append(" ");
		}
		finalText.append(word);
	  }

	}

	finalText.append("</BODY></html>");
	super.setText(finalText.toString());
  }
924672
def puts(s='', newline=True, stream=STDOUT):
    """"""
    max_width_ctx = _get_max_width_context()
    if max_width_ctx:
        cols, separator = max_width_ctx[-1]
        s = max_width(s, cols, separator)

    if newline:
        s = tsplit(s, NEWLINES)
        s = map(str, s)
        indent = ''.join(INDENT_STRINGS)

        s = (str('\n' + indent)).join(s)

    _str = ''.join((
        ''.join(INDENT_STRINGS),
        str(s),
        '\n' if newline else ''
    ))
    stream(_str)
1339271
def indent (text, indent_string="  "):
    """"""
    lines = str(text).splitlines()
    return os.linesep.join("%s%s" % (indent_string, x) for x in lines)
1090261
def wrap(self, width):
        """"""
        res = []
        prev_state = set()
        part = []
        cwidth = 0
        for char, _width, state in zip(self._string, self._width, self._state):
            if cwidth + _width > width:
                if prev_state:
                    part.append(self.ANSI_RESET)
                res.append("".join(part))
                prev_state = set()
                part = []
                cwidth = 0
            cwidth += _width
            if prev_state == state:
                pass
            elif prev_state <= state:
                part.extend(state - prev_state)
            else:
                part.append(self.ANSI_RESET)
                part.extend(state)
            prev_state = state
            part.append(char)
        if prev_state:
            part.append(self.ANSI_RESET)
        if part:
            res.append("".join(part))
        return res
131966
function reflowText (text, width, gfm) {
  // Hard break was inserted by Renderer.prototype.br or is
  // <br /> when gfm is true
  var splitRe = gfm ? HARD_RETURN_GFM_RE : HARD_RETURN_RE,
      sections = text.split(splitRe),
      reflowed = [];

  sections.forEach(function (section) {
    // Split the section by escape codes so that we can
    // deal with them separately.
    var fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
    var column = 0;
    var currentLine = '';
    var lastWasEscapeChar = false;

    while (fragments.length) {
      var fragment = fragments[0];

      if (fragment === '') {
        fragments.splice(0, 1);
        lastWasEscapeChar = false;
        continue;
      }

      // This is an escape code - leave it whole and
      // move to the next fragment.
      if (!textLength(fragment)) {
        currentLine += fragment;
        fragments.splice(0, 1);
        lastWasEscapeChar = true;
        continue;
      }

      var words = fragment.split(/[ \t\n]+/);

      for (var i = 0; i < words.length; i++) {
        var word = words[i];
        var addSpace = column != 0;
        if (lastWasEscapeChar) addSpace = false;

        // If adding the new word overflows the required width
        if (column + word.length + addSpace > width) {

          if (word.length <= width) {
            // If the new word is smaller than the required width
            // just add it at the beginning of a new line
            reflowed.push(currentLine);
            currentLine = word;
            column = word.length;
          } else {
            // If the new word is longer than the required width
            // split this word into smaller parts.
            var w = word.substr(0, width - column - addSpace);
            if (addSpace) currentLine += ' ';
            currentLine += w;
            reflowed.push(currentLine);
            currentLine = '';
            column = 0;

            word = word.substr(w.length);
            while (word.length) {
              var w = word.substr(0, width);

              if (!w.length) break;

              if (w.length < width) {
                currentLine = w;
                column = w.length;
                break;
              } else {
                reflowed.push(w);
                word = word.substr(width);
              }
            }
          }
        } else {
          if (addSpace) {
            currentLine += ' ';
            column++;
          }

          currentLine += word;
          column += word.length;
        }

        lastWasEscapeChar = false;
      }

      fragments.splice(0, 1);
    }

    if (textLength(currentLine)) reflowed.push(currentLine);
  });

  return reflowed.join('\n');
}
193820
def newline_text(self, text, indent = False):
        """"""
        self.newline(indent)
        self.text(text)
1022725
def truncate(string, width):
    
    if len(string) > width:
        return string[:width-3] + '...'
    else:
        return string.ljust(width)
915416
def text_width(text):
    """"""
    (xmin, xmax, d1, d2) = get_dimension(text)
    return xmax - xmin
38660
def append_text_column(self, text: str, index: int):
        
        width = self.columns[index]["width"]
        return f"{text:<{width}}"
146272
def fit_text(text, length):
    """"""
    text_length = wcswidth(text)

    if text_length > length:
        return trunc(text, length)

    if text_length < length:
        return pad(text, length)

    return text
1193741
def dumped(text, level, indent=2):
    """"""
    return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
309802
def tmpl_shorten(text, max_size=32):
        
        max_size = int(max_size)
        if len(text) <= max_size:
            return text
        text = textwrap.wrap(text, max_size)[0]
        import re
        text = re.sub(r'\W+$', '', text)
        return text.strip()
1373600
def wrap_onspace(self, text):

        '''
        '''

        def _truncate(line, word):
            return '{line}{part}{word}'.format(
                        line=line,
                        part=' \n'[(len(line[line.rfind('\n')+1:]) + len(word.split('\n', 1)[0]) >= self.width)],
                        word=word
                    )

        return reduce(_truncate, text.split(' '))
566670
def _LineWrap(text, width):
    
    return reduce(lambda line, word, width=width: '%s%s%s' %
                  (line,
                   ' \n'[(len(line) - line.rfind('\n') - 1 +
                         len(word.split('\n', 1)[0]) >= width)],
                   word),
                  text.split(' ')
                 )