A classic Vim tip to make it quick and easy to source the Vim script you're working on.
Press <F9> to reload the current Vimscript or Lua source file.
- Works from insert and normal modes.
Oftentimes, you'll see code atop a Vim plugin that prevents that script from being sourced twice. E.g., perhaps you've see code like this:
if exists('g:loaded_source_reloader') || &cp
finish
endif
let g:loaded_source_reloader = 1
Such code inhibits this plugin (and the :source command) from
reloading those scripts.
But there are a few ways to get around the guard clause so you can reload the file at runtime after you've made changes to it. (Skip to the third option for possibly the best approach.)
One option is to unlet the variable, either manually or by adding an unlet before the finish guard, e.g.:
" Uncomment the unlet to :source this file again at runtime.
unlet! g:loaded_source_reloader = 1
if exists('g:loaded_source_reloader') || &cp
finish
endif
let g:loaded_source_reloader = 1
Another option is to (temporarily) remove or comment out the finish, e.g.,
if exists('g:loaded_source_reloader') || &cp
" Comment the finish (temporarily) to reload this file at runtime.
"finish
endif
let g:loaded_source_reloader = 1
A third option works automatically by checking <sfile>, e.g.,
if expand('%:p') ==# expand('<sfile>:p')
unlet! g:loaded_source_reloader
endif
if exists('g:loaded_source_reloader') || &cp
finish
endif
let g:loaded_source_reloader = 1
(Props to EasyMotion
for this approach — it's the only source file this author has seen
that does it like that. So savvy!)
The original tip may be from the venerable Luc Hermitte, who commented on it, but the Wiki shows it was originally posted by 127.0.0.1.
-
Source current file when editing a script
http://vim.wikia.com/wiki/Source_current_file_when_editing_a_script
Be aware that calling :source will not always work!
You might see errors if your source code is not reentrant.
For instance:
-
Be sure to use
function!, with the bang, to overwrite existing functions of the same name. -
Be sure to use
augroup | au! ...to recreate autocommands. -
Be sure to avoid duplicate command maps, e.g., call
unmapornnoremap.
Take advantage of Vim's packages feature
(:h packages)
and install under ~/.vim/pack, e.g.,:
mkdir -p ~/.vim/pack/embrace-vim/start
cd ~/.vim/pack/embrace-vim/start
git clone https://github.com/embrace-vim/vim-source-reloader.git
" Build help tags
vim -u NONE -c "helptags vim-source-reloader/doc" -c q- Alternatively, install under
~/.vim/pack/embrace-vim/optand call:packadd vim-source-reloaderto load the plugin on-demand.
For more installation tips — including how to easily keep the
plugin up-to-date — please see INSTALL.md.
The embrace-vim logo by @landonb contains
coffee cup with straw by farra nugraha from Noun Project (CC BY 3.0).