" Whitespace & highlighting & language-specific config
" ----------------------------------------------------

" Strip trailing whitespace for code files on save
function! StripTrailingWhitespace()
  let save_cursor = getpos(".")
  %s/\s\+$//e
  call setpos('.', save_cursor)
endfunction

" Strip whitespace for code files
autocmd BufWritePre *.m,*.h,*.c,*.mm,*.cpp,*.hpp,*.swift call StripTrailingWhitespace()
autocmd BufWritePre *.rb,*.yml,*.js,*.jsx,*.coffee,*.css,*.less,*.sass,*.scss,*.html,*.xml,*.erb,*.haml,*.slim call StripTrailingWhitespace()
autocmd BufWritePre *.lua,*.java,*.php,*.feature,*.py call StripTrailingWhitespace()
autocmd BufWritePre *.md,*.ex,*.exs,*.erl,*.hs,*.rs,*.go call StripTrailingWhitespace()

" Highlight JSON files as javascript
autocmd BufRead,BufNewFile *.json set filetype=javascript

" Highlight Jasmine fixture files as HTML
autocmd BufRead,BufNewFile *.jasmine_fixture set filetype=html

" Insert ' => '
autocmd FileType ruby imap  <Space>=><Space>

" Open all folds in Markdown.
autocmd FileType mkd normal zR

autocmd FileType sql set filetype=sqlanywhere

autocmd FileType swift setlocal tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab

Add json, jbuilder to auto-trim whitespace extensions

" Whitespace & highlighting & language-specific config
" ----------------------------------------------------

" Strip trailing whitespace for code files on save
function! StripTrailingWhitespace()
  let save_cursor = getpos(".")
  %s/\s\+$//e
  call setpos('.', save_cursor)
endfunction

" Strip whitespace for code files
autocmd BufWritePre *.m,*.h,*.c,*.mm,*.cpp,*.hpp,*.swift call StripTrailingWhitespace()
autocmd BufWritePre *.rb,*.yml,*.js,*.jsx,*.json,*.coffee,*.css,*.less,*.sass,*.scss,*.html,*.xml,*.jbuilder,*.erb,*.haml,*.slim call StripTrailingWhitespace()
autocmd BufWritePre *.lua,*.java,*.php,*.feature,*.py call StripTrailingWhitespace()
autocmd BufWritePre *.md,*.ex,*.exs,*.erl,*.hs,*.rs,*.go call StripTrailingWhitespace()

" Highlight JSON files as javascript
autocmd BufRead,BufNewFile *.json set filetype=javascript

" Highlight Jasmine fixture files as HTML
autocmd BufRead,BufNewFile *.jasmine_fixture set filetype=html

" Insert ' => '
autocmd FileType ruby imap  <Space>=><Space>

" Open all folds in Markdown.
autocmd FileType mkd normal zR

autocmd FileType sql set filetype=sqlanywhere

autocmd FileType swift setlocal tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab


" VimTeX - LaTeX plugin for Vim
"
" Maintainer: Karl Yngve Lervåg
" Email:      karl.yngve@gmail.com
"

function! vimtex#syntax#p#tabularx#load(cfg) abort " {{{1
  call vimtex#syntax#packages#load('array')

  " The format is \begin{tabularx}{WIDTH}[POS]{PREAMBLE}
  syntax match texCmdTabularx "\\begin{tabularx}"
        \ skipwhite skipnl
        \ nextgroup=texTabularxWidth
        \ contains=texCmdEnv
  call vimtex#syntax#core#new_arg('texTabularxWidth', {
        \ 'next': 'texTabularxPreamble,texTabularxOpt,',
        \ 'contains': 'texLength',
        \})
  call vimtex#syntax#core#new_opt('texTabularxOpt', {
        \ 'next': 'texTabularxPreamble',
        \ 'contains': 'texComment,@NoSpell',
        \})
  call vimtex#syntax#core#new_arg('texTabularxPreamble', {
        \ 'contains': '@texClusterTabular'
        \})

  highlight def link texTabularxPreamble    texOpt
  highlight def link texTabularxWidth       texOpt
  highlight def link texTabularxOpt         texEnvOpt
endfunction

" }}}1

Fix highlight group for texTabularxWidth to texLength

" VimTeX - LaTeX plugin for Vim
"
" Maintainer: Karl Yngve Lervåg
" Email:      karl.yngve@gmail.com
"

function! vimtex#syntax#p#tabularx#load(cfg) abort " {{{1
  call vimtex#syntax#packages#load('array')

  " The format is \begin{tabularx}{WIDTH}[POS]{PREAMBLE}
  syntax match texCmdTabularx "\\begin{tabularx}"
        \ skipwhite skipnl
        \ nextgroup=texTabularxWidth
        \ contains=texCmdEnv
  call vimtex#syntax#core#new_arg('texTabularxWidth', {
        \ 'next': 'texTabularxPreamble,texTabularxOpt,',
        \ 'contains': 'texLength',
        \})
  call vimtex#syntax#core#new_opt('texTabularxOpt', {
        \ 'next': 'texTabularxPreamble',
        \ 'contains': 'texComment,@NoSpell',
        \})
  call vimtex#syntax#core#new_arg('texTabularxPreamble', {
        \ 'contains': '@texClusterTabular'
        \})

  highlight def link texTabularxPreamble    texOpt
  highlight def link texTabularxWidth       texLength
  highlight def link texTabularxOpt         texEnvOpt
endfunction

" }}}1


" Copyright 2010-present Greg Hurrell. All rights reserved.
" Licensed under the terms of the BSD 2-clause license.

if exists('g:command_t_loaded') || &compatible
  finish
endif
let g:command_t_loaded = 1

command! CommandTBuffer call commandt#BufferFinder()
command! CommandTJump call commandt#JumpFinder()
command! CommandTMRU call commandt#MRUFinder()
command! CommandTTag call commandt#TagFinder()
command! -nargs=? -complete=dir CommandT call commandt#FileFinder(<q-args>)
command! CommandTFlush call commandt#Flush()
command! CommandTLoad call commandt#Load()

if !hasmapto(':CommandT<CR>') && maparg('<Leader>t', 'n') ==# ''
  nnoremap <unique> <silent> <Leader>t :CommandT<CR>
endif

if !hasmapto(':CommandTBuffer<CR>') && maparg('<Leader>b', 'n') ==# ''
  nnoremap <unique> <silent> <Leader>b :CommandTBuffer<CR>
endif

Use <Plug> mappings as per standard best practises

" Copyright 2010-present Greg Hurrell. All rights reserved.
" Licensed under the terms of the BSD 2-clause license.

if exists('g:command_t_loaded') || &compatible
  finish
endif
let g:command_t_loaded = 1

command! CommandTBuffer call commandt#BufferFinder()
command! CommandTJump call commandt#JumpFinder()
command! CommandTMRU call commandt#MRUFinder()
command! CommandTTag call commandt#TagFinder()
command! -nargs=? -complete=dir CommandT call commandt#FileFinder(<q-args>)
command! CommandTFlush call commandt#Flush()
command! CommandTLoad call commandt#Load()

if !hasmapto('<Plug>(CommandT)') && maparg('<Leader>t', 'n') ==# ''
  nmap <unique> <Leader>t <Plug>(CommandT)
endif
nnoremap <silent> <Plug>(CommandT) :CommandT<CR>

if !hasmapto('<Plug>(CommandTBuffer)') && maparg('<Leader>b', 'n') ==# ''
  nmap <unique> <Leader>b <Plug>(CommandTBuffer)
endif
nnoremap <silent> <Plug>(CommandTBuffer) :CommandTBuffer<CR>


if has('nvim')
  "FUNCTIONS {{{
  " }}}

  " SETTINGS {{{
    let g:LanguageClient_autoStart = 1

    let g:LanguageClient_serverCommands = {
          \ 'rust': ['rustup', 'run', 'nightly', 'rls'],
          \ 'javascript': ['javascript-typescript-stdio'],
          \ 'typescript': ['javascript-typescript-stdio'],
          \ 'reason': ['reason-language-server.exe'],
          \ 'ocaml': ['ocaml-language-server', '--stdio'],
          \ 'go': ['go-langserver'],
          \ }
  " }}}

  " MAPPINGS {{{
    nnoremap <silent> K :call LanguageClient_textDocument_hover()<CR>
    nnoremap <silent> gd :call LanguageClient_textDocument_definition()<cr>
    nnoremap <silent> lf :call LanguageClient_textDocument_formatting()<cr>
    nnoremap <silent> lr :call LanguageClient_textDocument_rename()<CR>
  " }}}
end

Support language server for typescript.tsx

if has('nvim')
  "FUNCTIONS {{{
  " }}}

  " SETTINGS {{{
    let g:LanguageClient_autoStart = 1

    let g:LanguageClient_serverCommands = {
          \ 'rust': ['rustup', 'run', 'nightly', 'rls'],
          \ 'javascript': ['javascript-typescript-stdio'],
          \ 'typescript': ['javascript-typescript-stdio'],
          \ 'typescript.tsx': ['javascript-typescript-stdio'],
          \ 'reason': ['reason-language-server.exe'],
          \ 'ocaml': ['ocaml-language-server', '--stdio'],
          \ 'go': ['go-langserver'],
          \ }
  " }}}

  " MAPPINGS {{{
    nnoremap <silent> K :call LanguageClient_textDocument_hover()<CR>
    nnoremap <silent> gd :call LanguageClient_textDocument_definition()<cr>
    nnoremap <silent> lf :call LanguageClient_textDocument_formatting()<cr>
    nnoremap <silent> lr :call LanguageClient_textDocument_rename()<CR>
  " }}}
end


