vimtricks.wiki Concise Vim tricks, one at a time.

How do I execute Vimscript code from the current buffer?

Answer

:source % or :'<,'>source

Explanation

The :source command executes Vimscript from a file. When used with % (current file) or a visual selection, you can run code directly from your buffer — making Vim into an interactive Vimscript scratchpad.

Execute the entire file

:source %    " Execute all Vimscript in the current file
:so %        " Short form

Execute selected lines

" Select lines in visual mode, then:
:'<,'>source

" Or for a specific range:
:10,20source

Practical uses

" Reload your vimrc without restarting
:source ~/.vimrc
:source $MYVIMRC

" Test a function you're writing
" Write the function in a buffer, select it, source it
function! MyHelper(text)
  return toupper(a:text) . '!'
endfunction
" Select above, :'<,'>source, then test:
:echo MyHelper('hello')    " → HELLO!

" Apply a temporary setting
:source    " (with visual selection of 'set cursorline')

Interactive development workflow

  1. Open a .vim file or scratch buffer
  2. Write your Vimscript function or configuration
  3. Select the code and :source it
  4. Test it immediately
  5. Iterate and re-source

Tips

  • :source runs each line as an Ex command
  • For Lua (Neovim): use :luafile % or :lua << EOF ... EOF
  • $MYVIMRC is a built-in variable pointing to your vimrc
  • Use this workflow for developing custom functions, testing mappings, or debugging config
  • Neovim users can also use :source with Lua files (.lua)
  • Documented under :help :source

Next

How do I run the same command across all windows, buffers, or tabs?