Vim variable syntax highlighting

邮差的信 提交于 2019-11-30 18:11:25

As proof of concept, I tried

let vars = ['init', 'editable', 'init_ui']
let colors = ['ff0000', '00ff00', '0000ff']
for var in vars
  execute 'syn keyword var_' . var var
  execute 'hi default var_' . var 'guifg=#' . remove(colors, 0)
endfor

and it worked as expected. This created syntax items for each variable in the list: var_init, var_editable, and var_init_ui. Then it assigns a highlight color to each syntax item.

In order to get beyond proof of concept, you have to get a list of variable names. You can do this by parsing a tag file (as produced by ctags, for example) or by writing a parser in vim (which would be very portable). You can sort the list and remove duplicates, but I think the use of :hi default will save you if you skip this step. Come up with a better way of generating colors than my example.

You can do all of that using an autocommand when a buffer is entered, or when the user explicitly calls a function. Then you can start thinking about automatic updating as new variables are defined.

Benjifisher's answer outlines how such can be implemented, but that's still a major effort, and probably out of reach for a beginner. But, as majkinetor recommended in the comments, my Mark plugin would allow you to quickly set up different coloring for "interesting" variable names by manually (un-)marking them (the default mapping is <Leader>m, which usually translates to \ followed by M. I use this myself to understand complex parts of the code or when troubleshooting log files.

With the following command in your ~/.vimrc, you can have up to 77 different colors available:

let g:mwDefaultHighlightingPalette = 'maximum'

There is such a plugin: https://github.com/jaxbot/semantic-highlight.vim

Where every variable is a different color, an idea popularized by Evan Brooks' blog post.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!