Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim variable syntax highlighting

I'd like to change my vim config file to allow highlighting of only my declared variables, not keywords. This article shows and explains what I mean: Alternate syntax highlighting

I'm a beginner to vim (I've never changed the default config file). Could anyone point me in the right direction?

like image 207
CS Student Avatar asked Jan 27 '14 14:01

CS Student


People also ask

Does vim support syntax highlighting?

One of useful features of vim is syntax highlighting. The readability of any source code or configuration file can be increased by using different front and color for different part of the file. This task can be done by using syntax highlighting feature of vim.

How does syntax highlighting work in vim?

Syntax highlighting enables Vim to show parts of the text in another font or color. Those parts can be specific keywords or text matching a pattern. Vim doesn't parse the whole file (to keep it fast), so the highlighting has its limitations.

How do I change the highlight color in vim?

You can change color schemes at anytime in vi by typing colorscheme followed by a space and the name of the color scheme. For more color schemes, you can browse this library on the vim website. You can enable or disable colors by simply typing "syntax on" or "syntax off" in vi.


1 Answers

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.

like image 50
benjifisher Avatar answered Oct 11 '22 09:10

benjifisher