Wednesday, December 3, 2014

How to Echo Color from VIM using the :colorecho command



Embedded Color Codes in VIM Message Text

The Question

Does VIM have a :colorecho feature that supports embedded color codes and whatnot? YES. VIM does have :colorecho command, it doesn't make it available to the average user in the usual way.  Now I will tell you how YOU can use it too.

The Answer

There is not set format, but it is REALLY easy to make your own function to handle this. This example only touches on the tip of the iceberg, it can be made to be much more sophisticated:

... ~/.vimrc or some other file ...


fu! ColorEcho(str)
  let f:index=0
  for item in split(str,"|")
    let f:index+=1
    if f:index % 2
      echon item 
    el
      exec "echohl " . item 
    en
  endfo 
endf


...

 
com! -nargs=+ COLORECHO :call ColorEcho()

...


:COLORECHO "I need some |Comment|Real Color |Error|Here|None|!!!"

output:

  I need some Real Color Here!!!

This one-liner demonstrates this as well (if you don't believe me)

  :let j=0|for item in split("I need some |Comment|Real Color |Error|Here!","|") | let j+=1 | if j % 2 | echon item | else | exec "echohl " . item | en | endf

Re-night-capping


Wait, what about :colorecho, why is it in caps? Do you remember that 'usual way' thing I was talking about? Well, to make COLORECHO become :colorecho, you will have to do one last (possibly not good, for public script writers) thing, if pressing SHIFT is just too damn inconvenient  --- you can edit the source code from vim's google-code site, you will need an Hg client to do this, if you don't know what that is, please look it up.

Closing


Anyhow, this should get you rolling, any number of interesting things can be done to make this work better. Share some if you like, perhaps one day it will become 'core'.





No comments:

Post a Comment