Change Cursor in Vim in iTerm2

A neat trick I stumbled over in iTerm2’s documentation is that one can change the cursor shape from the block (default) to a vertical bar. This is great to do for Vim’s insert mode where the cursor conceptually is between characters. Adding the following to ~/.vimrc 1 will change the cursor to a vertical bar in insert mode and keep it as a block in the other modes. This should also work in Konsole, as far as I know, so if you use Konsole you should extend/replace the $TERM_PROGRAM check to look for Konsole.

" Change cursor shape between insert and normal mode in
if $TERM_PROGRAM =~ "iTerm"
    let &t_SI = "\<Esc>]50;CursorShape=1\x7" " Vertical bar in insert mode
    let &t_EI = "\<Esc>]50;CursorShape=0\x7" " Block in normal mode

A screenshot of how this looks:

iTerm2 cursor in Vim’s insert and normal mode

Addendum (2016-05-26): You can achieve the same in Neovim by setting the environment variable NVIM_TUI_ENABLE_CURSOR_SHAPE to 1.