autocmd FileType ruby map <c-j> ]m
autocmd FileType ruby map <c-k> [m

let g:ruby_indent_block_style = 'do'
let g:ruby_indent_assignment_style = 'variable'

Remove <c-j>, <c-k> for interfering pane movements


highlight link jsThis jsReturn
highlight link jsStorageClass jsClassKeyword
highlight link jsModuleKeywords jsClassKeyword
highlight link jsModuleOperators jsClassKeyword
highlight link jsArrowFunction NONE

Make JavaScript highlighting the same as before

highlight link jsThis jsReturn
highlight link jsStorageClass jsClassKeyword
highlight link jsModuleKeywords jsClassKeyword
highlight link jsModuleOperators jsClassKeyword
highlight link jsArrowFunction NONE
highlight link jsImport jsClassKeyword
highlight link jsFrom jsClassKeyword
highlight link jsExport jsClassKeyword
highlight link jsExportDefault jsFuncName


set encoding=utf-8 " default character encoding

" Set leader keys before anything else
let mapleader      = " "
let maplocalleader = ","

filetype off
call plug#begin()

Plug 'tpope/vim-sensible'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-endwise'
Plug 'kana/vim-smartinput' " To have automatic closed pairs like () or {}
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'airblade/vim-gitgutter'
Plug 'tpope/vim-repeat'
Plug 'sheerun/vim-polyglot'
Plug 'plasticboy/vim-markdown'
Plug 'elixir-lang/vim-elixir'
Plug 'slashmili/alchemist.vim'
Plug 'jgdavey/vim-blockle'
Plug 'neomake/neomake'
Plug 'kassio/neoterm'
Plug 'itchyny/lightline.vim'
Plug 'tpope/vim-eunuch' " Syntax sugar for unix commands
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'mhinz/vim-grepper'
Plug 'jnurmine/Zenburn'
Plug 'sjl/gundo.vim'

call plug#end()

filetype plugin indent on

Add vim-vinegar to improve netrw

set encoding=utf-8 " default character encoding

" Set leader keys before anything else
let mapleader      = " "
let maplocalleader = ","

filetype off
call plug#begin()

Plug 'tpope/vim-sensible'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-endwise'
Plug 'kana/vim-smartinput' " To have automatic closed pairs like () or {}
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'airblade/vim-gitgutter'
Plug 'tpope/vim-repeat'
Plug 'sheerun/vim-polyglot'
Plug 'plasticboy/vim-markdown'
Plug 'elixir-lang/vim-elixir'
Plug 'slashmili/alchemist.vim'
Plug 'jgdavey/vim-blockle'
Plug 'neomake/neomake'
Plug 'kassio/neoterm'
Plug 'itchyny/lightline.vim'
Plug 'tpope/vim-vinegar'
Plug 'tpope/vim-eunuch' " Syntax sugar for unix commands
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'mhinz/vim-grepper'
Plug 'jnurmine/Zenburn'
Plug 'sjl/gundo.vim'

call plug#end()

filetype plugin indent on


filetype off

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" let Vundle manage Vundle
" required!
Bundle 'gmarik/vundle'

" My plugins
Bundle 'tpope/vim-endwise'
Bundle 'scrooloose/nerdcommenter'
"Bundle 'scrooloose/nerdtree'
Bundle 'vim-ruby/vim-ruby'
Bundle 'godlygeek/tabular'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-fugitive'
Bundle 'kchmck/vim-coffee-script'
Bundle 'jgdavey/vim-turbux'
Bundle 'jgdavey/tslime.vim'
Bundle 'rking/ag.vim'
Bundle 'fatih/vim-go'

" Color Schemes
Bundle 'wesgibbs/vim-irblack'
Bundle 'altercation/vim-colors-solarized'
Bundle 'zeis/vim-kolor'
Bundle 'morhetz/gruvbox'

Add plugin to vim for rust

filetype off

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" let Vundle manage Vundle
" required!
Bundle 'gmarik/vundle'

" My plugins
Bundle 'tpope/vim-endwise'
Bundle 'scrooloose/nerdcommenter'
"Bundle 'scrooloose/nerdtree'
Bundle 'vim-ruby/vim-ruby'
Bundle 'godlygeek/tabular'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-fugitive'
Bundle 'kchmck/vim-coffee-script'
Bundle 'jgdavey/vim-turbux'
Bundle 'jgdavey/tslime.vim'
Bundle 'rking/ag.vim'
Bundle 'fatih/vim-go'
Bundle 'rust-lang/rust.vim'

" Color Schemes
Bundle 'wesgibbs/vim-irblack'
Bundle 'altercation/vim-colors-solarized'
Bundle 'zeis/vim-kolor'
Bundle 'morhetz/gruvbox'


let g:syntastic_enable_signs=1
let g:syntastic_quiet_warnings=1

Allow loc list if you ask for it

let g:syntastic_enable_signs=1
let g:syntastic_quiet_warnings=1
let g:syntastic_auto_loc_list=2


autocmd VimEnter * call StartUp()
autocmd VimEnter * wincmd p

autocmd BufWritePre * :call Preserve(":call TrimWhiteSpaces()")
autocmd BufRead,BufNewFile *.done,*.todo,*.task set filetype=taskpaper
autocmd BufRead,BufNewFile *.tpl,*.twig set filetype=html
autocmd BufWritePost *.* Neomake

autocmd User NeomakeFinished call lightline#update()

autocmd BufEnter,BufWritePost *.php let g:debug = system('ag var_dump ' . expand('%:T') . ' | wc -l') | call lightline#update()
autocmd BufEnter,BufWritePost *.js  let g:debug = system('ag console.log ' . expand('%:T') . ' | wc -l') | call lightline#update()
autocmd BufLeave *.* let g:debug = '' | call lightline#update()
autocmd BufWritePost *.less :silent !find public/themes public/assets -name main.less | xargs touch

autocmd! User GoyoEnter nested call GoyoEnter()
autocmd! User GoyoLeave nested call GoyoLeave()

Add command to fix cursor when leaving neovim

autocmd VimEnter * call StartUp()
autocmd VimEnter * wincmd p

autocmd BufWritePre * :call Preserve(":call TrimWhiteSpaces()")
autocmd BufRead,BufNewFile *.done,*.todo,*.task set filetype=taskpaper
autocmd BufRead,BufNewFile *.tpl,*.twig set filetype=html
autocmd BufWritePost *.* Neomake

autocmd User NeomakeFinished call lightline#update()

autocmd BufEnter,BufWritePost *.php let g:debug = system('ag var_dump ' . expand('%:T') . ' | wc -l') | call lightline#update()
autocmd BufEnter,BufWritePost *.js  let g:debug = system('ag console.log ' . expand('%:T') . ' | wc -l') | call lightline#update()
autocmd BufLeave *.* let g:debug = '' | call lightline#update()
autocmd BufWritePost *.less :silent !find public/themes public/assets -name main.less | xargs touch
autocmd VimLeave * set guicursor=a:block-Cursor-blinkon100

autocmd! User GoyoEnter nested call GoyoEnter()
autocmd! User GoyoLeave nested call GoyoLeave()


" Load emmet HTML quickwrite plugin.
packadd emmet-vim

set filetype=htmldjango

" vim:fdm=marker ft=vim et sts=2 sw=2

Remove switching HTML to HTMLDJANGO

" Load emmet HTML quickwrite plugin.
packadd emmet-vim

" vim:fdm=marker ft=vim et sts=2 sw=2


" Setup ag options for grepping
if executable("ag")
  set grepprg=ag\ --vimgrep\ -U\ $*
  set grepformat=%f:%l:%c:%m
endif

" Custom Ag command
command! -nargs=+ -bang Ag execute 'silent grep<bang> <args>' | copen | redraw!

" Find TODO and FIXME comments
command Todo call TODOSearch()
function! TODOSearch()
  if executable("ag") && exists(":Ag") > 0
    Ag! "TODO\|FIXME"
  else
    noautocmd vimgrep /TODO\|FIXME/j ** | copen
  endif
endfunction

" Custom search motions
" From http://www.vimbits.com/bits/153
nnoremap <silent> s :set operatorfunc=<SID>GrepMotion<CR>g@
nmap <silent> S s$
xnoremap <silent> s :<C-U>call <SID>GrepMotion(visualmode())<CR>

function! s:CopyMotionForType(type)
  if a:type ==# "v"
    silent execute "normal! `<" . a:type . "`>y"
  elseif a:type ==# "char"
    silent execute "normal! `[v`]y"
  endif
endfunction

function! s:GrepMotion(type) abort
  let save = @@
  call s:CopyMotionForType(a:type)
  execute "normal! :Ag! --literal '" . shellescape(@@) . "'\<CR>"
  let @@ = save
endfunction

Switch to grep in vim

set grepprg=grep\ -RIn\ --exclude-dir=build\ --exclude-dir=.git\ $*\ *

command -nargs=+ -complete=file -bar -bang Grep execute 'silent grep<bang> <args>' | copen

" Custom search motions
" From http://www.vimbits.com/bits/153
nnoremap <silent> s :set operatorfunc=<SID>GrepMotion<CR>g@

function! s:GrepMotion(type) abort
  let save = @@
  execute "Grep! '" . shellescape(@@) . "'"
  let @@ = save
endfunction


let s:save_cpo = &cpo
set cpo&vim

function! unite#sources#tmuxcomplete#define()
  return s:s
endfunction

" define the tmuxcomplete source
let s:s = {
      \ 'name' : 'tmuxcomplete',
      \ 'description' : 'strings from tmux sessions',
      \ 'hooks' : {},
      \ 'max_candidates' : 0,
      \ 'default_kind' : 'word',
      \ 'sorters' : 'sorter_rank',
      \ 'default_action' : 'insert',
      \ 'source__maxstrings' : 0,
      \ }

" function! s:s.hooks.on_init(args, context)
"   call unite#print_source_message('tmux content', s:s.name)
" endfunction

" provides the results for unite to search/filter/sort.
function! s:s.gather_candidates(args, context)
  return map(tmuxcomplete#words(s:s.source__maxstrings), "{
        \ 'word' : v:val,
        \ 'is_multiline' : 0,
        \ 'action__text' : v:val,
        \ }")
endfunction

let &cpo = s:save_cpo
unlet s:save_cpo

Remove trailing whitespace in unite source


function! GetVisual()
  let reg_save = getreg('"')
  let regtype_save = getregtype('"')
  let cb_save = &clipboard
  set clipboard&
  normal! ""gvy
  let selection = getreg('"')
  call setreg('"', reg_save, regtype_save)
  let &clipboard = cb_save
  return selection
endfunction

"grep the current word using K (mnemonic Kurrent)
nnoremap <silent> K :Ag <cword><CR>

"grep visual selection
vnoremap K :<C-U>execute "Ag " . GetVisual()<CR>

"grep current word up to the next exclamation point using ,K
nnoremap ,K viwf!:<C-U>execute "Ag " . GetVisual()<CR>

"grep for 'def foo'
nnoremap <silent> ,gd :Ag 'def <cword>'<CR>

",gg = Grep! - using Ag the silver searcher
" open up a grep line, with a quote started for the search
nnoremap ,gg :Ag ""<left>

"Grep Current Partial
function! AgCurrentPartial()
  let l:fileNameWithoutExtension = expand('%:t:r')
  let l:fileNameWithoutUnderscore = substitute(l:fileNameWithoutExtension, '^_','','g')
  let l:grepPattern = "render.*[\\\'\\\"].*" . l:fileNameWithoutUnderscore . "[\\\'\\\"]$"
  exec 'Ag "' . l:grepPattern . '"'
endfunction

command! AgCurrentPartial call AgCurrentPartial()
"
nnoremap ,gcp :AgCurrentPartial<CR>

"Grep for usages of the current file
nnoremap ,gcf :exec "Ag " . expand("%:t:r")<CR>

Remove grep current partial, doesn't work well

function! GetVisual()
  let reg_save = getreg('"')
  let regtype_save = getregtype('"')
  let cb_save = &clipboard
  set clipboard&
  normal! ""gvy
  let selection = getreg('"')
  call setreg('"', reg_save, regtype_save)
  let &clipboard = cb_save
  return selection
endfunction

"grep the current word using K (mnemonic Kurrent)
nnoremap <silent> K :Ag <cword><CR>

"grep visual selection
vnoremap K :<C-U>execute "Ag " . GetVisual()<CR>

"grep current word up to the next exclamation point using ,K
nnoremap ,K viwf!:<C-U>execute "Ag " . GetVisual()<CR>

"grep for 'def foo'
nnoremap <silent> ,gd :Ag 'def <cword>'<CR>

",gg = Grep! - using Ag the silver searcher
" open up a grep line, with a quote started for the search
nnoremap ,gg :Ag ""<left>

"Grep for usages of the current file
nnoremap ,gcf :exec "Ag " . expand("%:t:r")<CR>


" define function to turn current buffer into a scratch buffer
function! s:Scratch()
  setlocal buftype=nofile bufhidden=hide noswapfile
endfunction

" define commands to open scratch buffers with Scratch()
command! -nargs=0 Scratch enew | call s:Scratch()
command! -nargs=0 SScratch split | Scratch
command! -nargs=0 VScratch vsplit | Scratch
command! -nargs=0 TScratch tabnew | Scratch

Allow passing filetype to :Scratch

" define function to turn current buffer into a scratch buffer
function! s:Scratch(...)
  setlocal buftype=nofile bufhidden=hide noswapfile

  if exists('a:1')
    execute 'set filetype=' . a:1
  endif
endfunction

" define commands to open scratch buffers with Scratch()
command! -nargs=? -complete=filetype Scratch enew | call s:Scratch(<q-args>)
command! -nargs=? -complete=filetype SScratch split | Scratch <args>
command! -nargs=? -complete=filetype VScratch vsplit | Scratch <args>
command! -nargs=? -complete=filetype TScratch tabnew | Scratch <args>


"" Fix constant spelling mistakes
"-----------------------------------------------------------------------------
"
iab Acheive    Achieve
iab acheive    achieve
iab Alos       Also
iab alos       also
iab Aslo       Also
iab aslo       also
iab Becuase    Because
iab becuase    because
iab Bianries   Binaries
iab bianries   binaries
iab Bianry     Binary
iab bianry     binary
iab Charcter   Character
iab charcter   character
iab Charcters  Characters
iab charcters  characters
iab Exmaple    Example
iab exmaple    example
iab Exmaples   Examples
iab exmaples   examples
iab Fone       Phone
iab fone       phone
iab Lifecycle  Life-cycle
iab lifecycle  life-cycle
iab Lifecycles Life-cycles
iab lifecycles life-cycles
iab Seperate   Separate
iab seperate   separate
iab Seureth    Suereth
iab seureth    suereth
iab Shoudl     Should
iab shoudl     should
iab Taht       That
iab taht       that
iab Teh        The
iab teh        the

Add new typo, for destory to destroy.

"" Fix constant spelling mistakes
"-----------------------------------------------------------------------------
"
iab Acheive    Achieve
iab acheive    achieve
iab Alos       Also
iab alos       also
iab Aslo       Also
iab aslo       also
iab Becuase    Because
iab becuase    because
iab Bianries   Binaries
iab bianries   binaries
iab Bianry     Binary
iab bianry     binary
iab Charcter   Character
iab charcter   character
iab Charcters  Characters
iab charcters  characters
iab Exmaple    Example
iab exmaple    example
iab Exmaples   Examples
iab exmaples   examples
iab Fone       Phone
iab fone       phone
iab Lifecycle  Life-cycle
iab lifecycle  life-cycle
iab Lifecycles Life-cycles
iab lifecycles life-cycles
iab Seperate   Separate
iab seperate   separate
iab Seureth    Suereth
iab seureth    suereth
iab Shoudl     Should
iab shoudl     should
iab Taht       That
iab taht       that
iab Teh        The
iab teh        the
iab destory    destroy


" Turn on spell checking.
setlocal spell

" Mapping to insert current git ticket into file.
inoremap <C-g><C-t> <C-r>=execute('!git ticket')<cr>

" Mapping to retrieve commit message after failed commit.
function! GetPrevCommit()
  let l:git_toplevel = glob("`git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG")
  :0read `git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG
endfunction
nnoremap <buffer> <silent> <LocalLeader>b :call GetPrevCommit()<CR>

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2

Add ticket mapping to git commit filetype

" Turn on spell checking.
setlocal spell

" Mapping to insert current git ticket into file.
nnoremap <buffer> <silent> <LocalLeader>t :r !git ticket<cr>

" Mapping to retrieve commit message after failed commit.
function! GetPrevCommit()
  let l:git_toplevel = glob("`git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG")
  :0read `git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG
endfunction
nnoremap <buffer> <silent> <LocalLeader>b :call GetPrevCommit()<CR>

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2


if exists('g:loaded_dwall') || &compatible
    finish
endif

let g:loaded_dwall=1

function! Dwall(line1, line2, ...) range
    let buffer=join(getline(a:line1, a:line2), '\n')
    let args=join(a:000, ' ')
    let url=system('echo '.shellescape(buffer).' | dwall '.args)
    echo substitute(url, '\n$', '', '')
endfunction

command! -nargs=? -range=% Dwall :call Dwall(<line1>, <line2>, <f-args>)

Use script packaged with Vim plugin

if exists('g:loaded_dwall') || &compatible
    finish
endif

let g:loaded_dwall=1
let s:dwall=expand(expand('<sfile>:p:h:h')).'/dwall'

function! Dwall(line1, line2, ...) range
    let buffer=join(getline(a:line1, a:line2), '\n')
    let args=join(a:000, ' ')
    let url=system('echo '.shellescape(buffer).' | '.shellescape(s:dwall).' '.args)
    echo substitute(url, '\n$', '', '')
endfunction

command! -nargs=? -range=% Dwall :call Dwall(<line1>, <line2>, <f-args>)


" EasyMotion
nmap s <Plug>(easymotion-s2)
nmap t <Plug>(easymotion-t2)

" NERDTree
nmap <Leader>. :NERDTreeToggle %<CR>

" Multiple Indent
vmap >> >><ESC>gv
vmap << <<<ESC>gv

" NERDCommenter
nmap <C-\> <Leader>c<Space>
vmap <C-\> <Leader>c<Space>

" Tagbar
nmap <Leader>, :TagbarToggle<CR>

" Disable some useless functions.
" * Shift-Arrow actions
noremap <S-Up> <Up>
noremap <S-Down> <Down>
noremap <S-Left> <Left>
noremap <S-Right> <Right>
inoremap <S-Up> <Up>
inoremap <S-Down> <Down>
inoremap <S-Left> <Left>
inoremap <S-Right> <Right>

Change 'd' not to yank in VIM.

" EasyMotion
nmap s <Plug>(easymotion-s2)
nmap t <Plug>(easymotion-t2)

" NERDTree
nmap <Leader>. :NERDTreeToggle %<CR>

" Multiple Indent
vmap >> >><ESC>gv
vmap << <<<ESC>gv

" NERDCommenter
nmap <C-\> <Leader>c<Space>
vmap <C-\> <Leader>c<Space>

" Tagbar
nmap <Leader>, :TagbarToggle<CR>

" Disable some useless functions.
" * Shift-Arrow actions
noremap <S-Up> <Up>
noremap <S-Down> <Down>
noremap <S-Left> <Left>
noremap <S-Right> <Right>
inoremap <S-Up> <Up>
inoremap <S-Down> <Down>
inoremap <S-Left> <Left>
inoremap <S-Right> <Right>

" Remap D into deletion without yanking.
" Deletion without yanking is mapped to d.
nnoremap D d
nnoremap d "_d
vnoremap D d
vnoremap d "_d


set colorcolumn=80
set clipboard+=unnamedplus,unnamed

" Let me run off and modify files without write
set hidden
" Make hidden less "evil"
set autowrite
" Macro redrawing
set lazyredraw
" Stop file watchers from freaking out
set directory=~/.local/share/nvim/tmp
set backupdir=~/.local/share/nvim/backup
" Better diffing
set diffexpr=py3diff#diffexpr()

let g:localrc_filename = ".local.vim"

autocmd BufNewFile,BufRead init.vim
		  \ setlocal cc=60 |
		  \ setlocal foldmethod=marker |
		  \ setlocal autoindent

noremap <leader>vs :source $MYVIMRC<CR>
noremap <leader>ve :62vsplit $MYVIMRC<CR>

function! s:EditLayerComplete(ArgLead, CmdLine, CursorPos)
  return join(g:layer_names, "\n")
endfunction

function! s:EditLayer(args)
  tabnew
  exec ':e '.g:config_base_dir.'/layer/'.a:args.'/after'
  exec ':vsplit '.g:config_base_dir.'/layer/'.a:args.'/config.vim'
  exec ':vsplit '.g:config_base_dir.'/layer/'.a:args.'/package.vim'
endfunction

" Use custom, not customlist because vim filters the former
command! -complete=custom,s:EditLayerComplete -nargs=1 EditLayer :exe s:EditLayer(<q-args>)

Resolve absolute path of layer files for EditLayer

set colorcolumn=80
set clipboard+=unnamedplus,unnamed

" Let me run off and modify files without write
set hidden
" Make hidden less "evil"
set autowrite
" Macro redrawing
set lazyredraw
" Stop file watchers from freaking out
set directory=~/.local/share/nvim/tmp
set backupdir=~/.local/share/nvim/backup
" Better diffing
set diffexpr=py3diff#diffexpr()

let g:localrc_filename = ".local.vim"

autocmd BufNewFile,BufRead init.vim
		  \ setlocal cc=60 |
		  \ setlocal foldmethod=marker |
		  \ setlocal autoindent

noremap <leader>vs :source $MYVIMRC<CR>
noremap <leader>ve :62vsplit $MYVIMRC<CR>

function! s:EditLayerComplete(ArgLead, CmdLine, CursorPos)
  return join(g:layer_names, "\n")
endfunction

function! s:LR(path)
  return resolve(expand(a:path))
endfunction

function! s:EditLayer(args)
  tabnew
  exec ':e '.s:LR(g:config_base_dir.'/layer/'.a:args.'/after')
  exec ':vsplit '.s:LR(g:config_base_dir.'/layer/'.a:args.'/config.vim')
  exec ':vsplit '.s:LR(g:config_base_dir.'/layer/'.a:args.'/package.vim')
endfunction

" Use custom, not customlist because vim filters the former
command! -complete=custom,s:EditLayerComplete -nargs=1 EditLayer :exe s:EditLayer(<q-args>)


func! cmake#commands#build()
  " Build the KRAKEN!
  call cmake#util#run_make("all")
endfunc

func! cmake#commands#clean()
  " Clean your room.
  call cmake#util#run_make("clean")
endfunc

func! cmake#commands#test()
  call cmake#util#run_make("test")
endfunc

func! cmake#commands#install()
  call cmake#utils#run_make("install")
endfunc

Add logic to build new project.

func! cmake#commands#build()
  " Build the KRAKEN!
  call cmake#util#run_make("all")
endfunc

func! cmake#commands#clean()
  " Clean your room.
  call cmake#util#run_make("clean")
endfunc

func! cmake#commands#test()
  call cmake#util#run_make("test")
endfunc

func! cmake#commands#install()
  call cmake#utils#run_make("install")
endfunc

func! cmake#commands#preconfigure()
  call cmake#utils#run_cmake(".. -DCMAKE_INSTALL_PREFIX=" . g:cmake_install_prefix . " -DCMAKE_BUILD_TYPE=" . g:cmake_build_type . " -DBUILD_SHARED_LIBS=" . g:cmake_build_shared_libs)
endfunc

func! cmake#commands#reconfigure()
  for folder in g:cmake_build_dirs
    if isdirectory(getcwd() . "/" . folder)
      system("rm -rv " . getcwd() . "/" . folder)
      break
    endif
  endfor

  cmake#commands#preconfigure()
endfunc

func! cmake#commands#create_build()
  if !filereadable(getcwd() . "/CMakeLists.txt")
    echoerr "[cmake] No `CMakeLists.txt` found at " . getcwd()
    return
  endif

  mkdir g:cmake_build_dirs[0]
  cd g:cmake_build_dirs
  cmake#commands#preconfigure()
endif


let s:source = {
\   'name': 'kitten',
\   'kind': 'keyword',
\   'filetype': {
\       'swift': 1,
\   },
\   'mark': '[kitten]',
\   'min_pattern_length': 1,
\   'max_candidates': 10,
\ }

function! s:source.gather_candidates(context)
    " TODO: Implement.
    return []
endfunction

function! neocomplete#sources#kitten#define()
    return s:source
endfunction

Enable the source when SourceKitten is installed.

let s:source = {
\   'name': 'kitten',
\   'kind': 'keyword',
\   'filetype': {
\       'swift': 1,
\   },
\   'mark': '[kitten]',
\   'min_pattern_length': 1,
\   'max_candidates': 10,
\ }

function! s:source.gather_candidates(context)
    " TODO: Implement.
    return []
endfunction

function! neocomplete#sources#kitten#define()
    return executable('sourcekitten') ? s:source : {}
endfunction


set mouse=a
syntax on

" Some nice colors for right margin and current line
set termguicolors
let g:neosolarized_termtrans=1
set background=dark
colorscheme NeoSolarized
set colorcolumn=81 cursorline
highlight ColorColumn ctermbg=0
highlight CursorLine cterm=NONE ctermbg=0

set ruler showcmd title showmode modeline

" Show special characters and trailing whitespace
set list
set listchars=tab:▓▒
set listchars+=trail:░

Clean appearance. Add softer color for whitespace

set mouse=a
syntax on

" Use truecolor and set the appropriate colorscheme
set termguicolors
let g:neosolarized_termtrans=1
set background=dark
colorscheme NeoSolarized

" Some nice colors for right margin and current line
set colorcolumn=81 cursorline
highlight ColorColumn ctermbg=0
highlight CursorLine cterm=NONE ctermbg=0

set ruler showcmd title showmode modeline

" Show special characters and trailing whitespace
set list
set listchars=tab:▓▒
set listchars+=trail:░

" Highlight whitespace such as tabs and trailing spaces with a softer color
highlight SpecialKey guibg=none guifg=#586e75


" Vim syntax file
" file type: log files
" Quit when a (custom) syntax file was already loaded
if exists("b:current_syntax")
  finish
endif

syn match fatal ".* FATAL .*"
syn match fatal "^FATAL: .*"
syn match error ".* ERROR .*"
syn match error "^ERROR: .*"
syn match warn ".* WARN .*"
syn match warn "^WARN: .*"
syn match info ".* INFO .*"
syn match info "^INFO: .*"
syn match debug ".* DEBUG .*"
syn match debug "^DEBUG: .*"

syn match error "^java.*Exception.*"
syn match error "^java.*Error.*"

" Highlight colors for log levels.
hi fatal ctermfg=Red guifg=Red
hi error ctermfg=Red guifg=Red
hi warn ctermfg=Yellow guifg=Yellow
hi info ctermfg=Green guifg=Green
hi debug ctermfg=Gray guifg=Gray

let b:current_syntax = "log"

Fix identifiers for group to avoid conflict with predefined groups

" Vim syntax file
" file type: log files
" Quit when a (custom) syntax file was already loaded
if exists("b:current_syntax")
  finish
endif

syn match logError ".* FATAL .*"
syn match logError "^FATAL: .*"
syn match logError ".* ERROR .*"
syn match logError "^ERROR: .*"
syn match logWarn ".* WARN .*"
syn match logWarn "^WARN: .*"
syn match logInfo ".* INFO .*"
syn match logInfo "^INFO: .*"
"syn match logDebug ".* DEBUG .*"
"syn match logDebug "^DEBUG: .*"

syn match logError "^java.*Exception.*"
syn match logError "^java.*Error.*"

" Highlight colors for log levels.
hi logError ctermfg=Red guifg=Red
hi logWarn ctermfg=Yellow guifg=Yellow
hi logInfo ctermfg=Green guifg=Green
"hi logDebug ctermfg=Gray guifg=Gray

let b:current_syntax = "log"


if exists(":Tabularize")
  nnoremap <silent> <Leader>a= :call Preserve("Tabularize /=")<CR>
  vnoremap <silent> <Leader>a= :call Preserve("Tabularize /=")<CR>

  nnoremap <silent> <Leader>a: :call Preserve("Tabularize /:\zs")<CR>
  vnoremap <silent> <Leader>a: :call Preserve("Tabularize /:\zs")<CR>

  nnoremap <silent> <Leader>a> :call Preserve("Tabularize /=>")<CR>
  vnoremap <silent> <Leader>a> :call Preserve("Tabularize /=>")<CR>
endif

Revise logic for checking for Tabularize cmd

if !exists(':Tabularize')
  finish "quit here
endif

nnoremap <silent> <Leader>a= :call Preserve("Tabularize /=")<CR>
vnoremap <silent> <Leader>a= :call Preserve("Tabularize /=")<CR>

nnoremap <silent> <Leader>a: :call Preserve("Tabularize /:\zs")<CR>
vnoremap <silent> <Leader>a: :call Preserve("Tabularize /:\zs")<CR>

nnoremap <silent> <Leader>a> :call Preserve("Tabularize /=>")<CR>
vnoremap <silent> <Leader>a> :call Preserve("Tabularize /=>")<CR>


function! Stl_GetMode() " {{{
	let ret = mode()

	let ret = substitute(ret, '', '^V', 'g')

	return ret
endfunction " }}}
function! Stl_GetBranch(branch_symbol) " {{{
	let ret = fugitive#statusline()

	let ret = substitute(ret, 'GIT(\([a-z0-9\-_\./:]\+\))', ' '. a:branch_symbol .' \1 ', 'gi')

	return ret
endfunction " }}}
function! Stl_GetSyntaxErrors(line_symbol) " {{{
	" Temporarily change syntastic output format
	let old_stl_format = g:syntastic_stl_format
	let g:syntastic_stl_format = '╱╱╱%E{ ERRORS (%e) '. a:line_symbol .' %fe }%W{ WARNINGS (%w) '. a:line_symbol .' %fw }╱╱╱'

	let ret = SyntasticStatuslineFlag()

	let g:syntastic_stl_format = old_stl_format

	return ret
endfunction " }}}
function! Stl_GetCurrentFunction() " {{{
	return cfi#format(' %s', '')
endfunction " }}}

Check for variable in Stl_GetSyntaxErrors

function! Stl_GetMode() " {{{
	let ret = mode()

	let ret = substitute(ret, '', '^V', 'g')

	return ret
endfunction " }}}
function! Stl_GetBranch(branch_symbol) " {{{
	let ret = fugitive#statusline()

	let ret = substitute(ret, 'GIT(\([a-z0-9\-_\./:]\+\))', ' '. a:branch_symbol .' \1 ', 'gi')

	return ret
endfunction " }}}
function! Stl_GetSyntaxErrors(line_symbol) " {{{
	if ! exists('g:syntastic_stl_format')
		" Syntastic hasn't been loaded yet
		return ''
	endif

	" Temporarily change syntastic output format
	let old_stl_format = g:syntastic_stl_format
	let g:syntastic_stl_format = '╱╱╱%E{ ERRORS (%e) '. a:line_symbol .' %fe }%W{ WARNINGS (%w) '. a:line_symbol .' %fw }╱╱╱'

	let ret = SyntasticStatuslineFlag()

	let g:syntastic_stl_format = old_stl_format

	return ret
endfunction " }}}
function! Stl_GetCurrentFunction() " {{{
	return cfi#format(' %s', '')
endfunction " }}}


" define function to turn current buffer into a scratch buffer
function! s:Scratch(...)
  setlocal buftype=nofile bufhidden=hide noswapfile

  if exists('a:1')
    execute 'set filetype=' . a:1
  endif
endfunction

" define commands to open scratch buffers with Scratch()
command! -nargs=? -complete=filetype Scratch enew | call s:Scratch(<q-args>)
command! -nargs=? -complete=filetype SScratch split | Scratch <args>
command! -nargs=? -complete=filetype VScratch vsplit | Scratch <args>
command! -nargs=? -complete=filetype TScratch tabnew | Scratch <args>

Delete Scratch buffers on hide

" define function to turn current buffer into a scratch buffer
function! s:Scratch(...)
  setlocal buftype=nofile bufhidden=delete noswapfile

  if exists('a:1')
    execute 'set filetype=' . a:1
  endif
endfunction

" define commands to open scratch buffers with Scratch()
command! -nargs=? -complete=filetype Scratch enew | call s:Scratch(<q-args>)
command! -nargs=? -complete=filetype SScratch split | Scratch <args>
command! -nargs=? -complete=filetype VScratch vsplit | Scratch <args>
command! -nargs=? -complete=filetype TScratch tabnew | Scratch <args>


" Run ruby test for current file
nnoremap <localleader>mt :call VimuxRunCommand("clear; ruby -I 'lib:test' " . bufname("%"))<cr>

Use leader to run tests

" Run ruby test for current file
nnoremap <leader>mt :call VimuxRunCommand("clear; ruby -I 'lib:test' " . bufname("%"))<cr>


" ftplugin/javascript.vim

" intelligent autocompleter
set omnifunc=javascriptcomplete#CompleteJS

" F1 comment line
map <F1> 0i//<esc>j
imap <F1> <esc>0i//<esc>j

" F2 uncomment line
map <F2> :s/^\/\///e<return>:noh<return>j

" F3 structured comment
map <F3> o<esc>i/<esc>79.yyp0O//<space>
imap <F3> <esc>o<esc>i/<esc>79.yyp0O//<space>

" F4 file header
map <F4> <esc>1GO'use strict';<esc>o<esc>

" use TAB character when TAB is pressed
set expandtab

" number of spaces to show for a TAB
set tabstop=2

" number of spaces for indent (>>, endfunction
set shiftwidth=2

" number of spaces for a tab in editing operations
set softtabstop=2

set textwidth=0

set smartindent

" TODO it would be nice to have this when on a comment, but it's not cool for code
set nowrap
set smartcase

set number
colorscheme conanperlgray

" highlight unwanted spaces
call SpaceHighlightor()

Update comment/uncomment mappings to respect indentation

" ftplugin/javascript.vim

" intelligent autocompleter
set omnifunc=javascriptcomplete#CompleteJS

" F1 comment line
map <F1> _i//<esc>j
imap <F1> <esc>_i//<esc>j
vmap <F1> :norm _i//<enter>

" F2 uncomment line
map <F2> :s/\v^(\s*)\/\//\1/e<return>:noh<return>j
imap <F2> <esc>:s/\v^(\s*)\/\//\1/e<return>:noh<return>j
vmap <F2> :s/\v^(\s*)\/\//\1/<enter>

" F3 structured comment
map <F3> o<esc>i/<esc>79.yyp0O//<space>
imap <F3> <esc>o<esc>i/<esc>79.yyp0O//<space>

" F4 file header
map <F4> <esc>1GO'use strict';<esc>o<esc>

" use SPACES when TAB is pressed
set expandtab

" number of spaces to show for a TAB
set tabstop=2

" number of spaces for indent (>>, endfunction
set shiftwidth=2

" number of spaces for a tab in editing operations
set softtabstop=2

set textwidth=140

set smartindent

" TODO it would be nice to have this when on a comment, but it's not cool for code
set nowrap
set smartcase

set number
colorscheme conanperlgray

" highlight unwanted spaces
call SpaceHighlightor()


function! s:action(candidates, options) abort
  let options = extend({
        \ 'force': 0,
        \}, a:options)
  let args = [
        \ '--quiet', '--ignore-errors',
        \ options.force ? '--force' : '',
        \]
  let args += ['--'] + map(
        \ copy(a:candidates),
        \ 'fnameescape(get(v:val, "path2", v:val.path))',
        \)
  execute printf('Gita add %s', join(args))
endfunction

function! gita#action#add#define(disable_mappings) abort
  call gita#action#define('add', function('s:action'), {
        \ 'description': 'Add file contents to the index',
        \ 'requirements': ['path'],
        \ 'options': {},
        \})
  call gita#action#define('add:force', function('s:action'), {
        \ 'description': 'Add file contents to the index (force)',
        \ 'requirements': ['path'],
        \ 'options': { 'force': 1 },
        \})
  if a:disable_mappings
    return
  endif
endfunction

Use call instead of command

function! s:action(candidates, options) abort
  let options = extend({
        \ 'force': 0,
        \}, a:options)
  let filenames = map(
        \ copy(a:candidates),
        \ 'fnameescape(get(v:val, "path2", v:val.path))',
        \)
  call gita#command#add#call({
        \ 'quiet': 1,
        \ 'ignore-errors': 1,
        \ 'force': options.force,
        \ 'filenames': filenames,
        \})
endfunction

function! gita#action#add#define(disable_mappings) abort
  call gita#action#define('add', function('s:action'), {
        \ 'description': 'Add file contents to the index',
        \ 'requirements': ['path'],
        \ 'options': {},
        \})
  call gita#action#define('add:force', function('s:action'), {
        \ 'description': 'Add file contents to the index (force)',
        \ 'requirements': ['path'],
        \ 'options': { 'force': 1 },
        \})
  if a:disable_mappings
    return
  endif
endfunction


" plugin/ack.plugin.vim

" Use the silver searcher if available
if executable('ag')
  let g:ackprg = 'ag --vimgrep'
  let g:ack_use_dispatch = 1
endif

Add custom keybinding to search with Ack/Ag

" plugin/ack.plugin.vim

" Use the silver searcher if available
if executable('ag')
  let g:ackprg = 'ag --vimgrep'
  let g:ack_use_dispatch = 1
endif

" Search with Ack.vim
nnoremap <C-f> :call ack#Ack('grep<bang>', input('Search: ', expand('<cword>')))<CR>


" let g:ctrlp_map = '<c-p>'
" unmap <c-b>

set relativenumber
set number

set background=dark
set t_Co=16
colorscheme base16-eighties

set ts=3 sw=3 et
let g:indent_guides_start_level=2
let g:indent_guides_guide_size=1

Change indent for C/C++ files.

" let g:ctrlp_map = '<c-p>'
" unmap <c-b>

set relativenumber
set number

set background=dark
set t_Co=16
colorscheme base16-eighties

set ts=4 sw=4 et
let g:indent_guides_start_level=2
let g:indent_guides_guide_size=1
autocmd FileType cpp setlocal ts=2 sw=2 et
autocmd FileType c setlocal ts=2 sw=2 et
autocmd FileType fortran setlocal ts=3 sw=3 et


inoremap <buffer> --- —
inoremap <buffer> -- –

setlocal textwidth=80
setlocal colorcolumn=80
setlocal formatoptions+=n " Recognize numbered lists
setlocal nojoinspaces
setlocal spell

" Some keyboards are inclined to this
iabbrev ANd And
iabbrev CHrist Christ
iabbrev FOr For
iabbrev GOd God
iabbrev HIm Him
iabbrev HOly Holy
iabbrev JEsus Jesus
iabbrev JOb Job
iabbrev JOhn John
iabbrev LOrd Lord
iabbrev NEw New
iabbrev NOw Now
iabbrev OUr Our
iabbrev SOn Son
iabbrev SPirit Spirit
iabbrev THe The
iabbrev THere There
iabbrev THese These
iabbrev THey They
iabbrev THis This
iabbrev WHat What
iabbrev WHen When
iabbrev WHile While
iabbrev YOu You
iabbrev YOur Your
iabbrev teh the
iabbrev ahve have
iabbrev fo of
iabbrev LROD LORD
iabbrev utno unto

Add iabbrev's for thign -> thing

inoremap <buffer> --- —
inoremap <buffer> -- –

setlocal textwidth=80
setlocal colorcolumn=80
setlocal formatoptions+=n " Recognize numbered lists
setlocal nojoinspaces
setlocal spell

" Some keyboards are inclined to this
iabbrev ANd And
iabbrev CHrist Christ
iabbrev FOr For
iabbrev GOd God
iabbrev HIm Him
iabbrev HOly Holy
iabbrev JEsus Jesus
iabbrev JOb Job
iabbrev JOhn John
iabbrev LOrd Lord
iabbrev NEw New
iabbrev NOw Now
iabbrev OUr Our
iabbrev SOn Son
iabbrev SPirit Spirit
iabbrev THe The
iabbrev THere There
iabbrev THese These
iabbrev THey They
iabbrev THis This
iabbrev WHat What
iabbrev WHen When
iabbrev WHile While
iabbrev YOu You
iabbrev YOur Your
iabbrev teh the
iabbrev ahve have
iabbrev fo of
iabbrev LROD LORD
iabbrev utno unto
iabbrev thigns things
iabbrev Thigns Things
iabbrev thign thing
iabbrev Thign Thing


if has("gui_macvim")
  " Command-Shift-F on OSX
  call janus#add_mapping('ack', 'map', '<D-F>', ':Ack<space>')
else
  if maparg("<C-F>") == ""
    " Control-Shift-F on other systems
    call janus#add_mapping('ack', 'map', '<C-F>', ':Ack<space>')
  else
    " >leader>f on systems where <C-f> == <C-F>
    call janus#add_mapping('ack', 'map', '<leader>f', ':Ack<space>')
  endif
endif

Fix the logic behind the <c-f> binding checker

if has("gui_macvim")
  " Command-Shift-F on OSX
  call janus#add_mapping('ack', 'map', '<D-F>', ':Ack<space>')
else
  " Control-Shift-F on other systems
  call janus#add_mapping('ack', 'map', '<C-F>', ':Ack<space>')

  " Check if we defined <C-f> in the process
  if maparg("<C-f>") == ":Ack "
    " >leader>f on systems where <C-f> == <C-F>
    call janus#add_mapping('ack', 'map', '<leader>f', ':Ack<space>')
    map <C-f> <S-Down>
  end
endif


augroup nopastemode
    autocmd InsertLeave * :set nopaste
augroup END

Handle yaml files in a nicer way

augroup nopastemode
    autocmd InsertLeave * :set nopaste
augroup END

" Fix auto-indentation for YAML files
augroup yaml_fix
    autocmd!
    autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab indentkeys-=0# indentkeys-=<:>
augroup END


" read Vim manual in Vim
help

" comments are made with double quotes
" comment like this

" echo back messages
echo "Hello, world!"

" echo back messages more permanently
echom "Hello again, world!"

" boolean options
set number " <name>
set nonumber " no<name>

" toggling boolean options
set number! " toggle on/off
set number! " toggle off/on

" ask vim what option is currently set
set number? " <name>?

" set numeric options
set numberwidth=10

" set multiple options in one line
set number numberwidth=10

Add Vim note on finding help on specific options

" read Vim manual in Vim
help

" read Vim manual on particular topic
help wrap

" comments are made with double quotes
" comment like this

" echo back messages
echo "Hello, world!"

" echo back messages more permanently
echom "Hello again, world!"

" boolean options
set number " <name>
set nonumber " no<name>

" toggling boolean options
set number! " toggle on/off
set number! " toggle off/on

" ask vim what option is currently set
set number? " <name>?

" set numeric options
set numberwidth=10

" set multiple options in one line
set number numberwidth=10


" Turn on spell checking.
setlocal spell

" Mapping to insert current git ticket into file.
nnoremap <buffer> <silent> <LocalLeader>t :0read !git ticket<cr>

" Mapping to retrieve commit message after failed commit.
function! GetPrevCommit()
  let l:git_toplevel = glob("`git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG")
  :0read `git rev-parse --show-toplevel`/.git/COMMIT_EDITMSG
endfunction
nnoremap <buffer> <silent> <LocalLeader>b :call GetPrevCommit()<CR>

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2

Change git message recovery strategy

" Turn on spell checking.
setlocal spell

" Mapping to insert current git ticket into file.
nnoremap <buffer> <silent> <LocalLeader>t :0read !git ticket<cr>

" Save contents of a buffer to register g.
function! s:SaveBuffer() abort
  silent normal! gg
  silent normal! "gyG
endfunction
autocmd BufWritePre <buffer> call s:SaveBuffer()

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2


set background=dark
colorscheme molokai
set autoindent

set showmatch
set matchpairs=(:),{:},[:],<:>

"Show line numbers
set nu

" File types
au BufRead,BufNewFile *.thrift set filetype=thrift
autocmd FileType gitcommit DiffGitCached | wincmd L | wincmd h

"Extra highlighting settings
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhitespace /\s\+$/
highlight ExtraWhiteSpace ctermbg=52
setlocal spell spelllang=en_gb
hi SpellBad term=reverse ctermfg=white ctermbg=darkred

" Always show the status bar at the bottom of the window
set laststatus=2
set incsearch
if ! has('gui_running')
    set ttimeoutlen=10
    augroup FastEscape
        autocmd!
        au InsertEnter * set timeoutlen=0
        au InsertLeave * set timeoutlen=1000
    augroup END
endif

set noshowmode
set list lcs=trail:·,tab:»·

Remove the dirty hacks that were required for powerline

set background=dark
colorscheme molokai
set autoindent

set showmatch
set matchpairs=(:),{:},[:],<:>

"Show line numbers
set nu

" File types
au BufRead,BufNewFile *.thrift set filetype=thrift
autocmd FileType gitcommit DiffGitCached | wincmd L | wincmd h

"Extra highlighting settings
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhitespace /\s\+$/
highlight ExtraWhiteSpace ctermbg=52
setlocal spell spelllang=en_gb
hi SpellBad term=reverse ctermfg=white ctermbg=darkred

" Always show the status bar at the bottom of the window
set laststatus=2
set incsearch

set noshowmode
set list lcs=trail:·,tab:»·

let &t_SI = "\e]50;CursorShape=1\x7"
let &t_EI = "\e]50;CursorShape=0\x7"


function importjs#ImportJSImport()
  ruby $import_js.import
endfunction
endfunction
function importjs#ImportJSGoTo()
  ruby $import_js.goto
endfunction
function importjs#ImportJSRemoveUnusedImports()
  ruby $import_js.remove_unused_imports
endfunction
function importjs#ImportJSFixImports()
  ruby $import_js.fix_imports
endfunction

" WideMsg() prints [long] message up to (&columns-1) length
" guaranteed without "Press Enter" prompt.
" http://vim.wikia.com/wiki/How_to_print_full_screen_width_messages
function! importjs#WideMsg(msg)
  let x=&ruler | let y=&showcmd
  set noruler noshowcmd
  redraw
  echo a:msg
  let &ruler=x | let &showcmd=y
endfun

ruby << EOF
  begin
    require 'import_js'
    $import_js = ImportJS::Importer.new
  rescue LoadError
    load_path_modified = false
    ::VIM::evaluate('&runtimepath').to_s.split(',').each do |path|
      lib = "#{path}/lib"
      if !$LOAD_PATH.include?(lib) and File.exist?(lib)
        $LOAD_PATH << lib
        load_path_modified = true
      end
    end
    retry if load_path_modified
  end
EOF

Remove extraneous endfunction from vim autoload

function importjs#ImportJSImport()
  ruby $import_js.import
endfunction
function importjs#ImportJSGoTo()
  ruby $import_js.goto
endfunction
function importjs#ImportJSRemoveUnusedImports()
  ruby $import_js.remove_unused_imports
endfunction
function importjs#ImportJSFixImports()
  ruby $import_js.fix_imports
endfunction

" WideMsg() prints [long] message up to (&columns-1) length
" guaranteed without "Press Enter" prompt.
" http://vim.wikia.com/wiki/How_to_print_full_screen_width_messages
function! importjs#WideMsg(msg)
  let x=&ruler | let y=&showcmd
  set noruler noshowcmd
  redraw
  echo a:msg
  let &ruler=x | let &showcmd=y
endfun

ruby << EOF
  begin
    require 'import_js'
    $import_js = ImportJS::Importer.new
  rescue LoadError
    load_path_modified = false
    ::VIM::evaluate('&runtimepath').to_s.split(',').each do |path|
      lib = "#{path}/lib"
      if !$LOAD_PATH.include?(lib) and File.exist?(lib)
        $LOAD_PATH << lib
        load_path_modified = true
      end
    end
    retry if load_path_modified
  end
EOF


setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

if exists('b:command')
  let command_string = b:command.String()
  exe 'silent file WritableSearch:\ '.fnameescape(command_string)
else
  exe 'silent file WritableSearch'
endif

augroup writable_search
  autocmd!
  autocmd BufWriteCmd <buffer> call writable_search#Update()
augroup END

if g:writable_search_result_buffer_utilities
  command! -buffer -nargs=* Rerun call writable_search#Rerun(<q-args>)
  nnoremap <buffer> <c-w>f :silent call writable_search#ftplugin#OpenSource('split')<cr>
endif

Fix bug with multiple WritableSearch windows

setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

if exists('b:command')
  let command_string = b:command.String()
  exe 'silent file WritableSearch:\ '.fnameescape(command_string)
endif

augroup writable_search
  autocmd!
  autocmd BufWriteCmd <buffer> call writable_search#Update()
augroup END

if g:writable_search_result_buffer_utilities
  command! -buffer -nargs=* Rerun call writable_search#Rerun(<q-args>)
  nnoremap <buffer> <c-w>f :silent call writable_search#ftplugin#OpenSource('split')<cr>
endif


highlight ColorColumn ctermbg=DarkGray
highlight CursorLine ctermbg=None cterm=None
set cursorline

function! EnterInsertModeHighlight()
    let &colorcolumn="78,80,".join(range(100, 120), ",")
    highlight CursorLineNr ctermfg=White ctermbg=Magenta
endfunction

function! LeaveInsertModeHighlight()
    set colorcolumn=
    highlight CursorLineNr ctermfg=None ctermbg=None
endfunction

autocmd InsertEnter * call EnterInsertModeHighlight()
autocmd InsertLeave * call LeaveInsertModeHighlight()

let g:loaded_matchparen = 0

Fix vim line number style

highlight ColorColumn ctermbg=DarkGray
highlight CursorLine ctermbg=None cterm=None
set cursorline

function! EnterInsertModeHighlight()
    let &colorcolumn="78,80,".join(range(100, 120), ",")
    highlight CursorLineNr ctermfg=White ctermbg=Magenta
endfunction

function! LeaveInsertModeHighlight()
    set colorcolumn=
    highlight CursorLineNr ctermfg=Yellow ctermbg=None
endfunction

autocmd InsertEnter * call EnterInsertModeHighlight()
autocmd InsertLeave * call LeaveInsertModeHighlight()

let g:loaded_matchparen = 0


" Turn on syntax highlighting for ruby operators (==, ||, &&, etc)
let ruby_operators=1

Add error format for bare rspec summary results

" Turn on syntax highlighting for ruby operators (==, ||, &&, etc)
let ruby_operators=1

set errorformat+=\%f:%l


" vim-markdown
let g:markdown_fenced_languages = [
      \ 'objc',
      \ 'ruby',
      \ 'sh',
      \ 'swift',
      \ 'vim',
      \ 'yaml'
    \ ]

" vim-sort-motion
let g:sort_motion_flags = 'ui'

" vim-gnupg
let g:GPGDefaultRecipients = ['0x4C7167F8']
let g:GPGPreferArmor = 1

" Netrw
let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_list_hide =
      \ netrw_gitignore#Hide()
      \ . ',^\./'
      \ . ',^\.git/'

nnoremap <silent> <C-W>z :call zoom#toggle()<CR>

let g:gutentags_file_list_command = 'rg --files'
let g:gutentags_exclude_filetypes = ['gitcommit', 'gitconfig', 'gitrebase', 'gitsendemail', 'git']

let g:tmux_navigator_disable_when_zoomed = 1

let g:hdevtools_stack = 1

let g:signify_sign_change = '~'
nmap [g <plug>(signify-prev-hunk)
nmap ]g <plug>(signify-next-hunk)

Add git blame vim command

" vim-markdown
let g:markdown_fenced_languages = [
      \ 'objc',
      \ 'ruby',
      \ 'sh',
      \ 'swift',
      \ 'vim',
      \ 'yaml'
    \ ]

" vim-sort-motion
let g:sort_motion_flags = 'ui'

" vim-gnupg
let g:GPGDefaultRecipients = ['0x4C7167F8']
let g:GPGPreferArmor = 1

" Netrw
let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_list_hide =
      \ netrw_gitignore#Hide()
      \ . ',^\./'
      \ . ',^\.git/'

nnoremap <silent> <C-W>z :call zoom#toggle()<CR>

let g:gutentags_file_list_command = 'rg --files'
let g:gutentags_exclude_filetypes = ['gitcommit', 'gitconfig', 'gitrebase', 'gitsendemail', 'git']

let g:tmux_navigator_disable_when_zoomed = 1

let g:hdevtools_stack = 1

let g:signify_sign_change = '~'
nmap [g <plug>(signify-prev-hunk)
nmap ]g <plug>(signify-next-hunk)

nnoremap <leader>g :Git blame<CR>


" Close fugitive buffers when we are done with them
" See http://mixandgo.com/blog/vim-config-for-rails-ninjas
autocmd BufReadPost fugitive://* set bufhidden=delete

Use F9 to show Gstatus & Gdiff

" Close fugitive buffers when we are done with them
" See http://mixandgo.com/blog/vim-config-for-rails-ninjas
autocmd BufReadPost fugitive://* set bufhidden=delete

" Use <F9> to open Git status and diff
" see http://vimcasts.org/episodes/fugitive-vim-working-with-the-git-index/
nmap <F9> :Gstatus<ESC><C-W><C-W>:Gdiff<CR>


" Vim indent file
" Language: Windows PowerShell
" Maintainer: Peter Provost <peter@provost.org>
" Version: 1.0
"
" $LastChangedDate $
" $Rev 	$

" Only load this indent file when no other was loaded.
if exists("b:did_indent")
  finish
endif
let b:did_indent = 1

" PS indenting is like indenting C
setlocal cindent cinoptions& cinoptions+=+0

let b:undo_indent = "setl cin<"

Stop vim from unindenting PowerShell comments!

" Vim indent file
" Language: Windows PowerShell
" Maintainer: Peter Provost <peter@provost.org>
" Version: 1.0
"
" $LastChangedDate $
" $Rev 	$

" Only load this indent file when no other was loaded.
if exists("b:did_indent")
  finish
endif
let b:did_indent = 1

" PS indenting is like indenting C
setlocal cindent cinoptions& cinoptions+=+0 cinkeys-=0#

let b:undo_indent = "setl cin<"


" Save read-only files
cmap w!! w !sudo tee > /dev/null %

" Autocommands
autocmd BufWritePre * :call Preserve("%s/\\s\\+$//e")
autocmd VimEnter * call StartUp()
autocmd VimEnter * wincmd p
autocmd BufRead,BufNewFile *.done,*.todo,*.task set filetype=taskpaper
autocmd BufRead,BufNewFile *.tpl,*.twig set filetype=html
autocmd BufEnter * call UpdateJsHintConf()

" Keep cursor on column when leaving INSERT mode
let CursorColumnI = 0
autocmd InsertEnter * let CursorColumnI = col('.')
autocmd CursorMovedI * let CursorColumnI = col('.')
autocmd InsertLeave * if col('.') != CursorColumnI | call cursor(0, col('.')+1) | endif

augroup AutoSyntastic
    autocmd!
    autocmd BufWritePost *.* call CheckSyntax()
augroup END

Update mapping for saving with root

" Save read-only files
cmap ww w !sudo tee > /dev/null %

" Autocommands
autocmd BufWritePre * :call Preserve("%s/\\s\\+$//e")
autocmd VimEnter * call StartUp()
autocmd VimEnter * wincmd p
autocmd BufRead,BufNewFile *.done,*.todo,*.task set filetype=taskpaper
autocmd BufRead,BufNewFile *.tpl,*.twig set filetype=html
autocmd BufEnter * call UpdateJsHintConf()

" Keep cursor on column when leaving INSERT mode
let CursorColumnI = 0
autocmd InsertEnter * let CursorColumnI = col('.')
autocmd CursorMovedI * let CursorColumnI = col('.')
autocmd InsertLeave * if col('.') != CursorColumnI | call cursor(0, col('.')+1) | endif

augroup AutoSyntastic
    autocmd!
    autocmd BufWritePost *.* call CheckSyntax()
augroup END


set nocompatible
filetype off

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

Bundle 'gmarik/vundle'

" File Navigation
Bundle 'git://git.wincent.com/command-t.git'
Bundle 'scrooloose/nerdtree'
Bundle 'mileszs/ack.vim'

Bundle 'duff/vim-bufonly'

" Editing
Bundle 'scrooloose/nerdcommenter'
Bundle 'godlygeek/tabular'
Bundle 'scrooloose/syntastic'
Bundle 'msanders/snipmate.vim'
Bundle 'sjl/gundo.vim'
Bundle 'delimitMate.vim'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-rails'
Bundle 'robgleeson/hammer.vim'
Bundle 'kana/vim-textobj-user'
Bundle 'nelstrom/vim-textobj-rubyblock'

" Looks
Bundle 'skalnik/vim-irblack'
Bundle 'nathanaelkane/vim-indent-guides'

" Misc
Bundle 'tpope/vim-fugitive'
Bundle 'scratch.vim'
Bundle 'mattn/gist-vim'

filetype plugin indent on

Use MSch delimitMate to fix bug with ⌘-> & ⌘<-

set nocompatible
filetype off

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

Bundle 'gmarik/vundle'

" File Navigation
Bundle 'git://git.wincent.com/command-t.git'
Bundle 'scrooloose/nerdtree'
Bundle 'mileszs/ack.vim'

Bundle 'duff/vim-bufonly'

" Editing
Bundle 'scrooloose/nerdcommenter'
Bundle 'MSch/delimitMate'
Bundle 'godlygeek/tabular'
Bundle 'scrooloose/syntastic'
Bundle 'msanders/snipmate.vim'
Bundle 'sjl/gundo.vim'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-rails'
Bundle 'robgleeson/hammer.vim'
Bundle 'kana/vim-textobj-user'
Bundle 'nelstrom/vim-textobj-rubyblock'

" Looks
Bundle 'skalnik/vim-irblack'
Bundle 'nathanaelkane/vim-indent-guides'

" Misc
Bundle 'tpope/vim-fugitive'
Bundle 'scratch.vim'
Bundle 'mattn/gist-vim'

filetype plugin indent on


highlight ColorColumn ctermbg=DarkGray
set cursorline

" Change Color when entering Insert Mode
autocmd InsertEnter * let &colorcolumn="78,80,".join(range(100, 120), ",")
"
" Revert Color to default when leaving Insert Mode
autocmd InsertLeave * set colorcolumn=

Change comment style to be italic

highlight ColorColumn ctermbg=DarkGray
highlight Comment cterm=italic
set cursorline

" Change Color when entering Insert Mode
autocmd InsertEnter * let &colorcolumn="78,80,".join(range(100, 120), ",")
"
" Revert Color to default when leaving Insert Mode
autocmd InsertLeave * set colorcolumn=


set background=dark

if has("gui_running")
  colorscheme wombat
else
  colorscheme wombat256mod
endif

" Use the same background color for signs as we do for line numbers. This
" makes signs and line numbers look like one nice big column.
hi! link SignColumn LineNr

" Use a more subtle color to highlight whitespace when using 'listchars'.
hi! SpecialKey gui=NONE guifg=#113245 guibg=#002b36

hi! ColorColumn guibg=black ctermbg=black

" Use the same background colour everywhere, including non-text regions.
hi! Normal guibg=NONE ctermbg=NONE
hi! NonText guibg=NONE ctermbg=NONE

Fix background colours in GUI Vim

set background=dark

if has("gui_running")
  colorscheme wombat
else
  colorscheme wombat256mod
endif

" Use the same background color for signs as we do for line numbers. This
" makes signs and line numbers look like one nice big column.
hi! link SignColumn LineNr

" Use a more subtle color to highlight whitespace when using 'listchars'.
hi! SpecialKey gui=NONE guifg=#113245 guibg=#002b36

hi! ColorColumn guibg=black ctermbg=black

" Use the same background colour behind text, and non-text. This removes the
" two different background colours you get out-of-the-box.
hi! Normal ctermbg=NONE
hi! NonText ctermbg=NONE
hi! link NonText Normal


" keymappings for Ctrl-P
nnoremap <leader>pf :CtrlP<cr>
nnoremap <leader>pb :CtrlPBuffer<cr>
nnoremap <leader>pm :CtrlPMRU<cr>

" files = pf
" buffers = pb
" mru = pm

" tags = pt
" directory = pd
" line = pl
" changes = pc

" registers = pr
" marks = p'

Change CtrlP mapping prefix to \c... instead of \p...

" keymappings for Ctrl-P
nnoremap <leader>cf :CtrlP<cr>
nnoremap <leader>cb :CtrlPBuffer<cr>
nnoremap <leader>cm :CtrlPMRU<cr>

" tags = ct
" directory = cd
" line = cl
" changes = cc

" registers = cr
" marks = c'


" naive-note.vim - Innocent note taking
" Maintainer: Chris DeLuca <https://www.chrisdeluca.me/>
" Version: 0.0.1
" If you asked this plugin what it's most painful life experience was, it'd
" say, '…What?'
" TODO:
" - Un-archive mapping when in archive
" - Export as plugin(?)
"   - Note directory configurable
"   - Error when note directory variable isn't present
"   - All mappings configurable
"   - Configurable split calls
"   - Figure out minimum vim version needed
"   - Figure out what `&cp` is, and if needed
"   - Write documentation
"   - Write readme
"   - Type of file generated configurable(?)
" - Get dirvish to refresh

if exists('g:loaded_naive_note') || v:version < 700
  finish
endif
let g:loaded_naive_note = 1

if empty(glob('~/Dropbox/Notes/archive'))
  silent execute('~/Dropbox/Notes/archive')
endif

" Open note listing buffer mapping.
nnoremap <leader>o :split ~/Dropbox/Notes<CR>

" Open note archive mapping.
nnoremap <leader>p :split ~/Dropbox/Notes/archive<CR>

" Create a new note mapping.
nnoremap <leader>n :call naivenote#create()<CR>

Fix note archive folder creation

" naive-note.vim - Innocent note taking
" Maintainer: Chris DeLuca <https://www.chrisdeluca.me/>
" Version: 0.0.1
" If you asked this plugin what it's most painful life experience was, it'd
" say, '…What?'
" TODO:
" - Un-archive mapping when in archive
" - Export as plugin(?)
"   - Note directory configurable
"   - Error when note directory variable isn't present
"   - All mappings configurable
"   - Configurable split calls
"   - Figure out minimum vim version needed
"   - Figure out what `&cp` is, and if needed
"   - Write documentation
"   - Write readme
"   - Type of file generated configurable(?)
" - Get dirvish to refresh

if exists('g:loaded_naive_note') || v:version < 700
  finish
endif
let g:loaded_naive_note = 1

if empty(glob('~/Dropbox/Notes/archive'))
  silent execute(':!mkdir -p ~/Dropbox/Notes/archive')
endif

" Open note listing buffer mapping.
nnoremap <leader>o :split ~/Dropbox/Notes<CR>

" Open note archive mapping.
nnoremap <leader>p :split ~/Dropbox/Notes/archive<CR>

" Create a new note mapping.
nnoremap <leader>n :call naivenote#create()<CR>


" 2017-08-02: Aha! EZ-CI at last!

" USAGE: See: .trustme.sh

"echomsg "You've been Vimmed! at " . expand('%')

" @% is same as expand('%'), which for some miraculous reason
" is the path relative to this file??
"autocmd BufWrite *.rb echomsg "Hooray! at " . expand('%')
"autocmd BufWrite *.rb echomsg "Hooray! at " . @%

" Use an autocmd group so it's easy to delete the group,
" since every time we call autocmd, the command is appended,
" and this file gets sourced every switch to a corresponding
" project buffer.
augroup trustme
  " Remove! all trustme autocommands.
  autocmd! trustme
  "autocmd BufWrite *.rb silent !touch TOUCH
  " MEH/2017-08-02: This won't hook bin/murano.
  autocmd BufWrite *.rb silent !./.trustme.sh &
augroup END

Fix Vim autocmd in CI to only work on current buffer, rather than on all Ruby files.

" 2017-08-02: Aha! EZ-CI at last!

" USAGE: See: .trustme.sh

"echomsg "You've been Vimmed! at " . expand('%')

" @% is same as expand('%'), which for some miraculous reason
" is the path relative to this file??
"autocmd BufWrite *.rb echomsg "Hooray! at " . expand('%')
"autocmd BufWrite *.rb echomsg "Hooray! at " . @%

" Use an autocmd group so it's easy to delete the group,
" since every time we call autocmd, the command is appended,
" and this file gets sourced every switch to a corresponding
" project buffer.
augroup trustme
  " Remove! all trustme autocommands.
  autocmd! trustme
"  autocmd! trustme <buffer>
  "autocmd BufWrite *.rb silent !touch TOUCH
  " MEH/2017-08-02: This won't hook bin/murano.
  autocmd BufWrite <buffer> silent !./.trustme.sh &
augroup END


" Use spacebar as leader
let mapleader="\<Space>"

" Navigation
nnoremap j gj
nnoremap k gk

" Windows
" Move
nnoremap H <C-w>h
nnoremap J <C-w>j
nnoremap K <C-w>k
nnoremap L <C-w>l

" Maximize
nnoremap <leader>_ <C-w>_
nnoremap <leader>\| <C-w>\|
nnoremap <leader>= <C-w>_<C-w>\|

" Tabs
" Tab navigation
nnoremap <C-h> :tabprevious<CR>
nnoremap <C-l> :tabnext<CR>

" Close tab
nnoremap <leader>q :tabclose<CR>

Add neovim key to unhighlight search

" Use spacebar as leader
let mapleader="\<Space>"

" Navigation
nnoremap j gj
nnoremap k gk

" Windows
" Move
nnoremap H <C-w>h
nnoremap J <C-w>j
nnoremap K <C-w>k
nnoremap L <C-w>l

" Maximise
nnoremap <leader>_ <C-w>_
nnoremap <leader>\| <C-w>\|
nnoremap <leader>= <C-w>_<C-w>\|

" Tabs
" Tab navigation
nnoremap <C-h> :tabprevious<CR>
nnoremap <C-l> :tabnext<CR>

" Close tab
nnoremap <leader>q :tabclose<CR>

" Search
" Unhighlight search
nnoremap <leader>h :nohl<CR>


" General vim configurations
"
" vim-sensible takes care of most of the really common configuration changes
" for us. These configurations are more personal and to my liking.

colorscheme hybrid

set number     " Show line numbers
set nowrap     " Don't visually wrap lines
set noshowmode " Don't show mode (--INSERT--, etc)
set cursorline " Highlight the current cursor line
set hidden     " Allow buffer switching without having to save
set list       " Show non-printable characters
set hlsearch   " Highlight searched text
set ignorecase " Ignore case when searching
set smartcase  " Don't ignore case when using uppercase in a search
set autochdir  " Always stay in the working directory of the open file

" Disable backup files
set nobackup nowritebackup noswapfile

" Tab configurations
set smartindent expandtab tabstop=4 shiftwidth=4

" Ignore cache type files
set wildignore+=*/cache/*,*.sassc

" netrw: Hide banner and dsable history file
let g:netrw_banner=0
let g:netrw_dirhistmax = 0

" Enable spell checking on git commits
autocmd BufRead COMMIT_EDITMSG setlocal spell

Configure airline, bufferline, and netrw

" General vim configurations
"
" vim-sensible takes care of most of the really common configuration changes
" for us. These configurations are more personal and to my liking.

colorscheme hybrid

set number     " Show line numbers
set nowrap     " Don't visually wrap lines
set noshowmode " Don't show mode (--INSERT--, etc)
set cursorline " Highlight the current cursor line
set hidden     " Allow buffer switching without having to save
set list       " Show non-printable characters
set hlsearch   " Highlight searched text
set ignorecase " Ignore case when searching
set smartcase  " Don't ignore case when using uppercase in a search
set autochdir  " Always stay in the working directory of the open file

" Disable backup files
set nobackup nowritebackup noswapfile

" Tab configurations
set smartindent expandtab tabstop=4 shiftwidth=4

" Ignore cache type files
set wildignore+=*/cache/*,*.sassc

" netrw plugin configuration
let g:netrw_banner = 0     " Don't show help banner
let g:netrw_dirhistmax = 0 " Don't write history file

" airline plugin configuration
let g:airline_left_sep = ''       " Hide separators
let g:airline_right_sep = ''      " -
let g:airline_detect_modified = 0 " Don't change color for modified files

" bufferline plugin configuration
let g:bufferline_echo = 0 " Don't echo buffer list to command line

" Enable spell checking on git commits
autocmd BufRead COMMIT_EDITMSG setlocal spell


nnoremap ; :
nnoremap : ;
vnoremap ; :
vnoremap : ;

inoremap jk <Esc>
vnoremap jk <Esc>

Add some more mappings for nvim

nnoremap ; :
nnoremap : ;
vnoremap ; :
vnoremap : ;

nnoremap m d
nnoremap M D
vnoremap m d
vnoremap M D

inoremap jk <Esc>
inoremap kj <Esc>
vnoremap jk <Esc>
vnoremap kj <Esc>


" Unite.vim configuration.

" Set matcher behavior.
call unite#filters#matcher_default#use(['matcher_fuzzy'])

" Use ag to filter the async Unite buffer.
if executable('ag')
  let g:unite_source_rec_async_command= 'ag --nocolor --nogroup --hidden -g ""'
endif

" Customize the buffer.
autocmd FileType unite call s:unite_settings()
function! s:unite_settings()
  " SuperTab compatibility.
  let b:SuperTabDisabled=1
  " Enable navigation with Ctrl-J and Ctrl-K in insert mode.
  imap <buffer> <C-J> <Plug>(unite_select_next_line)
  imap <buffer> <C-K> <Plug>(unite_select_previous_line)
endfunction

Use ag or ack for Unite grep.

" Unite.vim configuration.

" Set matcher behavior.
call unite#filters#matcher_default#use(['matcher_fuzzy'])

if executable('ag')
  let g:unite_source_grep_command='ag'
  let g:unite_source_grep_default_opts='--nocolor --nogroup --hidden'
  let g:unite_source_grep_recursive_opt=''
elseif executable('ack')
  let g:unite_source_grep_command='ack'
  let g:unite_source_grep_default_opts='--no-heading --no-color -a'
  let g:unite_source_grep_recursive_opt=''
endif

" Use ag to filter the async Unite buffer.
if executable('ag')
  let g:unite_source_rec_async_command= 'ag --nocolor --nogroup --hidden -g ""'
endif

" Customize the buffer.
autocmd FileType unite call s:unite_settings()
function! s:unite_settings()
  " SuperTab compatibility.
  let b:SuperTabDisabled=1
  " Enable navigation with Ctrl-J and Ctrl-K in insert mode.
  imap <buffer> <C-J> <Plug>(unite_select_next_line)
  imap <buffer> <C-K> <Plug>(unite_select_previous_line)
endfunction


py3 import sys

function Py3test()
    py3 import time
    py3 from ctypes import *
    py3 lib = cdll.LoadLibrary("/usr/lib/libc.dylib")
    py3 print(time.ctime(lib.time(0)))
endfunction
" call Py3test()

Add virtualenv to sys.path to fix Python code completion

" ensure python3 is compiled into vim
py3 import sys

function Py3test()
    py3 import time
    py3 from ctypes import *
    py3 lib = cdll.LoadLibrary("/usr/lib/libc.dylib")
    py3 print(time.ctime(lib.time(0)))
endfunction
" call Py3test()

" Enable jedi-vim virtualenv support by injecting active VIRTUAL_ENV into sys.path.
py3 << EOF
import os, sys, pathlib
if 'VIRTUAL_ENV' in os.environ:
    venv = os.getenv('VIRTUAL_ENV')
    site_packages = next(pathlib.Path(venv, 'lib').glob('python*/site-packages'))
    if site_packages:
        sys.path.insert(0, str(site_packages))
EOF


" Make it beautiful - colors and fonts

if has("gui_running")
  " Show tab number (useful for Cmd-1, Cmd-2.. mapping)
  " For some reason this doesn't work as a regular set command,
  " (the numbers don't show up) so I made it a VimEnter event
  autocmd VimEnter * set guitablabel=%N:\ %t\ %M

  set lines=60
  set columns=190

  if has("gui_gtk2")
    set guifont=Inconsolata\ XL\ 12,Inconsolata\ 15,Monaco\ 12
  else
    set guifont=Inconsolata\ XL:h17,Inconsolata:h20,Monaco:h17
  end
else
  let g:CSApprox_loaded = 1

  " For people using a terminal that is not Solarized
  if exists("g:yadr_using_unsolarized_terminal")
    let g:solarized_termcolors=256
    let g:solarized_termtrans=1
  end
endif

" Tell the term has 256 colors.
set t_Co=256

colorscheme solarized
set background=dark

" Remove menu bar and tool bar.
set go=aei

Adjust gvim/mvim window size to be able to fit two panes.

" Make it beautiful - colors and fonts

if has("gui_running")
  " Show tab number (useful for Cmd-1, Cmd-2.. mapping)
  " For some reason this doesn't work as a regular set command,
  " (the numbers don't show up) so I made it a VimEnter event
  autocmd VimEnter * set guitablabel=%N:\ %t\ %M

  set lines=60
  set columns=190

  if has("gui_gtk2")
    set guifont=Inconsolata\ XL\ 11,Inconsolata\ 14,Monaco\ 11
  else
    set guifont=Inconsolata\ XL:h14,Inconsolata:h17,Monaco:h14
  end
else
  let g:CSApprox_loaded = 1

  " For people using a terminal that is not Solarized
  if exists("g:yadr_using_unsolarized_terminal")
    let g:solarized_termcolors=256
    let g:solarized_termtrans=1
  end
endif

" Tell the term has 256 colors.
set t_Co=256

colorscheme solarized
set background=dark

" Remove menu bar and tool bar.
set go=aei


let g:airline#extensions#branch#enabled = 0
let g:airline#extensions#tabline#enabled = 1
let g:airline_left_sep=''
let g:airline_right_sep=''

Disable neomake in airline, was dying

let g:airline#extensions#branch#enabled = 0
let g:airline#extensions#neomake#enabled = 0
let g:airline#extensions#tabline#enabled = 1
let g:airline_left_sep=''
let g:airline_right_sep=''


" Main plugins
Plug 'dense-analysis/ale'
Plug 'jiangmiao/auto-pairs'
Plug 'jlanzarotta/bufexplorer'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'junegunn/fzf', {'dir': '~/.fzf', 'do': './install --bin'}
Plug 'jparise/vim-graphql'
Plug 'autozimu/LanguageClient-neovim', {'branch': 'next', 'do': 'bash install.sh'}
Plug 'preservim/nerdtree'
Plug 'altercation/vim-colors-solarized'
Plug 'lambdalisue/suda.vim'
Plug 'ervandew/supertab'
Plug 'leafgarland/typescript-vim'
Plug 'SirVer/ultisnips'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'hynek/vim-python-pep8-indent'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'
Plug 'cespare/vim-toml'
Plug 'editorconfig/editorconfig-vim'

" Plugin extras
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'junegunn/fzf.vim'
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'

Add date support for increment and decrement

" Main plugins
Plug 'dense-analysis/ale'
Plug 'jiangmiao/auto-pairs'
Plug 'jlanzarotta/bufexplorer'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'junegunn/fzf', {'dir': '~/.fzf', 'do': './install --bin'}
Plug 'jparise/vim-graphql'
Plug 'autozimu/LanguageClient-neovim', {'branch': 'next', 'do': 'bash install.sh'}
Plug 'preservim/nerdtree'
Plug 'altercation/vim-colors-solarized'
Plug 'lambdalisue/suda.vim'
Plug 'ervandew/supertab'
Plug 'leafgarland/typescript-vim'
Plug 'SirVer/ultisnips'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'hynek/vim-python-pep8-indent'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-speeddating'
Plug 'cespare/vim-toml'
Plug 'editorconfig/editorconfig-vim'

" Plugin extras
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'junegunn/fzf.vim'
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'


if has('autocmd') && !exists('autocommands_loaded')
  " Load autocommands only once
  let autocommands_loaded = 1

  " === File type settings ===
  " Disable comment continuation when using 'o' or 'O'
  autocmd FileType * setlocal formatoptions-=o
  " Syntax highlighting for C custom types
  autocmd FileType c syntax match cType "\<\w\+_t\>"
  " Enable java completion
  autocmd FileType java set omnifunc=javacomplete#Complete
  " Activate spell checking for relevant files
  autocmd FileType gitcommit,markdown,tex set spell

  " === Tab settings ===
  autocmd FileType python setlocal shiftwidth=4 softtabstop=4 expandtab
  autocmd FileType make setlocal ts=8 sts=8 sw=8 noexpandtab

  " === Pane settings ===
  " Resize panes when resizing window
  autocmd VimResized * wincmd =
  " Make quickfix windows take all the lower section of the screen when there
  " are multiple windows open
  autocmd FileType qf wincmd J

  " === Buffer settings ===
  " Recognise markdown files properly
  autocmd BufRead,BufNewFile *.md set filetype=markdown
  " Refresh trailing whitespace indicator
  autocmd BufRead,BufWritePost * unlet! b:statusline_trailing_space_warning
endif

Add tags for standard libraries

if has('autocmd') && !exists('autocommands_loaded')
  " Load autocommands only once
  let autocommands_loaded = 1

  " === File type settings ===
  " Disable comment continuation when using 'o' or 'O'
  autocmd FileType * setlocal formatoptions-=o
  " Syntax highlighting for C custom types
  autocmd FileType c syntax match cType "\<\w\+_t\>"
  " Enable java completion
  autocmd FileType java set omnifunc=javacomplete#Complete
  " Activate spell checking for relevant files
  autocmd FileType gitcommit,markdown,tex set spell
  " Use tags from ~/.tags/<filetype>
  autocmd FileType * exec "setlocal tags+=~/.tags/" . &filetype

  " === Tab settings ===
  autocmd FileType python setlocal shiftwidth=4 softtabstop=4 expandtab
  autocmd FileType make setlocal ts=8 sts=8 sw=8 noexpandtab

  " === Pane settings ===
  " Resize panes when resizing window
  autocmd VimResized * wincmd =
  " Make quickfix windows take all the lower section of the screen when there
  " are multiple windows open
  autocmd FileType qf wincmd J

  " === Buffer settings ===
  " Recognise markdown files properly
  autocmd BufRead,BufNewFile *.md set filetype=markdown
  " Refresh trailing whitespace indicator
  autocmd BufRead,BufWritePost * unlet! b:statusline_trailing_space_warning
endif


" make Vim recognize stylesheet imports
let &l:include = '<link\>.*\<rel="stylesheet".*\<href="\zs\S\{-}\ze"'

" set up emmet maps
call maps#MapEmmet()

Set up HTML wrapping config for writing

" make Vim recognize stylesheet imports
let &l:include = '<link\>.*\<rel="stylesheet".*\<href="\zs\S\{-}\ze"'

" set up emmet maps
call maps#MapEmmet()

" set up nicer soft breaks
setlocal wrap
setlocal linebreak
setlocal breakindent


" Git wrapper
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'

" Make vimdiff use vertical splits for 3-way merges
set diffopt=vertical

" Open `git lg` in new buffer
nnoremap <Leader>l :split gitlg.txt<CR>:r!git lg<CR>:AnsiEsc<CR>gg

Delete Fugitive buffers after leaving

" Git wrapper
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'

" Make vimdiff use vertical splits for 3-way merges
set diffopt=vertical

" Open `git lg` in new buffer
nnoremap <Leader>l :split gitlg.txt<CR>:r!git lg<CR>:AnsiEsc<CR>gg

" Deletes any Fugitive buffer after exiting
autocmd BufReadPost fugitive://* set bufhidden=delete


" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" fmt.vim: Vim command to format Go files with gofmt.
"
" This filetype plugin add a new commands for go buffers:
"
"   :Fmt
"
"       Filter the current Go buffer through gofmt.
"       It tries to preserve cursor position and avoids
"       replacing the buffer with stderr output.
"

command! -buffer Fmt call s:GoFormat()

function! s:GoFormat()
    let view = winsaveview()
    %!gofmt
    if v:shell_error
        %| " output errors returned by gofmt
           " TODO(dchest): perhaps, errors should go to quickfix
        undo
	echohl Error | echomsg "Gofmt returned error" | echohl None
    endif
    call winrestview(view)
endfunction

" vim:ts=4:sw=4:et

Send GoFmt errors to a location list

" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" fmt.vim: Vim command to format Go files with gofmt.
"
" This filetype plugin add a new commands for go buffers:
"
"   :Fmt
"
"       Filter the current Go buffer through gofmt.
"       It tries to preserve cursor position and avoids
"       replacing the buffer with stderr output.
"

command! -buffer Fmt call s:GoFormat()

function! s:GoFormat()
    let view = winsaveview()
    silent %!gofmt
    if v:shell_error
        let errors = []
        for line in getline(1, line('$'))
            let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)')
            if !empty(tokens)
                call add(errors, {"filename": @%,
                                 \"lnum":     tokens[2],
                                 \"col":      tokens[3],
                                 \"text":     tokens[4]})
            endif
        endfor
        if empty(errors)
            % | " Couldn't detect gofmt error format, output errors
        endif
        undo
        if !empty(errors)
            call setloclist(0, errors, 'r')
        endif
        echohl Error | echomsg "Gofmt returned error" | echohl None
    endif
    call winrestview(view)
