Skip to content
Advertisement

How to wrap color coded text to fixed line length in terminal?

For text with color codes, how to wrap it to a fixed length in the terminal?

Text without color codes wraps nicely with fold:

JavaScript

But this red text wraps wrong:

JavaScript

Note: While the red text is wrapped wrong, it still is printed in red, which is the desired behavior.

(My use case is line wrapping the output of git log --color=always --oneline --graph.)

Advertisement

Answer

When determining the (printable) width of a prompt (eg, PS1) the special characters – [ and ] – are used to designate a series of non-printing characters (see this, this, this and this).

So far I’ve been unable to find a way to use [ and ] outside the scope of a prompt hence this awk hack …


Assumptions:

  • we don’t know the color codes in advance
  • for this exercise it is sufficient to deal with color codes of the format e[...m (e[m turns off color)
  • may have to deal with multiple color codes in the input

We’ll wrap one awk idea in a bash function (for easier use):

JavaScript

NOTES:

  • other non-color, non-printing characters will throw off the count
  • the regex could be expanded to address other non-printing color and/or character codes

Test run:

JavaScript

Displaying colors:

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement