1

How can I deal with the colored outputs of shell commands when inputing them with :read?

As an example, I have a self-defined git log command, and I would like to see it in a split window. That works well enough using

:new | read !git log-command

Unfortunately, the command outputs has some colours. And thus the result looks like

  • ^[[33mac74ef4^[[m 2018-10-22 [me, N] - some text

I guess I could just use as :substitute command to clean it up afterwards, or maybe pipe it through sed.

But I wanted to know if there was a better way to handle it?

As a minimum, I would like to remove those ^[[m characters. But even better would be to recognise them and adapt it to color the buffer accordingly.

4
  • Can Vim interpret terminal color escape codes? may be useful Oct 24, 2018 at 11:26
  • 1
    Specifically for git, you can disable colours, which is what I do. Can also use git --no-color. I would also expect git to automatically disable colours when outputting to something without stdin btw Oct 24, 2018 at 11:30
  • 1
    If there is no way to disable the generation of the Ansi escape sequences from your command (using e.g. a command line switch, usually --color=auto just works), you can strip it by post processing the output, e.g. :r! git log |sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" Oct 24, 2018 at 16:23
  • I might have an older oversion of git running, but --no-color is not recognised. I actually tried that. So sed and :substitute are the best options. Well the other page mentions some plugins, I might give them a try. Oct 25, 2018 at 4:43

1 Answer 1

2

Best way is to avoid the output of these ANSI escape codes. Some commands to this automatically when the output is not to a terminal, others have a command-line argument, e.g. --no-color or --color=never (even moderately outdated Git versions understand this). Some also react to the terminal type, so prepending TERM=dumb git ... might work, too (it does for me).

Alternatively, you can strip off the codes, e.g. with sed:

git ... | sed 's#\x1b\[[0-9;]*[mK]##g'

You can do the same inside Vim, too:

%substitute#\e\[[0-9;]*[mK]##g

Finally, there are plugins which translate (but not remove) the ANSI escape codes to Vim colors (via syntax highlighting and concealing of the sequences):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.