Skip to content

Instantly share code, notes, and snippets.

@itsvinayak
Last active August 4, 2021 17:54
Show Gist options
  • Save itsvinayak/03cd130be3567cc3b85eee02a002e63d to your computer and use it in GitHub Desktop.
Save itsvinayak/03cd130be3567cc3b85eee02a002e63d to your computer and use it in GitHub Desktop.
vimrc file for nvim
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" __ _(_)_ __ ___ _ __ ___
" \ \ / / | '_ ` _ \| '__/ __|
" \ V /| | | | | | | | | (__
" \_/ |_|_| |_| |_|_| \___|
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"
" ├── templates
" │ └── skeleton.cpp
"
"""""""""""""""""""""""""""""""""""""
if empty(glob('~/.config/nvim/autoload/plug.vim'))
silent !curl -fLo ~/.config/nvim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
autocmd VimEnter * PlugInstall
endif
call plug#begin('~/.config/nvim/plugged')
Plug 'mhinz/vim-startify'
Plug 'junegunn/vader.vim'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'morhetz/gruvbox'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'preservim/nerdtree'
Plug 'tpope/vim-surround'
Plug 'scrooloose/syntastic'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
"Plug 'chiel92/vim-autoformat'
Plug 'jiangmiao/auto-pairs'
Plug 'scrooloose/nerdcommenter'
Plug 'gorodinskiy/vim-coloresque'
Plug 'fergdev/vim-cursor-hist'
Plug 'tpope/vim-eunuch'
Plug 'lepture/vim-jinja'
Plug 'prettier/vim-prettier'
Plug 'tpope/vim-sensible'
Plug 'machakann/vim-highlightedyank'
Plug 'ryanoasis/vim-devicons' " icon nerd font needed
Plug 'luochen1990/rainbow'
Plug 'tiagofumo/vim-nerdtree-syntax-highlight'
Plug 'unkiwii/vim-nerdtree-sync'
Plug 'johngrib/vim-game-snake'
" ---------------------
Plug 'xuyuanp/scrollbar.nvim'
call plug#end()
syntax on
filetype plugin indent on
set encoding=utf-8
set nocompatible
set termguicolors
" theme gruvbox
let g:gruvbox_italic=1
autocmd vimenter * colorscheme gruvbox
let g:gruvbox_contrast_dark = "hard"
set background=dark
" -------------------- general ---------
" set mouse=a " enable mouse
set mouse-=a " disable mouse
set noerrorbells " no sound
set ruler
set spell
set cursorline " Highlight current line
set laststatus=2 " Always show status line
set cmdheight=2
" Numbers
set number
set numberwidth=1
set relativenumber
" auto complete filename
set wildignorecase
set wildmode=list:longest,full
" menu
set completeopt=menuone,preview
set colorcolumn=100 " for sidebar
set report=0 " Show all changes.
set nowrap " line in screen
set showmode " Show the current mode.
set showcmd " show partial command on last line of screen.
set showmatch " show matching parenthesis
set title " Show the filename in the window title bar.
set cursorline " show a visual line under the cursor's current line
set scrolloff=5 " Start scrolling n lines before horizontal
set t_Co=256 " 256 color support
set hidden " do something with buffer
set sidescrolloff=7 " Start scrolling n chars before end of screen.
set sidescroll=1 " The minimal number of columns to scroll
" horizontally
set autowrite " autosave
set autoread " reading a file
set smarttab " Better tabs
" Indentation
set smartindent " Insert new level of indentation
set autoindent " Copy indentation from previous line
set tabstop=2 " Columns a tab counts for
set softtabstop=2 " Columns a tab inserts in insert mode
set shiftwidth=2 " Columns inserted with the reindent operations
set shiftround " Always indent by multiple of shiftwidth
set expandtab " Always use spaces instead of tabs
" Temp Files
set nobackup " No backup file
set noswapfile " No swap file
set nowb
" Go to last active tab
au TabLeave * let g:lasttab = tabpagenr()
nnoremap <silent> <c-l> :exe "tabn ".g:lasttab<cr>
vnoremap <silent> <c-l> :exe "tabn ".g:lasttab<cr>
" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300
"Spell checking
set spelllang=en_us " English as default language
set spell " Enable by default
" Splits
set splitbelow " Horizontal split below
set splitright " Vertical split right
" Same color for sign column and line numbers
highlight clear SignColumn
" when using the >> or << commands, shift lines by 4 spaces
set shiftwidth=4
" Invisible characters
set nolist
set listchars=eol:¬,tab:▶\ ,trail:~,extends:⟩,precedes:⟨,nbsp:␣
set showbreak=↳\ \ \ "
set clipboard+=unnamedplus
" search
set incsearch
set hlsearch
set ignorecase
set smartcase
set shortmess-=S " for no. of occurrences
" Save file which you forgot to open with sudo
cnoremap w!! w !sudo tee % >/dev/null
cnoremap nt NERDTreeToggle %
" -------------- key binding ----------------------------
" disable arrow keys in normal mode
noremap <up> <nop>
noremap <down> <nop>
noremap <left> <nop>
noremap <right> <nop>
" key binding for moving line up and down
map <c-k> :m-2 <CR>
map <c-j> :m+1 <CR>
" use alt+hjkl to move between split/vsplit panels
tnoremap <A-h> <C-\><C-n><C-w>h
tnoremap <A-j> <C-\><C-n><C-w>j
tnoremap <A-k> <C-\><C-n><C-w>k
tnoremap <A-l> <C-\><C-n><C-w>l
nnoremap <A-h> <C-w>h
nnoremap <A-j> <C-w>j
nnoremap <A-k> <C-w>k
nnoremap <A-l> <C-w>l
" Go to tab by number
noremap <leader>1 1gt
noremap <leader>2 2gt
noremap <leader>3 3gt
noremap <leader>4 4gt
noremap <leader>5 5gt
noremap <leader>6 6gt
noremap <leader>7 7gt
noremap <leader>8 8gt
noremap <leader>9 9gt
noremap <leader>0 :tablast<cr>
" Commenting blocks of code.
" autocmd FileType c,cpp,java,scala let b:comment_g = '// '
" autocmd FileType sh,ruby,python let b:comment_g = '# '
" autocmd FileType conf,fstab let b:comment_g = '# '
" autocmd FileType tex let b:comment_g = '% '
" autocmd FileType mail let b:comment_g = '> '
" autocmd FileType vim let b:comment_g = '" '
" noremap <silent> ,cc :<C-B>silent <C-E>s/^/<C-R>=escape(b:comment_g,'\/')<CR>/<CR>:nohlsearch<CR>
" noremap <silent> ,cu :<C-B>silent <C-E>s/^\V<C-R>=escape(b:comment_g,'\/')<CR>//e<CR>:nohlsearch<CR>
" copy, cut and paste
vmap <C-c> "+y
vmap <C-x> "+c
vmap <C-v> c<ESC>"+p
imap <C-v> <ESC>"+pa
" disable autoindent when pasting text
" source: https://coderwall.com/p/if9mda/automatically-set-paste-mode-in-vim-when-pasting-in-insert-mode
let &t_SI .= "\<Esc>[?2004h"
let &t_EI .= "\<Esc>[?2004l"
" _______________________________________________________________
" _________________ error fix and abs -------------
" for opening images
au BufRead *.png,*.jpg,*.jpeg :call DisplayImage()
command! W :w " Error
command! Q :q
command! Wq :wq
command! WQ :wq
" ----------------------------- plugin setting-------------------
" vim-startify
" Show modified and untracked git files
let g:startify_custom_header = map(split(system('fortune | cowsay -f dragon | lolcat'), '\n'), '" ". v:val')
" returns all modified files of the current git repo
" `2>/dev/null` makes the command fail quietly, so that when we are not
" in a git repo, the list will be empty
function! s:gitModified()
let files = systemlist('git ls-files -m 2>/dev/null')
return map(files, "{'line': v:val, 'path': v:val}")
endfunction
" same as above, but show untracked files, honouring .gitignore
function! s:gitUntracked()
let files = systemlist('git ls-files -o --exclude-standard 2>/dev/null')
return map(files, "{'line': v:val, 'path': v:val}")
endfunction
let g:startify_lists = [
\ { 'type': 'files', 'header': [' MRU'] },
\ { 'type': 'dir', 'header': [' MRU '. getcwd()] },
\ { 'type': 'sessions', 'header': [' Sessions'] },
\ { 'type': 'bookmarks', 'header': [' Bookmarks'] },
\ { 'type': function('s:gitModified'), 'header': [' git modified']},
\ { 'type': function('s:gitUntracked'), 'header': [' git untracked']},
\ { 'type': 'commands', 'header': [' Commands'] },
\ ]
" Display NERDTree bookmarks
autocmd VimEnter *
\ if !argc()
\ | Startify
\ | NERDTree
\ | wincmd w
\ | endif
" Read ~/.NERDTreeBookmarks file and takes its second column
"function! s:nerdtreeBookmarks()
"let bookmarks = systemlist("cut -d' ' -f 2 ~/.NERDTreeBookmarks")
"let bookmarks = bookmarks[0:-2] " Slices an empty last line
"return map(bookmarks, "{'line': v:val, 'path': v:val}")
"endfunction
"let g:startify_lists = [
"\ { 'type': function('s:nerdtreeBookmarks'), 'header': [' NERDTree Bookmarks']}
"\]
" scrollbar
augroup ScrollbarInit
autocmd!
autocmd CursorMoved,VimResized,QuitPre * silent! lua require('scrollbar').show()
autocmd WinEnter,FocusGained * silent! lua require('scrollbar').show()
autocmd WinLeave,FocusLost * silent! lua require('scrollbar').clear()
augroup end
" coc
" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("patch-8.1.1564")
" Recently vim can merge signcolumn and number column into one
set signcolumn=number
else
set signcolumn=yes
endif
" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
\ pumvisible() ? "\<C-n>" :
\ <SID>check_back_space() ? "\<TAB>" :
\ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" Use <c-space> to trigger completion.
if has('nvim')
inoremap <silent><expr> <c-space> coc#refresh()
else
inoremap <silent><expr> <c-@> coc#refresh()
endif
" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current
" position. Coc only does snippet and additional edit on confirm.
" <cr> could be remapped by other vim plugin, try `:verbose imap <CR>`.
if exists('*complete_info')
inoremap <expr> <cr> complete_info()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"
else
inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
endif
" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>
function! s:show_documentation()
if (index(['vim','help'], &filetype) >= 0)
execute 'h '.expand('<cword>')
else
call CocAction('doHover')
endif
endfunction
" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')
" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)
" Formatting selected code.
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
augroup mygroup
autocmd!
" Setup formatexpr specified filetype(s).
autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
" Update signature help on jump placeholder.
autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end
" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a <Plug>(coc-codeaction-selected)
nmap <leader>a <Plug>(coc-codeaction-selected)
" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf <Plug>(coc-fix-current)
" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)
" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of LS, ex: coc-tsserver
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)
" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocAction('format')
" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call CocAction('fold', <f-args>)
" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR :call CocAction('runCommand', 'editor.action.organizeImport')
" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a :<C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p :<C-u>CocListResume<CR>
" rainbow
let g:rainbow_active = 1
autocmd vimenter * :RainbowToggleOn
" highlight coc-highlight
autocmd CursorHold * silent call CocActionAsync('highlight')
" Custom spell-checking highlighting
highlight SpellBad term=underline cterm=underline
highlight SpellCap term=underline cterm=underline
highlight SpellRare term=underline cterm=underline
highlight SpellLocal term=underline cterm=underline
" Tab line
highlight TabLine ctermfg=White ctermbg=Black cterm=NONE
highlight TabLineFill ctermfg=White ctermbg=Black cterm=NONE
highlight TabLineSel ctermfg=White ctermbg=DarkBlue cterm=NONE
" for comment
highlight Comment cterm=italic gui=italic
" fzf file search
let g:fzf_preview_window = 'right:60%'
nnoremap <g>rg :Rg<Space>
nnoremap <g>RG :Rg!<Space>
nnoremap <g>:fs :FZF <Space>
" vim-autoformat
"let g:formatters_python=['pylint']
"let g:autoformat_verbosemode=1
hi HighlightedyankRegion cterm=reverse gui=reverse
" set highlight duration time to 1000 ms, i.e., 1 second
let g:highlightedyank_highlight_duration = 1000
" gruvbox config
nnoremap <silent> [oh :call gruvbox#hls_show()<CR>
nnoremap <silent> ]oh :call gruvbox#hls_hide()<CR>
nnoremap <silent> coh :call gruvbox#hls_toggle()<CR>
nnoremap * :let @/ = ""<CR>:call gruvbox#hls_show()<CR>*
nnoremap / :let @/ = ""<CR>:call gruvbox#hls_show()<CR>/
nnoremap ? :let @/ = ""<CR>:call gruvbox#hls_show()<CR>?
let g:prettier#autoformat_require_pragma = 0
" status bar
let g:airline#extensions#tabline#formatter = "unique_tail_improved"
let g:airline#extensions#tabline#enabled = 1
let g:airline#extensions#tabline#buffer_nr_show = 1
let g:airline#extensions#tabline#show_close_button = 1
let g:airline_powerline_fonts = 1
" vim icon
set guifont=Hack\ Italic\ Nerd\ Font\ Complete\ Mono\ 11
" nerdtree
let g:NERDTreeHighlightFolders = 1 " enables folder icon highlighting using exact match
let g:NERDTreeHighlightFoldersFullName = 1 " highlights the folder name
let g:NERDTreeHighlightCursorline = 1
" nerdtree plug sync
let g:NERDTreeHighlightCursorline = 1
" sync open file with NERDTree
" " Check if NERDTree is open or active
"function! IsNERDTreeOpen()
"return exists("t:NERDTreeBufName") && (bufwinnr(t:NERDTreeBufName) != -1)
"endfunction
"" Call NERDTreeFind iff NERDTree is active, current window contains a modifiable
"" file, and we're not in vimdiff
"function! SyncTree()
"if &modifiable && IsNERDTreeOpen() && strlen(expand('%')) > 0 && !&diff
"NERDTreeFind
"wincmd p
"endif
"endfunction
"" Highlight currently open buffer in NERDTree
"autocmd BufEnter * call SyncTree()
" tabedit % | call CocActionAsync('jumpDefinition')
"-------------- extra function ------------------------------
" Switch CWD to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>:pwd<cr>
function! XTermPasteBegin()
set pastetoggle=<Esc>[201~
set paste
return ""
endfunction
inoremap <special> <expr> <Esc>[200~ XTermPasteBegin()
" History
set history=1000 " Remember more commands
if has('persistent_undo')
set undofile " Persistent undo
set undodir=~/.config/nvim/undo " Location to store undo history
set undolevels=1000 " Max number of changes
set undoreload=10000 " Max lines to save for undo on a buffer reload
endif
" cursor style
if has("autocmd")
au VimEnter,InsertLeave * silent execute '!echo -ne "\e[2 q"' | redraw!
au InsertEnter,InsertChange *
\ if v:insertmode == 'i' |
\ silent execute '!echo -ne "\e[6 q"' | redraw! |
\ elseif v:insertmode == 'r' |
\ silent execute '!echo -ne "\e[4 q"' | redraw! |
\ endif
au VimLeave * silent execute '!echo -ne "\e[ q"' | redraw!
endif
" Delete trailing white space on save, useful for some filetypes
fun! CleanExtraSpaces()
let save_cursor = getpos(".")
let old_query = getreg('/')
silent! %s/\s\+$//e
call setpos('.', save_cursor)
call setreg('/', old_query)
endfun
if has("autocmd")
autocmd BufWritePre *.txt,*.js,*.py,*.wiki,*.sh,*.coffee :call CleanExtraSpaces()
endif
" Return to last edit position when opening files
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" Disable tmux status-bar
autocmd VimEnter,VimLeave * silent !tmux set status
" -------------------------------------------------------------------------------------
" --------------- language -----------------------------------------------------------
" CPP ----------------------------
" autocmd BufNewFile,BufRead *.cpp let g:ycm_global_ycm_extra_conf = '~/.config/nvim/.ycm_extra_conf_cpp.py'
" autocmd BufNewFile,BufRead *.c let g:ycm_global_ycm_extra_conf = '~/.config/nvim/.ycm_extra_conf_cpp.py'
autocmd BufNewFile,BufRead *.c command r ! g++ % && ./a.out
" python -------------------------
let python_highlight_all = 1 " enable all Python syntax highlighting features
autocmd BufNewFile *py.py 0r ~/.config/nvim/templates/python.py
" coc
command! -nargs=0 Prettier :CocCommand prettier.formatFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment