Vim: a text-editing gamepad

Although Vim has been my editor of choice for years now, I am nowhere near being a power user. That’s simply because I didn’t do any real, full-time software development, and for that reason I didn’t have the need for any advanced features. Moreover, a lot of the power of Vim is hidden if you are just a casual user. On my new role I will be spending some more time coding, so I wanted to explore Vim a bit more and pick up some extras.

This article provides a brief overview of Vim 7, some useful key strokes and configuration settings, links to essential resources, with added focus on Python integration.

Overview

The thing that got me into vim is effective text editing. The commands are simple and clever. Most of them are a single key stroke which can be intelligently combined. For example, one of my favorite line movement commands is f{char}, where the cursor gets placed directly on the first position of {char} (eg. f” means position on the first double quote). You want a reverse function, to go to left? Just execute capital F{char}.

Vim is a modal editor. This means that commands can mean different things depending if you are in normal, insert, visual or command mode.

Furthermore, the advantage over most of the other editors is that it’s highly configurable and scriptable. Plugins for Vim can be written in Vim script or other modern languages like Python and Ruby.

Vim 7 is released in mid-2006.

Vim pros

Once you have learned and configured Vim to your liking, you become truly agile in text editing, with minimum keystrokes.

  • Normal mode: for efficiency spend time mostly in normal mode rather than in insert mode (repeat stuff with “.“)
  • Commands are incredibly powerful, and you can combine them to obtain the best results
  • One or two key motions move you directly anywhere on the line, or on the screen
  • Extremely configurable
  • Ubiquitous

Some other Vim features I wanted to mention:

  • Visual mode (it is cool to have this in terminal)
  • Macros and key bindings: easily record and replay repetitive tasks
  • Autocomplete words
  • Lightweight
  • Comprehensive documentation and huge community
  • Good for your health (HJKL movement)

Vim cons

  • Difficult to learn
  • Commands are not exactly mnemonic (the l command is for moving right)

Getting help

:h[elp] is a command used to display Vim’s on-line help. It jumps to the tag pattern, which can include wildcards. If there are several matches, the best one is used.

If you execute :help!, Vim Easter egg will print an error: Don’t panic!

Tips:

  • Use Tab for completion – :help tutor <Tab> 
  • Use CTRL+D for completion – :help tutor <CTRL+D>
  • To display help on CTRL+V:help ^V
  • To display help on za:help za
  • CTRL+] – to follow a link

If you don’t know the exact thing that you are looking for, you can use :helpgrep, e.g. :helpgrep syntax.

Other sources of help:

Tutorial

A good first step is to start with some basic commands and the movement commands.

Then go through the tutorial, especially the 30 minute hands-on vimtutor which you can run from the shell. After the tutorial, look at these searching tips, and best tips for more tricks. After you get familiar with Vim, this page has some awesome tips and use the quick reference (:help quickref). Complete all that with Vim anti-patterns (e.g. don’t move one line at a time, etc).

Learn the most useful features for you, and as time goes on your feature set will grow.

Some hand-picked tips:

  • Most commands are made from an operator [number] motion (dw, yw, c$, 2w, d2w, 3>)
  • H, M and L – take the cursor directly to the ‘H’ighest, ‘M’iddle, or ‘L’ower line on the screen
  • >aB – “indent a Block”
  • u – undo
  • U – undo the whole line
  • CTRL+R – redo (undo the undo)
  • C – change to end of line (like c$)
  • D – delete to end of line (like d$)
  • guu – lowercase line
  • gUU – uppercase line
  • ]p – just like p to paste, but adjusts the indent to the current line
  • = – (re)indent the text on the current line or on the area selected
  • =% – (re)indent the current braces { … }
  • R – replace mode
  • * – find next instance of a word that your cursor is over
  • . – repeats the last change (insert, change, delete)
  • ma – set mark a
  • ‘a – go to line marked as a
  • CTRL+G – cursor location and file status (:help ruler)
  • 100G – go to the 100th line
  • 0 – go to the first character in line
  • CTRL+O – great tip to know, takes you back to older positions, CTRL+I moves forward (used with movement, /search or 123G)
  • v motion d – another great tip, v for visual mode, select and then d to delete
  • v motion y p – visually select, copy and paste
  • :%s/old/new/gc – find every occurence in the whole file, and ask before substituting
  • :!command – execute a command
  • :r FILE – read a file
  • gf – open the file under the cursor
  • :r !date – read the output of command
  • CTRL+N, CTRL+P – autocomplete words
  • qa – start recording a macro to register a, q to stop, @a to repeat the macro (useful for code templates)
  • :split FILE – open a file in a horizontal split (CTRL+W CTRL+W to change between windows)
  • :e **/myfile.py – open myfile.c somewhere in the directory tree

