multiple-columnszshansi-escapeansi-colors

Columnizing a list with ANSI-color codes?


Using column or pr -T3 to columnize an input with ANSI escapes results in bad align of the items – they are under or overaligned. For example: ls -1 --color=always|column.

I'm writing a file manager and would want 2 columns format, like in Midnight Commander. The good part is that the project is written in Zsh script and I would want a nice way of columnizing color fd ./exa -1 --color=always/ls -1 --color=always output, including a Bash/Zsh/Awk/etc. script as a solution. Is there a way?


Solution

  • It looks like the zsh builtin print can handle colors when creating columns with the -C and -c options. The source code even has this note:

    * Prevent misaligned columns due to escape sequences by
    * skipping over them. Octals \033 and \233 are the
    * possible escape characters recognized by ANSI.
    

    Converting the command output to arguments for print can be slightly tricky, but this combination of a command substitution with $(...) and an expansion split by line using ${(f)...} should work:

    print -C 2 ${(f)"$(ls -1 --color=always)"}
    

    You also can pass in data via a coprocess.