keenan's log Recording things so that I don't forget them.

Compiling Python Code in Vim

At the beginning of the summer, I configured my vim environment for Python development, including being able to compile my code within the editor. Today, I pulled up some old files and couldn’t remember how to run it anymore…

I looked in my vimrc file and it looks like this:

" Set makeprg to compile current Python file
set makprg=python\ %
set noswapfile

" Map keys to compile Python scripts
:nnoremap <S-b> :b1 <bar> :w <bar> :1,1000bd! <bar> 
:b1 <bar> :botright vnew <bar> 
:read !python lol.py -m json.tool <CR>

What is this ugliness?! It looks like hitting Shift+B results in the following:

  1. Loads the first buffer (presumably where my code is)
  2. Writes the file (saves it)
  3. Closes buffers 1 through 1000 (essentially closes all buffers). I assume the exclamation forces this action without saving the other buffers.
  4. Reloads the first buffer
  5. Opens a new vertical buffer in the bottom right part of vim
  6. Runs the shell command python lol.py and reads the output into a new buffer
  7. Runs the Python module, json.tool
  8. Hits enter

Ignoring the fact that I apparently hardcoded a build sequence for one file, the output doesn’t look too bad. The results look like this:

Python output in vim buffer