Skip to content

[VIM] Directly Compile or Execute the Program in Vim Editor

Generally, when we use the IDE to develop a program, we often use the shortcut key set by IDE to quickly compile or execute the program. This is a very convenient function.

This article records how to configure the same function on Vim: you can execute the currently edited code when you press the shortcut keys.

This article uses python as an example.


Install Vim Plugin manager: Vundle

If you have been installed can be skipped directly.

First, if the ~/.vim data does not exist, you need to create this folder first, and then get the Vundle project from Github:

mkdir ~/.vim
mkdir ~/.vim/bundle
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim

At this point, Vundle already exists in our environment.


Install VIM Plugin

Then, use the following command to edit the .vimrc configuration file:

vim ~/.vimrc


Then set the plugin to be installed:

" Plugins
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'tell-k/vim-autopep8'
call vundle#end()
filetype plugin indent on

" Press F10 to execute Python script
map :Autopep8 :w :call RunPython()
function RunPython()
    let mp = &makeprg
    let ef = &errorformat
    let exeFile = expand("%:t")
    setlocal makeprg=python3\ -u
    set efm=%C\ %.%#,%A\ \ File\ \"%f\"\,\ line\ %l%.%#,%Z%[%^\ ]%\@=%m
    silent make %
    copen
    let &makeprg = mp
    let &errorformat = ef
endfunction

The upper part is the package that needs to be installed, and the lower part is the Python execution function we defined.

By the way, "autopep8" is a tool that can automatically typeset Python code into PEP8 format. The famous Python IDE, PyCharm, also uses autopep8 to automatically fix typesetting problems.

Of course, although we have set up the plug-in tools we want, we haven't installed it yet. Use the following commands in the VIM editor:

:PluginInstall

We will see that the lists we have just now are displayed on the left hand side and installed one by one. Until the word "Done" pops out at the bottom, it means the installation is successful.


Test Shortcuts

Now, let’s test the effect we just set. In my settings, I use F10 as my shortcut key. This is to not confuse it with the PyCharm I am used to.

Of course, you can freely set the shortcut keys you want. Suppose I have a program like this:

print('Hello World!')



Then, I press F10:

Under my VIM editor, the result after execution is automatically displayed.

I hope everyone can successfully configure their VIM environment! By the way, since I am still not used to running VIM programs like this, I still archived and exited obediently and used the "python3" command to execute the file.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version