File: formatters.py

package info (click to toggle)
python-clint 0.5.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 328 kB
  • sloc: python: 1,815; makefile: 3
file content (107 lines) | stat: -rw-r--r-- 2,826 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# -*- coding: utf-8 -*-

"""
clint.textui.formatters
~~~~~~~~~~~~~~~~~~~~~~~

Core TextUI functionality for text formatting.

"""

from __future__ import absolute_import

from .colored import ColoredString, clean
from ..utils import tsplit, schunk


NEWLINES = ('\n', '\r', '\r\n')


def min_width(string, cols, padding=' '):
    """Returns given string with right padding."""

    is_color = isinstance(string, ColoredString)

    stack = tsplit(str(string), NEWLINES)

    for i, substring in enumerate(stack):
        _sub = clean(substring).ljust((cols + 0), padding)
        if is_color:
            _sub = (_sub.replace(clean(substring), substring))
        stack[i] = _sub
        
    return '\n'.join(stack)


def max_width(string, cols, separator='\n'):
    """Returns a freshly formatted
    :param string: string to be formatted
    :type string: basestring or clint.textui.colorred.ColoredString
    :param cols: max width the text to be formatted
    :type cols: int
    :param separator: separator to break rows
    :type separator: basestring

        >>> formatters.max_width('123 5678', 8)
        '123 5678'
        >>> formatters.max_width('123 5678', 7)
        '123 \n5678'

    """

    is_color = isinstance(string, ColoredString)

    if is_color:
        string_copy = string._new('')
        string = string.s

    stack = tsplit(string, NEWLINES)

    for i, substring in enumerate(stack):
        stack[i] = substring.split()

    _stack = []
    
    for row in stack:
        _row = ['',]
        _row_i = 0

        for word in row:
            if (len(_row[_row_i]) + len(word)) <= cols:
                _row[_row_i] += word
                _row[_row_i] += ' '
                
            elif len(word) > cols:

                # ensure empty row
                if len(_row[_row_i]):
                    _row[_row_i] = _row[_row_i].rstrip()
                    _row.append('')
                    _row_i += 1

                chunks = schunk(word, cols)
                for i, chunk in enumerate(chunks):
                    if not (i + 1) == len(chunks):
                        _row[_row_i] += chunk
                        _row[_row_i] = _row[_row_i].rstrip()
                        _row.append('')
                        _row_i += 1
                    else:
                        _row[_row_i] += chunk
                        _row[_row_i] += ' '
            else:
                _row[_row_i] = _row[_row_i].rstrip()
                _row.append('')
                _row_i += 1
                _row[_row_i] += word
                _row[_row_i] += ' '
        else:
            _row[_row_i] = _row[_row_i].rstrip()

        _row = map(str, _row)
        _stack.append(separator.join(_row))

    _s = '\n'.join(_stack)
    if is_color:
        _s = string_copy._new(_s)
    return _s