Vim Tips Wiki
(add a function to source a range)
Line 31: Line 31:
 
<pre>
 
<pre>
 
nmap <C-A> :w<CR>:so %<CR>
 
nmap <C-A> :w<CR>:so %<CR>
  +
</pre>
  +
  +
----
  +
When developing a function it is sometime useful to source only a part of a file.
  +
The following function dumps a range in a file and source it:
  +
<pre>
  +
function! SourceRange() range
  +
let tmpsofile = tempname()
  +
call writefile(getline(a:firstline, a:lastline), l:tmpsofile)
  +
execute "source " . l:tmpsofile
  +
call delete(l:tmpsofile)
  +
endfunction
  +
  +
command! -range Source <line1>,<line2>call SourceRange()
  +
</pre>
  +
  +
Then, for sourcing a selection:
  +
<pre>
  +
:'<,'>Source
  +
</pre>
  +
  +
Or, for sourcing the whole buffer:
  +
<pre>
  +
:%Source
 
</pre>
 
</pre>

Revision as of 10:44, 28 September 2010

Tip 1229 Printable Monobook Previous Next

created May 12, 2006 · complexity intermediate · author DO · version 6.0


When you edit Vim script you often need to make a small change, then test some function, then make some another small change and so on. It is not convenient to restart Vim every time, and it is not convenient to run it from Ex command line.

So, it is reasonable to make a mapping:

noremap <silent><buffer> <F9> :exec 'source '.bufname('%')<CR>

You may to place this line into file {runtimepath}/ftplugin/vim.vim, to use this mapping for Vim files only.

Comments

It is quite convenient to run it from a command line:

:so %

Neither of the above works unless you save the file first. I use

nmap <C-A> :w<CR>:so %<CR>

When developing a function it is sometime useful to source only a part of a file. The following function dumps a range in a file and source it:

function! SourceRange() range
    let tmpsofile = tempname()
    call writefile(getline(a:firstline, a:lastline), l:tmpsofile)
    execute "source " . l:tmpsofile
    call delete(l:tmpsofile)
endfunction

command! -range Source <line1>,<line2>call SourceRange()

Then, for sourcing a selection:

:'<,'>Source

Or, for sourcing the whole buffer:

:%Source