endfunction

" vim:ts=4:sw=4:et


" Check if we want to enable YouCompleteMe
let s:enable_ycm = get(g:, 'enable_ycm', 1)

" Note that .plug files are in viml
au BufRead,BufNewFile *.plug set filetype=vim

" Start vim-plug
call plug#begin('~/.vim/plugged')

" TODO Make this more readable by splitting into groups
" Load all the default plugins
source ~/.vim/plugs/default.plug

" Load YCM if requested
if s:enable_ycm
    source ~/.vim/plugs/ycm.plug
endif

call plug#end()

Allow extra Vim plugins to be specified locally

" Check if we want to enable YouCompleteMe
let s:enable_ycm = get(g:, 'enable_ycm', 1)

" Note that .plug files are in viml
au BufRead,BufNewFile *.plug set filetype=vim

" Start vim-plug
call plug#begin('~/.vim/plugged')

" TODO Make this more readable by splitting into groups
" Load all the default plugins
source ~/.vim/plugs/default.plug

" Load YCM if requested
if s:enable_ycm
    source ~/.vim/plugs/ycm.plug
endif

" Allow user to specify plugins without the need to fork
if filereadable(expand("~/.local_plugs.vim"))
    source ~/.local_plugs.vim
endif

call plug#end()


" Set filetype for file names without format.
augroup file_type_check
  autocmd!
  autocmd BufNewFile,BufRead *named.conf* set ft=named
  autocmd BufNewFile,BufRead *.txt,INSTALL,LICENSE,NEWS,README,TODO
        \ if &ft == ""  |
        \   set ft=text |
        \ endif
