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

  • 2
    Doesn't work in all cases, but :@* – Mass Apr 5 '19 at 14:33

After you've done your Visual selection run this:


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

| improve this answer | |
  • 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
  • 1
    You'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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.