Split text into lines and calculate X positions. If we need more
        space in height than available we return the rest of the text
168359
def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
        
        self.lines = []
        self.height = 0
        self.maxWidth = self.width = maxWidth
        self.maxHeight = maxHeight
        boxStack = []

        style = self.style
        x = 0

        # Start with indent in first line of text
        if not splitted:
            x = style["textIndent"]

        lenText = len(self)
        pos = 0
        while pos < lenText:

            # Reset values for new line
            posBegin = pos
            line = Line(style)

            # Update boxes for next line
            for box in copy.copy(boxStack):
                box["x"] = 0
                line.append(BoxBegin(box))

            while pos < lenText:

                # Get fragment, its width and set X
                frag = self[pos]
                fragWidth = frag["width"]
                frag["x"] = x
                pos += 1

                # Keep in mind boxes for next lines
                if isinstance(frag, BoxBegin):
                    boxStack.append(frag)
                elif isinstance(frag, BoxEnd):
                    boxStack.pop()

                # If space or linebreak handle special way
                if frag.isSoft:
                    if frag.isLF:
                        line.append(frag)
                        break
                        # First element of line should not be a space
                    if x == 0:
                        continue
                        # Keep in mind last possible line break

                # The elements exceed the current line
                elif fragWidth + x > maxWidth:
                    break

                # Add fragment to line and update x
                x += fragWidth
                line.append(frag)

            # Remove trailing white spaces
            while line and line[-1].name in ("space", "br"):
                line.pop()

            # Add line to list
            line.dumpFragments()
            # if line:
            self.height += line.doLayout(self.width)
            self.lines.append(line)

            # If not enough space for current line force to split
            if self.height > maxHeight:
                return posBegin

            # Reset variables
            x = 0

        # Apply alignment
        self.lines[- 1].isLast = True
        for line in self.lines:
            line.doAlignment(maxWidth, style["textAlign"])

        return None
195481
def _spacingx(node, max_dims, xoffset, xspace):
    '''
    '''
    x_spacing = _n_terminations(node) * xspace

    if x_spacing > max_dims[0]:
        max_dims[0] = x_spacing

    return xoffset - x_spacing / 2.
641711
def each_line(text, separator)
      lines = text.split(separator)
      return yield(text) if text.empty?
      lines.reduce([]) do |aligned, line|
        aligned << yield(line)
      end.join(separator)
    end
1296033
function fullWidth(text, param) {
    let cols = process.stdout.columns;
    let lines = text.split('\n');

    for (i = 0; i < lines.length; i++) {
        let size = cols;
        if (i === 0) size = size - 15;
        if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2;
        while (lines[i].length < size) {
            lines[i] = lines[i] + ' ';
        }
    }
    text = lines.join('\n');

    return text;
}
863250
def _splitit(self, line, isheader):
        

        line_wrapped = []
        for cell, width in zip(line, self._width):
            array = []
            for c in cell.split('\n'):
                if c.strip() == "":
                    array.append("")
                else:
                    array.extend(textwrapper(c, width))
            line_wrapped.append(array)
        max_cell_lines = reduce(max, list(map(len, line_wrapped)))
        for cell, valign in zip(line_wrapped, self._valign):
            if isheader:
                valign = "t"
            if valign == "m":
                missing = max_cell_lines - len(cell)
                cell[:0] = [""] * int(missing / 2)
                cell.extend([""] * int(missing / 2 + missing % 2))
            elif valign == "b":
                cell[:0] = [""] * (max_cell_lines - len(cell))
            else:
                cell.extend([""] * (max_cell_lines - len(cell)))
        return line_wrapped
786586
def get_texts_box(texts, fs):
    """"""
    max_len = max(map(len, texts))
    return (fs, text_len(max_len, fs))
955709
def get_text_position(fig, ax, ha='left', va='top', pad_scale=1.0):
    """"""
    ## Check and preprocess input arguments
    try: pad_scale = float(pad_scale)
    except: raise TypeError("'pad_scale should be of type 'float'")
        
    for arg in [va, ha]: 
        assert type(arg) is str
        arg = arg.lower() # Make it lowercase to prevent case problem.
    
    ## Get axis size in inches
    ax_height, ax_width = get_ax_size_in_inch(fig, ax)
    
    ## Construct inversion factor from inch to plot coordinate
    length_x = ax.get_xlim()[1] - ax.get_xlim()[0]
    length_y = ax.get_ylim()[1] - ax.get_ylim()[0]
    inch2coord_x = length_x / ax_width
    inch2coord_y = length_y / ax_height
    
    ## Set padding size relative to the text size
    #pad_inch = text_bbox_inch.height * pad_scale
    #pad_inch = fontsize_points * point2inch * pad_scale
    ax_length_geom_average = (ax_height * ax_width) ** 0.5
    pad_inch = ax_length_geom_average * 0.03 * pad_scale
    pad_inch_x, pad_inch_y = pad_inch, pad_inch
    
    pad_coord_x = pad_inch_x * inch2coord_x
    pad_coord_y = pad_inch_y * inch2coord_y
    
    if ha == 'left': pos_x = ax.get_xlim()[0] + pad_coord_x
    elif ha == 'right': pos_x = ax.get_xlim()[1] - pad_coord_x
    else: raise Exception("Unsupported value for 'ha'")
    
    if va in ['top','up','upper']: pos_y = ax.get_ylim()[1] - pad_coord_y
    elif va in ['bottom','down','lower']: pos_y = ax.get_ylim()[0] + pad_coord_y
    else: raise Exception("Unsupported value for 'va'")
    
    return pos_x, pos_y
