nirum / tableprint

Pretty console printing :clipboard: of tabular data in python :snake:
https://tableprint.readthedocs.io/
MIT License
174 stars 16 forks source link

ANSI escape not supported #1

Closed nowox closed 7 years ago

nowox commented 7 years ago

The column size is improperly computed with the following example:

import tableprint as tp
from numpy.random import randn
from termcolor import colored

tp.table(randn(2,1), [colored('Foo', 'red')], style='fancy_grid')

It gives:

╒═══════════╕
│Foo│
╞═══════════╡
│  -0.060884│
│     -1.034│
╘═══════════╛

I think this can be corrected on header by using this:

    def format_headers(string):
        s = max(width - _ansi_len(string), 0)
        return (' ' * (s / 2)) + string + (' ' * (s - (s / 2))) if s else string

    data = map(format_headers, headers)  

Also the _ansi_len should be rewritten:

def _ansi_len(string):
    """Extra length due to any ANSI sequences in the string."""
    return len(re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', string))
nirum commented 7 years ago

Thanks! I updated the code to fix ANSI sequences in the header function.

image