Break line to fit screen width, factoring in ANSI/SGR escape sequences.

  Args:
    text: String to line wrap.
    omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length.

  Returns:
    Text with additional line wraps inserted for lines grater than the width.

def LineWrap(text, omit_sgr=False):
  """Break line to fit screen width, factoring in ANSI/SGR escape sequences.

  Args:
    text: String to line wrap.
    omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length.

  Returns:
    Text with additional line wraps inserted for lines grater than the width.
  """

  def _SplitWithSgr(text_line):
    """Tokenise the line so that the sgr sequences can be omitted."""
    token_list = sgr_re.split(text_line)
    text_line_list = []
    line_length = 0
    for (index, token) in enumerate(token_list):
      # Skip null tokens.
      if token is '':
        continue

      if sgr_re.match(token):
        # Add sgr escape sequences without splitting or counting length.
        text_line_list.append(token)
        text_line = ''.join(token_list[index +1:])
      else:
        if line_length + len(token) <= width:
          # Token fits in line and we count it towards overall length.
          text_line_list.append(token)
          line_length += len(token)
          text_line = ''.join(token_list[index +1:])
        else:
          # Line splits part way through this token.
          # So split the token, form a new line and carry the remainder.
          text_line_list.append(token[:width - line_length])
          text_line = token[width - line_length:]
          text_line += ''.join(token_list[index +1:])
          break

    return (''.join(text_line_list), text_line)

  # We don't use textwrap library here as it insists on removing
  # trailing/leading whitespace (pre 2.6).
  (_, width) = TerminalSize()
  text = str(text)
  text_multiline = []
  for text_line in text.splitlines():
    # Is this a line that needs splitting?
    while ((omit_sgr and (len(StripAnsiText(text_line)) > width)) or
           (len(text_line) > width)):
      # If there are no sgr escape characters then do a straight split.
      if not omit_sgr:
        text_multiline.append(text_line[:width])
        text_line = text_line[width:]
      else:
        (multiline_line, text_line) = _SplitWithSgr(text_line)
        text_multiline.append(multiline_line)
    if text_line:
      text_multiline.append(text_line)
  return '\n'.join(text_multiline)