augroup END

" Restore cursor position when opening file except for gitcommit filetype.
augroup restore_cursor_position
  autocmd!
  autocmd BufReadPost *
        \ if &ft !=# 'gitcommit' && line("'\"") > 1 && line("'\"") <= line("$") |
        \   exe "normal! g`\"" |
        \ endif
augroup END

augroup auto_save_and_read
    autocmd!
    autocmd TextChanged,InsertLeave,FocusLost * silent! wall
    autocmd CursorHold * silent! checktime
augroup END

" Only highlight the current line in the current window.
augroup cursor_line
  autocmd!
  autocmd VimEnter,WinEnter,BufWinEnter * setlocal cursorline
  autocmd WinLeave * setlocal nocursorline
augroup END

Set filetype for common JS config files

" Set filetype for file names without format.
augroup file_type_check
  autocmd!
  autocmd BufNewFile,BufRead .babelrc,.eslintrc,.lintstagedrc set ft=json
  autocmd BufNewFile,BufRead *named.conf* set ft=named
  autocmd BufNewFile,BufRead *.txt,INSTALL,LICENSE,NEWS,README,TODO
        \ if &ft == ""  |
        \   set ft=text |
        \ endif
augroup END

" Restore cursor position when opening file except for gitcommit filetype.
augroup restore_cursor_position
  autocmd!
  autocmd BufReadPost *
        \ if &ft !=# 'gitcommit' && line("'\"") > 1 && line("'\"") <= line("$") |
        \   exe "normal! g`\"" |
        \ endif
