Notes
Vim Notes🔗
Vim = VI + Improved
why vim ?
- Vim is Ubiquitous
- Vim is amazingly powerful
- Vim’s Knowledge Is Transferable
- Vim is Cross-Platform
- Vim is available in a TUI and a GUI
- Vim has Syntax Highlighting
- Commands are easy to Remember
- Vim is Like a Language
- Vim is Thoroughly Documented
Different Modes in Vim
- Normal/Command Mode
- Insert Mode
- Visual Mode
- Line Mode (
:
)
To exit Vim type :q
To open a new file vim myday.txt
To save and exit the file :wq
.
repeats previous command !
!
forces commands in vim. (there are more than 3 uses of !) : Toggle a setting, execute external commands
Navigation in Vim🔗
- Always use
h, j, k, l
for navigation instead of arrow keys. Ctrl-f
: Page up andCtrl-b
: Page Downw
: move forward one word,W
: move forward one word (ignore punctuation)b
: move backward one word,B
: move backward one word (ignore punctuation)e
: jumps to end of current work, and move forward to the end of next word, similar as above withE
z-CR
: move the view up0
or^
: jump to start of line ,$
: jump to end of linegg
: to move top of file,G
or:$
: move to bottom of fileNgg
or:N
: to jump to Nth lineCtrl-g
: view file info, like status etc, to enable this automaticset ruler
(Note to disable this :set ruler!
orset noruler
)
Deleting Text and “Thinking in Vim”🔗
- You can combine vim motions with delete !! : “operator + motion“
- Utilise motions to navigate to errors !
x
: to delete character cursor is on,X
: deletes character to left of cursordw
: delete the word, trydh, dj, dk, dl
and alsod0, d^, d$
dd
: delete current line,D
ord$
deletes all character from cursor to line endNdd
: delete N lines : “Count + operator + motion”
Getting Help🔗
:help
to get help, use:q
to exit:help <command>
to get help specific to a command. e.g.:help dd
:help {subject}
to get help on a given subject. e.g.:help count
:h
is short version of help.Ctrl-w w
to switch to editing and help window.Ctrl-o
: to move to previous cursor position,Ctrl-i
to move to next cursor position- Commands are of two types :
linewise
andcharacterwise
, always lookout for this in documentation :h help
to get understanding of how to read the documentation.
Deleting, Yanking and Putting🔗
- Register is clipboard like storage location
- All deletes are stored in
p
put command via unnamed/default register p
: put text after cursor,P
: puts before the cursor- Copy is usually performed by using yank
y
command puts the text in register. - cut-copy-paste : delete-yank-put
yw, y$, y^
: command + motionyy
: yank lines,Nyy
: yank N linesu
: undo operations,Ctrl-R
: redo operation
Registers🔗
- Unnamed =
“”
- Numbered =
“1 ”2 "3 "4 ... "9
- Named =
“a ”b ... "z
“”
: holds text from d, c, s, x and y operation“0
: holds the last text yanked (y)“1
: holds the last text deleted (d) or changed ©- Numbered registers shift with each d or c
- To view register contents
:reg
- To paste the contents of register
“x
type :“xP
e.g.“1P
, where x is a register - BlackHole register is used to execute commands without affecting other register.
“_dd
- To yank lines to specific register
“ayy
- To append more text to a register
“Ayy
- Trick :
teh
to fix this spelling take cursor toe
and executexp
that should swapeh
. Very useful trick :) when you are a fast typist.
Transforming and Substituting text in Vim🔗
i
: put your in insert mode.I
command puts you in insert mode and towards start of line.a
: appends(puts in insert) after the current character on cursor ,A
: append at the end of lineo
: start new line and puts in insert mode.O
: start new line above and put in insert mode.80i*
: can create a line with 80 asterisk. (Count) + operation5o#
: can create 5 comment lines :PR
invokes ‘REPLACE’ mode that overwrites the characters it encountersr
: invokes replace for only 1 character and keeps you in normal modecw
: change the entire word,c$
orC
: change till end of line (insert mode),cc
change entire line~
: change the case of character.g~w
for changing case of entire word,g~~
org~$
change case on entire line.gUU
changes the case the case to upper for entire line,guu
changes the case to lower for entire lineJ
joins two lines together with a space.gJ
joins two lines without space,NJ
: to join N lines
Search, Find and Replace🔗
f{char}
: find the first occurance of x towards right of line,F{char}
: find the first occurance of x towards left of line (Note : both case sensitive) (can combine count also)- use
;
to repeatfx
search forwards and,
for searching backwards tx
andTx
: similar tofx
put cursor before the search hitdfx
: deletes till character x (including x)dtx
: deletes till charcater x (doesn’t delete x)- use
/{key}
to search for key in file.n
: cycle next occurrence andN
: cycle previous occurence - Enable incremental search its very useful
set is
also disable highlight searchset nohls
- A Trick : use
/{key}
to search key andcw
to change it tolock
and thenn
to next occurence and.
to repeat previous command. you could also use:%s/key/lock/gc
it takes time to type this ;) - To reverse direction of search
?{key}
*
: searches word under cursor and use normal cycle keysn
andN
. or use#
a reversed search- To yank all the text from start to first occurance of x in register a
“ay/x
- search and replace (substitute) :
:[range]s/old/new/flag
: flags :g
: global,gc
: global confirm. Note this works on current line. Now here usually:%g/old/new
is used for entire file, you could also use some specific line like:1/x/old/new
. for changing from line 1-5 ::1,5s/g/old/new
.$
represent last line in file while.
represents first line in file. range could also a searchword:/firstword/,/secondword/s/old/new
- For linux user they need to change directory location it maybe difficult to write all escaping
\
characters they can use pattern separator.:%s#/local/mail#/usr/local/mail
Text Objects🔗
daw
deletes entire word on which cursor is placed (space after word also),diw
only deletes the word on which cursor is placed.- pattern : {operator}{a}{object} or {operator}{i}{object}
- most used shortcut is
ciw
(change inner word) anddaw
(delete a word) to quickly refactor variables. (Note usedas
deletes the sentence. trycis
also) - So
a
includes the boundaries whilei
doesn’t include boundries of delimiter. dip
(delete inner paragraph, doesn’t include boundry),dap
includes boundry and deletes paragraph- most used shortcut to edit the variable value
int name = "smk"
. Take the cursor on value of variable name.ci"
changes the inner text of delimiter“
whileda"
will delete word along with delimiter. ci(
,ci[
orci<
orci>
are some of other very used shortcuts, you can also yank these valueya(
oryi(
- for html you can use special
at
orit
.
Macros🔗
- Macros are recorded sequence of keystrokes. Useful for complex repeated tasks.
- There are no special registers for macros. There is only one a register.
q{register}
: To record in macro in a register. To stop, typeq
.@{register}
: Replay the macro stored in register.@@
: Repeats most recent macro.’- Best Practices while using macros
- Normalise the cursor position : 0,
- Perform edits and operations
- position your cursor to enable easy replays : j
- To execute macro on specific range of lines,
:15,20normal @a
- You can update macros any time : Its as simple as update register use capital letters for macros
- Saving Macros
- viminfo files :
.viminfo
or_viminfo
- Stores history and non-empty registers
- read when vim starts
- can easily overwrite registers
- vimrc files :
let @d = 'dd'
- viminfo files :
Vim Visual Mode🔗
v
: characterwise visual mode,V
: linewise visual mode,ctrl-v
: blockwise visual mode- vim motions and text-objects can be used to expand the visual area
- Commands that work in visual mode
- ~ : Switch Case, c : Change, d : Delete, y : Yank, r : Replace, x : Delete, I : Insert, A : Append, J : Join, u : Make lowercase, U : make Uppercase
- > : shift right, \< : shift left (very important to tab things)
- Blocks mode :
O
toggles current boundry left and righto
toggles up and down boundary - Block mode can be utilised to make changes to blocks of lines for example to append
end
to all lines in a block, select blockAend
will add same word each line - Note : shiftab defines how much shift operator shifts the selected text
- you can use selected lines/blocks as range in substitue commands
- you can also center text block using selection then
:'<,'>center
(Notice before center represents selection and are populated automatically) gv
reselects last selected text
vimrc🔗
- rc =
run commands
- system-wide vimrc and personal virmc
- each line is executed as a command
- To check which vim files are being sourced
:version
- To check value of some option or its disabled or enabled :
:set {option}?
" keep 1000 items in history
set history=1000
" show cursor position
set ruler
" show incomplete commands
set showcmd
" shows a menu while using tab completion
set wildmenu
set scrolloff=5
set hlsearch
set incsearch
set ignorecase
set smartcase
set nu
set backup
" set bex=
set lbr "easier linebreak
set ai " autoindent
set si " smartindent
set bg=light
color slate
"map KEY KEYSTROKE
map <F2> iJohn Smith<CR>123 Main Street<CR>London, UK<CR><ESC>
let mapleader=","
map <leader>w :w!<CR>
Vim Buffers🔗
- Temporary area where memory is stored while its being processed
- original file remained unchanged until you write that buffer to file
set hidden
: because vim always warns about open unsaved buffer which may be trouble when you wanna switch buffers quickly without saving:buffers
or:ls
: lists all open buffers:b3
: switches to buffer 3,:b smk.txt
: switched to buffers assiociated with filesmk.txt
:bn
or:bnext
: switches to next buffer ,:bp
or:bpreviouse
: switches to previous buffers (cyclic wrap)Ctrl-^
or:b#
: switches to last opened buffer (represented by#
in:ls
list)+
flag means changes of buffer has not been savedh
ora
: are hidden and active buffers. Buffers that do not have any flag are not loaded into memory:badd smk.txt
: addssmk.txt
to buffer:bdelete
or:bd1
: deletes and removes a buffer:bufdo %s/#/@/g
: applies some operation to all buffers (ifset hidden
is not used then vim can’t switch buffers :) ):wall
: saves all buffers:E
: opens explorer
Windows🔗
- A window is a view of buffer. (Previously we had multiple files in buffers but to look at more than one buffer at the same time we use window)
:sp
or:split
: splits and puts the same buffer in two windows horizontally:vs
or:vsplit
orCtrl-w v
: splits and puts the same buffer in two windows verticallyCtrl-w w
: cycle windows,Ctrl-w {motion}
: cycles cursor according motion:q
orCtrl-w q
: closes the split window:on
or:only
: closes all window except only currently active windowCtrl-w {resize operation}
: can be used to resize windows : operations allowed (+ , -, _,|, =, <, >)Ctrl-w J
orCtrl-w H
.. : can be move the cursor window around- Similar to
:bufdo
we have:windo
that executes some command to all windows
Gvim and MacVim🔗
- Why use graphical version of vim
- leverage some features which are not available in command line version of vim
- scrolling, text selection using mouse and copy-paste, etc.
- Vim usually maintains its own register systems for system clipboard, if you copy something in system, it can be accessed uses vims
“*
register and“+
registers - To make vim share system clipboard rather than using its own system
:set clipboard=unnamedplus
(operates on+
register, for only using*
register use:set clipboard=unnamed
commandKey+v
: works in MacVim because it behind the scenes pastes the*
register using“*gP
- gvimrc file is used to apply some specific settings to gvim versions.
:set gfn=*
: font-selector for gvim