How to make VIM an IDE for Python on FreeBSD

Install VIM
# pkg install vim

VIM Extensions
The first thing you need is a good extension manager.

Vundle
VIM has serveral extension managers, but I strongly recommend Vundle.

Let's get Vundle installed:
$ git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim

This command downloads the Vundle plugin manager and chucks it in your VIM
bundles directory. Now you  can manage all your extensions from the .vimrc configuration file.
$ touch ~/.vimrc

Now set up Vundle in your .vimrc by adding the following to the top of the file:

set nocompatible              " required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

" add all your plugins here (note older versions of Vundle
" used Bundle instead of Plugin)

" ...

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

That's it. You're now set up to use Vundle. Afterward, you can add the plugins you want to install, then fire up VIM and run:

:PluginInstall

This command tells Vundle to work its magic -- downloading all the plugins and installing/updating them for you.

Let's Make an IDE

Split Layouts
If you open a file with :sp <filename>, you split the layout vertically (opening the new file below the current file). If you reverse the keys to :vs <filename>, you get a horizontal split (opening the new file to the right of your current file).

Tip #1: Make sure to utilize tab completion to find files after typing: sp.

Tip #2: You can also specify different areas of the screen where the splits should occur by adding the following lines to the .vimrc file:

set splitbelow
set splitright

Tip #3:  Want to move between the splits without using the mouse? If you simply add the following to .vimrc, you’ll be able to jump between splits with just one key combination:

"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

Key combos:

  • Ctrl + J   move to the split below
  • Ctrl + K  move to the split above
  • Ctrl + L   move to the split the right
  • Ctrl + H  move to the split the left
In other words, press Ctrl plus the standard VIM movement key to move to a specific pane.

Tip #4:  At the end of the :ls output, VIM will prompt with Hit enter to continue. You can instead type :b <buffer number> and pick the buffer immediately while you still have the list displayed. Doing so will save you a keystroke, and you won’t have to remember the buffer number.

Code Folding

Most “modern” IDEs provide a way to collapse (or fold) methods and classes, showing you just the class/method definition lines instead of all the code.

You can enable that in .vimrc with the following lines:

" Enable folding
set foldmethod=indent
set foldlevel=99

This works all right, but you have to type za to fold(and unfold). The space key would be much better. So add this line to your .vimrc file as well:

" Enable folding with the spacebar
nnoremap <space> za

Now you can easily hide portions of your code that you're not currectly working on.

The initial command, set foldmethod=indent, creates folds based upon line indents. This, however, often creates more folds than you really want. But have no fear! There are several extensions that attempt to rectify that. We recommend SimpylFold. Install it with Vundle by adding the following line to .vimrc:

Plugin 'tmhedberg/SimpylFold'

Note: Don't forget to install the plugin - :PluginInstall.

Tip #5: Try this if you want to see the docstrings for folded code:

let g:SimpylFold_docstring_preview=1

Python Indentation

Of course, for code folding to work based on indentations, you want your indents to be correct. Again, VIM falls short a bit out of the box because it doesn’t handle auto-indent after a function definition. You can do two things with indentation:
  1. Get indentation to follow PEP 8 standards.
  2. Better handle auto-indentation.
PEP 8
To add the proper PEP 8 indentation, add the following to your .vimrc:

au BufNewFile,BufRead *.py
    \ set tabstop=4 |
    \ set softtabstop=4 |
    \ set shiftwidth=4 |
    \ set textwidth=79 |
    \ set expandtab |
    \ set autoindent |
    \ set fileformat=unix

This will give you the standard four spaces when you hit tab, ensure your line length doesn’t go beyond 80 characters, and store the file in a Unix format so you don’t get a bunch of conversion issues when checking into GitHub and/or sharing with other users.

For full stack development, you can use another au command for each filetype:

au BufNewFile,BufRead *.js, *.html, *.css
    \ set tabstop=2 |
    \ set softtabstop=2 |
    \ set shiftwidth=2 |
    \ set fileformat=unix


This way, you can have different settings for different filetypes. There is also a plugin called ftypes that will allow you to have a separate file for each filetype you want to maintain settings for, so use that if you see fit.

Auto-Indentation

autoindent will help, but in some cases (like when a function signature spans multiple lines), it doesn’t always do what you want, especially when it comes to conforming to PEP 8 standards. To fix that, you can use the indentpython.vim extension:

Plugin 'vim-scripts/indentpython.vim'

Flagging Unnecessary Whitespace

You also want to avoid extraneous whitespace. You can have VIM flag that for you so that it’s easy to spot and then remove:

au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/