augroup END

augroup auto_save_and_read
    autocmd!
    autocmd TextChanged,InsertLeave,FocusLost * silent! wall
    autocmd CursorHold * silent! checktime
augroup END

" Only highlight the current line in the current window.
augroup cursor_line
  autocmd!
  autocmd VimEnter,WinEnter,BufWinEnter * setlocal cursorline
  autocmd WinLeave * setlocal nocursorline
augroup END


set mouse=a
syntax on
filetype plugin indent on

" Set cache folder
set directory=$XDG_CACHE_HOME/nvim/swap

" Set persistent history in cache folder
set undofile
set undodir=$XDG_CACHE_HOME/nvim/undo

" Some nice colors for right margin and current line
set colorcolumn=81 cursorline
highlight ColorColumn ctermbg=0
highlight CursorLine cterm=NONE ctermbg=0

" Better identation and search options
set autoindent smartindent
set incsearch hlsearch ignorecase smartcase
set ruler showcmd title showmode modeline

" More natural split opening
set splitbelow splitright

map Q gq

Move to persistent cache folder

set mouse=a
syntax on
filetype plugin indent on

" Set cache folder
set directory=$XDG_DATA_HOME/nvim/swap

" Set persistent history in cache folder
set undofile
set undodir=$XDG_CACHE_HOME/nvim/undo

