I would like to highlight or color certain lines to mark them visually, and then move around freely in the file without affecting the selection. Is there a way of doing this? I know I can do 'v' to select, but with that the selection moves with the cursor, so you cannot move around freely.
You can use Vim's syntax highlighting mechanism but you'll need some code:
function! HilightVisSel() abort let higroup = "Error" let [_, lineno1, column1, _] = getpos("'<") let [_, lineno2, column2, _] = getpos("'>") let sellines = getline(lineno1, lineno2) let sellines[-1] = sellines[-1][: column2 - 1] let sellines = sellines[column1 - 1:] let matchtext = join(sellines, "\\n") let pat = '\V' . matchtext call matchadd(higroup, pat) endfunction
And a couple mappings (change the mapped keys to whatever you want):
:vnoremap <leader>x :<c-u>call HilightVisSel()<CR> :vnoremap <leader>X :<c-u>call clearmatches()<CR>
Now select some text with
v and run the first mapping and the text will be colored like an error message. (Change the
let higroup line to something other than "Error" if you want less conspicuous coloring. Run
:hi and you'll see your choices.) Repeat selecting and running first mapping as many times as you want. When you don't want the highlighting any more run the second mapping.
There's some refinement needed. I haven't tested with
V and the
clearmatches() call is kind of scorched earth. But if this generally meets your needs we can tackle those later.
Note: Upon submitting I noticed a problem with the boundaries of the matching pattern. In a rush since I didn't want broken code floating here I looked at the column slicing done in a plugin called vim-interestingwords and used a variation of what it does. So I wanted to give a shout out to them. (That plugin does something similar to the above but operates on individual words. Nice feature is giving different words different colors and they are user-customizable).