medikoo/cli-color

trim (chop) styled string to width

StreetStrider opened this issue · 3 comments

Hello.
Sometimes I need to trim to certain width string which have been already styled and contains control sequences. If use naive string.slice it very probably will break the styling. Is it possible to solve this issue under the cli-color's roof, so I could be able to:

var slice = require('cli-color/slice')
styled = slice(styled, 0, 80) // ← works like String.prototype.slice, but respects styling

?

It will be the feature I would use. Sometimes to workaround this I need to implement some lispy-constructors which save styles and still allows to chop/slice (something like this):

var s = [ 'long', [ clc.red, 'string' ], 'long' ]
slice_then_style(s)

@StreetStrider it's a nice feature request, and I'll be happy to take a pull request for that.

I imagine it should resemble native str.slice so it should also accept negative indexes for end argument.

It might be a bit challenging to implement it well. I think most straightforward way to do it, would be to first create a map of a string (kind of AST that provides all information about ANSI styles in a string), and then we can attack string either from start or end and generate expected result.

@medikoo, I was thinking about the same implementation. Let's keep this open, I'll start to investigate cli-color's code then.

I believe we addressed that with slice