" Some nice colors for right margin and current line
set colorcolumn=81 cursorline
highlight ColorColumn ctermbg=0
highlight CursorLine cterm=NONE ctermbg=0

" Better identation and search options
set autoindent smartindent
set incsearch hlsearch ignorecase smartcase
set ruler showcmd title showmode modeline

" More natural split opening
set splitbelow splitright

map Q gq


" plugin/plugin.neosnippet.vim
"
" @file Configuration of the Neosnippet plugin

if !dw#IsLoaded('neosnippet') | finish | endif

augroup dwneosnippet
  autocmd!
augroup END

" Customize the path to the user directory containing snippet definitions
let g:neosnippet#snippets_directory = g:vim_home . '/snippets'

" Disable default snippets and only use our custom ones
let g:neosnippet#disable_runtime_snippets = { '_': 1 }

" Disable the use of conceal markers
let g:neosnippet#enable_conceal_markers = 0

" Expand snippets using neosnippet
imap <C-k> <Plug>(neosnippet_expand_or_jump)
smap <C-k> <Plug>(neosnippet_expand_or_jump)
xmap <C-k> <Plug>(neosnippet_expand_target)

" Remove remaining markers when leaving insert mode
autocmd dwneosnippet InsertLeave * NeoSnippetClearMarkers

