I can source a file, e.g. my vimrc
with :so %
or :so <filename>
. But what do I do when I need to source only part of a file. I want some way to visually select a portion of the file with :h v
and then source it. Kinda like emacs's M-x eval-region
After you've done your Visual selection run this:
y:@"<CR>
y
copies the selection to the unnamed register ("
) since we didn't explicitly name a register. Then :@"
executes the contents of that register as Ex commands.
See help :@
and https://stackoverflow.com/questions/20262519/vim-how-to-source-a-part-of-the-buffer
-
So, you're saying I should just copy and paste it in my command-line window? That's... easier than I thought. – klaus Apr 5 '19 at 14:59
-
1You're not pasting to the command line, which would entail something like reading the data and storing it in an input buffer. You're just telling vim to process the data from an existing memory allocation (the register store) which is a lot less overhead. – B Layer May 13 '19 at 9:28
An alternative implementation which does not stop at the first error in a script:
command! -range=% Exec call execute(getline(<line1>, <line2>), '')
Now in visual mode type :'<,'>Exec
to process the selected lines ('<,'>
is added automatically as usual). Also, :Exec
in normal mode executes the whole buffer, just as :source %
, except the buffer does not need to be saved first.
If needed the mappings, they can be added easily.
:@*
– Mass Apr 5 '19 at 14:33