Vim commands and shortcuts

Vim commands and shortcuts

About

My .vimrc and other files: https://gitlab.com/tuckerw/vimrc/

It’s also a submodule in my dotfiles repo: https://gitlab.com/tuckerw/dotfiles/

Clone repo:

mv ~/.vim ~/.vim.bak
git clone https://gitlab.com/tuckerw/vimrc.git ~/.vim
cat ~/.vim/README.md

Or just get the .vimrc file:

cd
wget https://gitlab.com/tuckerw/vimrc/raw/master/.vimrc # OR
curl -O https://gitlab.com/tuckerw/vimrc/raw/master/.vimrc

Learning Vim

What is vim

Vim is referred to as a ‘modal text-editor’. This means that, unlike other text-editors that can be thought of as always operating in ‘insert mode’, vim has multiple modes, each which allows you to accomplish different things, often with blinding speed and efficiency.

Some of the modes:

Why you should learn vim

There are so many reasons… I’ll have to fill out this section later.

Vimtutor and Vim Adventures

The first thing you should do is launch vimtutor by simply typing vimtutor into your terminal. Vimtutor should take an hour or less. It launches you into a vim session editing a buffer containing the vimtutor text. All you need to do is follow along, navigating and editing the buffer as the text instructs.

After having run through vimtutor you’ll have a good grasp of the basics, though you may not remember all of it! At this point I recommend you simply begin using vim to edit files.

Vim Adventures: a 2.5D Vim game:

https://vim-adventures.com/

Principles

Try to adhere to the following precepts to get the hang of vim more quickly:

Vim Cheatsheet

https://devhints.io/vim

Basics

vim filename.ext open filename.txt from the command line in vim

vim filename1.ext filename2.ext open multiple files from the command line

i enter insert mode to type characters into the file

<Esc> exit insert mode, returning to normal mode

:q quit vim, closing all buffers

:q! force-quit vim, not saving any unwritten changes

:wq, :x, ZZ save current buffer and quit vim

u undo

<C-r> redo (<C-r> denotes typing Ctrl + r simultaneously)

Settings

Here are some basic settings I’d recommend. As mentioned, you can add these to your ~/.vimrc file.

" Be IMproved
set nocompatible

" Enable syntax
syntax on

" allow editing multiple buffers with unsaved changes
set hidden

" expand tabs to spaces
set expandtab

" set default indent to 4 spaces
set tabstop=4
set shiftwidth=4
set ci

" enable mouse mode
set mouse=a

Movements

The first thing to learn in vim is the basic movements.

h go back/left a character

l go forward/right a character

j go up a line

k go down a line

gj go up a visual line (on wrapped lines)

gk go down a visual line (on wrapped lines)

w go forward a word

W go forward a Word (space-delimited)

e go forward to end of word

E go forward to end of Word (space-delimited)

b go backward a word

B go backward a Word (space-delimited)

ge go backward to end of word

gE go backward to end of Word (space-delimited)

gg go to beginning of file

G go to end of file

} go to next empty line (i.e. line after end of paragraph)

{ go to previous empty line (i.e. line before start of paragraph)

]] go to next function/heading (if vim settings and filetype support it)