Change keybindings for snippet expansion

" plugin/plugin.neosnippet.vim
"
" @file Configuration of the Neosnippet plugin

if !dw#IsLoaded('neosnippet') | finish | endif

augroup dwneosnippet
  autocmd!
augroup END

" Customize the path to the user directory containing snippet definitions
let g:neosnippet#snippets_directory = g:vim_home . '/snippets'

" Disable default snippets and only use our custom ones
let g:neosnippet#disable_runtime_snippets = { '_': 1 }

" Disable the use of conceal markers
let g:neosnippet#enable_conceal_markers = 0

" Expand snippets using neosnippet
imap <C-l> <Plug>(neosnippet_expand)
smap <C-l> <Plug>(neosnippet_expand)
xmap <C-l> <Plug>(neosnippet_expand_target)

" Jump to the next placeholder
imap <C-k> <Plug>(neosnippet_jump)
smap <C-k> <Plug>(neosnippet_jump)

" Remove remaining markers when leaving insert mode
autocmd dwneosnippet InsertLeave * NeoSnippetClearMarkers


" Javascript
autocmd Filetype javascript setlocal et ts=2 sts=2 sw=2
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd BufNewFile,BufRead Gulpfile* set filetype=javascript
autocmd FileType javascript let g:SuperTabDefaultCompletionType = "<c-x><c-o>"

autocmd FileType javascript set formatprg=prettier\ --stdin\ --parser\ flow\ --single-quote\ --no-bracket-spacing\ --trailing-comma\ none

autocmd BufWritePre *.js Neoformat

Add automatic JS formatting with prettier

