Skip to content

Instantly share code, notes, and snippets.

@niksaak
Created October 31, 2016 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niksaak/6cb3b716e14194169fa927c9d4d266e5 to your computer and use it in GitHub Desktop.
Save niksaak/6cb3b716e14194169fa927c9d4d266e5 to your computer and use it in GitHub Desktop.
function! s:get_visual_selection()
" Why is this not a built-in Vim script function?!
let [lnum1, col1] = getpos("'<")[1:2]
let [lnum2, col2] = getpos("'>")[1:2]
let lines = getline(lnum1, lnum2)
let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)]
let lines[0] = lines[0][col1 - 1:]
return join(lines, "\n")
endfunction
@effctcodes
Copy link

effctcodes commented Nov 1, 2016

We also used this:
:autocmd CursorMoved * :if mode() == 'v' | :call feedkeys("\<Esc>gv",'n') | :exe printf(':match CursorColumn /\V\<%s\>/', escape(Get_visual_selection(), '/\')) | :endif

(Likely you want to drop the word borders \< \> around the %s in the :match pattern.)

I'm not sure the feedkeys() does anything.

An easier workaround to the whole s:get_visual_selection() approach would be just yanking the selection. Drawback is that that could overwrite a users's register. (But you could backup and restore the register.)
:
call feedkeys("\"tygv",'n') […] escape(@t, '/\'))

It's well possible there's a bug in col2 - (&selection == 'inclusive' ? 1 : 2). In particular the script crashes at line borders, so I think this does a 'buffer underrun' – try to access an index < 0. (Overrun also thinkable.)

Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment