43

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?

1
39

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 -
1
  • 2
    You can also use \e in vim's regular expressions and vimscript strings instead of typing <C-v><Esc>. – rampion Feb 7 '20 at 18:31
9

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.

1
  • Note: Terminal buffers are by default unmodifiable, and any modification will make the colours disappear. – preferred_anon Mar 5 '20 at 17:22
5

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"
}

e.g.

ansivim build.log
3
  • Welcome to Vi and Vim! – D. Ben Knoble Jan 28 '20 at 14:24
  • drkicknrush, is there a way to do this with stdin? I'm not sure what is going on, and I can only get it to work with actual files. thx! – marinara Aug 14 '20 at 1:28
  • 1
    hi @marinara, that is something I wanted as well :-) but I could not get it to work, sorry... – drkicknrush Aug 20 '20 at 11:58
0

Trying to get drkicknursh's code work, I got:

vim -c ":term cat $1"

Although there should be many problems like malformed inputs, I think it's enough for personal use.

1
  • Welcome to Vi and Vim! I've edited your post for some formatting; that said, if your answer is just a repeat of another, it may not really belong. If you think you can distinguish this answer, edits to do so are welcome! – D. Ben Knoble Mar 16 at 16:45
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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