Vim Commands - ankit-jha/commands GitHub Wiki
:set number "Display line number
:set guifont=Ubuntu\ Mono:h16 "Set your font and font-size
:syntax on "Set syntax highlighting on
:colorscheme desert "Set colorscheme
:set hlsearch "Set highlight search on
:set ruler "Displays column number
:set backspace=indent,eol,start "Ensures normal backspace key usage
command! FormatJson %!python -m json.tool "Json formatting via python
"Mapping very magic mode to /
nnoremap / /\v
:set ignorecase "No case matching
:set smartcase "Only case sensitive when encounters uppercase
:set incsearch "Search as you type
s # Deletes the character under the cursor and then enters insert mode
r # Replace the character under cursor in normal mode
x # Delete current character
s # Substitute current character
diw # (Delete Inside The Word) Delete the word at the cursor but preserve the space around it.
daw # (Delete A The Word) Delete the word at the cursor and also the spaces around it.
dtX # (Delete Till The Character) Delete forward up to character 'X'.
dfX # (Delete Till The Character) Delete forward up to and including character 'X'.
dTX # (Delete Till The Character) Delete backward up to character 'X'.
dFX # (Delete Till The Character) Delete backward up to and including character 'X'.
di( # (Delete Inside The parentheses) Delete within the current parentheses
di" # Delete the text between the quotes
dw # Delete current word
dd # Delete current line
5dd # Delete five lines
d$ # Delete to end of line
d0 # Delete to beginning of line
C # Delete to end of line and change to insert mode
caw # Delete a word the cursor is currently on and switch to insert mode
yaw # Yank a word the cursor is currently on
2yaw #Yank a word the cursor in currently on and the next (2 words total)
ya( #Yank a matched parentheses containing the cursor
yf. #Yank from the cursor to the next .
y$ #Yank from the cursor to the end of the line
10i* #Insert * 10 times at the current cursor position
v% #To visually select all the text in between opening or closing parenthesis, square bracket or a curly brace
vi( # (Select Inside The parentheses) Select within the current parentheses
q: To access command history
ggVG #Select All
u # Undo
:[v]new # Create vertical/horizontal split windows with new file
Ctrl-r # Redo
:echo expand("%:p") or :echo %:p # Shows absolute path of the file
:echo expand("%:p:h") " absolute path dirname
:cal cursor(1,25) #Moves the cursor to given row and column
:nohl #Turns off the highlighting of searched terms
J #Join next line
:%j #Join all the lines
:%d #Delete All lines
where
: tells vi to go in command mode
% means all the line
d : delete
:8,$d #Delete lines from line number 8 to last
:.,$d #Delete lines from current cursor to last
gg # First Line
G # Go to Last line
123G # Go To Line
0 moves to the start of the line.
$ moves to the end of the line.
^ moves to the first non-blank character of the line.
g_ moves to the last non-blank character of the line.
gj moves the cursor to the next screen line (when a buffer line is wrapped across multiple screen lines)
gk moves the cursor to the next screen line (when a buffer line is wrapped across multiple screen lines)
g$ goes to the end of the screen line (when a buffer line is wrapped across multiple screen lines)
O # Open a new line above the current line and switch to insert mode
o # Open a new line below the current line and switch to insert mode
I # Move to the beginning of the line and switch to insert mode
A # Move to the end of the line and switch to insert mode
A 'word' is a sequence of all alphanumeric or punctuation signs
w # Move forward to the beginning of the next word
b # Move backward to the beginning of previous word
e # Move forward to the end of the next word
ge # Move backward to the end of the previous word
A 'WORD' is a sequence of any non-blank characters
W # Move to forward to the start of the word
( or ) Jump between next and previous sentences
{ or } Jump between next and previous paragraphs
% #Jump to a matching opening or closing parenthesis, square bracket or a curly brace
Ctrl-y # Moves screen up one line
Ctrl-e # Moves screen down one line
Ctrl-f # Move (f)orward one page, cursor to first line
Ctrl-b # Move (b)ack one page, cursor to last line
Ctrl-u # Moves cursor & screen (u)p half a page
Ctrl-d # Moves cursor & screen (d)own half a page
H #Move the cursor to the (H)igh/top of the screen
M #Move the cursor to the (M)iddle of the screen
L #Move the cursor to the (L)ow/bottom of the screen
zt #Move the current line (where cursor is located) to the top of the screen
zz #Move the current line to the middle of the screen
zb #Move the current line to the bottom of the screen
Ctrl-w + h/j/k/l # Move between split windows
Mnemonic for scrolling
+-------------------------------+
^ |
|c-e (keep cursor) |
|H(igh) zt (top) |
| ^ |
| ze | zs |
|M(iddle) zh/zH <--zz--> zl/zL |
| | |
| v |
|L(ow) zb (bottom) |
|c-y (keep cursor) |
v |
+-------------------------------+
Normal mode
>> #Indents the current line
<< #Unindents the current line
Insert mode
Ctrl-T #Indents the current line
Ctrl-D #Unindents the current line
The "." command repeats the last change made in normal mode. For example, if you press dw to delete a word, you can then press . to delete another word (. is dot, aka period or full stop).
The "@:" command repeats the last command-line change (a command invoked with ":", for example :s/old/new/). After the first repeat further repeats can be done with @@.
Esc # Switch to normal mode
Ctrl-[ # Switch to normal mode
Ctrl-o # Switch to insert normal mode. Allows you to switch from insert to normal mode for one normal mode command.
Open tab: tabnew
Next tab: g t
Prior tab: g T
Numbered tab: nnn g t
tabm i #Move tab to position where i is a number denoting the position (starting from zero)
tabm +i #Move tab i positions to the right
tabm -i #Move tab i positions to the left
Ctrl-*
In Windows, + and * are equivalent. In unix there is a subtle difference between + and *
:source ~/.vimrc
~ - Toggle case of the character under the cursor, or all visually-selected characters
g~w - Toggle case from cursor to end of word
g~iw - Toggle case of entire word
gU - Change to upper case "HellO" to "HELLO"
gu - Change to lower case "HellO" to "hello"
gUU - Change the current line to uppercase
guu - Change the current line to lowercase
:ls - List all the buffers
:buf 4 - Go to buffer number 4
:bp - Go to the previous buffer visited
:bn - Go to the next buffer
:b# - Go to the last buffer
Ctrl ^ - Go to the last buffer visited (Keyboard shortcut)
:bd - Delete the current buffer
:bd 4 - Delete the buffer 4
:sb 4 - Open buffer 4 in horizontal split window
:vert sb 4 - Open buffer 4 in vertical split window
:on[ly]/Ctrl-W o - Make the current buffer/window the only one on the screen.
ma - Mark current position with a
'a - Move to line with mark a
`a - Move to line and column with mark a
'a-z - Use marker a-z to move in the same file
'A-Z - Use marker A-Z to move in between files
`. - Moves the cursor to the line and column where the last edit was made.
'. - Moves the cursor to the line where the last edit was made.
Ctrl-o - Moves the cursor to the last(older) jump.
Ctrl-i - Moves the cursor to the previous jump.
Install universal-ctags
Create tags file at the root of the project
ctags -R
ctags -R -f ./.git/tags
Ctrl-[ - Jump to the tag underneath the cursor
Ctrl-t - Jump back in the tag stack
:ts <tag> <RET> Search for a particular tag
:tn Go to the next definition for the last tag
:tp Go to the previous definition for the last tag
:ts List all of the definitions of the last tag
:term #Opens a new terminal in a new split window
:term cat build.log #Opens up a buffer with all the terminal codes interpreted(Colored Log Ouput)
ctrl+w :q #Close the terminal
:set foldmethod=indent - Setup folding using indents. Works with python language
:set foldnestmax=2 - Setup maximum nested folds to 2. With python this only folds Classes and methods
:set filetype=json
:syntax on
:set foldmethod=syntax - Setup folding using syntax. Works with json
n - repeat forward search
N - repeat backward
* - forward search for word currently under cursor
# - backward search for word currently under cursor
/pattern - search forward for pattern
?pattern - search backward
/\<dev\> - searches for exact word dev not dev_ or develop
Ctrl-g/Ctrl-t - Used to jump to next/previous search while the focus is still in search box i.e /
Ctrl-r + " - Ctrl R plus register to paste from (default register is ")
Ctrl + r + Ctrl + w - Search the word under cursor
q/ - To access search history
/\vword1|word2|word3 - searches for all three words
/word1\|word2\|word3 - searches for all three words
/<ctr-v>u201C - searches for unicode character “ . Check more on vim help :help unicode
ga or :as - get the ASCII or Unicode value of the character under the cursor by pressing ga in command mode or :as /:ascii on the command line. This displays the value of the current character in decimal, hex and octal. (Think "get ascii.")
Explanation:
/ - start search
<Ctr-v>u - init utf-8 code input
201C - hex code combine character
fx - search forward and move to character x
Fx - search backward and move to character x
; - repeat forward search
, - repeat search in opposite direction
:[range]s/search/replace/
e.g.
:%s/search/replace/g #Search entire file and (g flag to) replace all occurences
:8,10 s/search/replace/g #Search from line 8 to 10 file and replace all occurences
:%s/,/\r/g #Search for commas and replace it with carriage return (move to the beginning of the new line)
:%s/\n/,/g #Search for new line and replace it with comma
:%s//,/g #Search for the last search pattern (if present) and replace it with comma
:%s//\r&/g #Search for the last search pattern (if present) and replace it with (\r) newline and the (&) search hit
:%s/print\( .*\)/logging.info\(\1\)/gc #Search for print statements and replace with logging.info. \1 is reference to the group captured inside (.*)
Execute a regular search like /pattern
Use the keystroke cgn on the first result to replace it
Type n or N to go to the next result
Use . to replace the occurrence with the same replacement (or go to the next result if you want to keep it)
:%s/pattern//gn #Shows the number of times that pattern matches text in the current buffer
Explanation:
%s
search the whole file
g
search globally
n
do not subsitute
:%s/pattern//n #Shows the number of lines that pattern matches text in the current buffer
:g/pattern/p
:global/pattern/print
:g/^$/d #Delete All Empty Lines
Explanation:
g
search globally
^$
regex pattern for empty lines
d
delete the line
:v/pattern/d #Delete All Lines except the ones that match the pattern
:vimgrep calc * #Search calc in all the files in the current working directory
:vimgrep calc a.txt b.txt c.txt #Search calc in all the given files
:vimgrep calc *.py #Search calc in all the python files in the current working directory
:vimgrep calc **/* #Search calc in all the files recursively in the current working directory
:vimgrep calc **/*.py #Search calc in all the python files recursively in the current working directory
qaq
:%s/pattern/\=setreg('A', submatch(0), 'V')/n
Explanation:
qaq
Clear register a
:%s/pattern/
Substitute the pattern
\=setreg('A', submatch(0), 'V')
Appends the register 'a' linewise 'V' with matched pattern values
/n
The n flag will run the command in a sandbox so nothing will actually get replaced but the side effects of the statement will happen.
qaq:g/pattern/y A
Explanation:
qaq
Clear register a
:g/pattern/
Search the pattern
y A
y A is an Ex command.It yanks the current line into register A (append to register a).
qaq
:g/pattern/-1,+3y A
Explanation:
qaq
Clear register a
:g/pattern/
Search the pattern
-1,+3
current line , -1 one line above and +3 lines below
y A
y A is an Ex command.It yanks the current line into register A (append to register a).
:[range]write !{cmd}
:'<,'>write !python
:{range}!{filter}
:sort u #Sort and remove duplicate lines
:%!uniq #Remove duplicate lines without sorting
A sequence of commands recorded to a register
q<letter><commands>q #Enter a macro
<number>@<letter> #Execute the macro <number> times (once by default)
Steps
qd start recording to register d
... your complex series of commands
q stop recording
@d execute your macro
@@ execute your macro again
:%normal @d execute macro on the whole buffer
VG + :'<,'>normal @d execute macro only on the selection
:bufdo execute "normal @a" | write
:%s/^/\=printf('%04d', line('.')) #Prints the line number in front of every line. This is useful if we want the line number reference of the copied pattern
Explanation:
^
matches the start of every line
\=
replacement is the result of evaluated expression
printf('%04d', line('.'))
formats the number of the current line: %04d inserts leading zeroes.
yy p/P
Explanation:
yy
Yank (Copy) the line
p
Paste the line below
P
Paste the line above
"x p/P
Explanation:
"x
Get the content from register x
p
Paste the line below
P
Paste the line above
While in insert mode hit Ctrl-r= this will open an expression register in form of a = sign on the command line.
Enter expressions to calculate e.g. =35*6 and hit Enter. This will insert calculated value at the insert cursor position.
Ctrl-x+Ctrl-e then you edit the command, save and quit, you're back to the prompt with the edited command
vi -c "command" fileName
vi -c "%s/old/new/" functions #Opens vim and substitute word "old" with "new"
vi +LineNumber fileName #vi +546 functions
vi +/searchTermHere fileName
vi +/proc functions.txt #Searches for word proc when opening the file
vi +/"kill proc" functions.txt #Searches for "kill proc" when opening the file
vi "+sort" "+wq" file.txt
vim -d a b c Starts vim in diff mode with several files in horizontal splitted windows
vim -o a b c Starts vim with several files in horizontal splitted windows
vim -O a b c Starts vim with several files in vertical splitted windows
vim -p a b c Starts vim with several files in a tabs
:args file1 file2 file3 |tab sall
curl https://archive.ics.uci.edu/ml/machine-learning-databases/url/url.names | vi -
:r !curl -s https://archive.ics.uci.edu/ml/machine-learning-databases/url/url.names
:Ex or :Explore
:Sex (Split Horizontally and show files in the current directory)
:Vex (Split Vertically and show files in the current directory)
:Tex (Open a new tab and show files in the current directory)
:CTRL-G #Displays the full name of the current file in the buffer
:1 CTRL-G #Displays the full path of the current file in the buffer
Ctrl-x + Ctrl-n/p # Keyword local completion
Ctrl-x + Ctrl-n/p # Select next/previous local completion
Ctrl-x + Ctrl-o # Omni completion completion
Ctrl-x + Ctrl-] # Tags file completion
Ctrl-x + Ctrl-d # Definition completion
Ctrl-x + Ctrl-f # Filename completion (based on files in $PWD)
Ctrl-x + Ctrl-i # Path pattern completion
Ctrl-x + Ctrl-k # Dictionary completion
Ctrl-x + Ctrl-l # Whole line completion
Ctrl-x + Ctrl-v # Command line completion
:cd%:p:h #Sets the working directory to directory of the current file in the buffer (global current directory)
:lcd%:p:h #Sets the working directory of the current window only to directory of the current file in the buffer (local current directory)
Explanation:
cd/lcd change directory/local change directory
% gives the name of the current file
%:p gives its full path
%:p:h gives its directory (the "head" of the full path)
:lcd- #Sets the working directory to last working directory value
:lcd! #Sets the working directory to global current working directory
Shift + v + J/K + p/P
Explanation:
Shift + v
Enter Visual Line Mode
J/K
Select line by moving up (J) or down (K)
p/P
Paste the lines below (p) or above (P) the cursor
You should yank the text to the * or + registers:
gg "*y G
Explanation:
gg
gets the cursor to the first character of the file
"*y
Starts a yank command to the register * from the first line, until...
G
go the end of the file
Use below command to yank all lines.
:%y+
Explanation:
% to refer the next command to work on all the lines
y to yank those lines
+ to copy to the system clipboard
:redir @+
:history
:g/fred/
" any other commands
:redir END
:set nowrap
:set wrap
:set more
:set showcmd
:set noshowcmd
Execute a command directly from the editor :! command
:! wc % Runs word count on the current file
Execute commands to bulk rename multiple files
:ls | vim - #This will get the list of all files in the current folder
:%s/.*/mv -i '&' \L'&'/g #Substitute command will change each line to mv based rename command
'&' refers to the searched pattern
\L changes all characters to lower case
:w !sh #Vim will write(execute) each command line one by one and rename all files
Inserts text from a specified file into the current buffer
:r textfile
You can also read in the output of shell applications
:read !{cmd}
:r !ls -1 /home/user
:r !date
Ctrl-w H/J/K/L will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.
Ctrl-w | will zoom in the current window for vertical splits
Ctrl-w _ will zoom in the current window for horizontal splits
Ctrl-w = will zoom out the current window for vertical and horizontal splits
:vs otherfile (open otherfile in vertical split screen)
:set scrollbind (turn on scrollbind mode in original file)
Ctrl+w l/h (switch to newly opened file)
:set scrollbind (turn on scrollbind mode in opened file)
:set scb! (Enter scb as an abbreviation for scrollbind, and the ! flag causes :set to toggle a boolean option)
:vs otherfile (open otherfile in vertical split screen)
:diffthis (turn on diff mode in original file)
Ctrl+w l/h (swap to newly opened file)
:diffthis (turn on diff mode in opened file)
:diffoff in each pane to turn off diff
:vert diffsplit otherfile (Diff file in single step)
$vimdiff <(sed -n '3,33p' file1.py) <(sed -n '30,60p' file2.py)
Uses combination of vimdiff and sed for comparing parts of two different or same files
]c – Jump to the next difference
[c – Jump to the previous difference
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
du - (diff update) updates the current diff view
zo - open a folded section
zc - fold a section
zM - Close all folds (Fold More)
zR - Open all folds (Fold Reduce)
$vim scp://[email protected]/filepath
e.g. $vim scp://[email protected]//tmp/message.txt
:e scp://[email protected]/path/to/file
e.g. scp://[email protected]//tmp/message.txt
:Nread scp://jarvis@localhost//tmp/message.txt # Using net read
:set bt=acwrite # Setting buffer type to write
:w # Save the file
:Nwrite scp://jarvis@localhost//tmp/message.txt # Using net write
Unix uses 0xA for a newline character. Windows uses a combination of two characters: 0xD 0xA. 0xD is the carriage return character. ^M happens to be the way vim displays 0xD. You c an remove all the ^M characters by running the following:
:%s/^M//g
Where ^M is entered by holding down Ctrl and typing v followed by m, and then releasing Ctrl
visual block select with Ctrl-V then I# (insert # in the begining).
Then press Esc (give it a second), and it will insert a # character on all other selected lines.
visual block select with Ctrl-V then x (delete the first symbol on the line)
Put your cursor on the top line of the block of text/code to remove.
Press V (That's capital "V" : Shift + v )
Move your cursor down to the bottom of the block of text/code to remove.
Press d.