443178
def fill(text, delimiter="", width=70):
    
    texts = []
    for i in xrange(0, len(text), width):
        t = delimiter.join(text[i:i + width])
        texts.append(t)
    return "\n".join(texts)
1340700
def split_tokens(self):
        """"""
        if not self._split_tokens_calculated:
            # split into items (whitespace split)
            self._split_tokens = self._line_str.split()
            self._split_tokens_calculated = True

        return self._split_tokens
1047429
def readlines(self, size=None):
        
        last_pos = self._pos
        result = []
        if size is not None:
            end = min(self.limit, last_pos + size)
        else:
            end = self.limit
        while 1:
            if size is not None:
                size -= last_pos - self._pos
            if self._pos >= end:
                break
            result.append(self.readline(size))
            if size is not None:
                last_pos = self._pos
        return result
1330562
def line_and_column(text, position):
    """"""
    position_counter = 0
    for idx_line, line in enumerate(text.splitlines(True)):
        if (position_counter + len(line.rstrip())) >= position:
            return (idx_line, position - position_counter)
        else:
            position_counter += len(line)
1342490
def colformat(strings, num_sep_spaces=1, terminal_width=None):
    """"""
    if terminal_width is None:
        terminal_width = get_terminal_size().columns

    if not strings:
        return

    num_items = len(strings)
    max_len = max([len(strip_ansi_escapes(s)) for s in strings])

    num_columns = min(
        int((terminal_width + num_sep_spaces) / (max_len + num_sep_spaces)),
        num_items)
    num_columns = max(1, num_columns)

    num_lines = int(math.ceil(float(num_items) / num_columns))
    num_columns = int(math.ceil(float(num_items) / num_lines))

    num_elements_last_column = num_items % num_lines
    if num_elements_last_column == 0:
        num_elements_last_column = num_lines

    lines = []
    for i in range(num_lines):
        line_size = num_columns
        if i >= num_elements_last_column:
            line_size -= 1
        lines.append([None] * line_size)

    for i, line in enumerate(lines):
        line_size = len(line)
        for j in range(line_size):
            k = i + num_lines * j
            item = strings[k]
            if j % line_size != line_size - 1:
                item_len = len(strip_ansi_escapes(item))
                item = item + ' ' * (max_len - item_len)
            line[j] = item

    sep = ' ' * num_sep_spaces
    for line in lines:
        yield sep.join(line)
791449
def shorten_text(self, text):
        """"""
        if len(text) > self.width:
            return text[:self.width - 3] + '...'
        return text
12232
def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
                         direction='xy'):
    
    if ax is None:
        ax = plt.gca()
    if renderer is None:
        r = ax.get_figure().canvas.get_renderer()
    else:
        r = renderer
    bboxes = get_bboxes(texts, r, expand)
    if 'x' not in direction:
        ha = ['']
    else:
        ha = ['left', 'right', 'center']
    if 'y' not in direction:
        va = ['']
    else:
        va = ['bottom', 'top', 'center']
    alignment = list(product(ha, va))
    for i, text in enumerate(texts):
        counts = []
        for h, v in alignment:
            if h:
                text.set_ha(h)
            if v:
                text.set_va(v)
            bbox = text.get_window_extent(r).expanded(*expand).\
                transformed(ax.transData.inverted())
            c = get_points_inside_bbox(x, y, bbox)
            counts.append(len(c) + bbox.count_overlaps(bboxes) - 1)
        a = np.argmin(counts)
        if 'x' in direction:
            text.set_ha(alignment[a][0])
        if 'y' in direction:
            text.set_va(alignment[a][1])
        bboxes[i] = text.get_window_extent(r).expanded(*expand).\
            transformed(ax.transData.inverted())
    return texts
614337
def _text_position(size, text, font):
        
        width, height = font.getsize(text)
        left = (size - width) / 2.0
        top = (size - height) / 3.0
        return left, top
601284
def _line(self, text, indent=0):
        """"""
        leading_space = '  ' * indent
        while len(leading_space) + len(text) > self.width:
            # The text is too wide; wrap if possible.

            # Find the rightmost space that would obey our width constraint and
            # that's not an escaped space.
            available_space = self.width - len(leading_space) - len(' $')
            space = available_space
            while True:
                space = text.rfind(' ', 0, space)
                if (space < 0 or
                    self._count_dollars_before_index(text, space) % 2 == 0):
                    break

            if space < 0:
                # No such space; just use the first unescaped space we can find.
                space = available_space - 1
                while True:
                    space = text.find(' ', space + 1)
                    if (space < 0 or
                        self._count_dollars_before_index(text, space) % 2 == 0):
                        break
            if space < 0:
                # Give up on breaking.
                break

            self.output.write(leading_space + text[0:space] + ' $\n')
            text = text[space+1:]

            # Subsequent lines are continuations, so indent them.
            leading_space = '  ' * (indent+2)

        self.output.write(leading_space + text + '\n')
594416
def pad_to_size(text, x, y):
    
    input_lines = text.rstrip().split("\n")
    longest_input_line = max(map(len, input_lines))
    number_of_input_lines = len(input_lines)
    x = max(x, longest_input_line)
    y = max(y, number_of_input_lines)
    output = ""

    padding_top = int((y - number_of_input_lines) / 2)
    padding_bottom = y - number_of_input_lines - padding_top
    padding_left = int((x - longest_input_line) / 2)

    output += padding_top * (" " * x + "\n")
    for line in input_lines:
        output += padding_left * " " + line + " " * (x - padding_left - len(line)) + "\n"
    output += padding_bottom * (" " * x + "\n")

    return output