The vimrc: options and mappings

Vim · Practical · 12 min

A small, understood vimrc makes Vim comfortable without turning it into someone else's editor.

Vim reads its config from ~/.vimrc (or ~/.vim/vimrc). If none exists, Vim loads defaults.vim, which turns on syntax highlighting, incsearch and a few other niceties; as soon as you create a vimrc that file is no longer loaded, so start yours with source $VIMRUNTIME/defaults.vim or set those options yourself.

Options are set with :set: boolean ones on/off (set number, set nonumber, toggle with set number!), others with a value (set tabstop=4). :set option? shows the current value and :verbose set option? shows which file set it.

Mappings bind keys to keystrokes, per mode: nnoremap (Normal), inoremap (Insert), vnoremap/xnoremap (Visual), onoremap (operator-pending). Always use the noremap forms: the plain map variants re-interpret the right-hand side through other mappings and cause loops and surprises.

The leader key is a prefix for your own mappings. Set let mapleader = " " before defining mappings, then use <leader> in them. <CR> means Enter, <C-x> means Ctrl-x, <silent> hides the command echo.

Edit with :e $MYVIMRC and reload with :source %. Add options one at a time, with a comment saying why, and look each up with :help 'optionname'.

Example

source $VIMRUNTIME/defaults.vim   " keep the sane defaults
set number relativenumber
set expandtab shiftwidth=4 tabstop=4
set ignorecase smartcase hlsearch
set hidden                        " switch buffers without saving
set undofile                      " persistent undo
let mapleader = " "
nnoremap <leader>w :w<CR>
nnoremap <silent> <leader>h :nohlsearch<CR>
nnoremap <C-h> <C-w>h
inoremap jk <Esc>

Remember

  • Creating ~/.vimrc disables defaults.vim unless you source it
  • Use nnoremap/inoremap/xnoremap, never plain map
  • Set mapleader before defining <leader> mappings

Watch out for

  • Using map instead of noremap, so your mapping triggers other mappings recursively.

Check yourself

  1. Why prefer `nnoremap` over `nmap`?
  2. How do you see which script last set the `tabstop` option?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/map.txt.html