Skip to content

Instantly share code, notes, and snippets.

@lucs
Last active December 11, 2022 14:45
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 lucs/412c1746a7f33ed676adf02dcb7aa804 to your computer and use it in GitHub Desktop.
Save lucs/412c1746a7f33ed676adf02dcb7aa804 to your computer and use it in GitHub Desktop.
Vim: execute the text that is visually highlighted.
" --------------------------------------------------------------------
" Execute the text that is visually highlighted. This is very practical
" when wanting to try out stuff one may want to put in their .vimrc file
" or something.
function! ExecHighlighted () range
" Grab the highlighted text: save the contents of an arbitrary
" register, yank the highlighted text to it, copy the register
" contents to a local variable, and restore the register
" contents.
let l:saved_a = @a
silent! normal! gv"ay
let l:text = @a
let @a = l:saved_a
" Concatenate continuation lines, else for some reason it
" fails to work.
let l:text = substitute(l:text, '\n\s*\\\\', ' ', 'g')
" Execute the grabbed text.
" echo '⦃' . l:text . '⦄'
exec l:text
endfunction
" Have a Visual-mode-only mapping to invoke the function.
xnoremap <f9> :call ExecHighlighted()<cr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment