Post

Vim Cheatsheet

Extensive collection of vim basic to advanced Vim commands and plugins to enhance your vim text editing and coding experiences.

VIM Modes

Vim has several modes, each designed for a specific purpose. Here’s a breakdown of the main modes in Vim:

Normal Mode

  • Default mode when you open Vim.
  • Used for navigating and making simple edits (e.g., deleting, copying, pasting text).
  • Press Esc to return to Normal Mode from other modes.

Insert Mode

  • For entering and editing text.
  • To enter Insert Mode, press i, I, a, A, o, or O.
  • Press Esc to exit Insert Mode and return to Normal Mode.

Visual Mode

  • Used to select text.
  • Enter by pressing v for character selection, V for line selection, or Ctrl+v for block (or column) selection.
  • Once selected, you can perform commands (like delete, copy, or change) on the selection.
  • Press Esc to exit Visual Mode.
  • Navigate in visual mode using j (down), k (up), h (right), l (left)

Easy way to remember the keys (j)ump down, (k)ite up, (h)ieve right, (l)eft

### Command-Line Mode - For executing commands that affect the whole file (e.g., save, quit, search). - Enter by pressing : (for commands), / (for search), or ? (for reverse search). - To execute a command, type it and press Enter.

### Replace Mode - Similar to Insert Mode, but characters are replaced instead of inserted. - Enter by pressing R in Normal Mode. - Press Esc to return to Normal Mode.

### Select Mode - Similar to Visual Mode, but keystrokes replace selected text immediately. - Used less frequently but can be useful for quick, in-place edits.

### Ex Mode - Allows you to execute multiple-line commands and scripts. - Accessed with Q from Normal Mode. - Press Esc to return to Normal Mode.

Each mode in Vim is tailored to different editing or navigation tasks, making Vim a highly efficient text editor when mastered.

Trouble shooting

