Search code examples
vimkey-bindings

Run code directly from Gvim with a keybinding


I am looking for a way to run the most used programming languages (python, c, c++, etc)

With a keybinding. A plugin would be preferred.

Thank you


Solution

  • Scripting languages (e.g. python):
    To run the current python script with a shortcut (for example F1):

    For Windows, add the following line to your _vimrc:

    autocmd FileType python nmap <silent> <buffer> <F1> :silent up<CR>:silent <C-r>=!cmd /k python <C-r>=expand("%:p")<CR><CR>
    
    • For this to run correctly, python directory should be added to your %Path%.
    • If python scripts (*.py) are associated with python.exe, no need to call python then the script as an argument, as the script can be called directly.

    For Linux, add the following line to your .vimrc:

    autocmd FileType python nmap <silent> <buffer> <F1> :silent up<CR>:silent <C-r>=!python <C-r>=expand("%:p")<CR> &<CR>
    

    Compiled languages (e.g. C):
    Map a shortcut to compile the file:

    autocmd FileType c nmap <buffer> <F1> :up<CR>:!gcc <C-r>=expand("%:p")<CR> -o <C-r>=expand("%:p:r")<CR><CR>
    

    And map another shortcut to run the resulting executable:

    autocmd FileType c nmap <silent> <buffer> <S-F1> :silent <C-r>=!<C-r>=expand("%:p:r")<CR> &<CR>