This will mark extra whitespace as bad and probably color it red.

UTF-8 Support
For the most part, you should be using UTF-8 when working with Python, especially if you’re working with Python 3. Make sure VIM knows that with the following line:

set encoding=utf-8

Auto-Complete

The best plugin for Python auto-complete is YouCompleteMe. Again, use Vundle to install:

Bundle 'Valloric/YouCompleteMe'

Under the hood, YouCompleteMe uses a few different auto-completers (including Jedi for Python), and it needs some C libraries to be installed for it to work correctly. The docs have very good installation instructions, so I won’t repeat them here, but be sure you follow them.

It works out of the box pretty well, but let’s add a few customizations:

let g:ycm_autoclose_preview_window_after_completion=1
map <leader>g  :YcmCompleter GoToDefinitionElseDeclaration<CR>

The first line ensures that the auto-complete window goes away when you’re done with it, and the second defines a shortcut for goto definition.

Note: My leader key is mapped to space, so space-g will goto definition of whatever I’m currently on. That’s helpful when I’m exploring new code.

Syntax Checking/Highlighting

You can have VIM check your syntax on each save with the syntastic extension:

Plugin 'vim-syntastic/syntastic'

Also add PEP 8 checking with this nifty little plugin:

Plugin 'nvie/vim-flake8'

Finally, make your code look pretty:

let python_highlight_all=1
syntax on

Color Schemes

Color schemes work in conjunction with the basic color scheme that you are using. Check out solarized for GUI mode, and Zenburn for terminal mode:

Plugin 'jnurmine/Zenburn'
Plugin 'altercation/vim-colors-solarized'

Then, just add a bit of logic to define which scheme to use based upon the VIM mode:

if has('gui_running')
  set background=dark
  colorscheme solarized
else
  colorscheme zenburn
endif

Solarized also ships with a dark and light theme. To make switching between them very easy (by pressing F5) add:
call togglebg#map("<F5>")

File Browsing

If you want a proper file tree, then NERDTree is the way to go:
Plugin 'scrooloose/nerdtree'

If you want to use tabs, utilize vim-nerdtree-tabs:
Plugin 'jistr/vim-nerdtree-tabs'

Want to hide .pyc files? Then add the following line:
let NERDTreeIgnore=['\.pyc$', '\~$'] "ignore files in NERDTree

Super Searching

Want to search for basically anything from VIM? Check out ctrlP:
Plugin 'kien/ctrlp.vim'

As you might expect, pressing Ctrl+P will enable the search, so you can just start typing. If your search matches anything close to the file you’re looking for, it will find it. Oh, and it’s not just files: it will find tags as well! For more, check out this YouTube video.

Line Numbering

Turn on line numbers on the side of the screen with:
set nu

Git Integration

Want to perform basic git commands without leaving the comfort of VIM? Then vim-fugitive is the way to go:
Plugin 'tpope/vim-fugitive'

See it in action on VIMcasts.

Powerline

Powerline is a status bar that displays things like the current virtualenv, git branch, files being edited, and much more.
It’s written in Python, and it supports a number of other environments like zsh, bash, tmux, and IPython:
Plugin 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}

Take a look at the official docs for all the configuration options.

System Clipboard

Vim usually has its own clipboard and ignores the system keyboards, but sometimes you might want to cut, copy, and/or paste to/from other applications outside of VIM. On OS X, you can access your system clipboard with this line:
set clipboard=unnamed

VIM in the Shell

Finally, once you’ve mastered VIM and its keyboard shortcuts, you’ll often find yourself getting annoyed with the lack of those same shortcuts in the shell. Fear not: most shells have a VI mode. To turn it on for your shell, add the following line to ~/.inputrc:
set editing-mode vi

Now, you will be able to use VIM key combos not only in the shell but also in the Python interpreter and any other tool that uses GNU Readline (most database shells). Now you have VIM everywhere!

Conclusion

That’s more or less it (for Python development, at least). There are a ton of other extensions that you can use, as well as alternatives to everything detailed in this post. What are some of your favorite extensions? How have you configured VIM to match your personality?

Here is a link to my current VIM config. Got one of your own? Please share!

Thanks for reading!

Comments

Popular posts from this blog

BdsDex: failed to load Boot0001 "UEFI BHYVE SATA DISK BHYVE-OABE-20A5-E582" from PciRoot(0x0)/Pci (0x2, 0x0)/Stat(0x0,0xFFFF,0x0) : Not Found

How to Dockerizing LEMP Stack with Docker-Compose

How To Install Nginx, MySQL and PHP (FEMP) Stack on FreeBSD 13.0