Skip to content

Instantly share code, notes, and snippets.

@benfrain benfrain/init.vim

Last active May 4, 2020
What would you like to do?
init.vim for neovim config
if &compatible
set nocompatible " Be iMproved
nnoremap <SPACE> <Nop>
let mapleader=" "
" Required:
filetype plugin indent on
" Only set syntax highlighting once!
if !exists("g:syntax_on")
syntax enable
call plug#begin('~/.config/nvim/plugged')
Plug 'leafgarland/typescript-vim'
Plug 'alvan/vim-closetag'
Plug 'jiangmiao/auto-pairs'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'tpope/vim-surround'
"Plug 'wellle/targets.vim'
Plug 'tpope/vim-repeat'
Plug 'airblade/vim-gitgutter'
Plug 'tpope/vim-fugitive'
Plug 'vim-airline/vim-airline'
Plug 'honza/vim-snippets'
Plug 'scrooloose/nerdcommenter'
Plug 'arcticicestudio/nord-vim'
Plug 'tommcdo/vim-exchange'
Plug '/usr/local/opt/fzf'
Plug 'junegunn/fzf.vim'
Plug 'prettier/vim-prettier', { 'do': 'yarn install' }
Plug 'ryanoasis/vim-devicons'
Plug 'machakann/vim-highlightedyank'
Plug 'vim-pandoc/vim-pandoc'
Plug 'vim-pandoc/vim-pandoc-syntax'
call plug#end()
" These functions handle saving and restoring buffers
function! MakeSession()
let b:sessiondir = $HOME . "/.config/nvim/sessions" . getcwd()
if (filewritable(b:sessiondir) != 2)
exe 'silent !mkdir -p ' b:sessiondir
let b:filename = b:sessiondir . '/session.vim'
exe "mksession! " . b:filename
function! LoadSession()
let b:sessiondir = $HOME . "/.config/nvim/sessions" . getcwd()
let b:sessionfile = b:sessiondir . "/session.vim"
if (filereadable(b:sessionfile))
exe 'source ' b:sessionfile
echo "No session loaded."
" Controls the open/close Vim functions
augroup vimSessions
" Adding automatons for when entering or leaving Vim
au VimEnter * nested :call LoadSession()
au VimLeave * :call MakeSession()
augroup END
augroup markdownSpell
autocmd FileType markdown setlocal spell
autocmd BufNewFile,BufRead *.txt,*.md set syntax=markdown
autocmd FileType text setlocal spell
autocmd BufRead,BufNewFile *.md,*.txt setlocal spell
" Stop any default wrapping when in txt or markdown
set textwidth=0
" When editing a file, always jump to the last known cursor position.
" Don't do it for commit messages, when the position is invalid, or when
" inside an event handler (happens when dropping a file on gvim).
autocmd BufReadPost *
\ if &ft != 'gitcommit' && line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal g`\"" |
\ endif
augroup END
" Prevent CTRL+Z suspending Vim
nnoremap <c-z> <nop
" Use fd instead of find so node_modules doesn't get indexed
let FZF_DEFAULT_COMMAND='fd --type f'
" ripgrep if we have it
if executable('rg')
let $FZF_DEFAULT_COMMAND = 'rg --files --hidden --follow --glob "!.git/*"'
function! RipgrepFzf(query, fullscreen)
let command_fmt = 'rg --column --line-number --no-heading --color=always --smart-case %s || true'
let initial_command = printf(command_fmt, shellescape(a:query))
let reload_command = printf(command_fmt, '{q}')
let spec = {'options': ['--phony', '--query', a:query, '--bind', 'change:reload:'.reload_command]}
call fzf#vim#grep(initial_command, 1, fzf#vim#with_preview(spec), a:fullscreen)
command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)
" Files + devicons
function! Fzf_dev()
let l:fzf_files_options = '--preview "bat --theme="OneHalfDark" --style=numbers,changes --color always {2..-1} | head -'.&lines.'"'
function! s:files()
let l:files = split(system($FZF_DEFAULT_COMMAND), '\n')
return s:prepend_icon(l:files)
function! s:prepend_icon(candidates)
let l:result = []
for l:candidate in a:candidates
let l:filename = fnamemodify(l:candidate, ':p:t')
let l:icon = WebDevIconsGetFileTypeSymbol(l:filename, isdirectory(l:filename))
call add(l:result, printf('%s %s', l:icon, l:candidate))
return l:result
function! s:edit_file(item)
let l:pos = stridx(a:item, ' ')
let l:file_path = a:item[pos+1:-1]
execute 'silent e' l:file_path
call fzf#run({
\ 'source': <sid>files(),
\ 'sink': function('s:edit_file'),
\ 'options': '-m ' . l:fzf_files_options,
\ 'down': '40%' })
" CTRL-A CTRL-Q to select all and build quickfix list
function! s:build_quickfix_list(lines)
call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
let g:fzf_action = {
\ 'ctrl-q': function('s:build_quickfix_list'),
\ 'ctrl-t': 'tab split',
\ 'ctrl-x': 'split',
\ 'ctrl-v': 'vsplit' }
let $FZF_DEFAULT_OPTS = '--bind ctrl-a:select-all'
" Files with preview
" which references this:
nnoremap <silent> <leader>f :call Fzf_dev()<CR>
" Pressing ctrl+b gives me a quick buffer chooser
nnoremap <Leader>b :Buffers<CR>
if !&scrolloff
set scrolloff=3 " Show next 3 lines while scrolling.
if !&sidescrolloff
set sidescrolloff=5 " Show next 5 columns while side-scrolling.
augroup numbertoggle
autocmd BufEnter,FocusGained,InsertLeave * set relativenumber
autocmd BufLeave,FocusLost,InsertEnter * set norelativenumber
augroup END
" Prettier - to enable format on save
let g:prettier#autoformat = 0
"let g:prettier#autoformat_config_present = 1
"let g:prettier#autoformat_require_pragma = 0
"let g:prettier#exec_cmd_async = 1
augroup prettier
autocmd BufWritePre *.js,*.jsx,*.mjs,*.ts,*.tsx,*.css,*.less,*.scss,*.json,*.graphql,*.md,*.vue,*.yaml,*.html PrettierAsync
augroup END
" Airline configuration
let g:airline_theme='nord'
let g:airline#extensions#coc#enabled = 1
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline#parts#ffenc#skip_expected_string='utf-8[unix]'
" Just show the filename (no path) in the tab
let g:airline#extensions#tabline#fnamemod = ':t'
let g:airline_powerline_fonts = 1
" Don't bother telling me about whitespace
silent! call airline#extensions#whitespace#disable()
" Don't bother telling me about spelling
let g:airline_detect_spell=0
" Show system time
let g:airline_section_b = '%{strftime("%H:%M")}'
" Coc Vim stuff
" You will have bad experience for diagnostic messages when it's default 4000.
set updatetime=300
" don't give |ins-completion-menu| messages.
set shortmess+=c
" always show signcolumns
set signcolumn=yes
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
inoremap <silent><expr> <TAB>
\ pumvisible() ? coc#_select_confirm() :
\ coc#expandableOrJumpable() ? "\<C-r>=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\<CR>" :
\ <SID>check_back_space() ? "\<TAB>" :
\ coc#refresh()
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
let g:coc_snippet_next = '<tab>'
" COC Diagnostic Shortcuts
" (n)ext error
nmap <silent> <Leader>dn <Plug>(coc-diagnostic-next)
" (p)revious error
nmap <silent> <Leader>dp <Plug>(coc-diagnostic-prev)
" jump to (d)efinition
nmap <silent> <Leader>dd <Plug>(coc-definition)
" list (a)ll diagnostic errors
nnoremap <silent> <Leader>da :<C-u>CocList diagnostics<cr>
" (r)ename symbol under cursor
nmap <silent> <leader>dr <Plug>(coc-rename)
" (f)efactor symbol under cursor
nmap <silent> <leader>df <Plug>(coc-codeaction-selected)
vmap <silent> <leader>df <Plug>(coc-codeaction-selected)
" Make coc see CSS as SCSS
let g:coc_filetype_map = {
\ 'css': 'scss',
\ }
"""""""""""""""End Coc Vim Config"""""""""""""""
"" After searching, pressing escape stops the highlight
nnoremap <silent> <esc> :noh<cr><esc>
" Open nvimrc file
nnoremap <Leader>v :sp $MYVIMRC<CR>
" Source nvimrc file
nnoremap <Leader>sv :source $MYVIMRC<CR>
" Quick new file
nnoremap <Leader>n :enew<CR>
" Easy open devDiary file
nnoremap <Leader>od :edit ~/Desktop/DevDiary/<CR>
" Easy select all of file
nnoremap <Leader>sa ggvG<c-$>
" Easy show registers
nnoremap <silent> <Leader>zz :reg<CR>
" Make splits open in more natural locations
set splitbelow
set splitright
" Now make navigating between splits a little easier. Just use leader h,j,k,l
nnoremap <Leader>j <C-W><C-J>
nnoremap <Leader><Down> <C-W><C-J>
nnoremap <Leader>k <C-W><C-K>
nnoremap <Leader><Up> <C-W><C-K>
nnoremap <Leader>l <C-W><C-L>
nnoremap <Leader><Right> <C-W><C-L>
nnoremap <Leader>h <C-W><C-H>
nnoremap <Leader><Left> <C-W><C-H>
" Auto-resize splits when Vim gets resized.
autocmd VimResized * wincmd =
" Update a buffer's contents on focus if it changed outside of Vim.
au FocusGained,BufEnter * :checktime
" Make visual yanks pace the cursor back where started
vmap y ygv<Esc>
" Line bubbling
" Use these two if you don't have prettier
"nnoremap <silent> <c-j> :m .+1<CR>==
"nnoremap <silent> <c-k> :m .-2<CR>==
nnoremap <silent> <c-j> :m .+1<CR>
nnoremap <silent> <c-k> :m .-2<CR>
inoremap <silent> <c-j> <Esc>:m .+1<CR>==gi
inoremap <silent> <c-k> <Esc>:m .-2<CR>==gi
vnoremap <silent> <c-j> :m '>+1<CR>gv=gv
vnoremap <silent> <c-k> :m '<-2<CR>gv=gv
" A few niceties
nnoremap <Leader>w :w<CR>
nnoremap <Leader>q :q<CR>
nnoremap <Leader>d :bd<CR>
nnoremap <Leader>s :sp<CR>
" Standard Fuzzy find thing project wide
nnoremap <Leader>r :RG<space>
" Find the thing put use quickfix window for find and replace
nnoremap <Leader>R :Rg<space>
" Quickly open netrw
nnoremap <Leader>e :Lexplore<CR>
" The cfdo command for find and replace from quickfix window
nnoremap <Leader>t
\ :cfdo %s/<C-r>s//g \| update
" 1. Press Leader r to invoke RG and fuzzy type to get what you want.
" 2. Arrow to the item you want. Tab and Shift-Tab to select the entries you are interested in
" 3. Press enter and that adds them to the QuickFix window
" 4. Type ':cfdo %s/EXISTINGTEXT/NEWTEXT/g | :w' and that will change the text in each buffer of the quickfix list
" 5. Type ':ccl' to close the Quick Fix window
"Auto close tags
imap ,/ </<C-X><C-O>
if exists('+termguicolors') && ($TERM == "st-256color" || $TERM == "tmux-256color")
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
set termguicolors
set guicursor=n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50,a:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor,sm:block-blinkwait175-blinkoff150-blinkon175
" Pandoc settings
let g:pandoc#modules#disabled = ["folding"] " diable folds
" Nord theme config
let g:nord_italic = 1
let g:nord_italic_comments = 1
let g:nord_underline = 1
let g:nord_uniform_status_lines = 1
let g:nord_uniform_diff_background = 1
let g:nord_cursor_line_number_background = 1
colorscheme nord
" Set matching bracket for 1 second
set mat=1
" Cursor line but only current window and not when inserting text
set cursorline
autocmd InsertLeave,WinEnter * set cursorline
autocmd InsertEnter,WinLeave * set nocursorline
" Get a preview of replacements
set inccommand=split
" Put the cursor anywhere
set virtualedit=all
"" Use spelling for markdown files ‘]s’ to find next, ‘[s’ for previous, 'z=‘ for suggestions when on one.
" Source:
set spelllang=en
set spellsuggest?
set wrap linebreak nolist
set formatoptions=l
set hidden
" Make the gutter for numbers wider by default
set numberwidth=5
set display+=lastline
set clipboard=unnamedplus
set mouse=a
set ruler " Show the line and column numbers of the cursor.
set autoread
set noshowmode " Show current mode.
set encoding=utf-8 " Set default encoding to UTF-8
set incsearch " Shows the match while typing
set hlsearch " Highlight found searches
set ignorecase " Search case insensitive...
set smartcase " ... but not when search pattern contains upper case characters
set autoindent
set tabstop=4 shiftwidth=4 expandtab
"set gdefault " use g flag by default on searches
set number relativenumber
" Autocomplete with dictionary words when spell check is on
set complete+=kspell
set mouse=a
"Here are things you will need to get this working:
"brew install bat
"brew install ripgrep
"you will also need to create a :CocConfig JSON with the following: "suggest.noselect": false
" You will also want to run :CocInstall coc-snippets
" When setting up iTerm2 you can add a badge:

This comment has been minimized.

Copy link
Owner Author

benfrain commented Oct 18, 2019

Added the exchange plugin for swapping sections of text

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.