Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Last active May 12, 2024 12:02
Show Gist options
  • Save rochacbruno/3536ee7899f9535bb6cab001a90d4e06 to your computer and use it in GitHub Desktop.
Save rochacbruno/3536ee7899f9535bb6cab001a90d4e06 to your computer and use it in GitHub Desktop.
Vim Configs and CheatSheet

VIM CheatSheet

Based on configuration provided in .config/nvim/init.vim

Glossary

  • L = Leader Key, mapped to a single space " "
  • C = Control
  • S = Shift
  • A = Left Alt

Basic Usage

Key Mode Description
i N Enters Insert Mode
v N Enters Visual Mode
V N Enters Visual Line Mode
Esc * Get Back to Normal mode
:w N Write file
:x N Write and exit (ZZ)
:qa! N Quit not saving all buffers (ZQ)
. N Repeat last registered action
u N Undo
C-r N Redo

Movement

Key Mode Description
gg N File Home
G N File End
5G N Go to line 5
:-3 N Go to 3 alines above
b N Move to start of previous word
B N Move to start previous WORD
e N Move to end of next word
E N Move to end of next WORD
w N Move to start of next word
W N Move to start of next WORD
$ N Move to end of line
0 N Move to start of line
% N Go to corresponding bracket
* N Go to next, prev # match of word
fa N Go to next letter a (, and ; navigates)
ta N Go to before of next letter a (, and ; navigates)

Tip: WORD is a word + ponctuation, F and T do backwards.

Text Manipulation

Key Mode Description
ggVG N Select all text
Yp N Duplicate Line
gcap N Comment whole paragraph
gcc N Comment the whole line
cs"' N Change surrounding " to '
ds" N Delete surrounding "
cst" N Change <foo> to "foo"
ysiw N Add surrounds to a word foo
I N Insert at start of the line
a N Insert after cursor
A N Insert at the end of the line
o N New line above
O N New line below
r N Replace Char
x N Delete current char
cc N Replace line
cw N Replace to the end of workd
ciw N Replace the inner word
c$ N Replace to the end of word
~ N Change char case, repeat with .
C-A N Increment a number

Text Selection and Copying

Key Mode Description
yy N, V Copy a line or selection
5yy N, V Copy 5 lines
yw N Copy a word
ye N Copy until the end of word
y$ N Copy to the end of the line
y2/foo N Copy until second foo
p N Paste after cursor
4p N Paste after cursor 4 times
P N Paste before cursor
dd N Cut line
3dd N Cut 3 lines
dw N Cut word
D N Delete to the end of line
d$ N Delete to the end of line
dt" N Delete to the next "
/s N Search

Visual mode

Key Mode Description
vi" V Select everything inner "
va" V Select everything including "
vi) V Select everything inner () "
v2i) V Select evertyhing inner 2 outer )

Multi line edit

Key Mode Description
0 C-q select I-- Esc N Enters block mode, selects all first columns, add --
C-q select $ A-- Esc N Adds -- to the end of all lines
J V Join selected lines
< > V Indent
= V auto indent

Files

Key Mode Description
L-pw N Rg search the current word
L-ps N Rg content search in current folder files
L-pf N Open/Preview files in current folder
L-b N Open buffers preview
L-f N Another File NAvigator
C-P N Git Giles
F3 N NERDTree
F4 N TagBar
L-e N Opens a file in the current dir
L-e N Opens a file n the current dir
L-te N Opens a file in the current dir on a tab
L-prw N CocSearch current word on all buffers
L-ghw N Get Help for Word

Windows

Key Mode Description
L-hjkl N Switch windows (C-W-hjkl)
L-z, L-x N Next/Previous Buffer
L-c N Close current buffer
L-q N Close current split (C-w-c)
L-o N Open new file in vertical (vnew)
L-] N New Horizontal Split
L-\ N New vertical split
C-w-n N New file on horizontal split
C-w-s N Split horizontal current file
C-w-v N Split vertically current file
C-w-w N Next Split
C-w-p N Prev Split
C-w-arrows N Move to split
C-w-hjkl N Move to Split
C-w-T N Move split to a tab (why?)
C-w->,< N Increase/DEcrease width
C-w-+,- N Increase/DEcrease height
C-w-q N Close Split and file
C-w-o N Keep only current split
C-w-` ` N
C-w-_ N Maximize Horizontal Split
C-w-= N Restore split sizes

