Run any code from Vim

RMAG news

Do you want to quickly run and test any code without leaving Vim and without even opening a :terminal?

There is a very simple way of achieving this. All we need is a runner function, a run command and a mapping to call it.

Here is an example:

function! CodeRunner()
if &ft ==# ‘python’
execute ‘RPy’
endif
endfunction

and the run command:

command! RPy :!python3 %

and the mapping:

nnoremap <F12> :call CodeRunner()<CR>

I prefer to wrap the mapping and the run command inside an augroup:

augroup code_runner
au!
au FileType python command! RPy :!python3 %
nnoremap <F12> :call CodeRunner()<CR>
augroup end

Place the above snippets in your .vimrc and source it. Now, every time you’re inside a python file, you can just press F12 to run the code and see its output.

You can add other languages to the function and to the augroup too:

“===[ Execute From Vim ]===”
function! CodeRunner()
if &ft ==# ‘python’
execute ‘RPy’
elseif &ft ==# ‘sh’
execute ‘RB’
elseif &ft ==# ‘javascript’
execute ‘RJs’
elseif &ft ==# ‘php’
execute ‘RPHP’
elseif &ft ==# ‘go’
execute ‘RGo’
endif
endfunction

And the corresponding augroup:

augroup code_runner
au!
au FileType python command! RPy :!python3 %
au FileType sh command! RB :!bash %
au FileType javascript command! RJs :!node %
au FileType go command! RGo :!go run %
au FileType php command! RPHP :!php %
nnoremap <F12> :call CodeRunner()<CR>
augroup end

With this, you can run bash, python, javascript, golang and php with the F12 key.

A similar method can be used for compiled languages, such as C.

Example:

function! CompileAndRun()
let current_file = expand(‘%’)
let file_name = fnamemodify(current_file, ‘:t:r’)
let compile_cmd = ‘gcc ‘ . current_file . ‘ -o ‘ . file_name . ‘ && ./’ . file_name
execute ‘!’.compile_cmd
endfunction

The function above, will compile the C code inside the current buffer using gcc, and then execute the binary output.

Naturally, we need a corresponding mapping:

nnoremap <F8> :call CompileAndRun()<CR>

More arguments can be added to the compile _cmd to serve your needs.

One last addition that I recommend, is a shortcut for clearing the terminal:

nnoremap l :!clear<CR><CR>

Once your terminal becomes full with output, just press l (that is L) in normal mode to clear it.