DEV Community

woland
woland

Posted on

Run any code from Vim

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
Enter fullscreen mode Exit fullscreen mode

and the run command:

command! RPy :!python3 %
Enter fullscreen mode Exit fullscreen mode

and the mapping:

nnoremap <F12> :call CodeRunner()<CR>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)