[[ go to previous function/heading (if vim settings and filetype support it)

<integer>gg, <integer>G go to line <integer>

:<integer> go to line <integer>

<integer>% go to <integer> percent of file

/search-pattern go to next occurrence of search-pattern

?search-pattern go to previous occurrence of search-pattern

f<character> go to next occurrence of character on current line

F<character> go to previous occurrence of character on current line

t<character> go to character before next occurrence of character on current line

T<character> go to character after previous occurrence of character on current line

; equivalent to last f / F / t / T command

, equivalent to the reverse of last f / F / t / T command

'<char> go to line of mark <char>

`<char> go to line and column of mark <char>

Only work with inner / outer ( i / a )

p paragraph

s sentence

t tag e.g. <div class="red"><p>text</p></div>

' single-quoted region e.g. 'this is a string'

" double-quoted region e.g. "this is a string"

(, ) parentheses block e.g. (index, value)

[, ] square-brace block e.g. ['one', 'two']

{, } curly-brace block e.g. { i++; closeSession(); }

<, > ankle-brace block e.g. <input type="hidden" name="test">

Scrolling / Cursor Movements

zt Scroll page so current line is at top of page

zz Scroll page so current line is at middle of page

zb Scroll page so current line is at bottom of page

H Move cursor to top of page

M Move cursor to middle of page

L Move cursor to bottom of page

zh Scroll page one column left (requires :set nowrap)

zl Scroll page one column right (requires :set nowrap)

:set sidescroll=n Set page to scroll horizontally by n columns automatically (requires :set nowrap)

<C-e> Scroll page one line down

<C-y> Scroll page one line up

<C-u> Scroll half a page up

<C-d> Scroll half a page down

<C-b> Scroll one page up

<C-f> Scroll one page down

<C-o> Go to previous instance in jump list

<C-i> Go to next instance in jump list

Descriptors

i inner

a around

Actions

Now that you have basic movements down, it’s time to learn actions. Note that most actions can be combined with a movement in some way.

Single-character

r replace character under curser or every character in selection with next character entered

x delete character under curser or in selection

s delete character under curser or in selection and enter insert mode (equivalent of cl)

o add newline below current line and enter insert mode

O add newline above current line and enter insert mode

J join current line to next line with a space between

Formatting

= autoformat line(s)

>> indent line(s)

<< de-indent line(s)

Multi-character (require a motion)

y yank

d delete

c change

v visual select

V visual select by line

<C-v> visual-block select

gu make lowercase

gU make uppercase

g~ switch capitalization

~ switch capitalization under cursor

gq break lines at 80 characters or whatever setting

:sort sort alphabetically

:sort i sort case-insensitively

g commands

(Under Construction)

gj
gk
g^
g0
g$
gq
gf
C-^
gJ join like `J` but without spaces
gu
gU
~
g~
g& run previous sed replacement on whole file
g* like `*` but without word boundaries (`\<` `\>`)

Examples:

viw select inner word

daw delete around word

c3aw change around 3 words

gUi" make everything in the quoted region uppercase

vip:sort sort the lines in a paragraph

== auto-indent line

=5ap auto-indent current paragraph plus the next 4

>i} indent all lines inside curly braces ({ ... })

Yanking and Pasting

* - Search for word under cursor

<C-r> 0 - paste contents of register 0 when in insert mode (any register can be substituted)

<C-r> " - paste contents of register " when in insert mode (any register can be substituted)

Registers

:registers - show contents of registers

a-z A-Z - normal available registers

+ - clipboard register

0-9 - number registers (more details later)

Marks, Jumps, Changes

:marks list all marks

:jumps list all jumps

:changes list all changes

m[a-z] mark current line/column with lowercase letter

m[A-Z] mark current line/column/file with uppercase letter

'[a-z] jump to mark line in current file

'[A-Z] jump to mark line in any file

`[a-z] jump to mark line and column in current file

`[A-Z] jump to mark line and column in any file

<C-o> Go to previous instance in jump list

<C-i> Go to next instance in jump list

g; go to previous instance in change list

g, go to next instance in change list

[c go to previous changed line (if using gitgutter plugin)

]c go to next changed line (if using gitgutter plugin)

Buffers Tabs and Args

Buffers are essentially your open files. Tabs, on the other hand, are better thought of as workspaces: Arrangements of buffers, splits, etc.

:ls list open buffers

:tabs list open tabs

:args list args

:e file.ext open file.ext in new buffer

:b file.ext switch to file.ext buffer

:tabe file.ext open file.ext in new tab

gt go forward a tab

gT go backward a tab

:bn go forward a buffer

:bp go backward a buffer

:b 1 go to buffer 1

:bfirst go to first buffer

:blast go to last buffer

bufdo %s#search#replace#g | update replace search with `replace in every buffer and save each

In my .vimrc only:

gb go forward a buffer

gB go backward a buffer

With these mappings:

" move among buffers
map gB :bprev<CR>
map gb :bnext<CR>

:bd exit buffer

:bd! force-exit buffer, even with unsaved changes

:tabclose exit tab

:tabclose! force-exit tab

:arga file.ext add file.exe to the arglist

:argd file.ext remove file.exe from the arglist

:args one.ext two.ext manually populate arglist with one.ext and two.ext

:args **/*.ext glob all *.ext files into the arglist

:args `find . -type f -name '*.ext'` populate arglist from find command

`[a-z] jump to mark line and column in current file

:next go forward an arglist file

:prev go back an arglist file

:first go to first arglist file

:last go to last arglist file

argdo %s#search#replace#g | update replace search with `replace in every arglist file and save each

Undo, Redo

u undo

<C-r> redo

g- go back 1 text-change (can get to ‘lost’ text-states unlike normal undo and redo)

g+ go forward 1 text-change (can get to ‘lost’ text-states unlike normal undo and redo)

Time Travel

:earlier 3 undo last 3 changes

:earlier 5m go back to state from 5 minutes ago

:earlier 5h go back to state from 5 hours ago

:earlier 1d go back to state from 1 day ago

:later 3 redo last 3 changes

:later 5m go forward to state 5 minutes from now

:later 5h go forward to state 5 hours from now

:later 1d go forward to state 1 day from now

Macros

qa start recording macro into register a

q stop recording macro

qA append further commands onto macro in register a

@a execute macro a

@@ execute last macro executed

Insert Mode

Insert Mode Cheatsheet <C-o> Enter insert-normal mode, where you can do a normal-mode command then return to insert-mode

<C-o>3k go up 3 lines and stay in insert mode

<C-o>zz center current line vertically and stay in insert mode

<C-o>!!git status | head paste output of git status | head directly into buffer

View and change options interactively

:options
:options | resize

External Commands

w|tabs write and list tabs

w|!git status write and see git status

w|!git status write and see git status

:w|silent !tmux split-window -h "git diff" write and run git diff command in new vertical tmux split

:w|silent !tmux split-window -h "ls -althr; read;" write and run ls -althr command in new vertical tmux split, returning focus to vim, and keeping pane open with read;

Editable command and search history

q: view commands

q/ view searches

Enter Executes

<C-c> copies to command line

Vimdiff

Ignore whitespace:

:set diffopt+=iwhiteall
:h diffopt

Set a nice colorscheme:

:colo evening

Also useful for colors:

:syntax off

Vimdiff commands

]c advance to the next block with differences

[c reverse search for the previous block with differences

do (diff obtain) bring changes from the other file to the current file

dp (diff put) send changes from the current file to the other file

zo unfold/unhide text

zc refold/rehide text

zr unfold both files completely

zm fold both files completely

:'<,'>diffget equiv. of do in visual mode

:'<,'>diffput equiv. of dp in visual mode

:diffupdate rescan files for changes

:h copy-diffs view help for vimdiff

Vimdiff as git mergetool

Settings for ~/.gitconfig:

git config—global merge.tool vimdiff
git config—global merge.conflictstyle diff3
git config—global mergetool.prompt false

# don't automatically mark conflicts as resolved when exiting vimdiff
git config—global mergetool.vimdiff.trustExitCode false

Run mergetool after conflicts arise on attempted merge:

git mergetool <file>

Vimdiff mergetool commands

:diffg LO get from LOCAL

:diffg RE get from REMOTE

:diffg BA get from BASE

Use vimdiff as mergetool

Ed/Sed Commands

:[range]g/pattern/cmd

Where cmd is an ed command! (Will be listed below)

Learn ed:

$ info—vi-keys Ed

Search and replace all array variables unquoted with quotes

In place with sed (saves a .bak file):

sed -i.bak "s/\[\([a-zA-Z]\w*\)\]/\[\"\1\"\]/g" test.php

Search pattern in vim:

\[[a-zA-z]\w*\]

Search-and-replace in vim:

%s#\[[a-zA-z]\w*\]#\[\'\0\'\]#c

Folding

Manual Mode

`zf`   => create fold
`zf%`  => create fold to matching brace etc.
`zf5j` => create fold to 5 lines down
`zo`   => open fold
`zc`   => close fold
`za`   => toggle fold
`zm`   => increase global fold level
`zM`   => close all folds
`zr`   => decrease global fold level
`zR`   => open all folds

File Exploring

:Vex Open default file-explorer (Netrw) in vertical-split

:Vex! Open default file-explorer (Netrw) in vertical-split on opposite-side (to the right)

:Sex Open default file-explorer (Netrw) in horizontal-split

:Hex! Open default file-explorer (Netrw) in horizontal-split on opposite side (on the top)

:Tex Open default file-explorer (Netrw) in new tab

:Ex Open default file-explorer (Netrw) in current buffer

s Change sort between name, time, and filesize

r Reverse sort-order

gh toggle hidden files

i Change between listing modes

Enter open file/directory

o open in new horizontal split

v open in new vertical split

t open in new tab

A helpful list of Netrw Commands

Misc

Open multiple files piped to vim

gresp -i fullsize | vim - -c "%normal gf gb" -c 'bd!' -c ':bn'

Set tab settings:

:set expandtab
:set tabstop=4
:set shiftwidth=4
:set ft={php,js,html,c,...}
:set ci

Highlight line and column

:set cursorline
:set cursorcolumn

Edit files on remote server

vim scp://user@server//path/to/folder/
vim scp://user@server//path/to/document

To do

Insert-mappings

" Remap if_ to if
:inoremap if_ if () {<CR>}<esc>k<esc>4li

" Remap ie_ to if/else
:inoremap ie_ if () {<cr>} else {<cr>}<esc>kk<esc>4li

" Remap iee_ to if/elseif/else
:inoremap iee_ if () {<cr>} elseif () {<cr>} else {<cr>}<esc>2k<esc>4li

" Remap fn_ to function
:inoremap fn_ function () {<cr>}<esc>kf(i

" Remap pr_ to print "<pre>" . print_r(, true) . "</pre>";
:inoremap pr_ print "<pre>" . print_r(, true) . "</pre>";<esc>F,i

Search for visual selection text

maps // to search for visually selected text

vnoremap // y/\V<C-R>=escape(@",'/\')<CR><CR>

Count matches for pattern

maps / to count matches for pattern

nnoremap <leader>/ :%s///gn<CR>

Indent lines

let g:indentLine_color_term ='darkblue' | e

Colours

Show relevant help

:h highl

Show all highlight groups

:so $VIMRUNTIME/syntax/hitest.vim

Show highlight settings for given group

:hi LineNr

Set highlight settings for given group

:hi LineNr term=underline ctermfg=103 ctermbg=236 guifg=#878787 guibg=#303030

Type special characters

<C-k> letter + symbol General format

<C-k> e' é

<C-k> D* Δ

<C-k> d* δ

<C-k> O/ Ø

Type Greek letters with Digraphs

/\(\("https:\/\/\)\?{\?\(" \?\. \?\)\?\$GLOBALS\["\?\(frontend_domain\|backend_document_root\)"\?\]\( \?\. \?"\)}\?\/\)\?artistsimages\|artistimages\|"aws_samples"
/"\?\(https:\/\/"\? \?\. \?\)\?{\?$GLOBALS\["\?\w\+"\?\]}\?\( \?\. \?"\)\?\/\?artistsimages\|artistimages\|"aws_samples"
/"\?\(https:\/\/\("\? \?\. \?\)\?\)\?{\?$GLOBALS\["\?\w\+"\?\]}\?\( \?\. \?"\)\?\/\?artistsimages\|artistimages\|"aws_samples"
/'\?"\?\(https:\/\/\("\? \?\. \?\)\?\)\?{\?$GLOBALS\["\?\w\+"\?\]}\?\( \?\. \?"\)\?\/\?artistsimages\|artists\?images\|"aws_samples"
/'\?"\?\(https:\/\/\("\? \?\. \?\)\?\)\?{\?$GLOBALS\["\?\w\+"\?\]}\?\( \?\. \?"\)\?\/\?artists\?images\|'\?\/\?artists\?images\|"aws_samples"
/"\?\(https:\/\/\("\? \?\. \?\)\?\)\?{\?$GLOBALS\["\?\w\+"\?\]}\?\( \?\. \?"\)\?\/\?artists\?images\|\/\?artists\?images\|"aws_samples"
/"\?\(https:\/\/\(www\.callforentry\.org\)\?\("\? \?\. \?\)\?\)\?\({\?$GLOBALS\["\?\w\+"\?\]}\?\)\?\( \?\. \?"\)\?\/\?artists\?images\|\/\?artists\?images\|"aws_samples"
/"\?\(https:\/\/\(www\.callforentry\.org\)\?\("\? \?\. \?\)\?\)\?\(<?= \)\?\({\?$GLOBALS\["\?\w\+"\?\]}\?\)\?\( ?>\)\?\( \?\. \?"\)\?\/\?artists\?images\|\/\?artists\?images\|"aws_samples"