Skip to content

Instantly share code, notes, and snippets.

@rdavila
Last active October 5, 2015 02:27
Show Gist options
  • Save rdavila/b3643398ccdce30de9d8 to your computer and use it in GitHub Desktop.
Save rdavila/b3643398ccdce30de9d8 to your computer and use it in GitHub Desktop.
Vimscript function to eval the contents of the current file or only the selected lines based on file extension
function! GetSelectedLines(type, ...) range
let sel_save = &selection
let &selection = "inclusive"
let reg_save = @@
if a:type == 'n'
silent exe a:firstline . "," . a:lastline . "y"
elseif a:type == 'c'
silent exe a:1 . "," . a:2 . "y"
else
silent exe "normal! `<" . a:type . "`>y"
endif
let lines = split(@@,"\n")
let &selection = sel_save
let @@ = reg_save
return lines
endfunction
function! EvalMyFile(type, ...) range
let full_path = expand('%:p')
let file_ext = expand('%:e')
let file_handlers = {
\ 'exs' : 'elixir',
\ 'ex' : 'elixir',
\ 'rb' : 'ruby',
\}
let handler = file_handlers[file_ext]
let selected_lines = GetSelectedLines(a:type)
let tmpfile = tempname()
if len(selected_lines) >= 1
call writefile(selected_lines, tmpfile)
execute "!" . handler . " " . tmpfile
else
execute "!" . handler . " " . full_path
endif
endfunction
vnoremap <D-r> :call EvalMyFile(visualmode(), 1)<cr>
nnoremap <D-r> :call EvalMyFile('n', 1)<cr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment