53

Many CLI programs output nicely-highlighted text. While most of them check if the output is going to a file, some include the terminal escape codes. I like the output with the escape codes, but viewing these files in Vim is painful.

Can Vim interpret these escape codes into the expected colors? If not, can Vim be set to ignore these escape codes?

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
beatgammit
  • 1,253
  • 2
  • 10
  • 8

4 Answers4

48

There are various plugins which allow you to view ANSI colours through escape codes:


If you want to remove all escape codes, you could use:

:%s/<1b>\[[0-9;]*m//g

Note: <1b> is not literal text, it is the escape character, use Ctrl+v followed by Esc to insert it (it may also show up as ^[, depending on your display setting).

Or you can remove them with sed; for example:

$ sed 's|\x1b\[[;0-9]*m||g' somefile | vi -
Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
  • 2
    You can also use \e in vim's regular expressions and vimscript strings instead of typing <C-v><Esc>. – rampion Feb 07 '20 at 18:31
  • Colorizer failed to parse a 4400-line file with 'redrawtime' exceeded, syntax highlighting disabled – chb Oct 19 '22 at 16:18
13

If you have a sufficiently modern vim that has the +terminal feature, you can do :term cat somefile and you'll get a buffer with all the terminal codes interpreted.

This might work better on large files than e.g. Colorizer, which made my vim unusably slow when I let it loose on a 6000-line file.

Marius Gedminas
  • 281
  • 3
  • 4
7

Building on the previous answer, with this bash function you can open vim and the required file will be displayed with colours instead of codes in a new window "a little bit later" (depending on the size of $1).

ansivim ()                               
{                                        
    vim -c ":term ++hidden ++open cat $1"
}
  • ++hidden runs the command wihout any open viewport (i.e. window) on it, and
  • ++open will open a window on the buffer only when "the job terminates" i.e. when the cat command has finished printing the file.

In summary this effectively makes the window with the file content open only when cat has returned in order to have Vim start directly instead of lagging when cat-ting large files.

e.g.

ansivim build.log
adamency
  • 142
  • 5
drkicknrush
  • 71
  • 1
  • 2
1

If you only want to view the file with terminal escape sequences and not edit it, there is vimpager (uses AnsiEsc internally). I also have developed a rewrite: nvimpager.

Lucas
  • 1,629
  • 10
  • 21