This page is about Vim everyday usage.
Remember: The best way to get any Vim answers is to use :help
command.
Why I like VIM
Vim is only ever doing one thing at a time.
It’s not scanning your directory for function definitions, it’s not traversing a syntax tree to give you complex autocomplete suggestions, it’s not calculating the context of your cursor and doing requests to a documentation API, it’s not doing a git blame
on every line of code and it’s not auto-downloading syntax for every file. But Vim can do all of these things when you tell it to.
Open, Save & Close files
Press ESC
to exit INSERT
mode.
Keys | Action |
---|---|
:enew | Create new empty buffer |
:e filename | Open file for edit |
:e! filename | Override (forget) any changes and open file for edit |
:w | Save file |
:wq | Save file and quit |
:q | Quit |
:q! | Override changes and quit |
:qa | Quit all buffers and split windows |
:saveas filename | Save file with different name |
Selection, copy & paste
Press ESC
to exit INSERT
mode.
Keys | Action |
---|---|
v | Enable/Disable selection mode |
v, e | Select one word after cursor position |
v, b | Select one word before cursor position |
Shift + v | Select whole line |
Ctrl + v | Enable/Disable column selection mode |
y / x | Copy/Cut |
p / P | Paste after/before cursor position |
o / O | Insert new line after/before current one |
u / Ctrl + R | Undo / Redo |
vib | Select everything inside brackets |
Replace selected word with yanked (copied) word:
Keys | Action |
---|---|
yiw | Yank inner word (copy word under cursor) |
viwp | Select and then replace word with copied one |
viw"0p | Select another one, then replace it with copied one |
Check out "Mapping Keys" section to learn how to map this commands and make your editing easier.
To add ' ' to the end of each line in selected block. Which is a common thing when you work with bash scripts.
:norm A \
Clipboard (X11)
Check the native clipboard support in X11. Usually Vim compiled without native clipboard support which allows it to run on console only machines.
vim --version | grep .xterm_clipboard -o
-xterm_clipboard
output means you don't have clipboard support enabled (-
sign).
The faith test: install vim-gtk3
package to enable X11 (xterm) clipboard support.
# apt install vim-gtk3
Now in view mode (ESC
) you can use register +
which is the X11 clipboard register in Debian (Linux).
Keys | Action |
---|---|
"+y | Copy selection to X11 clipboard. |
"+p | Paste from X11 clipboard. |
Paste block bellow the copied one
- Select text block with
Shift + v
and pressy
to copy it into the register 0. - Press
'
and then separately press]
to set cursor position on the last copied line. - Press
p
to paste copied block.
Buffers
Buffer is a temporary copy of file's contents. When you open a file, Vim loads its contents into memory. The original file remains intact until you save changes. This is how you can control buffers in Vim.
N - buffer number, integer.
Keys | Action |
---|---|
:ls / :buffers | List buffers |
:bN | Switch to buffer N |
:bd | Unload current buffer and remove it from buffer list |
:bdN | The same as :bd but for certain buffer N |
:bw | Unload current buffer even if it has unsaved changes |
:bwN | The same as :bw but for certain buffer N |
Ctrl + o | Previous buffer |
You can map :bn
to <C-Tab>
in gVim to switch next buffer. Console Vim can't understant difference between <C-Tab>
and <Tab>
. So you can use any function key like F12.
nmap <C-Tab> :bn<CR>
Split windows
Vim allows user to split content area into vertical or horizontal windows. Window is a view of buffer. Here are some commands I use with windows.
Keys | Action |
---|---|
:vnew | Create an empty buffer in new vertical split window |
:Vexplore | Create an filesystem explorer in new vertical split window |
:Sexplore | The same as :Vexplore but in new horizontal split window |
Ctrl + w + w | Switch to next split window |
Ctrl + w + arrow keys | Switch to next split window in arrow direction |
:term | Open terminal in new horizontal split window |
:sp / :vsp | Split current buffer in 2 horizontal or vertical windows |
:sp filename / : vsp filename | Open file in new horizontal or vertical split window |
Open several files in split windows. Use -o
for horizontal layout and -O
for vertical layout.
vim -o {file path 1} {file path 2}
vim -O {file path 1} {file path 2}
Search & Replace
Press /
to enter search mode.
To replace Press :
and type replace expression.
:%s/old/new/gc
To replace in selection press :
and the command line will automatically enter the range.
:'<,'>s/old/new/g
Using gc
instead of g
allows user manually confirm each replacement.
You can select text, press Ctrl+r
and choose register 0 to paste its contents.
:%s/<C-r>0/
Sessions
A developer who is working with a lots of projects will need a sessions.
:mks ~/.vim/sessions/blog.vim
:source ~/.vim/session/blog.vim
Mapping keys
You can use your functional keys to execute custom commands. Here are seveal examples.
Mapping functional keys.
nmap <F1> :Vexplore<CR>
nmap <S-F1> :Sexplore<CR>
nmap <F2> :set number!<CR>
nmap <S-F2> :set list!<CR>
nmap <F3> :buffers<CR>:buffer<Space>
nmap <F4> :terminal<CR>
nmap <S-F4> :tab terminal<CR>
nmap <S-Tab> :bn<CR>
nmap <C-Tab> :b#<CR>
Use <Leader>
keyword to map \
key in combination with other keys. In this example pressing \ + d
will paste current timestamp in a new line:
nmap <Leader>D :pu=strftime('%c')<CR>
Here is an example of how to map keys in insert
mode in current cursor position:
imap <F12> <C-R>=strftime('%c')<CR>
Configuration gvimrc
Mostly works for Vim CLI.
Changing font and color scheme for GUI Vim:
if has('gui_gtk')
set guifont=Hack\ Regular\ 12
endif
colorscheme torte
let g:terminal_ansi_colors = [
\'#eeeeee', '#af0000', '#008700', '#5f8700',
\'#f0fafa', '#878787', '#005f87', '#444444',
\'#bcbcbc', '#d70000', '#d70087', '#8700af',
\'#d75f00', '#d75f00', '#005faf', '#005f87' ]
Additional configuration options.
Redraw GUI Vim when windows size changed.
autocmd VimResized * exe "normal \<c-w>="
Always on status bar.
set laststatus=2
You can imitate console vim using empty guioptions
parameter in /etc/vim/gvimrc
:
set guioptions=
Disable syntax highlight for Diff mode and better looking colors.
if &diff
syntax off
hi DiffText cterm=none ctermfg=Black ctermbg=Red gui=none guifg=Black guibg=Red
hi DiffChange cterm=none ctermfg=Black ctermbg=LightMagenta gui=none guifg=Black guibg=LightMagenta
endif
Highlight cursor line and column:
set cursorline
set cursorcolumn
Do not wrap long lines
set nowrap
Set characters for whitespaces:
set listchars=eol:↓,tab:\▸\ ,trail:·,space:·,extends:»,precedes:«,nbsp:×
Using bash-like completion when opening files with e
.
set wildmenu
set wildmode=list:longest
set wildignore=*.docx,*.jpg,*.png,*.gif,*.pdf,*.pyc,*.exe,*.flv,*.img,*.xlsx
Open netrw
when you start Vim without arguments.
augroup InitNetrw
autocmd!
autocmd VimEnter * if argc() == 0 | Explore! | endif
augroup end
Folding TERM /etc/vim/vimrc
.
set foldmethod=syntax
hi Folded ctermbg=grey ctermfg=black
hi FoldColumn ctermbg=darkgrey ctermfg=white
Folding GUI /etc/vim/gvimrc
.
set foldmethod=syntax
hi Folded guibg=grey guifg=black
hi FoldColumn guibg=darkgrey guifg=white
Important sessions configuration for GVIm.
" do not store global and local values in a session
set ssop-=options
" do not store folds
set ssop-=folds
Code completion
- Internal dictionary completion function that mapped on
C-n
andC-p
hotkeys. - Full row completion in insert mode with
C-x C-l
. - Omni Completion - the filetype specific code completion which acts like most IDEs SKD-based completion does.
Here are configuration options to activate Omni Completion and override internal dictionary completion:
filetype plugin on
set omnifunc=syntaxcomplete#Complete
Changing completion menu colors:
hi Pmenu ctermfg=white ctermbg=black gui=NONE guifg=black guibg=gray
hi PmenuSel ctermfg=white ctermbg=blue gui=bold guifg=gray guibg=blue
You can check filetype of the current buffer with command :set ft?
or manually set the filetype of the current buffer with command :set ft=python
.
This command will change the completeopt
option so that Vim's popup menu doesn't select the first completion item, but rather just inserts the longest common text of all matches; and the menu will come up even if there's only one match. The longest
setting is responsible for the former effect and the menuone
is responsible for the latter.
:set completeopt=longest,menuone
The next mapping will change the behavior of the Enter
key when the popup menu is visible. In that case the Enter
key will simply select the highlighted menu item, just as C-y
does.
:inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
Other
Add this line at bottom of the configuration file to start Vim in insert mode by default.
:startinsert
Other tweaks.
set so=7 " Not loosing context when jumping pages
set autochdir " Change current directory to opened file path
Commands
Convert all tabs into spaces (2 spaces here).
:%s/\t/ /g
Delete
di'
— delete inside the 'single quotes'.
da"
— delete around the "double quotes".
dit
— delete inside the html tags.
di(
- delete inside current round brackets of a function.
di{
- delete inside curly brackets of an object.
ci[
— change inside the [square brackets].
Motions
Motions are the type of key-command you'll use the most in Vim because they can be used on their own to move the cursor around. Some motions work on their own and some only work when used as a part of a combo.
For example the w
(for word) key will skip the cursor forward one word at a time, but the '
single-quote isn’t a motion on it's own, and does something completely different.
Some motions become different types depending on if they're used in combo or on their own. For example the b
key in the three-part combos meant block
but when you use it on it's own it means back
, and moves the cursor backwards one word at a time.