sty icon indicating copy to clipboard operation
sty copied to clipboard

[Suggestion] Text width (string length without sequences).

Open rysson opened this issue 1 year ago • 2 comments

Yours lib is awesome, I used it for years. Now I have a little problem, a have fine formatting and print table separated.

Is any way to find printable text width to calculate table cell width? If not I suggest add a function to count length of the text without sequences.

Of course I can add some regex to transform text before taking its length but it'll be nice to have it out of the box.


EDIT: some example

rx_omit_sequences = re.compile(r'(?:\033\[|\x9b)[0-?]*[!-/]*[@-~]')

def text_width(s: str) -> int:
    return len(rx_omit_sequences.sub('', s))

s = f'{fg.red}This is red text!{fg.rs}'
print('-' * len(s))
print(s)
print('-' * text_width(s))

20240111-132352-231x50

rysson avatar Jan 11 '24 11:01 rysson

Thanks for your kind words! :-)

I'm not sure if I understand the use case yet. Couldn't you just write:

s = "This is red text!"

print('-' * len(s))
print(f'{fg.red}{s}{fg.rs}')
print('-' * len(s))

I usually apply the styling/formatting as the very last step. Adding styles and then remove them via regex doesn't seem right to me.

Maybe a util function would make sense, but I'm not sure if it's really needed. I could see it misused a lot.

feluxe avatar Jan 15 '24 23:01 feluxe

Of course, I could :smiley:

I wrote a function to print data in table layout. I want to allow there use formatted strings too.

I could add separate table with formats (or use table with cell objects rather, text with align, formatting etc.). Next replace format with callable, maybe some formats are complex. It's going to be more complicated.

OK, I see, it's my problem, I've to think about it more.

rysson avatar Jan 17 '24 08:01 rysson