Other cool features

  • vimdiff file1 file2 – diff with highlighting differences
  • vim changes.txt.gz 
  • vim archive.tar
  • vim sftp://nemanjad@myhost.com/www/index.html – remote edit
  • V jjjj zf – fold the text
  • zo – open the text (unfold)
  • za – open and close a fold
  • zfi} – fold everything inside the { block }
  • xp – swap characters
  • :abbreviate teh the
  • V select lines :sort – sorting

Windows

  • CTRL+W V – vertical split
  • CTRL+W S – horizontal split
  • CTRL+W, CTRL+W – move between windows
  • CTRL+W Q – close the current window

No need for tabs

Open a file in the new buffer with :e /path/to/file. Type :buffers to list buffers, and :b1 or :b2 to jump to a specific buffer. Close the buffer with :bw.

Customization

Configuration files

  • :set runtimepath – list of directories that will be searched for runtime files (e.g. a local runtime directory at ~/.vim/)
  • $HOME/.vimrc – start Vim with favorite mappings and settings (:help vimrc-intro)

It takes time to craft a perfect vimrc file, but it’s worth the effort!

Options

The options come in three forms: boolean (on/off), number and string. To see the current option set, execute the :set command alone.

File types

Searching

Indentation

Vim also allows you to customize indentation per file type. For example put these commands in your .vimrc file:

autocmd FileType python setlocal expandtab shiftwidth=4 softtabstop=4

Custom commands

You can map keys to commands, e.g. in insert, normal and visual mode:

:map <F3> :!cpplint *.cpp<CR>
:nmap <F3> :!cpplint *.cpp<CR>
:vmap <F3> s/^/ #/<CR>

My ~/.vimrc

Here’s an example of my rather basic .vimrc file. As I discover new tricks I’ll update it, and perhaps move the file to GitHub.

" =======
" General
" =======

set wildmenu                    " completion menu of command line commands, file names, and more
set wildmode=list:longest,full
set laststatus=2                " show the status line
set statusline=%f\ %y\ %=%l/%L  " filename, ft, line/column
set number                      " line numbers
set showcmd                     " shows what I'm typing as a command in the lower right corner
set backup                      " make a backup before overwriting a file
set backupdir=~/.vim/backup     " backup files go here 
set directory=~/.vim/tmp        " swap files go here

" ==========
" File types
" ==========

filetype on         " recognize filetypes (triggers FileType event)
filetype plugin on  " loading of filetype plugins for specific filetypes
filetype indent on  " loading the indent file for specific file types

" ======
" Syntax
" ======

syntax on
set background=dark
color elflord

" ======
" Search
" ======

set ignorecase      " ignore case while searching
set smartcase       " if search contains uppercase, treat as case-sensitive search
set hlsearch        " highlight search results
set incsearch       " search as you type

" ===========
" Indentation
" ============

set expandtab       " use spaces instead of tabs
set tabstop=4       " 1 tab == 4 spaces
set softtabstop=4   " make spaces feel like real tabs
set shiftwidth=4    " number of spaces to use for each (auto)indent (used with <<, >>)
set smartindent     " automatically insert one extra level in some cases

" ====
" Misc
" ====

"set bs=2
"set encoding=utf8

" ========
" Key maps
" ========

" easy visual indentation, very cool!
vnoremap < <gv 
vnoremap > >gv 

" ======
" Python
" ======

" wrap text after 79 characters
au BufEnter *.py set textwidth=79
" folding based on indentation, use 'za' to open and close a fold
au BufEnter *.py set foldmethod=indent foldlevel=99   
" highlight trailing whitespace
au BufEnter *.py match Error /\s\+$/
" more syntax highlighting, defined in syntax python.vim file
au BufEnter *.py let python_highlight_all = 1
" smart indenting for Python
au BufEnter *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
" :make to check syntax (:cn for next error), F5 to run code
autocmd BufRead *.py set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
autocmd BufRead *.py set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
autocmd BufRead *.py nmap <F5> :!python %<CR>
" Install https://github.com/msanders/snipmate.vim for def<tab> completion

Vim and Python

There’s a plugin to ease your Python life inside Vim called python-mode. It provides some nice features such as K on a keyword brings up pydoc, Pylint to check the code on every save, rope for functions autocomplete / organizing imports / goto function definition / refactoring, breakpoint debugging, …

The guide at http://www.sontek.net/blog/2011/05/07/turning_vim_into_a_modern_python_ide.html is also very good in enumerating various plugins and tricks.

If you want to make your own Vim configuration for Python, perhaps resources at http://vim.wikia.com/wiki/Category:Python could help.

Sources

Comments are closed.