Vim Tips Wiki
(add a function to source a range)
(formatting and some rewording)
Line 4: Line 4:
 
|previous=1228
 
|previous=1228
 
|next=1230
 
|next=1230
|created=May 12, 2006
+
|created=2006
 
|complexity=intermediate
 
|complexity=intermediate
 
|author=DO
 
|author=DO
Line 34: Line 34:
   
 
----
 
----
When developing a function it is sometime useful to source only a part of a file.
+
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:
The following function dumps a range in a file and source it:
 
 
<pre>
 
<pre>
 
function! SourceRange() range
 
function! SourceRange() range
let tmpsofile = tempname()
+
let tmpsofile = tempname()
call writefile(getline(a:firstline, a:lastline), l:tmpsofile)
+
call writefile(getline(a:firstline, a:lastline), l:tmpsofile)
execute "source " . l:tmpsofile
+
execute "source " . l:tmpsofile
call delete(l:tmpsofile)
+
call delete(l:tmpsofile)
 
endfunction
 
endfunction
 
 
command! -range Source <line1>,<line2>call SourceRange()
 
command! -range Source <line1>,<line2>call SourceRange()
 
</pre>
 
</pre>

Revision as of 07:18, 22 January 2011

Tip 1229 Printable Monobook Previous Next

created 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