Configuring Vim: vimrc, Mappings, and Plugins
Build a vimrc you understand: where Vim loads it from, options, per-filetype settings, safe mappings and commands, a commented starter file, and plugins as native packages.
By The Dark DebuggerUpdated 22 min read
This article turns Vim from "whatever the package ships" into an editor configured on purpose. It covers where Vim looks for its configuration and in what order, how options work and how to find out who set one, per-filetype settings, mappings and user commands, a complete commented starter vimrc, and installing plugins with Vim's built-in package system. It assumes you're comfortable with the editing and Ex-command material in the earlier articles, especially Ex Commands, Ranges, and :global.
Why: the empty vimrc surprise
Here is an experiment worth doing once. On a fresh Ubuntu 24.04 account with no ~/.vimrc, I
opened a file and asked Vim about four options:
:set scrolloff? incsearch? showcmd? ruler? scrolloff=5
incsearch
showcmd
rulerThen I created an empty ~/.vimrc (touch ~/.vimrc) and asked again:
scrolloff=0
noincsearch
noshowcmd
rulerCreating a vimrc, even an empty one, turned off features I was relying on. The reason: when
you have no vimrc, Vim loads $VIMRUNTIME/defaults.vim, which switches on syntax
highlighting, filetype plugins, incremental search, showcmd, scrolloff=5 and more. As soon
as a vimrc exists, Vim assumes you're in charge and skips it. (ruler stayed on because
Ubuntu's system-wide config sets it; :verbose set ruler? pointed at
/usr/share/vim/vim91/debian.vim line 8.)
Most "my Vim got worse after I configured it" stories start here. The starter vimrc later in
this article begins by loading defaults.vim explicitly.
Where Vim looks for configuration
vim --version lists the files it will read:
vim --version | grep -E 'vimrc|defaults file' system vimrc file: "/etc/vim/vimrc"
user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
defaults file: "$VIMRUNTIME/defaults.vim"Vim reads the system file, then the first of ~/.vimrc and ~/.vim/vimrc that exists. I
prefer ~/.vim/vimrc: then all your configuration (vimrc, plugins, filetype overrides) lives in
one directory that you can put under version control. On Windows the equivalents are
$HOME\_vimrc and $HOME\vimfiles\vimrc (I did not test on Windows). Inside Vim,
:echo $MYVIMRC prints the file that was actually loaded:
/home/sid/.vimrc(My test home directory was a sandbox, hence the long path.)
:scriptnames lists every script Vim has sourced, in order, which shows the startup sequence
for real. With the starter vimrc from this article (the list is trimmed):
:scriptnames
1: /etc/vim/vimrc
2: /usr/share/vim/vim91/debian.vim
3: /usr/share/vim/vim91/syntax/syntax.vim
[…]
7: /usr/share/vim/vim91/filetype.vim
8: /usr/share/vim/vim91/syntax/yaml.vim
9: ~/.vimrc
10: /usr/share/vim/vim91/defaults.vim
11: /usr/share/vim/vim91/ftplugin.vim
12: /usr/share/vim/vim91/indent.vim
[…]
14: /usr/share/vim/vim91/plugin/getscriptPlugin.vim
[…]
26: /usr/share/vim/vim91/pack/dist/opt/matchit/plugin/matchit.vim
27: /usr/share/vim/vim91/ftplugin/yaml.vim
28: /usr/share/vim/vim91/indent/yaml.vimThe order is: system vimrc, your vimrc (and anything it sources, like defaults.vim), then
plugins from plugin/ directories and packages, then, once a file is opened, its filetype
plugin and indent script.
Three command-line switches help when something is wrong:
| Command | Starts Vim with |
|---|---|
vim -u NONE | no vimrc at all and no plugins (-N adds nocompatible) |
vim -u DEFAULTS | only defaults.vim: what a new user sees |
vim --clean | defaults.vim, no user files: the "is it my config?" test |
vim --startuptime t.log | normal startup, with timings written to t.log |
--startuptime is how you find a slow plugin. From my run with the two plugins installed
later in this article:
038.860 035.964 000.682: sourcing /etc/vim/vimrc
047.316 008.397 001.457: sourcing $HOME/.vimrc
057.526 000.531 000.531: sourcing /home/sid/.vim/pack/plugins/start/vim-commentary/plugin/commentary.vim
058.807 000.928 000.928: sourcing /home/sid/.vim/pack/plugins/start/vim-surround/plugin/surround.vim
071.406 000.002: editing files in windowsThe second column is the time spent in each script, in milliseconds. 71 ms to a usable editor is fine.
Options
Almost everything in a vimrc is set commands. The syntax is the same in the vimrc and on the
command line:
| Command | Effect |
|---|---|
:set number / :set nonumber | turn a boolean option on / off |
:set number! | toggle it |
:set shiftwidth=4 | set a value |
:set shiftwidth? | show the current value |
:set shiftwidth& | reset to the default |
:set wildignore+=*.o / -= | add to / remove from a list option |
:setlocal shiftwidth=2 | change it only for the current buffer or window |
:verbose set shiftwidth? | show the value and where it was last set |
:verbose is the debugging tool for configuration. Opening a Python file with filetype
plugins on, I hadn't set anything for Python, yet the indent was 4 spaces:
:verbose set shiftwidth? expandtab? shiftwidth=4
Last set from /usr/share/vim/vim91/ftplugin/python.vim line 119
expandtab
Last set from /usr/share/vim/vim91/ftplugin/python.vim line 119Vim's own Python plugin applies the PEP 8 style. Every option has a help page; the name in
quotes is the tag: :help 'shiftwidth', :help 'hidden'. These are the options worth
understanding first:
| Option | Help tag | What it does |
|---|---|---|
hidden | 'hidden' | keep modified buffers loaded when you switch away |
number, relativenumber | 'number' | line numbers; relative numbers help with 5j-style counts |
expandtab | 'expandtab' | Tab key inserts spaces |
shiftwidth | 'shiftwidth' | width of >>, << and automatic indent |
softtabstop | 'softtabstop' | how far Tab and Backspace move in Insert mode |
tabstop | 'tabstop' | how wide a real tab character is displayed; leave it at 8 |
ignorecase, smartcase | 'smartcase' | case-insensitive search unless the pattern has a capital |
hlsearch, incsearch | 'hlsearch' | highlight matches; show them while typing |
undofile, undodir | 'undofile' | persistent undo across sessions |
wildmenu, wildmode | 'wildmode' | Tab completion on the command line |
list, listchars | 'listchars' | show tabs and trailing spaces |
scrolloff | 'scrolloff' | lines of context kept around the cursor |
splitbelow, splitright | 'splitright' | where new windows open |
Filetype detection, plugins and indent
filetype plugin indent on (which defaults.vim runs for you) does three things: detects the
type of each file, loads the matching ftplugin/ script (options such as commentstring,
formatoptions, the Python indent above) and loads the matching indent/ script. :filetype
shows the state. With an empty vimrc:
filetype detection:ON plugin:OFF indent:OFFWith filetype plugin indent on in the vimrc:
filetype detection:ON plugin:ON indent:ONDetection was already on because Ubuntu's system vimrc enables syntax highlighting, which
needs it. Plugins and indent were not. :set filetype? shows what Vim decided a file is.
Per-filetype settings
There are two good ways to change settings for one file type, and one trap.
An autocommand group in the vimrc
augroup vimrc_filetypes
autocmd!
autocmd FileType make setlocal noexpandtab shiftwidth=8 softtabstop=0
autocmd FileType sh setlocal shiftwidth=2 softtabstop=2
augroup ENDsetlocal matters: set would change the global value and leak into every other buffer.
autocmd! at the top of the group matters too. Every time a vimrc is sourced, its autocmd
lines are added again. I sourced a file containing a bare
autocmd FileType yaml setlocal shiftwidth=2 three times and listed the result:
:autocmd FileType yaml--- Autocommands ---
FileType
yaml setlocal shiftwidth=2
setlocal shiftwidth=2
setlocal shiftwidth=2Harmless here, but duplicated autocommands that write files or run commands get slow and
strange. Inside a group that starts with autocmd!, sourcing twice still leaves one copy:
--- Autocommands ---
vimrc_filetypes FileType
yaml setlocal shiftwidth=2Files in ~/.vim/after/ftplugin/
For more than a line or two per language, a file per filetype is tidier. Files in
~/.vim/after/ftplugin/ run after Vim's own filetype plugin, so they win:
" ~/.vim/after/ftplugin/yaml.vim: runs after Vim's own YAML ftplugin
setlocal shiftwidth=2 softtabstop=2 expandtabThe trap: indent scripts run last
In Visual Mode we saw that YAML's indentkeys re-indents a line
when you type #. I put setlocal indentkeys-=0# in after/ftplugin/yaml.vim and it had no
effect:
indentkeys=!^F,o,O,0#,0},0],<:>,0-
Last set from /usr/share/vim/vim91/indent/yaml.vim line 15indentkeys belongs to the indent script, which runs after all ftplugins, including the
after/ ones. Settings owned by the indent script go in ~/.vim/after/indent/:
" ~/.vim/after/indent/yaml.vim: runs after Vim's YAML indent script
setlocal indentkeys-=0# indentkeys=!^F,o,O,0},0],<:>,0-
Last set from ~/.vim/after/indent/yaml.vim line 2
shiftwidth=2
Last set from ~/.vim/after/ftplugin/yaml.vim line 2Mappings
A mapping makes a key sequence type another key sequence. The command name says which mode it applies to and whether it is recursive:
| Command | Mode |
|---|---|
nnoremap | Normal |
inoremap | Insert |
xnoremap | Visual (vnoremap also covers Select mode, which you rarely want) |
cnoremap | command line |
onoremap | operator-pending (after d, c, y, …) |
noremap | Normal, Visual and operator-pending together |
noremap versus map
The nore means "the right-hand side is not remapped". With map, the keys a mapping produces
are themselves checked against mappings. I mapped x to dd and then X to x:
:nmap x dd
:nmap X xPressing X on line 1 deleted the whole line, because X produced x, which was then mapped
to dd. With :nnoremap X x instead, X deleted one character, as the plain x command does
(line one became ine one). Use the noremap forms always, unless you are deliberately
mapping to another mapping, such as a plugin's <Plug> mappings.
The leader key
<leader> is a prefix reserved for your own mappings, so they don't collide with Vim's. It is
\ by default; Space is a popular choice:
let mapleader = " "
nnoremap <silent> <leader>w :update<CR><leader> is replaced when the mapping is defined, so mapleader must be set first. This
file has the order wrong for the first mapping:
nnoremap <leader>w :update<CR>
let mapleader = " "
nnoremap <leader>q :quit<CR>:nmapn <Space>q * :quit<CR>
n \w * :update<CR>The first mapping ended up on \w. The * means "not remappable" (a noremap mapping).
Useful modifiers and notation
<silent>hides the command from the command line while it runs.<buffer>makes the mapping local to the current buffer, which is what you want inafter/ftplugin/files.- Special keys are written
<CR>,<Esc>,<Space>,<Tab>,<C-x>(Ctrl-X),<S-x>,<M-x>and<leader>. :verbose nmap <leader>wshows a mapping and the file and line that defined it.
User commands
:command defines your own Ex commands; they must start with a capital letter.
-range=% lets the command take a range and defaults to the whole file:
command! -range=% TrimWhitespace <line1>,<line2>s/\s\+$//eOn a YAML file with trailing spaces and a tab (cat -A shows line ends as $ and tabs as
^I):
name: checkout $
replicas: 3^I$
image: api:1.4.2$:TrimWhitespacename: checkout$
replicas: 3$
image: api:1.4.2$:'<,'>TrimWhitespace or :10,20TrimWhitespace limit it to some lines. The ! after
command lets the vimrc be sourced again without an "already exists" error.
A starter vimrc
This is a complete vimrc I tested line by line. Every line is there for a reason you've now
seen, and nothing in it depends on a plugin. Save it as ~/.vim/vimrc (or ~/.vimrc).
" ~/.vimrc -- a small, explained starting point for Vim 9.
" Look up any option with :help 'optionname' (quotes included).
" Start from Vim's own defaults: syntax highlighting, filetype plugins and
" indenting, ruler, showcmd, incsearch, scrolloff=5 and more. Without these
" two lines, creating a vimrc switches all of that off.
unlet! skip_defaults_vim
source $VIMRUNTIME/defaults.vim
" ---- Files and buffers -------------------------------------------------
set hidden " switch buffers without saving first
set confirm " ask what to do instead of failing on :q
set autoread " reload a file changed outside Vim, if unmodified
" Keep swap, backup and undo files out of project directories.
" The trailing // builds unique names from each file's full path.
let s:state = expand('~/.vim/state')
for s:dir in ['swap', 'backup', 'undo']
if !isdirectory(s:state .. '/' .. s:dir)
call mkdir(s:state .. '/' .. s:dir, 'p', 0o700)
endif
endfor
let &directory = s:state .. '/swap//'
let &backupdir = s:state .. '/backup//'
let &undodir = s:state .. '/undo//'
set undofile " undo history survives closing the file
" ---- Display -------------------------------------------------------------
set number " line numbers
set laststatus=2 " always show a status line with the file name
set showmatch " briefly jump to the matching bracket
set list listchars=tab:>\ ,trail:-,nbsp:+ " make tabs and trailing spaces visible
set splitbelow splitright " new windows open below and to the right
" ---- Searching -----------------------------------------------------------
set hlsearch " highlight every match
set ignorecase smartcase " case-insensitive unless the pattern has a capital
" ---- Indentation (filetype plugins can override this per language) -------
set expandtab " the Tab key inserts spaces
set shiftwidth=4 " >>, << and auto-indent use 4 columns
set softtabstop=4 " Tab and Backspace move by 4 columns
set autoindent " keep the previous line's indent
" ---- Command-line completion -------------------------------------------
set wildmenu wildmode=longest:full,full
set wildignore+=*.o,*.pyc,*/.git/*,*/node_modules/*
" ---- Numbers -------------------------------------------------------------
set nrformats+=unsigned " Ctrl-A treats "-" as a hyphen, never a minus sign
" ---- Mappings ------------------------------------------------------------
let mapleader = " " " must come before any mapping that uses <leader>
nnoremap <silent> <leader>w :update<CR>
nnoremap <silent> <leader>h :nohlsearch<CR>
nnoremap <leader>b :ls<CR>:buffer<Space>
nnoremap Y y$
" ---- Commands ------------------------------------------------------------
command! -range=% TrimWhitespace <line1>,<line2>s/\s\+$//e
" ---- Per-filetype settings -----------------------------------------------
augroup vimrc_filetypes
autocmd!
autocmd FileType make setlocal noexpandtab shiftwidth=8 softtabstop=0
autocmd FileType gitcommit setlocal spell textwidth=72
autocmd FileType sh setlocal shiftwidth=2 softtabstop=2
augroup END
" ---- Plugins ---------------------------------------------------------------
" Third-party plugins go in ~/.vim/pack/plugins/start/ (see below).
" matchit ships with Vim: % then also jumps between if/else/fi, HTML tags, ...
packadd! matchitA few lines deserve a note. <leader>b lists the buffers and leaves you at a :buffer prompt,
so switching is Space b, a few letters of the name, Enter (see
Buffers, Windows, and Tabs). nnoremap Y y$ makes Y
consistent with D and C. The state block creates the directories on first start; the
swap files go there instead of littering .file.swp next to your sources. Comments after
set and let commands are fine, but never after a mapping (see Common mistakes).
When I loaded it, Vim started without a single error message, and :verbose confirmed that
each layer ends up where it should. A YAML file got its indent from Vim's YAML plugin, a shell
script and a Makefile from the vimrc's autocommands:
shiftwidth=2
Last set from /usr/share/vim/vim91/ftplugin/yaml.vim line 21 shiftwidth=2
Last set from ~/.vimrc line 67noexpandtab
Last set from ~/.vimrc line 65The state directories were created on first start:
/home/sid/.vim/state
/home/sid/.vim/state/backup
/home/sid/.vim/state/swap
/home/sid/.vim/state/undoPlugins as native packages
Since Vim 8, plugins need no plugin manager. A package is a directory under
~/.vim/pack/, and inside it:
start/<plugin>: loaded automatically at every startup,opt/<plugin>: loaded only when you run:packadd <plugin>.
The first directory level (plugins below) is just a name for grouping; use whatever you like.
Installing two of the most useful plugins with git:
mkdir -p ~/.vim/pack/plugins/start
cd ~/.vim/pack/plugins/start
git clone --depth 1 https://github.com/tpope/vim-commentary.git
git clone --depth 1 https://github.com/tpope/vim-surround.git
git -C vim-commentary log -1 --format='%h %cs %s'
git -C vim-surround log -1 --format='%h %cs %s'Cloning into 'vim-commentary'...
Cloning into 'vim-surround'...
64a654e 2024-10-21 Tweak whitespace logic when nesting a comment
3d188ed 2022-10-25 Call out opening bracket behavior in FAQThen generate the help tags once, so :help commentary works:
:helptags ALLThat's the whole installation. Updating is git -C ~/.vim/pack/plugins/start/vim-surround pull; removing is deleting the directory.
Trying them out
vim-commentary adds gc as an operator that toggles comments using the file type's
commentstring. On a backup script, 4Ggcc commented line 4:
#!/usr/bin/env bash
set -euo pipefail
rsync -a /srv/app/ /backup/app/
# find /backup/app -mtime +30 -delete
echo "backup finished"Then 3Ggc2j on lines 3 to 5, where only line 4 was already commented:
#!/usr/bin/env bash
set -euo pipefail
# rsync -a /srv/app/ /backup/app/
# # find /backup/app -mtime +30 -delete
# echo "backup finished"When any line in the range is uncommented, gc comments all of them, adding a second # to
line 4. Running it again on the same lines removes one level from each. Because gc is a real
operator, gcap, gcj and . all work, which block insert (from
Visual Mode) can't offer.
vim-surround edits the "surroundings": quotes, brackets and tags. On log_level: debug:
| Keys | Result |
|---|---|
ysiw" | log_level: "debug" (you surround: inner word, with ") |
cs"' | log_level: 'debug' (change surrounding " to ') |
ds' | log_level: debug (delete surrounding ') |
I ran the three in that order on the line and got exactly those results.
Optional packages and :packadd
Moving vim-surround to ~/.vim/pack/plugins/opt/ stopped it loading at startup:
:echo exists("g:loaded_surround")
:packadd vim-surround
:echo exists("g:loaded_surround")0
1That's the way to keep rarely used plugins out of your startup time, or to load a plugin only
for some projects. Vim also ships optional packages of its own in $VIMRUNTIME/pack/dist/opt.
In this Vim 9.1 they were cfilter, dvorak, editorconfig, editexisting, justify,
matchit, shellmenu, swapmouse and termdebug. The starter vimrc enables matchit with
packadd! (the ! adds it to the runtime path without sourcing it immediately, which is the
right form inside a vimrc).
Plugins worth knowing
Start with no plugins, add one when you notice a repeated pain, and read its documentation. These are widely used, maintained, and solve problems Vim doesn't solve itself. Apart from the two above, I did not install them for this article:
| Plugin | Why |
|---|---|
tpope/vim-commentary | comment operator gc that works with . and text objects |
tpope/vim-surround | add, change and delete quotes, brackets and tags |
tpope/vim-repeat | lets . repeat plugin mappings, including surround's |
tpope/vim-fugitive | Git inside Vim: blame, staged diffs, interactive staging |
junegunn/fzf.vim | fuzzy-find files, buffers and grep results (needs the fzf binary) |
dense-analysis/ale | runs linters asynchronously and marks problems as you type |
Plugin managers such as vim-plug add parallel installs and pinned versions on top of the same idea. For a handful of plugins, git and the package directories are enough.
Neovim: init.lua
Neovim reads ~/.config/nvim/init.lua (or init.vim) instead of ~/.vimrc. Its defaults are
closer to the starter vimrc above, and its configuration is usually written in Lua. The
equivalents of a few starter lines look like this. Neovim isn't installed in my test lab, so
this snippet was not run:
-- ~/.config/nvim/init.lua
vim.opt.number = true
vim.opt.expandtab = true
vim.opt.shiftwidth = 4
vim.g.mapleader = " "
vim.keymap.set("n", "<leader>w", "<cmd>update<CR>", { silent = true })Most of what this article teaches (options, :verbose, after/ directories, packages under
pack/) applies to Neovim unchanged.
Where you'll use this
- Every machine you work on: keep
~/.vimin a git repository (vimrc,after/directories, plugins as clones or submodules) and clone it on a new laptop or server. - Team conventions: Vim's bundled EditorConfig package reads
.editorconfigfiles, so the project decides indentation instead of each person's vimrc. - Servers: a ten-line vimrc (
set hidden,set number,set expandtab shiftwidth=4, thedefaults.vimlines) copied over SSH covers most config-editing work.
A complete example of the team case. A web project has this .editorconfig:
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.js]
indent_style = space
indent_size = 2
[Makefile]
indent_style = tabWith the starter vimrc, a JavaScript file got the vimrc's 4-space indent:
shiftwidth=4
Last set from ~/.vimrc line 41I added one line to the vimrc:
packadd! editorconfigand reopened the file:
shiftwidth=2
Last set from /usr/share/vim/vim91/pack/dist/opt/editorconfig/plugin/editorconfig.vim line 479
expandtab
Last set from /usr/share/vim/vim91/pack/dist/opt/editorconfig/plugin/editorconfig.vim line 453To check trim_trailing_whitespace, I appended three spaces to line 1 and saved; cat -A
showed the line ending right after the brace, function total(items) {$. Anyone on the team,
with any editor that supports EditorConfig, gets the same result.
Common mistakes
Creating a vimrc turns off defaults.vim
Covered at the start, and worth repeating because it's the most common one: put
unlet! skip_defaults_vim and source $VIMRUNTIME/defaults.vim at the top of your vimrc, or
set the options you care about yourself.
A vimrc with Windows line endings
A vimrc edited on Windows and copied to Linux with CRLF line endings gave this at startup:
Error detected while processing /home/sid/.vimrc:
line 1:
E488: Trailing characters: number^M
line 2:
E521: Number required after =: shiftwidth=4^M^M is the carriage return. file ~/.vimrc reports ASCII text, with CRLF line terminators.
Fix it from Vim with :set fileformat=unix and :w; afterwards file said ASCII text.
A comment after a mapping becomes part of it
nnoremap <leader>h :nohlsearch<CR> " clear search highlighting:verbose nmap shows the problem, with a similar line from my test vimrc:
n <Space>q * :quit<CR> " quit the window
Last set from ~/.vimrc line 3Everything after :nohlsearch<CR> is typed too. When I pressed Space h, the highlight
cleared and the cursor jumped two columns to the right: the two spaces before the comment ran
as motions, and the " that followed started an invalid register name, which stopped the rest.
Put comments for mappings on the line above.
Settings in after/ftplugin that don't stick
If :verbose setlocal shows that an indent script set the option last, move the line to
~/.vim/after/indent/<filetype>.vim, as in the YAML indentkeys example.
mapleader set too late
Mappings defined before let mapleader use the old leader (\), as the :nmap listing above
showed. Set it near the top of the vimrc.
Summary
- Without a vimrc Vim loads
defaults.vim; with one, it doesn't. Source it explicitly at the top of your vimrc. - Vim reads
/etc/vim/vimrc, then~/.vimrcor~/.vim/vimrc;:echo $MYVIMRC,:scriptnamesandvim --startuptimeshow what really happened.vim --cleanrules your config in or out. :verbose set opt?tells you the value and which file set it last;:help 'opt'explains it.- Per-filetype settings:
setlocalinsideaugroup … autocmd! … augroup END, or files in~/.vim/after/ftplugin/; options owned by indent scripts go in~/.vim/after/indent/. - Use
nnoremap/xnoremap/inoremap, setmapleaderbefore mappings that use it, and never put a comment on a mapping line. command! -range=% Name …creates Ex commands that take a range.- Plugins are git clones in
~/.vim/pack/*/start/(always loaded) oropt/(:packadd); run:helptags ALLafter installing.
Exercises
Open any Python file and find out which file set shiftwidth, and on which line. Then do the
same for formatoptions in a shell script.
Show Solution
:verbose set shiftwidth? shiftwidth=4
Last set from /usr/share/vim/vim91/ftplugin/python.vim line 119In a shell script:
:verbose set formatoptions? formatoptions=croql
Last set from /usr/share/vim/vim91/ftplugin/sh.vim line 20If :verbose shows no "Last set from" line, the option still has its default value.
Add a mapping so that Space h clears search highlighting, with a comment explaining it, and
verify with :verbose nmap that the mapping contains nothing extra.
Show Solution
let mapleader = " "
" Space h: clear search highlighting
nnoremap <silent> <leader>h :nohlsearch<CR>:verbose nmap <leader>hn <Space>h * :nohlsearch<CR>
Last set from ~/.vimrc line 55The comment is on its own line, so it isn't part of the mapping. (Line 55 is where the mapping sits in the starter vimrc.)
Make Markdown files wrap at 80 columns and spell-check in US English, without touching your vimrc. Prove that your file is the one that set the options.
Show Solution
" ~/.vim/after/ftplugin/markdown.vim
setlocal textwidth=80 spell spelllang=en_usOpening runbook.md:
:verbose setlocal textwidth? spell? textwidth=80
Last set from ~/.vim/after/ftplugin/markdown.vim line 1
spell
Last set from ~/.vim/after/ftplugin/markdown.vim line 1Install vim-surround so that it does not load at startup, then load it in a running Vim and confirm it's active.
Show Solution
mkdir -p ~/.vim/pack/plugins/opt
git clone --depth 1 https://github.com/tpope/vim-surround.git ~/.vim/pack/plugins/opt/vim-surroundIn Vim:
:echo exists("g:loaded_surround")
:packadd vim-surround
:echo exists("g:loaded_surround")0
1Plugins set a g:loaded_… variable when they load; checking it is the quickest way to see
whether one is active. To load it for every session after all, add packadd! vim-surround to
the vimrc.
The :TrimWhitespace command leaves the cursor on the last line it changed. Rewrite it so the
cursor and the view stay where they were, while still accepting a range.
Hint
winsaveview() and winrestview() save and restore the cursor and scroll position. A command
can call a function and pass it <line1> and <line2>.
Show Solution
function! s:Trim(line1, line2) abort
let l:view = winsaveview()
execute a:line1 .. ',' .. a:line2 .. 's/\s\+$//e'
call winrestview(l:view)
endfunction
command! -range=% TrimWhitespace call s:Trim(<line1>, <line2>)On a four-line test file where lines 1, 2 and 4 had trailing whitespace, I ran
:TrimWhitespace with the cursor on line 3. All three lines were trimmed, and line(".") was
still 3. The one-line version from the article left the cursor on line 4.
:1,2TrimWhitespace trimmed only the first two lines and left line 4 alone.
Tested with: Vim 9.1 (Ubuntu 24.04 package 9.1.0016) on Ubuntu 24.04 (WSL2), November 2026,
with a sandboxed home directory so each vimrc was loaded exactly as written. vim-commentary and
vim-surround were cloned from GitHub at the commits shown. Every :verbose, :scriptnames,
:nmap and :autocmd listing is a capture of a real terminal session in tmux. The Windows file
locations and the Neovim init.lua snippet were not tested. Paths from the test machine's scratch directories are shown shortened to /home/sid/….
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Vim tutorial here is tested end to end before publishing.