" Javascript
autocmd Filetype javascript setlocal et ts=2 sts=2 sw=2
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd BufNewFile,BufRead Gulpfile* set filetype=javascript
autocmd FileType javascript let g:SuperTabDefaultCompletionType = "<c-x><c-o>"

let g:neoformat_enabled_javascript = ['prettier']
autocmd FileType javascript set formatprg=prettier\ --stdin\ --parser\ flow\ --single-quote\ --no-bracket-spacing\ --trailing-comma\ none

autocmd BufWritePre *.js Neoformat
autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat


" The tree buffer makes it easy to drill down through the directories of your
" git repository, but it’s not obvious how you could go up a level to the
" parent directory. Here’s a mapping of .. to the above command, but
" only for buffers containing a git blob or tree
autocmd User fugitive
  \ if fugitive#buffer().type() =~# '^\%(tree\|blob\)$' |
  \   nnoremap <buffer> .. :edit %:h<CR> |
  \ endif

" Every time you open a git object using fugitive it creates a new buffer.
" This means that your buffer listing can quickly become swamped with
" fugitive buffers. This prevents this from becomming an issue:

autocmd BufReadPost fugitive://* set bufhidden=delete

Replace call to deprecated function

" The tree buffer makes it easy to drill down through the directories of your
" git repository, but it’s not obvious how you could go up a level to the
" parent directory. Here’s a mapping of .. to the above command, but
" only for buffers containing a git blob or tree
autocmd User fugitive
  \ get(b:, 'fugitive_type', '') =~# '^\%(tree\|blob\)$' |
  \   nnoremap <buffer> .. :edit %:h<CR> |
  \ endif

" Every time you open a git object using fugitive it creates a new buffer.
" This means that your buffer listing can quickly become swamped with
" fugitive buffers. This prevents this from becomming an issue:

autocmd BufReadPost fugitive://* set bufhidden=delete


au BufRead,BufNewFile *.tf setlocal filetype=terraform
au BufRead,BufNewFile *.tfvars setlocal filetype=terraform
au BufRead,BufNewFile *.tfstate setlocal filetype=json

Set json filetype for .tfstate.backup files

au BufRead,BufNewFile *.tf setlocal filetype=terraform
au BufRead,BufNewFile *.tfvars setlocal filetype=terraform
au BufRead,BufNewFile *.tfstate setlocal filetype=json
au BufRead,BufNewFile *.tfstate.backup setlocal filetype=json


nmap <S-Enter> O<Esc>j
nmap <CR> o<Esc>k
map <leader>rf :%!astyle<cr>

highlight Pmenu ctermbg=Blue ctermfg=White
highlight PmenuSel ctermbg=Magenta ctermfg=Black

imap jj <Esc>

Add mapping for VIM Yankring

nmap <S-Enter> O<Esc>j
nmap <CR> o<Esc>k
map <leader>rf :%!astyle<cr>

highlight Pmenu ctermbg=Blue ctermfg=White
highlight PmenuSel ctermbg=Magenta ctermfg=Black

imap jj <Esc>

nnoremap <silent> <F11> :YRShow<CR>


"if exists("g:loaded_lsc")
"  finish
"endif
"let g:loaded_lsc = 1

" Diagnostics {{{1

" Highlight groups {{{2
if !hlexists('lscDiagnosticError')
  highlight link lscDiagnosticError Error
endif
if !hlexists('lscDiagnosticWarning')
  highlight link lscDiagnosticWarning SpellBad
endif
if !hlexists('lscDiagnosticInfo')
  highlight link lscDiagnosticInfo SpellBad
endif
if !hlexists('lscDiagnosticHint')
  highlight link lscDiagnosticHint SpellBad
endif

" HighlightDiagnostics {{{2
"
" Adds a match to the a highlight group for each diagnostics severity level.
"
" diagnostics: A list of dictionaries. Only the 'severity' and 'range' keys are
" used. See https://git.io/vXiUB
function! HighlightDiagnostics(diagnostics) abort
  if !exists('w:lsc_diagnostic_matches')
    let w:lsc_diagnostic_matches = []
  endif
  for current_match in w:lsc_diagnostic_matches
    call matchdelete(current_match)
  endfor
let w:lsc_diagnostic_matches = []

  for diagnostic in a:diagnostics
    if diagnostic.severity == 1
      let group = 'lscDiagnosticError'
    elseif diagnostic.severity == 2
      let group = 'lscDiagnosticWarning'
    elseif diagnostic.severity == 3
      let group = 'lscDiagnosticInfo'
    elseif diagnostic.severity == 4
      let group = 'lscDiagnosticHint'
    endif
    call add(w:lsc_diagnostic_matches, matchaddpos(group, [diagnostic.range]))
  endfor
endfunction

Handle case where match was cleared elsewhere

"if exists("g:loaded_lsc")
"  finish
"endif
"let g:loaded_lsc = 1

" Diagnostics {{{1

" Highlight groups {{{2
if !hlexists('lscDiagnosticError')
  highlight link lscDiagnosticError Error
endif
if !hlexists('lscDiagnosticWarning')
  highlight link lscDiagnosticWarning SpellBad
endif
if !hlexists('lscDiagnosticInfo')
  highlight link lscDiagnosticInfo SpellBad
endif
if !hlexists('lscDiagnosticHint')
  highlight link lscDiagnosticHint SpellBad
endif

" HighlightDiagnostics {{{2
"
" Adds a match to the a highlight group for each diagnostics severity level.
"
" diagnostics: A list of dictionaries. Only the 'severity' and 'range' keys are
" used. See https://git.io/vXiUB
function! HighlightDiagnostics(diagnostics) abort
  if !exists('w:lsc_diagnostic_matches')
    let w:lsc_diagnostic_matches = []
  endif
  for current_match in w:lsc_diagnostic_matches
    silent! call matchdelete(current_match)
  endfor
let w:lsc_diagnostic_matches = []

  for diagnostic in a:diagnostics
    if diagnostic.severity == 1
      let group = 'lscDiagnosticError'
    elseif diagnostic.severity == 2
      let group = 'lscDiagnosticWarning'
    elseif diagnostic.severity == 3
      let group = 'lscDiagnosticInfo'
    elseif diagnostic.severity == 4
      let group = 'lscDiagnosticHint'
    endif
    call add(w:lsc_diagnostic_matches, matchaddpos(group, [diagnostic.range]))
  endfor
endfunction


let g:rainbow_active = 1

augroup EnableRainbowHighlighting
   " re-enable in case 'syntax' mode is disabled after buffer loaded (e.g. bufdo)
   autocmd! BufRead,BufWinEnter * if !empty(&l:filetype) | execute 'RainbowToggleOn' | endif
augroup END

Fix RainbowToggle autcmd to always enable

let g:rainbow_active = 1

augroup EnableRainbowHighlighting
   " re-enable in case 'syntax' disabled after buffer loaded (e.g.  bufdo)
   autocmd! BufRead,BufWinEnter *
            \ if !empty(&l:filetype) |
            \     exe 'RainbowToggle' |
            \     exe 'RainbowToggleOn' |
            \ endif
augroup END


" plugin/nose.vim
" Author: Pascal Lalancette (okcompute@icloud.com)

if !has('python')
    echo "Error: Required vim compiled with +python"
    finish
endif

let g:vim_python_runner= 'pytest'

" Command Mappings
" ================

function! s:set_run_commands()
    if expand("%:r") =~ "test_.*"
        " Filename match test file pattern. Inject normal 'run' commands.
        command! -buffer -bang RunTest :call nose#run_test(<bang>0)
        command! -buffer -bang RunCase :call nose#run_case(<bang>0)
        command! -buffer -bang RunModule :call nose#run_module(<bang>0)
    else
        " For no-test files, run 'remembered' test.
        command! -buffer -bang RunTest :call nose#run_last_test(<bang>0)
        command! -buffer -bang RunCase :call nose#run_last_case(<bang>0)
        command! -buffer -bang RunModule :call nose#run_last_module(<bang>0)
    endif
    " RunAllTest is available everywhere
    command! -bang RunAllTests :call nose#run_all(<bang>0)
endfunction

" For python file, set commands relative to file being a test module or not.
"
" Note: Code is not located in ftplugin voluntary. The file pattern detection
"       requires the logic to be ran in an autocmd.
autocmd BufEnter *.py   call s:set_run_commands()

Set pytest as default runner

" plugin/nose.vim
" Author: Pascal Lalancette (okcompute@icloud.com)

if !has('python')
    echo "Error: Required vim compiled with +python"
    finish
endif

" Default runner is `pytest`
if !exists("g:vim_python_runner")
    let g:vim_python_runner= 'pytest'
endif

" Command Mappings
" ================

function! s:set_run_commands()
    if expand("%:r") =~ "test_.*"
        " Filename match test file pattern. Inject normal 'run' commands.
        command! -buffer -bang RunTest :call nose#run_test(<bang>0)
        command! -buffer -bang RunCase :call nose#run_case(<bang>0)
        command! -buffer -bang RunModule :call nose#run_module(<bang>0)
    else
        " For no-test files, run 'remembered' test.
        command! -buffer -bang RunTest :call nose#run_last_test(<bang>0)
        command! -buffer -bang RunCase :call nose#run_last_case(<bang>0)
        command! -buffer -bang RunModule :call nose#run_last_module(<bang>0)
    endif
    " RunAllTest is available everywhere
    command! -bang RunAllTests :call nose#run_all(<bang>0)
endfunction

" For python file, set commands relative to file being a test module or not.
"
" Note: Code is not located in ftplugin voluntary. The file pattern detection
"       requires the logic to be ran in an autocmd.
autocmd BufEnter *.py   call s:set_run_commands()


let g:yadr_disable_solarized_enhancements = 1

let g:hybrid_custom_term_colors = 0
let g:hybrid_reduced_contrast = 1

set background=dark
colorscheme hybrid

Enable hybrid reduced colors for iterm2 beta

let g:yadr_disable_solarized_enhancements = 1

let g:hybrid_custom_term_colors = 1
let g:hybrid_reduced_contrast = 1

set background=dark
colorscheme hybrid


" Need this here for Vundle
set nocompatible

" Load Vundle for managing scripts
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" Let Vundle update itself
Plugin 'gmarik/vundle'

" Color schemes
" Plugin 'Wombat'
Plugin 'sheerun/vim-wombat-scheme'

" Commenting
Plugin 'scrooloose/nerdcommenter'
" Numbers
Plugin 'myusuf3/numbers.vim'
" Surroundings
Plugin 'tpope/vim-surround'
" File finding
Plugin 'kien/ctrlp.vim'
" Text aligning
Plugin 'godlygeek/tabular'
" LaTeX bundle
Plugin 'jcf/vim-latex'
" Bufferline
Plugin 'bling/vim-bufferline'
" Statusline
Plugin 'bling/vim-airline'
" Sensible defaults
Plugin 'tpope/vim-sensible'
" Easier PO editing
Plugin 'vim-scripts/po.vim'
" Shell-like bindings in Vim
Plugin 'tpope/vim-rsi'
" Other
Plugin 'scrooloose/syntastic'
Plugin 'easymotion/vim-easymotion'

Change kien/ctrlp.vim for maintained fork over ctrlpvim/ctrlp.vim

" Need this here for Vundle
set nocompatible

" Load Vundle for managing scripts
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" Let Vundle update itself
Plugin 'gmarik/vundle'

" Color schemes
" Plugin 'Wombat'
Plugin 'sheerun/vim-wombat-scheme'

" Commenting
Plugin 'scrooloose/nerdcommenter'
" Numbers
Plugin 'myusuf3/numbers.vim'
" Surroundings
Plugin 'tpope/vim-surround'
" File finding
Plugin 'ctrlpvim/ctrlp.vim'
" Text aligning
Plugin 'godlygeek/tabular'
" LaTeX bundle
Plugin 'jcf/vim-latex'
" Bufferline
Plugin 'bling/vim-bufferline'
" Statusline
Plugin 'bling/vim-airline'
" Sensible defaults
Plugin 'tpope/vim-sensible'
" Easier PO editing
Plugin 'vim-scripts/po.vim'
" Shell-like bindings in Vim
Plugin 'tpope/vim-rsi'
" Other
Plugin 'scrooloose/syntastic'
Plugin 'easymotion/vim-easymotion'


" increase max line length
setlocal textwidth=100

Set Go tabstop to 4

" increase max line length
setlocal textwidth=100

setlocal shiftwidth=4     " set 'shift' size
setlocal softtabstop=4    " set 'tab' size during indent mode
setlocal tabstop=4        " set tab character size


let g:ale_lint_on_text_changed = 0
let g:ale_fix_on_save = 1

let g:ale_linters = {
      \ 'ruby': ['rubocop'],
      \ 'go': ['goimports', 'gofmt', 'golint', 'go vet', 'go build'],
      \ 'rust': ['cargo', 'rustc', 'rustfmt']
      \ }

let g:ale_fixers = {
      \ 'ruby': ['rubocop'],
      \ 'go': ['goimports'],
      \ 'rust': ['rustfmt']
      \ }

let g:ale_echo_msg_format = '[%linter%] %s'
let g:ale_sign_error = 'x'
let g:ale_sign_warning = '⚠'

Configure ALE settings for ts and js

let g:ale_lint_on_text_changed = 0
let g:ale_fix_on_save = 1

let g:ale_linters = {
      \ 'ruby': ['rubocop'],
      \ 'go': ['goimports', 'gofmt', 'golint', 'go vet', 'go build'],
      \ 'rust': ['cargo', 'rustc', 'rustfmt'],
      \ 'javascript': ['prettier-eslint', 'eslint', 'flow'],
      \ 'typescript': ['prettier', 'tslint', 'tsserver']
      \ }

let g:ale_fixers = {
      \ 'ruby': ['rubocop'],
      \ 'go': ['goimports'],
      \ 'rust': ['rustfmt'],
      \ 'javascript': ['prettier-eslint', 'eslint'],
      \ 'typescript': ['prettier', 'tslint']
      \ }

let g:ale_echo_msg_format = '[%linter%] %s'
let g:ale_sign_error = 'x'
let g:ale_sign_warning = '⚠'