If vim is stuck in insert mode ctrl [ to exit.

Search and Replace

  1. Utilizes a regular expression for searching every occurrence of [pattern] and replaces it with [replacement] without asking for confirmation.
1
   :%s/[pattern]/[replacement]/g

Now if your pattern contains forward slashes such as a https:// protocal you can use the # separator instead

This pattern is good for doing search and replace on an sql file.

1
   :%s#[pattern]#[replacement]#g
  1. Same as the previous command but asks for confirmation before replacing each instance of [pattern] with [replacement].
1
  :%s/[pattern]/[replacement]/gc
  1. Instead of replacing every single instance of [pattern] on your file, this Vim command will replace only those [pattern] that are in the current line with [replacement].
1
   :s/[pattern]/[replacement]/g
  1. select some text and go into to visual mode vim will put charaters in the prompt for you, then on the end of that put your search and replace
1
s/[pattern]/[replacement]/

buffers

Vim buffer editing is a basic vim operation and it goes hand in hand with editing vim files. I’ve written this cheat sheet as a way of remembering some of these simple, powerful, everyday vim commands.

What is a vim buffer?

When your editing files in vim. Keep in mind that you’re editing the memory buffer of a file and not the actual file. This is just how vim works by default.

Open a new empty buffer

This will open a new empty buffer in a vertical split window.

1
:new

Open a new empty buffer in a full tab without a split

1
:enew

Refresh the current buffer

1
:e

Change buffer file type

It can be helpful to change the file type of the current buffer. For instance, if you have prettier installed and you have a lot of html mixed into a php file. You can use your html prettier in your php file by changing the file type from php to html.

Change the filetype to html

1
set ft=html

Check the current filetype

1
set ft?

Macros

As a developer, we adopt the philosophy of dry. “do not repeat yourself”. This is what sparked my interest in Vim macros, as macros enable us to automate the repetitive process of certain tasks.

Vim macros allow you to repeat a set of keystrokes with the one keyboard shortcut.

Vim Macros allow you to repeat a set of commands of your choosing.

Vim macros are recordings of vim commands which you can easily repeat back.

The way it works, is you record all of commands and then you can play that recorded command back.

Create a macro

start recording a new macro called “a”

1
qa

End recording / macro

to end a recording

1
q

Run a Macro

To run a recording type

1
@a

Execute a Macro multiple times

to repeat macro h 5 times

1
5@h

Execute the last Macro multiple times

Repeat last macro 50 times

1
50@@

See vim macros usage example of adding a dash before each line

img-description vim macros usage example

Macro notes:

  • These recordings are stored in registers.
  • The recordings will be cleared when you close your buffer.
  • The recordings do not persist from buffer to buffer.

Saving persistant Macros

The problem with the default Vim macros is that they’re not persistent. Every time you fire up them. Those old macros you were using yesterday are no longer there. In fact.. macros are confined to the buffer by default. So being able to save persistent macros, which can be used in daily operations, and from buffer the buffer is a bit of a game changer.

Persistant buffers

Quick generation of html tags with these persistant Macros and the surround plugin.

Prerequisites

fire off the below commands by stiking @ and proceeding charater

Create list html tags

1
let @l = 'VS<li>\<Esc>'

Create h1 html tags

1
let @1 = 'VS<H1>\<Esc>'

create h2 html tags

1
let @h = 'VS<H2>\<Esc>'

Create h3 html tags

1
let @3 = 'VS<H3>\<Esc>'

Create h4 html tags

1
let @4 = 'VS<H4>\<Esc>'

Create p html tags

1
let @p = 'VS<p>\<Esc>'

Create span html tags

1
let @s = 'VS<span>\<Esc>'

Create div html tags

1
let @d = 'VS<div>\<Esc>'

Create ul html tags

1
let @u = 'VS<ul>\<Esc>'

Create ol html tags

1
let @o = 'VS<ol>\<Esc>'

Text Editing

Mastering Vim is the most efficient way for editing text files. Here are some critical Vim commands that will get you editing text efficiently with Vim.

Basic movement

h l k j character left, right; line up, down

b w word/token left, right

ge e end of word/token left, right

{ } beginning of previous, next paragraph

( ) beginning of previous, next sentence

0 gm beginning, middle of line

^ $ first, last character of line

nG ngg line n, default the last, first

n% percentage n of the file (n must be provided)

n| column n of current line

% match of next brace, bracket, comment, #define

nH nL line n from start, bottom of window

M middle line of window

% go to closing html tag

Increment and decrement numbers

In normal mode, typing Ctrl-A will increment the next number, and typing Ctrl-X will decrement the next number.

Insertion & replace → insert mode

i a Insert before, after cursor I A insert at beginning, end of line gI insert text in first column o O open a new line below, above the current line rc replace character under cursor with c grc like r, but without affecting layout R replace characters starting at the cursor gR like R, but without affecting layout cm change text of movement command m cc or S change current line C change to the end of line s change one character and insert ~ switch case and advance cursor g~m switch case of movement command m gum gUm lowercase, uppercase text of movement m <m >m shift left, right text of movement m n<< n>> shift n lines left, right

Deletion

x X delete character under, before cursor

dm delete text of movement command m

dd D delete current line, to the end of line

J gJ join current line with next, without space

:rd↵ delete range r lines

:rdx↵ delete range r lines into register x

Insert mode

^Vc ^Vn insert char c literally, decimal value n

^A insert previously inserted text

^@ same as ^A and stop insert → command mode

^Rx ^R^Rx insert content of register x, literally

^N ^P text completion before, after cursor

^W delete word before cursor

^U delete all inserted character in current line

^D ^T shift left, right one shift width

^Kc1c2 or c1←c2 enter digraph \c1,c2\

^Oc execute c in temporary command mode

^X^E ^X^Y scroll up, down

<esc> or ^[ abandon edition → command mode

Copying

"x use register x for next delete, yank, put

:reg↵ show the content of all registers

:reg x↵ show the content of registers x

ym yank the text of movement command m

yy or Y yank current line into register

p P put register after, before cursor position

]p [p like p, P with indent adjusted

gp gP like p, P leaving cursor after new text

Visual mode

v V ^V start/stop highlighting characters, lines, block

o exchange cursor position with start of highlighting

gv start highlighting on previous visual area

aw as ap select a word, a sentence, a paragraph

ab aB select a block ( ), a block { }

v35G Select everything from the cursor up to line 35.

Undoing, repeating & registers

u U undo last command, restore last changed line

. ^R repeat last changes, redo last undo

n. repeat last changes with count replaced by n

qc qC record, append typed characters in register c

q stop recording

@c execute the content of register c

@@ repeat previous @ command

:@c↵ execute register c as an Ex command

:rg/p/c↵ execute Ex command c on range r where pattern p matches

Complex movement

- + line up, down on first non-blank character

B W space-separated word left, right

gE E end of space-separated word left, right

n_ down n-1 line on first non-blank character

g0 beginning of screen line

g^ g$ first, last character of screen line

gk gj screen line up, down

fc Fc next, previous occurence of character c

tc Tc before next, previous occurence of c

; , repeat last fFtT, in opposite direction

[[ ]] start of section backward, forward

[] ][ end of section backward, forward

[( ]) unclosed (, ) backward, forward

[{ ]} unclosed {, } backward, forward

[m ]m start of backward, forward Java method

[# ]# unclosed #if, #else, #endif backward, forward

[* ]* start, end of /* */ backward, forward

Search & substitution

` :’<,’>s/default/newtext/g ` Search and replace a selected chunk of text

/s↵ ?s↵ search forward, backward for s

/s/o↵ ?s?o↵ search fwd, bwd for s with offset o

n or /↵ repeat forward last search

N or ?↵ repeat backward last search

* search backward, forward for word under cursor

g# g* same, but also find partial matches

gd gD local, global definition of symbol under cursor

:rs/f/t/x↵ substitute f by t in range r

x: g-all occurrences, c-confirm changes

:rs x↵ repeat substitution with new r & x

Marks and motions

mc mark current position with mark c ∈[a..Z]

c C go to mark c in current, C in any file

0..9 go to last exit position

[ ] go to start, end of previously operated text

:marks↵ print the active marks list

:jumps↵ print the jump list

n^O go to nth older position in jump list

n^I go to nth newer position in jump list

Key mapping & abbreviations

:map c e↵ map c ↦ e in normal & visual mode

:map! c e↵ map c ↦ e in insert & cmd-line mode

:unmap c↵ :unmap! c↵ remove mapping c

:mk f↵ write current mappings, settings… to file f

:ab c e↵ add abbreviation for c ↦ e

:ab c↵ show abbreviations starting with c

:una c↵ remove abbreviation c

Scrolling & multi-windowing

^E ^Y scroll line up, down

^D ^U scroll half a page up, down

^F ^B scroll page up, down

zt or z↵ set current line at top of window

zz or z. set current line at center of window

zb or z- set current line at bottom of window

zh zl scroll one character to the right, left

zH zL scroll half a screen to the right, left

^Ws or :split↵ split window in two

^Wn or :new↵ create new empty window

^Wo or :on↵ make current window one on screen

^Wj ^Wk move to window below, above

^Ww ^W^W move to window below, above (wrap)

Folding

zfm create fold of movement m

:rfo create fold for range r

zd zE delete fold at cursor, all in window

zo zc zO zC open, close one fold; recursively

[z ]z move to start, end of current open fold

zj zk move down, up to start, end of next fold

Miscellaneous

` :e ` Reload the current document

:sh↵ :!c↵ start shell, execute command c in shell

K lookup keyword under cursor with man

:make↵ start make, read errors and jump to first

:cn↵ :cp↵ display the next, previous error

:cl↵ :cf↵ list all errors, read errors from file

^L ^G redraw screen, show filename and position

g^G show cursor column, line, and character position

ga show ASCII value of character under cursor

gf open file which filename is under cursor

:redir>f↵ redirect output to file f

:mkview [f] save view configuration [to file f]

:loadview [f] load view configuration [from file f]

^@ ^K ^_ \ Fn ^Fn unmapped keys

Git Commands

1
:vert diffsplit native.php

reload vimrc

1
:source ~/.vimrc

Install theme for color scheme

Install plugin via plug

1
Plug 'morhetz/gruvbox'

set to default in init.vim

1
colorscheme gruvbox

Install Plugin with VimPlug

Install using plug

add to .config/nvim/init.vim

1
2
3
4
5
6
call plug#begin('~/.config/nvim/plugged')
  Plug 'plasticboy/vim-markdown'
  Plug 'honza/vim-snippets'
  Plug 'morhetz/gruvbox'
call plug#end()

Install with lazy

1
:Lazy

Macrobatics Plugin

Vim Macros are great for reducing repetitive keystrokes and speeding up your web development code editing processes. By default the Vim Macro process is a little fiddly. Using the Macrobiotics plug-in helps make the macro process a little easier.

Here we clean up a convoluted HTML document using some repeatable VM commands which makes the process of cleaning up the document a lot easier. Firstly we activate the macro recording using gq and then we use our VM command of delete surrounding tags with the dst keys now it’s time to end the recording so we can do this with gq. Now because we want to repeat this command many times throughout this convoluted document we can simply repeat the last macro with the . key.

delete surrounding html tags automatically with vim macros

Prerequisites

Vim Macrobotics plugin installed more info

Start Recording New Macro

1
gq

End Recording Macro

1
gq

Playback Last Recording

1
q

Playback Last Recording Multiple Times

1
30q

Quickscope Plugin

To enhance your content or code editing experience the Quickscope plugin empowers you to move the cursor along your current line to any position. With just a couple of keystrokes.

Now to move to a specific character on a line. You dont need a plugin. But quickscope makes the native vim a little nicer.

I unofficially refer to f, F, t, T, ; and , as the character motions. They form your swiss army knife for moving across a line:

Why use Quickscope?

It will help you break the habit of holding down Vim keys to move back and forward along the line. This is inefficient. Even if you have sped up your vim cursor to move super fast. Quickscope is a faster to navigate your cursor across a page of text.

The three primary Quickscope commands.

  1. Find/Go forward
  2. Find/Go backward
  3. Repeat last motion

Go to a specific character

  • Hit f then the character you want to move to in the forward direction along your line
  • Hit F the the character you want to go to in the backwards direction along the line
  • Hit , to repeat the last Quickscope motion you performed.

Go before the character

  • In the forward direction t then the letter you want the cursor to go before
  • the backwards direction hit t then the lefter you want to go before.

Repeating motions

Repeating motions is common as often the character you want to move to is not the first occurrence on the line. Quickscope provides and easy way to repeat your forwards and backwards motions.

  • , repeats the last character motion in the opposite direction.
  • ; repeats the last character motion in the original direction.

Format php code

Install plugin

visit the repo for all the information

If you’re using neovim to edit php and you want the php to format itself then you will need some extra thing’s installed to make this work.

install squizlabs php code sniffer using composer into your project directory

1
composer global require "squizlabs/php_codesniffer=\*"

visit the repo for all the information

In the vim buffer, run the command to format the php. You should see some indenting happen.

1
:Neoformat

php code will also auto format as you move code around the document. Please note Html auto formatting does not work.

Open large file in vim

Switch off the formatting

1
vim -u NONE large_file.txt
This post is licensed under CC BY 4.0 by the author.