Code Analysis

Key Mode Description
L-gd N Go to definition
L-gy N Go to type definition
L-gi N Go to implementations
L-gr N Go to references
L-cr N Coc Restart

Utilities

Key Mode Description
L-u N Undo tree
L-y N Undo History
L-, N Clear highlivght (noh)
L-. N Set working dir
L-g N Current line on git

More

Key Mode Description
100ifoo [ESC] N Will write "foo" 100 times
100ifoo[ENTER][ESC] N Will write "foo" in 100 lines
3. N Will write "foo" 3 times after above command
L-id N Generates an UUID

Tricks

Macro

qa record your actions in the register a. Then @a will replay the macro saved into the register a as if you typed it. @@ is a shortcut to replay the last executed macro.

Example

On a line containing only the number 1, type this:

  • qaYp<C-a>q
    • qa start recording.
    • Yp duplicate this line.
    • <C-a> increment the number.
    • q stop recording.
  • @a → write 2 under the 1
  • @@ → write 3 under the 2
  • Now do 100@@ will create a list of increasing numbers until 103.

References

syntax on
filetype plugin indent on
set nocompatible
set guicursor=
set number relativenumber
set ruler
" set nohlsearch
set hidden
set cursorline
set noerrorbells
set tabstop=4 softtabstop=4
set shiftwidth=4
set expandtab
set smartindent
set nu
set nowrap
set smartcase
set noswapfile
set nobackup
set undodir=~/.vim/undodir
set undofile
set incsearch
set termguicolors
set scrolloff=8
set noshowmode
set encoding=utf-8
set fileencoding=utf-8
set fileencodings=utf-8
set backspace=indent,eol,start
set hlsearch
set ignorecase
set fileformats=unix,dos,mac
set autoread
set nowritebackup
" Give more space for displaying messages.
set cmdheight=2
" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=50
" Don't pass messages to |ins-completion-menu|.
set shortmess+=c
set colorcolumn=80,100,120
highlight ColorColumn ctermbg=0 guibg=lightgrey
highlight Comment ctermfg=red
set mousemodel=popup
set t_Co=256
set guioptions=egmrti
set gfn=Monospace\ 10
if exists('$SHELL')
set shell=$SHELL
else
set shell=/bin/sh
endif
"" Disable the blinking cursor.
set gcr=a:blinkon0
set scrolloff=3
"" Status bar
set laststatus=2
"" Use modeline overrides
set modeline
set modelines=10
set title
set titleold="Terminal"
set titlestring=%F
set statusline=%F%m%r%h%w%=(%{&ff}/%Y)\ (line\ %l\/%L,\ col\ %c)\
" Show tabs and spavces visually
set list
set listchars+=tab:>-,space:.
" Start Plugin Management
call plug#begin('~/.vim/plugged')
" Markdown editing and preview
Plug 'suan/vim-instant-markdown', {'for': 'markdown'}
Plug 'gabrielelana/vim-markdown'
" Soft or Hard Word Wrapping
Plug 'reedes/vim-pencil'
" Align tables
Plug 'godlygeek/tabular'
"Auto Complete and Language Server
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" Git integration
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb' " required by fugitive to :Gbrowse
Plug 'airblade/vim-gitgutter'
" Useful commenting - gcc, gcap
Plug 'tpope/vim-commentary'
" Show latest changes and allow navigation
Plug 'mbbill/undotree'
" Object/AST tag bar
Plug 'majutsushi/tagbar'
" Linter
Plug 'w0rp/ale'
" Show the visual mark on indendation blocks ┆
Plug 'Yggdroot/indentLine'
" Syntax Highlighting
Plug 'sheerun/vim-polyglot'
" Rainbow match pairs
Plug 'kien/rainbow_parentheses.vim'
" Fuzzy Search :)
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'yuki-ycino/fzf-preview.vim', { 'branch': 'release', 'do': ':UpdateRemotePlugins' }
" Dispatch tasks to run async e.g: `:Dispatch PlugInstall`
Plug 'tpope/vim-dispatch'
" Allow repeating of plugin 3rd party actions
Plug 'tpope/vim-repeat'
" Manipulate surrounding chars such as quotes and brackets
Plug 'tpope/vim-surround'
" Beautiful Dark theme
Plug 'gruvbox-community/gruvbox'
" Auto Format
Plug 'sbdchd/neoformat'
" Another Fuzzy Finder that can search mru
Plug 'Yggdroot/LeaderF', { 'do': './install.sh' }
" Interactive command execution
let g:make = 'gmake'
if exists('make')
let g:make = 'make'
endif
Plug 'Shougo/vimproc.vim', {'do': g:make}
"" Vim-Session
Plug 'xolox/vim-misc'
Plug 'xolox/vim-session'
"" Snippets
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'
"" Status and tab bar
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
"" Auto close/match brackets
Plug 'Raimondi/delimitMate'
"" A lot of colorschemes
Plug 'flazz/vim-colorschemes'
"" DEvicons for trees and bars
Plug 'ryanoasis/vim-devicons'
"" Python formatting
Plug 'ambv/black'
"" Do we need NERDTree?
Plug 'preservim/nerdtree'
"" Auto complete navigation with tab
Plug 'ervandew/supertab'
"" End of plugin management
call plug#end()
"" Apprearance
colorscheme gruvbox
set guifont=DroidSansMono\ Nerd\ Font\ 11
" This changes gruvbox bg to real dark
let g:gruvbox_contrast_dark = 'hard'
"" Theme improvements for embedded terminals
" if exists('+termguicolors')
" let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
" let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
" endif
let g:gruvbox_invert_selection='0'
set background=dark
" hi Normal guibg=NONE ctermbg=NONE
if has("gui_running")
if has("gui_mac") || has("gui_macvim")
set guifont=Menlo:h12
set transparency=7
endif
else
let g:CSApprox_loaded = 1
" IndentLine
let g:indentLine_enabled = 1
let g:indentLine_concealcursor = 0
let g:indentLine_char = '┆'
let g:indentLine_char_list = ['|', '¦', '┆', '┊']
let g:indentLine_faster = 1
endif
"" Session Management (Do I need this?)
let g:session_directory = "~/.config/nvim/session"
let g:session_autoload = "no"
let g:session_autosave = "no"
let g:session_command_aliases = 1
"" Searching and Navigation
"" fzf.vim
set wildmode=list:longest,list:full
set wildignore+=*.o,*.obj,.git,*.rbc,*.pyc,__pycache__
let $FZF_DEFAULT_COMMAND = "find * -path '*/\.*' -prune -o -path 'node_modules/**' -prune -o -path 'target/**' -prune -o -path 'dist/**' -prune -o -type f -print -o -type l -print 2> /dev/null"
" ripgrep
if executable('rg')
let g:rg_derive_root='true'
let $FZF_DEFAULT_COMMAND = 'rg --files --hidden --follow --glob "!.git/*"'
set grepprg=rg\ --vimgrep
command! -bang -nargs=* Find call fzf#vim#grep('rg --column --line-number --no-heading --fixed-strings --ignore-case --hidden --follow --glob "!.git/*" --color "always" '.shellescape(<q-args>).'| tr -d "\017"', 1, <bang>0)
endif
let loaded_matchparen = 1
let mapleader = " "
let g:netrw_browse_split = 2
let g:netrw_banner = 0
let g:netrw_winsize = 25
let g:fzf_layout = { 'window': { 'width': 0.8, 'height': 0.8 } }
let $FZF_DEFAULT_OPTS='--reverse'
let no_buffers_menu=1
" vim-airline
let g:airline_theme = 'powerlineish'
let g:airline#extensions#branch#enabled = 1
let g:airline#extensions#ale#enabled = 1
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tagbar#enabled = 1
let g:airline_skip_empty_sections = 1
"" Bindings
cnoreabbrev W! w!
cnoreabbrev Q! q!
cnoreabbrev Qall! qall!
cnoreabbrev Wq wq
cnoreabbrev Wa wa
cnoreabbrev wQ wq
cnoreabbrev WQ wq
cnoreabbrev W w
cnoreabbrev Q q
cnoreabbrev Qall qall
nnoremap <leader>ghw :h <C-R>=expand("<cword>")<CR><CR>
nnoremap <leader>prw :CocSearch <C-R>=expand("<cword>")<CR><CR>
nnoremap <leader>pw :Rg <C-R>=expand("<cword>")<CR><CR>
nnoremap <leader>h :wincmd h<CR>
nnoremap <leader>j :wincmd j<CR>
nnoremap <leader>k :wincmd k<CR>
nnoremap <leader>l :wincmd l<CR>
nnoremap <leader>u :UndotreeShow<CR>
"" I prefer NERDTree so I kept it here just as an example.
" nnoremap <leader>pv :wincmd v<bar> :Ex <bar> :vertical resize 30<CR>
nnoremap <Leader>ps :Rg<SPACE>
nnoremap <C-p> :GFiles<CR>
nnoremap <Leader>pf :Files<CR>
nnoremap <Leader><CR> :so ~/.config/nvim/init.vim<CR>
nnoremap <Leader>+ :vertical resize +5<CR>
nnoremap <Leader>- :vertical resize -5<CR>
nnoremap <Leader>rp :resize 100<CR>
"" Coding snippets here?
"nnoremap <Leader>ee oif err != nil {<CR>log.Fatalf("%+v\n", err)<CR>}<CR><esc>kkI<esc>
"" Using a terminal inside VIM is bad!! (dont use it)
nnoremap <silent> <leader>sh :terminal<CR>
"" Split
noremap <Leader>] :<C-u>split<CR>
noremap <Leader>\ :<C-u>vsplit<CR>
noremap <Leader>q :<C-u>close<CR>
noremap <Leader>o :<C-u>vnew<CR>
"" Buffer nav
noremap <leader>z :bp<CR>
noremap <leader>x :bn<CR>
"" Close the current buffer and move to the previous one
" This replicates the idea of closing a tab
noremap <leader>c :bp <BAR> bd #<CR>
"" Clean search (highlight)
nnoremap <silent> <leader>, :noh<cr>
"" Vmap for maintain Visual Mode after shifting > and <
vmap < <gv
vmap > >gv
"" Move visual block
vnoremap J :m '>+1<CR>gv=gv
vnoremap K :m '<-2<CR>gv=gv
nnoremap <A-j> :m .+1<CR>==
nnoremap <A-k> :m .-2<CR>==
inoremap <A-j> <Esc>:m .+1<CR>==gi
inoremap <A-k> <Esc>:m .-2<CR>==gi
vnoremap <A-j> :m '>+1<CR>gv=gv
vnoremap <A-k> :m '<-2<CR>gv=gv
"" Open current line on GitHub
nnoremap <Leader>g :.Gbrowse<CR>
"" Show all current buffers with preview (this is damn good)
nnoremap <silent> <leader>b :Buffers<CR>
" Dont needd this because we have <leader>ps to open Rg:
"nnoremap <silent> <leader>e :FZF -m<CR>
"Recovery commands from history through FZF
nmap <leader>y :History:<CR>
" snippets
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<c-b>"
let g:UltiSnipsEditSplit="vertical"
" NERDTree toggle
nmap <silent> <F3> :NERDTreeToggle<CR>
" Tagbar
nmap <silent> <F4> :TagbarToggle<CR>
let g:tagbar_autofocus = 1
" Disable visualbell
set noerrorbells visualbell t_vb=
if has('autocmd')
autocmd GUIEnter * set visualbell t_vb=
endif
"" Copy/Paste/Cut
if has('unnamedplus')
set clipboard=unnamed,unnamedplus
endif
noremap YY "+y<CR>
noremap <leader>p "+gP<CR>
noremap XX "+x<CR>
"" Set working directory
nnoremap <leader>. :lcd %:p:h<CR>
"" Opens an edit command with the path of the currently edited file filled in
noremap <Leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
"" Opens a tab edit command with the path of the currently edited file filled
noremap <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR>
"" Tabs
nnoremap <Tab> gt
nnoremap <S-Tab> gT
nnoremap <silent> <S-t> :tabnew<CR>
" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
nnoremap n nzzzv
nnoremap N Nzzzv
if exists("*fugitive#statusline")
set statusline+=%{fugitive#statusline()}
endif
nnoremap <leader>ob :colorscheme gruvbox<CR>
nmap <leader>tb :hi Normal guibg=NONE ctermbg=NONE<CR>
vnoremap X "_d
inoremap <C-c> <esc>
command! -nargs=0 Prettier :CocCommand prettier.formatFile
inoremap <silent><expr> <C-space> coc#refresh()
" GoTo code navigation.
nmap <leader>gd <Plug>(coc-definition)
nmap <leader>gy <Plug>(coc-type-definition)
nmap <leader>gi <Plug>(coc-implementation)
nmap <leader>gr <Plug>(coc-references)
nmap <leader>rr <Plug>(coc-rename)
nmap <leader>g[ <Plug>(coc-diagnostic-prev)
nmap <leader>g] <Plug>(coc-diagnostic-next)
nmap <silent> <leader>gp <Plug>(coc-diagnostic-prev-error)
nmap <silent> <leader>gn <Plug>(coc-diagnostic-next-error)
nnoremap <leader>cr :CocRestart
" ale
let g:ale_linters = {}
:call extend(g:ale_linters, {
\'python': ['flake8'], })
" vim-airline
let g:airline#extensions#virtualenv#enabled = 1
" Syntax highlight
" Default highlight is better than polyglot
" polyglot breaks markdown fences
let g:polyglot_disabled = ['python', 'markdown', 'mkd']
let python_highlight_all = 1
" Sweet Sweet FuGITive
nmap <leader>gh :diffget //3<CR>
nmap <leader>gu :diffget //2<CR>
nmap <leader>gs :G<CR>
fun! TrimWhitespace()
let l:save = winsaveview()
keeppatterns %s/\s\+$//e
call winrestview(l:save)
endfun
if !exists('*s:setupWrapping')
function s:setupWrapping()
set wrap
set wm=2
set textwidth=79
endfunction
endif
augroup highlight_yank
autocmd!
autocmd TextYankPost * silent! lua require'vim.highlight'.on_yank()
augroup END
autocmd BufWritePre * :call TrimWhitespace()
"*****************************************************************************
"" Convenience variables
"*****************************************************************************
" vim-airline
if !exists('g:airline_symbols')
let g:airline_symbols = {}
endif
let g:airline_powerline_fonts = 1
if !exists('g:airline_powerline_fonts')
let g:airline#extensions#tabline#left_sep = ' '
let g:airline#extensions#tabline#left_alt_sep = '|'
let g:airline_left_sep = '▶'
let g:airline_left_alt_sep = '»'
let g:airline_right_sep = '◀'
let g:airline_right_alt_sep = '«'
let g:airline#extensions#branch#prefix = '⤴' "➔, ➥, ⎇
let g:airline#extensions#readonly#symbol = '⊘'
let g:airline#extensions#linecolumn#prefix = '¶'
let g:airline#extensions#paste#symbol = 'ρ'
let g:airline_symbols.linenr = '␊'
let g:airline_symbols.branch = '⎇'
let g:airline_symbols.paste = 'ρ'
let g:airline_symbols.paste = 'Þ'
let g:airline_symbols.paste = '∥'
let g:airline_symbols.whitespace = 'Ξ'
else
let g:airline#extensions#tabline#left_sep = ''
let g:airline#extensions#tabline#left_alt_sep = ''
" powerline symbols
let g:airline_left_sep = ''
let g:airline_left_alt_sep = ''
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ''
endif
"" Disabling arrow keys
" for key in ['<Up>', '<Down>', '<Left>', '<Right>']
" exec 'nnoremap' key '<Nop>'
" exec 'vnoremap' key '<Nop>'
" endfor
for key in ['<C-S>', '<C-Z>']
exec 'noremap' key '<Nop>'
exec 'inoremap' key '<Nop>'
exec 'cnoremap' key '<Nop>'
endfor
"" Ctrl+J-K navigates auto complete windows
inoremap <expr> <C-J> pumvisible() ? "\<C-N>" : "j"
inoremap <expr> <C-K> pumvisible() ? "\<C-P>" : "k"
"" Generate uuid
if executable('uuidgen')
nnoremap <leader>id :execute 'normal! o' . system('uuidgen')<esc>ddk==
else
nnoremap <leader>id :execute 'normal! o' . system('python3 -c "import uuid; print(str(uuid.uuid4()))"')<esc>ddk==
endif
" -- sudo save
cmap w!! w !sudo tee >/dev/null %
@rochacbruno
Copy link
Author

vim_shot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment