Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text ranges in Vim

Tags:

vim

vi

Is it possible to mark a range of text in Vim and change the highlight color of it (to red) than select another range of text and change that color (to green) keeping the previous highlight and so on?

like image 442
Vereb Avatar asked Nov 28 '22 19:11

Vereb


1 Answers

The basic stuff to start from is:

:hi Green guibg=#33ff33
:syntax region Green start=/\%20l/ end=/\%30l/

What it does:

  1. Define 'Green' highlight group with green background color.
  2. Define syntax region which should be highlighted with 'Green' highlight group started from line nr 20 to line nr 30.

Now you can write a function or/and command which takes visually selected text and applies one of the multiple predefined color groups to it. Once you have that function -- bind it to your keys: for example \g for green, \r for red,

Upd:

And here is a bit of vimscript:

function! HighlightRegion(color)
  hi Green guibg=#77ff77
  hi Red guibg=#ff7777
  let l_start = line("'<")
  let l_end = line("'>") + 1
  execute 'syntax region '.a:color.' start=/\%'.l_start.'l/ end=/\%'.l_end.'l/'
endfunction

vnoremap <leader>g :<C-U>call HighlightRegion('Green')<CR>
vnoremap <leader>r :<C-U>call HighlightRegion('Red')<CR>

Note:

It can't reapply the highlighting (Green to Red for instance).

like image 144
Maxim Kim Avatar answered Dec 14 '22 23:12

Maxim Kim