" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh RobotoMono
set guifont=RobotoMono\ Nerd\ Font\ 12

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Remove toolbar
set guioptions-=T

" Default size
set lines=40
set columns=120

Disable fast redraw for gvim

" Use Nerdfont for GUI
" Clone https://github.com/ryanoasis/nerd-fonts
" ./install.sh RobotoMono
set guifont=RobotoMono\ Nerd\ Font\ 12

" Remove left and right scrollbars
set guioptions-=L
set guioptions-=R

" Remove toolbar
set guioptions-=T

" Default size
set lines=40
set columns=120

" GVim does not need redraw speedups
set ttyfast=0
set lazyredraw=0


" 'K' on a Vim keyword brings up Vim help
set keywordprg=":help"

Use 2 space indent for Vim files

" specify 2-space indent for Vim files
 setlocal expandtab
 setlocal tabstop=2 shiftwidth=2 softtabstop=2

" 'K' on a Vim keyword brings up Vim help
set keywordprg=":help"


autocmd FileType python
      \ let b:dispatch = 'python %'
autocmd FileType ruby
      \ if expand('%') =~# '_test\.rb$' |
      \   let b:dispatch = 'testrb %' |
      \ elseif expand('%') =~# '_spec\.rb$' |
      \   let b:dispatch = 'rspec %' |
      \ elseif !exists('b:dispatch') |
      \   let b:dispatch = 'ruby -wc %' |
      \ endif

nnoremap <silent> <leader>d :Dispatch<CR>

Use octodown for markdown rendering

autocmd FileType markdown
      \ let b:dispatch = 'octodown %'
autocmd FileType python
      \ let b:dispatch = 'python %'
autocmd FileType ruby
      \ if expand('%') =~# '_test\.rb$' |
      \   let b:dispatch = 'testrb %' |
      \ elseif expand('%') =~# '_spec\.rb$' |
      \   let b:dispatch = 'rspec %' |
      \ elseif !exists('b:dispatch') |
      \   let b:dispatch = 'ruby -wc %' |
      \ endif

nnoremap <silent> <leader>d :Dispatch<CR>


" Author: Jansen Mitchell https://github.com/JansenMitchell
" Description: proselint for Fountain files

call ale#linter#Define('fountain', {
\	'name': 'proselint',
\	'executable': 'proselint',
\	'command': 'proselint %t',
\	'callback': 'ale#handlers#unix#HandleAsWarning',
\})

Add four spaces, not tabs.


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

"VimCompletesMe
Plug 'ajh17/VimCompletesMe'
"Surround
Plug 'tpope/vim-surround'
"Repeat (lets you use . with surround)
Plug 'tpope/vim-repeat'
"Vimwiki
Plug 'vimwiki/vimwiki'
"Tagbar
Plug 'majutsushi/tagbar'
"ctrlp
Plug 'kien/ctrlp.vim'
"Python Syntax Highlighting
Plug 'hdima/python-syntax'
"Git support
Plug 'tpope/vim-fugitive'
" Better Diffing using git 1.8
Plug 'chrisbra/vim-diff-enhanced'
" PEP8 compliant indenting
Plug 'hynek/vim-python-pep8-indent'

call plug#end()

Change `ctrlp` repository to maintained version

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

"VimCompletesMe
Plug 'ajh17/VimCompletesMe'
"Surround
Plug 'tpope/vim-surround'
"Repeat (lets you use . with surround)
Plug 'tpope/vim-repeat'
"Vimwiki
Plug 'vimwiki/vimwiki'
"Tagbar
Plug 'majutsushi/tagbar'
"ctrlp
Plug 'ctrlpvim/ctrlp.vim'
"Python Syntax Highlighting
Plug 'hdima/python-syntax'
"Git support
Plug 'tpope/vim-fugitive'
" Better Diffing using git 1.8
Plug 'chrisbra/vim-diff-enhanced'
" PEP8 compliant indenting
Plug 'hynek/vim-python-pep8-indent'

call plug#end()


function! spacevim#lang#rust#Run() abort
  if has_key(g:plugs, 'asyncrun.vim')
    AsyncRun cargo run
  else
    !cargo run
  endif
endfunction

function! spacevim#lang#rust#Build() abort
  if has('terminal')
    call spacevim#vim#term#Run('cargo', 'build')
  elseif has_key(g:plugs, 'asyncrun.vim')
    AsyncRun cargo build
  else
    !cargo build
  endif
endfunction

function! spacevim#lang#rust#Fmt() abort
  if exists('*LanguageClient#textDocument_formatting()')
    call LanguageClient#textDocument_formatting()
  elseif exists(':RustFmt')
    RustFmt
  else
    call spacevim#util#warn('No Rust formatting tools avaliable')
  endif
endfunction

function! spacevim#lang#rust#Test(bang, ...) abort
  let funcs = join(a:000, ' ')
  let cmd = 'cargo test '.funcs.' -- --nocapture'
  let opts = {'cmd': cmd}
  if a:bang
    call extend(opts, {'cwd': expand('%:p:h')})
  endif
  call spacevim#vim#term#Open(opts)
endfunction

Convert Go variable to Rust const easily

function! spacevim#lang#rust#Run() abort
  if has_key(g:plugs, 'asyncrun.vim')
    AsyncRun cargo run
  else
    !cargo run
  endif
endfunction

function! spacevim#lang#rust#Build() abort
  if has('terminal')
    call spacevim#vim#term#Run('cargo', 'build')
  elseif has_key(g:plugs, 'asyncrun.vim')
    AsyncRun cargo build
  else
    !cargo build
  endif
endfunction

function! spacevim#lang#rust#Fmt() abort
  if exists('*LanguageClient#textDocument_formatting()')
    call LanguageClient#textDocument_formatting()
  elseif exists(':RustFmt')
    RustFmt
  else
    call spacevim#util#warn('No Rust formatting tools avaliable')
  endif
endfunction

function! spacevim#lang#rust#Test(bang, ...) abort
  let funcs = join(a:000, ' ')
  let cmd = 'cargo test '.funcs.' -- --nocapture'
  let opts = {'cmd': cmd}
  if a:bang
    call extend(opts, {'cwd': expand('%:p:h')})
  endif
  call spacevim#vim#term#Open(opts)
endfunction

 " Convert UnixfsChunkSize/unixfsChunkSize under cursor to UNIXFS_CHUNK_SIZE
function! spacevim#lang#rust#GoVariable2RustConst() abort
  let cword = expand('<cword>')
  let words = split(cword, '\U\ze\u\zs')
  let adjusted = map(words[:-2], 'v:val[:-2]')
  call add(adjusted, words[-1])
  let uppers = map(adjusted, 'toupper(v:val)')
  execute 'normal! ciw'.join(uppers, '_')
endfunction


" Librarian-Chef Cheffiles are ruby files
au BufRead,BufNewFile Cheffile set filetype=ruby

Correct capitalization of 'Ruby' in Ruby ftdetect

" Librarian-Chef Cheffiles are Ruby files
au BufRead,BufNewFile Cheffile set filetype=ruby


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

" Add a group of plug-ins to Pathogen
"
" @param [String] The plugin name
function! janus#add_group(name)
  if !exists("g:janus_loaded_groups")
    let g:janus_loaded_groups = []
  endif

  call add(g:janus_loaded_groups, a:name)
  call pathogen#runtime_prepend_subdirectories(g:janus_path . pathogen#separator() . a:name)
endfunction

Add more functions to easily enable/disable plugins.

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

" Add a group of plug-ins to Pathogen
"
" @param [String] The plugin name
function! janus#add_group(name)
  if !exists("g:janus_loaded_groups")
    let g:janus_loaded_groups = []
  endif

  call add(g:janus_loaded_groups, a:name)
  call pathogen#runtime_prepend_subdirectories(g:janus_path . pathogen#separator() . a:name)
endfunction

" Which group contains a plugin ?
"
" @param [String] The plugin name
" @return [String] The group name
function! janus#which_group(name)
  if !exists("g:janus_loaded_groups")
    return ""
  endif

  for group in g:janus_loaded_groups
    if isdirectory(janus#plugin_path(a:name, group))
      return group
    endif
  endfor
endfunction

" Disable a plugin
"
" @param [String] The plugin name
function! janus#disable_plugin(name)
  if !exists("g:pathogen_disabled")
    let g:pathogen_disabled = []
  endif
  if !exists("g:janus_disabled_plugins")
    let g:janus_disabled_plugins = []
  endif
  " Find the plugin path
  let plugin_path = janus#plugin_path(a:name)
  " Add it to janus_disabled_plugins
  call add(g:janus_disabled_plugins, plugin_path)
  " Add it to pathogen_disabled
  call add(g:pathogen_disabled, plugin_path)
endfunction

" Return the plugin path
"
" @param [String] The plugin name
" @param [String] Optional the group name
" @return [String] The plugin name
function! janus#plugin_path(...)
  if a:0 < 1 || a:0 > 2
    return ""
  elseif a:0 == 1
    " Fetch the group name of the plugin
    let group = janus#which_group(a:1)
  else
    " Assigns the group to the argument
    let group = a:2
  endif

  return group . pathogen#separator() . a:1
endfunction

" Is plugin disabled?
"
" @param [String] The plugin name
function! janus#is_plugin_disabled(name)
  return index(g:janus_disabled_plugins, janus#plugin_path(a:name)) != -1
endfunction


" Indentation with four spaces
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab

" Display errors nicely (and silently)
set noerrorbells
set novisualbell
hi clear SpellBad
hi SpellBad cterm=underline ctermfg=red

" Display search results nicely
hi Search ctermbg=red ctermfg=white

" Add line numbers
set relativenumber
set number

" Complain about trailing whitespace
set list
set list listchars=tab:→\ ,trail:·,nbsp:⌴

" Glorious technicolour!
set termguicolors
"colorscheme base16-materia-meshy
colorscheme base16-github
syntax on
let g:SignatureMarkTextHLDynamic = 1
let g:rainbow_active = 1
let g:rainbow_conf = {'separately': {'htmldjango': 0}}

" Add rulers to highlight overly long lines
set colorcolumn=80,88,100

" Visual feedback on autocompleted commands
set wmnu

" Show colour codes as the colour.
lua require'colorizer'.setup()

" Set up vim-airline
set laststatus=2
let g:airline_powerline_fonts = 1
let g:airline_theme="base16"

Add extra long line ruler

" Indentation with four spaces
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab

" Display errors nicely (and silently)
set noerrorbells
set novisualbell
hi clear SpellBad
hi SpellBad cterm=underline ctermfg=red

" Display search results nicely
hi Search ctermbg=red ctermfg=white

" Add line numbers
set relativenumber
set number

" Complain about trailing whitespace
set list
set list listchars=tab:→\ ,trail:·,nbsp:⌴

" Glorious technicolour!
set termguicolors
"colorscheme base16-materia-meshy
colorscheme base16-github
syntax on
let g:SignatureMarkTextHLDynamic = 1
let g:rainbow_active = 1
let g:rainbow_conf = {'separately': {'htmldjango': 0}}

" Add rulers to highlight overly long lines
set colorcolumn=80,88,100,120

" Visual feedback on autocompleted commands
set wmnu

" Show colour codes as the colour.
lua require'colorizer'.setup()

" Set up vim-airline
set laststatus=2
let g:airline_powerline_fonts = 1
let g:airline_theme="base16"


"disable completion (default: 0)
if !exists("g:disablecompletion")
    let g:disablecompletion = 0
endif

if !g:disablecompletion && g:python_neovim
    let g:deoplete#enable_at_startup = 1
    let deoplete#tag#cache_limit_size = 5000000
endif

Remove the deoplate cache_limit variable as this is no longer used by the plugin

"disable completion (default: 0)
if !exists("g:disablecompletion")
    let g:disablecompletion = 0
endif

if !g:disablecompletion && g:python_neovim
    let g:deoplete#enable_at_startup = 1
endif


augroup clang2
  autocmd!
  autocmd FileType c,cpp,objc,objcpp call clang2#init()
augroup END

if empty(remote#host#PluginsForHost('clang2-rplugin'))
  let s:path = expand('<sfile>:p:h:h')

  " This seems a bit greedy, but it prevents blocking while the main python3
  " provider is dealing with completions.  Deoplete might be the one that needs
  " to run in a Python3 clone.
  call remote#host#RegisterClone('clang2-rplugin', 'python3')

  " rplugin is not placed in rplugin/python3 so that it won't be added to the
  " manifiest when :UpdateRemotePlugins is called.
  call remote#host#RegisterPlugin('clang2-rplugin', s:path.'/rplugin/clang2', [
        \ {'sync': v:true, 'name': '_clang2_objc_close_brace', 'type': 'function', 'opts': {}},
        \ ])
endif

Make plugin only work in Neovim

if !has('nvim')
  finish
endif

augroup clang2
  autocmd!
  autocmd FileType c,cpp,objc,objcpp call clang2#init()
augroup END

if empty(remote#host#PluginsForHost('clang2-rplugin'))
  let s:path = expand('<sfile>:p:h:h')

  " This seems a bit greedy, but it prevents blocking while the main python3
  " provider is dealing with completions.  Deoplete might be the one that needs
  " to run in a Python3 clone.
  call remote#host#RegisterClone('clang2-rplugin', 'python3')

  " rplugin is not placed in rplugin/python3 so that it won't be added to the
  " manifiest when :UpdateRemotePlugins is called.
  call remote#host#RegisterPlugin('clang2-rplugin', s:path.'/rplugin/clang2', [
        \ {'sync': v:true, 'name': '_clang2_objc_close_brace', 'type': 'function', 'opts': {}},
        \ ])
endif


Guifont Liberation Mono:h10

Enable external autocompletion popup menu

Guifont Liberation Mono:h10
if exists('g:GtkGuiLoaded')
    call rpcnotify(1, 'Gui', 'Option', 'Popupmenu', 1)
endif


set softtabstop=4
set shiftwidth=4
set textwidth=88 "Per black
set foldmethod=syntax

let b:ale_linters = ["black", "flake8", "isort", "mypy", "pyls"]
let b:ale_fixers = ["black", "isort", "remove_trailing_lines", "trim_whitespace"]

Configure pyls to use flake8 settings file.

set softtabstop=4
set shiftwidth=4
set textwidth=88 "Per black
set foldmethod=syntax

let b:ale_linters = ["black", "flake8", "isort", "mypy", "pyls"]
let b:ale_fixers = ["black", "isort", "remove_trailing_lines", "trim_whitespace"]
let b:ale_python_pyls_config = {"pyls": {"configurationSources": ["flake8"] } }


" Use deoplete
let g:deoplete#enable_at_startup = 1
" Use smartcase
let g:deoplete#enable_smart_case = 1
" Set the minimum autocompletion trigger length
let g:deoplete#auto_completion_start_length = 1

" Keyword for normal files
call deoplete#custom#option('keyword_patterns', { 'default': '\h\w*' })

" Put snippets above buffers, but below most sources
call deoplete#custom#source('ultisnips', 'rank', 400)

" Plugin key-mappings.
inoremap <expr><C-g>     deoplete#undo_completion()
inoremap <expr><C-l>     deoplete#complete_common_string()

" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> deoplete#smart_close_popup()."\<C-h>"
inoremap <expr><BS> deoplete#smart_close_popup()."\<C-h>"

" <C-Space> forces autocomplete
inoremap <expr><C-Space> deoplete#manual_complete()

" Map tab to iterate through candidates
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
inoremap <expr><S-TAB>  pumvisible() ? "\<C-p>" : "\<S-TAB>"

Update deoplete for smart case

" Use deoplete
let g:deoplete#enable_at_startup = 1
" Use smartcase
call deoplete#custom#option('smart_case', 1)
" Set the minimum autocompletion trigger length
let g:deoplete#auto_completion_start_length = 1

" Keyword for normal files
call deoplete#custom#option('keyword_patterns', { 'default': '\h\w*' })

" Put snippets above buffers, but below most sources
call deoplete#custom#source('ultisnips', 'rank', 400)

" Plugin key-mappings.
inoremap <expr><C-g>     deoplete#undo_completion()
inoremap <expr><C-l>     deoplete#complete_common_string()

" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> deoplete#smart_close_popup()."\<C-h>"
inoremap <expr><BS> deoplete#smart_close_popup()."\<C-h>"

" <C-Space> forces autocomplete
inoremap <expr><C-Space> deoplete#manual_complete()

" Map tab to iterate through candidates
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
inoremap <expr><S-TAB>  pumvisible() ? "\<C-p>" : "\<S-TAB>"


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

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

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

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

Disable highlighting match paren in vim

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

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

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

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

let g:loaded_matchparen = 0


" Disable bracketed-paste in normal mode and operator pending mode
nunmap <f28>
ounmap <f28>
nnoremap <f29> <nop>
onoremap <f29> <nop>

Disable bracketed-paste in terminal mode

" Disable bracketed-paste in normal mode, operator pending mode and terminal mode
nunmap <f28>
ounmap <f28>
tnoremap <f28> <nop>
nnoremap <f29> <nop>
onoremap <f29> <nop>
tnoremap <f29> <nop>


if g:spacevim.timer
  MP 'tmhedberg/SimpylFold',    { 'on': [] }
  MP 'python-mode/python-mode', { 'on': [] }
else
  MP 'tmhedberg/SimpylFold',    { 'for': 'python' }
  MP 'python-mode/python-mode', { 'for': 'python' }
endif

Add vim-pythonsense and drop SimpylFold

MP 'jeetsukumaran/vim-pythonsense'
if g:spacevim.timer
  MP 'python-mode/python-mode', { 'on': [] }
else
  MP 'python-mode/python-mode', { 'for': 'python' }
endif


let g:syntastic_ruby_checkers = ['rubocop']
let g:syntastic_ruby_rubocop_args = '--auto-correct'

let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_args = '--fix'

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1

let g:syntastic_warning_symbol = '⚠'
let g:syntastic_error_symbol = '💩'

Remove Syntastic statusline addition that caused blank statusline

let g:syntastic_ruby_checkers = ['rubocop']
let g:syntastic_ruby_rubocop_args = '--auto-correct'

let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_args = '--fix'

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1

let g:syntastic_warning_symbol = '⚠'
let g:syntastic_error_symbol = '💩'


" ============ My super cool mappings ================= "

" Habit breaking
nnoremap <Up> <NOP>
nnoremap <Down> <NOP>
nnoremap <Left> <NOP>
nnoremap <Right> <NOP>
inoremap <Up> <NOP>
inoremap <Down> <NOP>
inoremap <Left> <NOP>
inoremap <Right> <NOP>

" Reselect visual block after indent/outdent
vnoremap < <gv
vnoremap > >gv

" Map leader key
let mapleader = "\\"

" ============================================================================
" ============ From this point, you can use you leader keys ==================
" ============================================================================

" Shortcut to rapidly toggle `set list`
map <leader>p :set list!<CR>

" Swap line up/down
nnoremap <leader>J ddjP
nnoremap <leader>K ddkP

" Quicksave
nnoremap <leader>s :w<CR>

" Duplicate line
nnoremap <leader>d yyp

" Reload .vimrc at will
nnoremap <leader>t :source ~/.vimrc<CR>
"
" Easy splitted window navigation
map <leader>h :wincmd h<CR>
map <leader>j :wincmd j<CR>
map <leader>k :wincmd k<CR>
map <leader>l :wincmd l<CR>

" Reload file
nnoremap <F5> :e!<CR>

Disable ESC key on both INSERT and VISUAL mode

" ============ Disable ESC key in visual and insert mode ============
vnoremap <esc> <NOP>
inoremap <esc> <NOP>

" ============ Disable arrow keys in both visual and insert mode ============
nnoremap <Up> <NOP>
nnoremap <Down> <NOP>
nnoremap <Left> <NOP>
nnoremap <Right> <NOP>
inoremap <Up> <NOP>
inoremap <Down> <NOP>
inoremap <Left> <NOP>
inoremap <Right> <NOP>

" Reselect visual block after indent/outdent
vnoremap < <gv
vnoremap > >gv

" Map leader key
let mapleader = "\\"

" ============================================================================
" ============ From this point, you can use you leader keys ==================
" ============================================================================

" Shortcut to rapidly toggle `set list`
map <leader>p :set list!<CR>

" Swap line up/down
nnoremap <leader>J ddjP
nnoremap <leader>K ddkP

" Quicksave
nnoremap <leader>s :w<CR>

" Duplicate line
nnoremap <leader>d yyp

" Reload .vimrc at will
nnoremap <leader>t :source ~/.vimrc<CR>
"
" Easy splitted window navigation
map <leader>h :wincmd h<CR>
map <leader>j :wincmd j<CR>
map <leader>k :wincmd k<CR>
map <leader>l :wincmd l<CR>

" Reload file
nnoremap <F5> :e!<CR>


" ==========================================
" Syntastic settings

let g:syntastic_javascript_syntax_checker = "jshint"
let g:syntastic_coffee_coffeelint_args = "--csv --file $HOME/.coffeelint.json"
let g:syntastic_ruby_checkers = ['mri', 'rubocop']
let g:syntastic_ruby_rubocop_exec = "$RBENV_ROOT/shims/ruby $RBENV_ROOT/shims/rubocop"
let g:syntastic_check_on_open = 0
let g:syntastic_html_tidy_exec = ['tidy5']
let g:syntastic_scss_checkers = ['scss_lint']

Remove html 5 tidy syntax checker

" ==========================================
" Syntastic settings

let g:syntastic_javascript_syntax_checker = "jshint"
let g:syntastic_coffee_coffeelint_args = "--csv --file $HOME/.coffeelint.json"
let g:syntastic_ruby_checkers = ['mri', 'rubocop']
let g:syntastic_ruby_rubocop_exec = "$RBENV_ROOT/shims/ruby $RBENV_ROOT/shims/rubocop"
let g:syntastic_check_on_open = 0
let g:syntastic_scss_checkers = ['scss_lint']


Plug 'airblade/vim-gitgutter'
Plug 'danro/rename.vim'
Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-abolish'
Plug 'tpope/vim-cucumber'
Plug 'tpope/vim-endwise'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'
Plug 'tpope/vim-surround'
Plug 'vim-scripts/matchit.zip'
Plug 'zxqfl/tabnine-vim'

Drop tabnine until it's fixed with Apple M1s


" ============================
" Sideways Plugin
" ============================
nnoremap g<C-L> :SidewaysRight<cr>
nnoremap g<C-H> :SidewaysLeft<cr>

" ============================
" Fugitiv Plugin
" ============================
nnoremap <leader>gd :Gdiff<cr>
nnoremap <leader>gs :Gstatus<cr>
nnoremap <leader>gw :Gwrite<cr>
nnoremap <leader>ga :Gadd<cr>
nnoremap <leader>gb :Gblame<cr>
nnoremap <leader>gco :Gcheckout<cr>
nnoremap <leader>gci :Gcommit<cr>
nnoremap <leader>gm :Gmove<cr>
nnoremap <leader>gr :Gremove<cr>
nnoremap <leader>gl :Shell git gl -18<cr>:wincmd \|<cr>

Remove leftovers mappings in the wrong place


#!/usr/bin/vim -S
if has('multibyte')
	if empty(&encoding)
		call writefile(['&encoding option value is empty, even though Vim has +multibyte'], 'message.fail')
		cquit
	endif
	qall
endif
if !empty(&encoding)
	call writefile(['&encoding option value is not empty, even though Vim does not have +multibyte'], 'message.fail')
	cquit
endif

let g:powerline_config_paths = [expand('<sfile>:p:h:h') . '/powerline/config_files']

try
	source powerline/bindings/vim/plugin/powerline.vim
catch
	call writefile(['Unexpected exception:', v:exception], 'message.fail')
	cquit
endtry
set ls=2
redrawstatus!
redir => g:messages
	messages
redir END
let mess=split(g:messages, "\n")
if len(mess)>1
	call writefile(['Unexpected message(s):']+mess, 'message.fail')
	cquit
endif
qall!

Fix typo in multi_byte feature name

#!/usr/bin/vim -S
if has('multi_byte')
	if empty(&encoding)
		call writefile(['&encoding option value is empty, even though Vim has +multibyte'], 'message.fail')
		cquit
	endif
	qall
endif
if !empty(&encoding)
	call writefile(['&encoding option value is not empty, even though Vim does not have +multibyte'], 'message.fail')
	cquit
endif

let g:powerline_config_paths = [expand('<sfile>:p:h:h') . '/powerline/config_files']

try
	source powerline/bindings/vim/plugin/powerline.vim
catch
	call writefile(['Unexpected exception:', v:exception], 'message.fail')
	cquit
endtry
set ls=2
redrawstatus!
redir => g:messages
	messages
redir END
let mess=split(g:messages, "\n")
if len(mess)>1
	call writefile(['Unexpected message(s):']+mess, 'message.fail')
	cquit
endif
qall!


com! -nargs=1 -complete=dir DeployEclimd call s:deploy_eclimd(<f-args>)

function! s:deploy_eclimd(eclipsePath)
  let l:eclim_d = '/tmp/eclim'
  let l:eclipse_d = resolve(getcwd() . '/' . a:eclipsePath)
  let l:vim_d = '/tmp/vim-eclim'

  if ! executable('git')
    echom 'Please install git first.'
    return
  endif

  if ! filereadable(l:eclipse_d . '/eclipse.ini')
    echom 'Eclipse path invalid.'
    return
  endif

  " download code, build and then remove
  execute 'silent !git clone https://github.com/ervandew/eclim.git ' . l:eclim_d
  execute 'cd ' . l:eclim_d

  " always checkout last release to build from
  let l:last_tag = split(system('git tag'), '\n')[-1]
  execute 'silent !git checkout ' . l:last_tag
  execute 'silent !ant -Dvim.files=' . l:vim_d ' -Declipse.home=' . l:eclipse_d
  execute 'cd -'
  execute 'silent !rm -rf ' . l:eclim_d . ' ' . l:vim_d
endfunction

" vim: sw=2 ts=2 sts=2

Allow specifying Eclipse path by absolute path

com! -nargs=1 -complete=dir DeployEclimd call s:deploy_eclimd(<f-args>)

function! s:deploy_eclimd(eclipsePath)
  let l:eclim_d = '/tmp/eclim'
  let l:eclipse_d = resolve(getcwd() . '/' . a:eclipsePath)
  let l:vim_d = '/tmp/vim-eclim'

  if ! executable('git')
    echom 'Please install git first.'
    return
  endif

  if ! filereadable(l:eclipse_d . '/eclipse.ini') &&
        \ ! filereadable(expand(a:eclipsePath) . '/eclipse.ini')
    echom 'Eclipse path invalid.'
    return
  endif

  " download code, build and then remove
  execute 'silent !git clone https://github.com/ervandew/eclim.git ' . l:eclim_d
  execute 'cd ' . l:eclim_d

  " always checkout last release to build from
  let l:last_tag = split(system('git tag'), '\n')[-1]
  execute 'silent !git checkout ' . l:last_tag
  execute 'silent !ant -Dvim.files=' . l:vim_d ' -Declipse.home=' . l:eclipse_d
  execute 'cd -'
  execute 'silent !rm -rf ' . l:eclim_d . ' ' . l:vim_d
endfunction

" vim: sw=2 ts=2 sts=2


" Enable true color mode.
let $NVIM_TUI_ENABLE_TRUE_COLOR = 1

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

" Set font.
GuiFont Inconsolata-g for Powerline:h12

" Set color scheme and vim-airline theme dynamically.
let g:zenburn_high_Contrast = 1
let g:airline_theme = 'zenburn'
set background=dark
colorscheme zenburn

Set default fzf command in GUI

" Enable true color mode.
let $NVIM_TUI_ENABLE_TRUE_COLOR = 1

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

" Set font.
GuiFont Inconsolata-g for Powerline:h12

" Set color scheme and vim-airline theme dynamically.
let g:zenburn_high_Contrast = 1
let g:airline_theme = 'zenburn'
set background=dark
colorscheme zenburn

" Set default fzf command.
if executable('fzf') && executable('ag')
  let $FZF_DEFAULT_COMMAND = '(ag -g "")'
endif


let g:Pl#Mod#theme = []

function! Pl#Mod#UpdateTheme(theme) " {{{
	let theme = a:theme

	for mod in g:Pl#Mod#theme
		" We have to loop through instead of using index() because some
		" segments are lists!
		let target_seg_idx = -1
		for i in range(0, len(theme) - 1)
			unlet! segment
			let segment = theme[i]

			if type(segment) == type(mod.target_segment) && segment == mod.target_segment
				let target_seg_idx = i
				break
			endif
		endfor

		if mod.action == 'insert'
			" Insert segment
			if target_seg_idx != -1
				call insert(theme, mod.new_segment, (mod.where == 'before' ? target_seg_idx : target_seg_idx + 1))
			endif
		elseif mod.action == 'remove'
			" Remove segment
			if target_seg_idx != -1
				call remove(theme, target_seg_idx)
			endif
		endif
	endfor

	return theme
endfunction " }}}

Fix issue with theme update functions

let g:Pl#Mod#theme = []

function! Pl#Mod#UpdateTheme(theme) " {{{
	let theme = deepcopy(a:theme)

	for mod in g:Pl#Mod#theme
		" We have to loop through instead of using index() because some
		" segments are lists!
		let target_seg_idx = -1

		for i in range(0, len(theme) - 1)
			unlet! segment
			let segment = theme[i]

			if type(segment) == type(mod.target_segment) && segment == mod.target_segment
				let target_seg_idx = i
				break
			endif
		endfor

		if mod.action == 'insert'
			" Insert segment
			if target_seg_idx != -1
				call insert(theme, mod.new_segment, (mod.where == 'before' ? target_seg_idx : target_seg_idx + 1))
			endif
		elseif mod.action == 'remove'
			" Remove segment
			if target_seg_idx != -1
				call remove(theme, target_seg_idx)
			endif
		endif
	endfor

	return theme
endfunction " }}}


" Make mru list larger
let g:FuzzyFinderOptions = {'MruCmd': {}}
let g:FuzzyFinderOptions.MruCmd.max_item = 200

" Ignore temporary files
let g:fuzzy_ignore = "*.log,tmp/*,.svn/*,.git/*"

" Disable dicwin.vim plugin provied by kaoriya patch which is using <C-k>
let g:plugin_dicwin_disable = 1

" I'm not sure why but we can't use <SID>ExecuteCommandOnCR with FuzzyFinderBuffer
nnoremap <silent> <CR>  :if &buftype == ''<CR>execute('FuzzyFinderBuffer')<CR>else<CR>call feedkeys("\r", 'n')<CR>endif<CR>
nnoremap <silent> <C-j> :FuzzyFinderTextMate<CR>
nnoremap <silent> <C-k> :FuzzyFinderFileWithCurrentBufferDir<CR>
nnoremap <silent> <C-l> :FuzzyFinderMruFile<CR>

Expand ceiling number up to 20,000

" Make mru list larger
let g:FuzzyFinderOptions = {'MruCmd': {}}
let g:FuzzyFinderOptions.MruCmd.max_item = 200

" Ignore temporary files
let g:fuzzy_ignore = "*.log,tmp/*,.svn/*,.git/*"
let g:fuzzy_ceiling = 20000

" Disable dicwin.vim plugin provied by kaoriya patch which is using <C-k>
let g:plugin_dicwin_disable = 1

" I'm not sure why but we can't use <SID>ExecuteCommandOnCR with FuzzyFinderBuffer
nnoremap <silent> <CR>  :if &buftype == ''<CR>execute('FuzzyFinderBuffer')<CR>else<CR>call feedkeys("\r", 'n')<CR>endif<CR>
nnoremap <silent> <C-j> :FuzzyFinderTextMate<CR>
nnoremap <silent> <C-k> :FuzzyFinderFileWithCurrentBufferDir<CR>
nnoremap <silent> <C-l> :FuzzyFinderMruFile<CR>


" ~/.vim/colors.vim

if has('syntax')
  " Enable syntax highlight.
  syntax enable
  " Set 256 color terminal support.
  set t_Co=256
  " Set dark background.
  set background=dark

  " Set color scheme.
  silent! colorscheme molokai
endif

Enable Vim 8.0+ True Color support

" ~/.vim/colors.vim

if has('syntax')
  " Enable syntax highlight.
  syntax enable
  " Set 256 color terminal support.
  set t_Co=256
  " Set dark background.
  set background=dark

  " Enable True Color (vim >= 8.0).
  if has('termguicolors')
    set termguicolors
  endif

  " Set color scheme.
  silent! colorscheme molokai
endif


" Bindings
imap jj <Esc>

" Toggle spell check
nmap <silent> <leader>z :set spell!<CR>

" Start a search and replace for current word
map <Leader>rw :%s/\<<C-r><C-w>\>/

" Insert new line without going into insert mode
map <F9> O<Esc>
map <F8> o<Esc>

" map NERDtree shortcut
map <C-n> :NERDTreeToggle<CR>

" Run all specs
map <Leader>rsa :call Send_to_Tmux("bundle exec rspec spec\n")<CR>

" Run all specs/features
map <Leader>rsf :call Send_to_Tmux("bundle exec rspec spec/features\n")<CR>

map <F5> :setlocal spell! spelllang=en_us<cr>
imap <F5> <ESC> :setlocal spell! spelllang=en_us<cr>

Add key binding to save vim file as sudo

" Bindings
imap jj <Esc>

" Toggle spell check
nmap <silent> <leader>z :set spell!<CR>

" Start a search and replace for current word
map <Leader>rw :%s/\<<C-r><C-w>\>/

" Insert new line without going into insert mode
map <F9> O<Esc>
map <F8> o<Esc>

" map NERDtree shortcut
map <C-n> :NERDTreeToggle<CR>

" Run all specs
map <Leader>rsa :call Send_to_Tmux("bundle exec rspec spec\n")<CR>

" Run all specs/features
map <Leader>rsf :call Send_to_Tmux("bundle exec rspec spec/features\n")<CR>

map <F5> :setlocal spell! spelllang=en_us<cr>
imap <F5> <ESC> :setlocal spell! spelllang=en_us<cr>

map <Leader>sas :w !sudo tee %<CR>


"mark syntax errors with :signs
let g:syntastic_enable_signs=1
"automatically jump to the error when saving the file
let g:syntastic_auto_jump=0
"show the error list automatically
let g:syntastic_auto_loc_list=1
"don't care about warnings
let g:syntastic_quiet_messages = {'level': 'warnings'}

Add check for jsx syntax

"mark syntax errors with :signs
let g:syntastic_enable_signs=1
"automatically jump to the error when saving the file
let g:syntastic_auto_jump=0
"show the error list automatically
let g:syntastic_auto_loc_list=1
"don't care about warnings
let g:syntastic_quiet_messages = {'level': 'warnings'}

autocmd! BufEnter  *.jsx  let b:syntastic_checkers=['jsxhint']


" Vim compiler file
" Compiler: Py.test <http://pytest.org/>
" Maintainer: Whyme Lyu <5longluna at gmail.com>
" URL: https://github.com/5long/pytest-vim-compiler

if exists("current_compiler")
  finish
endif
let current_compiler = "pytest"

if exists(":CompilerSet") != 2 " older Vim always used :setlocal
  command -nargs=* CompilerSet setlocal <args>
endif

let s:cpo_save = &cpo
set cpo-=C

CompilerSet makeprg=py.test\ --tb=short\ -q

CompilerSet errorformat=
  \%+G%*[_]\ %m\ %*[_],
  \%A%>%f:%l:\ %.%#,
  \%-Z>%*[\ ]%m,
  \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save

Remove underscores from header messages

" Vim compiler file
" Compiler: Py.test <http://pytest.org/>
" Maintainer: Whyme Lyu <5longluna at gmail.com>
" URL: https://github.com/5long/pytest-vim-compiler

if exists("current_compiler")
  finish
endif
let current_compiler = "pytest"

if exists(":CompilerSet") != 2 " older Vim always used :setlocal
  command -nargs=* CompilerSet setlocal <args>
endif

let s:cpo_save = &cpo
set cpo-=C

CompilerSet makeprg=py.test\ --tb=short\ -q

CompilerSet errorformat=
  \%*[_]\ %m\ %*[_],
  \%A%>%f:%l:\ %.%#,
  \%-Z>%*[\ ]%m,
  \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save


" Author: Jake Zimmerman <jake@zimmerman.io>, Eddie Lebow https://github.com/elebow
" Description: eruby checker using `erubis`, instead of `erb`

function! ale_linters#eruby#erubis#GetCommand(buffer) abort
    let l:rails_root = ale#ruby#FindRailsRoot(a:buffer)

    if empty(l:rails_root)
        return 'erubis -x %t | ruby -c'
    endif

    " Rails-flavored eRuby does not comply with the standard as understood by
    " Erubis, so we'll have to do some substitution. This does not reduce the
    " effectiveness of the linter—the translated code is still evaluated.
    return 'ruby -r erubis -e ' . ale#Escape('puts Erubis::Eruby.new($stdin.read.gsub(%{<%=},%{<%})).src') . '< %t | ruby -c'
endfunction

call ale#linter#Define('eruby', {
\   'name': 'erubis',
\   'executable': 'erubis',
\   'output_stream': 'stderr',
\   'command_callback': 'ale_linters#eruby#erubis#GetCommand',
\   'callback': 'ale#handlers#ruby#HandleSyntaxErrors',
\})

Remove a Unicode character Vint complains about

" Author: Jake Zimmerman <jake@zimmerman.io>, Eddie Lebow https://github.com/elebow
" Description: eruby checker using `erubis`, instead of `erb`

function! ale_linters#eruby#erubis#GetCommand(buffer) abort
    let l:rails_root = ale#ruby#FindRailsRoot(a:buffer)

    if empty(l:rails_root)
        return 'erubis -x %t | ruby -c'
    endif

    " Rails-flavored eRuby does not comply with the standard as understood by
    " Erubis, so we'll have to do some substitution. This does not reduce the
    " effectiveness of the linter - the translated code is still evaluated.
    return 'ruby -r erubis -e ' . ale#Escape('puts Erubis::Eruby.new($stdin.read.gsub(%{<%=},%{<%})).src') . '< %t | ruby -c'
endfunction

call ale#linter#Define('eruby', {
\   'name': 'erubis',
\   'executable': 'erubis',
\   'output_stream': 'stderr',
\   'command_callback': 'ale_linters#eruby#erubis#GetCommand',
\   'callback': 'ale#handlers#ruby#HandleSyntaxErrors',
\})


command NpmStart :call NpmStartFunc()

function! NpmStartFunc()
  if filereadable('package-lock.json')
    :edit term://npm\ start
  elseif filereadable('yarn.lock')
    :edit term://yarn\ start
  else
    echo 'Not a NPM/Yarn repo'
  endif
endfunction

Add vim command to stop a npm/yarn process

command NpmStart :call NpmStartFunc()
command NpmStop :call NpmStopFunc()

function! NpmStartFunc()
  if filereadable('package-lock.json')
    :edit term://npm\ start
  elseif filereadable('yarn.lock')
    :edit term://yarn\ start
  else
    echo 'Not a NPM/Yarn repo'
  endif
  if !exists('g:npm_commands_buffer_id')
    let g:npm_commands_buffer_id = bufnr('%')
  endif
endfunction

function! NpmStopFunc()
  if exists('g:npm_commands_buffer_id')
    :execute 'bdelete!' . g:npm_commands_buffer_id
    unlet! g:npm_commands_buffer_id
  endif
endfunction


set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc

Add Python paths to nvim config

let g:python_host_prog = "/usr/local/opt/python@2/bin/python2"
let g:python3_host_prog = "/usr/local/opt/python/bin/python3"

set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc


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>

Fix first comma and first colon alignment patterns

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

"align on first =
nnoremap <silent> <Leader>a= :Tabularize /^[^=]*\zs=<CR>
vnoremap <silent> <Leader>a= :Tabularize /^[^=]*\zs=<CR>

"align on first :
nnoremap <silent> <Leader>a: :Tabularize /^[^:]*:\zs/l0c1<CR>
vnoremap <silent> <Leader>a: :Tabularize /^[^:]*:\zs/l0c1<CR>

" align on Ruby hash rocket
nnoremap <silent> <Leader>a> :Tabularize /=><CR>
vnoremap <silent> <Leader>a> :Tabularize /=><CR>

" align on first comma
nnoremap <silent> <Leader>a, :Tabularize /,\zs<CR>
vnoremap <silent> <Leader>a, :Tabularize /,\zs<CR>


pythonx << EOF
import socket

def watchd_pub():
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect('/tmp/watchd.sock')
        sock.send(b'CHANGE\n')
    except socket.error:
        # Silently ignore (the server is off, so there are no subscribers)
        return
    finally:
        sock.close()

EOF

function! WatchdNotify()
  pythonx << EOF
watchd_pub()
EOF
endfunction

autocmd BufWritePost * call WatchdNotify()

Use python3 instead of pythonx

python3 << EOF
import socket

def watchd_pub():
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect('/tmp/watchd.sock')
        sock.send(b'CHANGE\n')
    except socket.error:
        # Silently ignore (the server is off, so there are no subscribers)
        return
    finally:
        sock.close()

EOF

function! WatchdNotify()
  python3 << EOF
watchd_pub()
EOF
endfunction

autocmd BufWritePost * call WatchdNotify()


"map control-movement to move between windows
noremap <C-j> <C-w>j
noremap <C-k> <C-w>k
noremap <BS> <C-w>h
noremap <C-l> <C-w>l

Fix nvim config for new nvim version

"map control-movement to move between windows
noremap <C-j> <C-w>j
noremap <C-k> <C-w>k
noremap <C-h> <C-w>h
noremap <C-l> <C-w>l


" map meta keys for tmux-navigator
silent! execute 'set <F31>=\<Esc>h'
silent! execute 'set <F32>=\<Esc>j'
silent! execute 'set <F33>=\<Esc>k'
silent! execute 'set <F34>=\<Esc>l'
nnoremap <silent> <M-h> :TmuxNavigateLeft<CR>
nnoremap <silent> <M-j> :TmuxNavigateDown<CR>
nnoremap <silent> <M-k> :TmuxNavigateUp<CR>
nnoremap <silent> <M-l> :TmuxNavigateRight<CR>
nmap <F31> <M-h>
nmap <F32> <M-j>
nmap <F33> <M-k>
nmap <F34> <M-l>

Fix Meta keybinds in terminal

" map Meta keys for tmux-navigator
nnoremap <silent> <M-h> :TmuxNavigateLeft<CR>
nnoremap <silent> <M-j> :TmuxNavigateDown<CR>
nnoremap <silent> <M-k> :TmuxNavigateUp<CR>
nnoremap <silent> <M-l> :TmuxNavigateRight<CR>

" handle Meta keys in terminal
if !has('gui_running')
  silent! execute 'set <F31>=h'
  silent! execute 'set <F32>=j'
  silent! execute 'set <F33>=k'
  silent! execute 'set <F34>=l'
  nmap <F31> <M-h>
  nmap <F32> <M-j>
  nmap <F33> <M-k>
  nmap <F34> <M-l>
endif


set background=dark
colorscheme solarized

Patch solarized bug in terminal

set background=dark
colorscheme solarized

if colors_name == 'solarized'
  if has('gui_macvim')
    set transparency=0
  endif

  if !has('gui_running') && $TERM_PROGRAM == 'Apple_Terminal'
    let g:solarized_termcolors = &t_Co
    let g:solarized_termtrans = 1
    colorscheme solarized
  endif

  call togglebg#map("<F2>")
endif


set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc
tnoremap <Esc> <C-\><C-n>

Set cpoptions-=_, which makes "cw" work like other "w" commands.

set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc
" make it easier to get to command mode from terminal mode
tnoremap <Esc> <C-\><C-n>
" make "cw" consistent with other "w" commands
set cpoptions-=_


function! s:isAnsible()
  let filepath = expand("%:p")
  let filename = expand("%:t")
  if filepath =~ '\v/(tasks|roles|handlers)/.*\.ya?ml$' | return 1 | en
  if filepath =~ '\v/(group|host)_vars/' | return 1 | en
  if filename =~ '\v(playbook|site|main|local)\.ya?ml$' | return 1 | en

  let shebang = getline(1)
  if shebang =~# '^#!.*/bin/env\s\+ansible-playbook\>' | return 1 | en
  if shebang =~# '^#!.*/bin/ansible-playbook\>' | return 1 | en

  return 0
endfunction

function! s:setupTemplate()
  if exists("g:ansible_template_syntaxes")
    let filepath = expand("%:p")
    for syntax_name in items(g:ansible_template_syntaxes)
      let s:syntax_string = '\v/'.syntax_name[0]
      if filepath =~ s:syntax_string
        execute 'set ft='.syntax_name[1].'.jinja2'
        return
      endif
    endfor
  endif
  set ft=jinja2
endfunction

au BufNewFile,BufRead * if s:isAnsible() | set ft=yaml.ansible | en
au BufNewFile,BufRead *.j2 call s:setupTemplate()
au BufNewFile,BufRead hosts set ft=ansible_hosts

Add au ftdetects in augroups (google's coding style)

function! s:isAnsible()
  let filepath = expand("%:p")
  let filename = expand("%:t")
  if filepath =~ '\v/(tasks|roles|handlers)/.*\.ya?ml$' | return 1 | en
  if filepath =~ '\v/(group|host)_vars/' | return 1 | en
  if filename =~ '\v(playbook|site|main|local)\.ya?ml$' | return 1 | en

  let shebang = getline(1)
  if shebang =~# '^#!.*/bin/env\s\+ansible-playbook\>' | return 1 | en
  if shebang =~# '^#!.*/bin/ansible-playbook\>' | return 1 | en

  return 0
endfunction

function! s:setupTemplate()
  if exists("g:ansible_template_syntaxes")
    let filepath = expand("%:p")
    for syntax_name in items(g:ansible_template_syntaxes)
      let s:syntax_string = '\v/'.syntax_name[0]
      if filepath =~ s:syntax_string
        execute 'set ft='.syntax_name[1].'.jinja2'
        return
      endif
    endfor
  endif
  set ft=jinja2
endfunction

augroup ansible_vim_ftyaml_ansible
    au!
    au BufNewFile,BufRead * if s:isAnsible() | set ft=yaml.ansible | en
augroup END
augroup ansible_vim_ftjinja2
    au!
    au BufNewFile,BufRead *.j2 call s:setupTemplate()
augroup END
augroup ansible_vim_fthosts
    au!
    au BufNewFile,BufRead hosts set ft=ansible_hosts
augroup END


" These keys are easier to type than the default set
" We exclude semicolon because it's hard to read and
" i and l are too easy to mistake for each other slowing
" down recognition. The home keys and the immediate keys
" accessible by middle fingers are available
let g:EasyMotion_keys='asdfjkoweriop'
nmap <leader><ESC> <Plug>(easymotion-bd-w)
nmap <leader><S-ESC> <Plug>(easymotion-bd-b)

Make easymotion coherent with smart case

" These keys are easier to type than the default set
" We exclude semicolon because it's hard to read and
" i and l are too easy to mistake for each other slowing
" down recognition. The home keys and the immediate keys
" accessible by middle fingers are available
let g:EasyMotion_keys='asdfjkloweiopqrnv'
let g:EasyMotion_smartcase = 1 "With this, v will match both v and V, but V will match V only
let g:EasyMotion_use_smartsign_us = 1 " Same as above, but for symbols and numerals. 1 will match 1 and !; ! matches ! only
nmap <leader><ESC> <Plug>(easymotion-bd-w)
nmap <leader><S-ESC> <Plug>(easymotion-bd-b)


let s:loaded = 0

if g:spacevim.os.mac
  let s:path_to_chrome = 'open -a safari'
elseif g:spacevim.os.windows
  let s:path_to_chrome = 'C:\\Program Files (x86)\Google\Chrome\Application\chrome.exe'
else
  let s:path_to_chrome = 'google-chrome'
endif

function! spacevim#autocmd#markdown#Init()
  if !s:loaded
  " previm {
    let g:previm_open_cmd = s:path_to_chrome
  " }

  " vim-markdown {
    let g:vim_markdown_math = 1
    let g:vim_markdown_frontmatter = 1
    let g:vim_markdown_conceal = 0
  " }

  " vim-markdown-toc {
    let g:vmt_auto_update_on_save = 1
    let g:vmt_dont_insert_fence = 0
    let g:vim_markdown_toc_autofit = 1
  " }
  endif
  let s:loaded = 1
endfunction

Allow to use user defined setting

let s:loaded = 0

if g:spacevim.os.mac
  let s:path_to_chrome = 'open -a safari'
elseif g:spacevim.os.windows
  let s:path_to_chrome = 'C:\\Program Files (x86)\Google\Chrome\Application\chrome.exe'
else
  let s:path_to_chrome = 'google-chrome'
endif

function! spacevim#autocmd#markdown#Init()
  if !s:loaded
  " previm {
    let g:previm_open_cmd = get(g:, 'previm_open_cmd', s:path_to_chrome)
  " }

  " vim-markdown {
    let g:vim_markdown_math = 1
    let g:vim_markdown_frontmatter = 1
    let g:vim_markdown_conceal = 0
  " }

  " vim-markdown-toc {
    let g:vmt_auto_update_on_save = 1
    let g:vmt_dont_insert_fence = 0
    let g:vim_markdown_toc_autofit = 1
  " }
  endif
  let s:loaded = 1
endfunction


nnoremap <buffer> <Left> :CoqToCursor<CR>
nnoremap <buffer> <Right> :CoqToCursor<CR>
nnoremap <buffer> <Up> :CoqUndo<CR>
nnoremap <buffer> <Down> :CoqNext<CR>

inoremap <buffer> <Left> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Right> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Up> <C-o>:CoqUndo<CR>
inoremap <buffer> <Down> <C-o>:CoqNext<CR>

Add vim binding to go to last evaulated in Coq

nnoremap <buffer> <Left> :GotoDot<CR>
nnoremap <buffer> <Right> :CoqToCursor<CR>
nnoremap <buffer> <Up> :CoqUndo<CR>
nnoremap <buffer> <Down> :CoqNext<CR>

inoremap <buffer> <Left> <C-o>:GotoDot<CR>
inoremap <buffer> <Right> <C-o>:CoqToCursor<CR>
inoremap <buffer> <Up> <C-o>:CoqUndo<CR>
inoremap <buffer> <Down> <C-o>:CoqNext<CR>


" set leader key
let mapleader=","
let maplocalleader=" "
set timeoutlen=500
noremap <,> <Nop>

" make j and k move inside of a split line
noremap <silent> <expr> j (v:count == 0 ? 'gj' : 'j')
noremap <silent> <expr> k (v:count == 0 ? 'gk' : 'k')

" make HJKL jump to the extreme of their lowercase counterparts
noremap <silent> H ^
noremap <silent> L $
noremap <silent> J G
noremap <silent> K gg

" disable "ex mode"
nnoremap Q <Nop>

" set <Tab>, <S-tab> to indent/unindent lines
vnoremap <Tab> >gv
vnoremap <S-Tab> <gv
" normal mode equivalents
nnoremap <Tab> >>
nnoremap <S-Tab> <<

" since CTRL-I and <Tab> are the same key (*sigh*), we need to unclobber the original CTRL-I binding.
nnoremap <leader>CTRL-I CTRL-I

" map CTRL-L to nohlsearch
nnoremap <silent> <C-L> :nohlsearch<C-R>=has('diff')?'<Bar>diffupdate':''<CR><CR><C-L>
inoremap <C-l> <Esc><C-l>a

" toggle relative line numbering
nnoremap <silent> <leader>r :set relativenumber!<CR>

" mouse compatibility
set mouse=a

" x clipboard access
set clipboard=unnamedplus

Remove insert mode nohlsearch binding, as it doesn't work

" set leader key
let mapleader=","
let maplocalleader=" "
set timeoutlen=500
noremap <,> <Nop>

" make j and k move inside of a split line
noremap <silent> <expr> j (v:count == 0 ? 'gj' : 'j')
noremap <silent> <expr> k (v:count == 0 ? 'gk' : 'k')

" make HJKL jump to the extreme of their lowercase counterparts
noremap <silent> H ^
noremap <silent> L $
noremap <silent> J G
noremap <silent> K gg

" disable "ex mode"
nnoremap Q <Nop>

" set <Tab>, <S-tab> to indent/unindent lines
vnoremap <Tab> >gv
vnoremap <S-Tab> <gv
" normal mode equivalents
nnoremap <Tab> >>
nnoremap <S-Tab> <<

" since CTRL-I and <Tab> are the same key (*sigh*), we need to unclobber the original CTRL-I binding.
nnoremap <leader>CTRL-I CTRL-I

" map CTRL-L to nohlsearch
nnoremap <silent> <C-L> :nohlsearch<C-R>=has('diff')?'<Bar>diffupdate':''<CR><CR><C-L>

" toggle relative line numbering
nnoremap <silent> <leader>r :set relativenumber!<CR>

" mouse compatibility
set mouse=a

" x clipboard access
set clipboard=unnamedplus


" vim: et sw=2 sts=2

scriptencoding utf-8

" Function: #list_active_buffers {{{1
function! sy#debug#list_active_buffers() abort
  for b in range(bufnr('$'))
    if !buflisted(b) || empty(getbufvar(b, 'sy', {}))
      continue
    endif

    let sy = copy(getbufvar(b, 'sy'))
    let path = remove(sy, 'path')
    echo "\n". path ."\n". repeat('=', strlen(path))
    for stat in sort(keys(sy))
      echo printf("%20s  =  %s\n", stat, string(sy[stat]))
    endfor
  endfor
endfunction

Fix :SyDebug for certain corner cases

" vim: et sw=2 sts=2

scriptencoding utf-8

" Function: #list_active_buffers {{{1
function! sy#debug#list_active_buffers() abort
  for b in range(0, bufnr('$'))
    if !buflisted(b) || empty(getbufvar(b, 'sy', {}))
      continue
    endif

    let sy   = copy(getbufvar(b, 'sy'))
    let path = remove(sy, 'path')

    echo "\n". path ."\n". repeat('=', strlen(path))
    for stat in sort(keys(sy))
      echo printf("%20s  =  %s\n", stat, string(sy[stat]))
    endfor
  endfor
endfunction


" Cucumber navigation commands {{{
  Rnavcommand feature features                  -suffix=.feature
  Rnavcommand steps   features/step_definitions -suffix=_steps.rb
  Rnavcommand support features/support
" }}}

" Ember.js navigation commands {{{
  Rnavcommand econtroller app/assets/javascripts/controllers -suffix=.js.coffee  -default=controller()
  Rnavcommand ehelper     app/assets/javascripts/helpers     -suffix=.js.coffee
  Rnavcommand emodel      app/assets/javascripts/models      -suffix=.js.coffee  -default=model()
  Rnavcommand eroutes     app/assets/javascripts/routes      -suffix=.js.coffee  -default=app_router
  Rnavcommand etemplate   app/assets/javascripts/templates   -suffix=.handlebars -default=application
  Rnavcommand eview       app/assets/javascripts/views       -suffix=.js.coffee  -default=application_view
" }}}

" Uploaders
Rnavcommand uploader app/uploaders  -suffix=_uploader.rb

" Jobs/Workers
Rnavcommand worker app/workers app/jobs -suffix=.rb

" Decorators
Rnavcommand decorator app/decorators -suffix=_decorator.rb

" Serializers
Rnavcommand serializer app/serializers -suffix=_serializer.rb

" Blueprints
Rnavcommand blueprint spec/blueprints -default=model()

" Jasmine
Rnavcommand jasmine spec/javascripts -default=support/jasmine.yml

Fix Ember view & controller nav commands

" Cucumber navigation commands {{{
  Rnavcommand feature features                  -suffix=.feature
  Rnavcommand steps   features/step_definitions -suffix=_steps.rb
  Rnavcommand support features/support
" }}}

" Ember.js navigation commands {{{
  Rnavcommand econtroller app/assets/javascripts/controllers -suffix=_controller.js.coffee -default=controller()
  Rnavcommand ehelper     app/assets/javascripts/helpers     -suffix=.js.coffee
  Rnavcommand emodel      app/assets/javascripts/models      -suffix=.js.coffee            -default=model()
  Rnavcommand eroutes     app/assets/javascripts/routes      -suffix=.js.coffee            -default=app_router
  Rnavcommand etemplate   app/assets/javascripts/templates   -suffix=.handlebars           -default=application
  Rnavcommand eview       app/assets/javascripts/views       -suffix=_view.js.coffee       -default=application_view
" }}}

" Uploaders
Rnavcommand uploader app/uploaders  -suffix=_uploader.rb

" Jobs/Workers
Rnavcommand worker app/workers app/jobs -suffix=.rb

" Decorators
Rnavcommand decorator app/decorators -suffix=_decorator.rb

" Serializers
Rnavcommand serializer app/serializers -suffix=_serializer.rb

" Blueprints
Rnavcommand blueprint spec/blueprints -default=model()

" Jasmine
Rnavcommand jasmine spec/javascripts -default=support/jasmine.yml


" Add shortcuts for Autoformat.
nnoremap <Leader>+ :Autoformat<CR>
vnoremap <Leader>+ :Autoformat<CR>

Add <C-U> to Autoformat shortcut

" Add shortcuts for Autoformat.
nnoremap <Leader>+ :<C-U>Autoformat<CR>
vnoremap <Leader>+ :Autoformat<CR>


" Cameron Rossington File definition vimscript
" created 170605

" ##### Python #####
au BufNewFile,BufRead *.py,*.pyw  "PEP8 style settings
  \ set tabstop=4       |
  \ set softtabstop=4   |
  \ set shiftwidth=4    |
  \ set expandtab       |
  \ set autoindent      |
  \ set fileformat=unix |
  \ setlocal colorcolumn=100

" ##### Web Files #####
au BufNewFile,BufRead *.js,*.css,*.htm,*.html,*.php
  \ set tabstop=2     |
  \ set softtabstop=2 |
  \ set shiftwidth=2  |
  \ set noexpandtab   |
  \ set autoindent    |
  \ set fileformat=unix

" ##### C files #####
au BufNewFile,BufRead *.c,*.h
  \ set tabstop=4     |
  \ set softtabstop=4 |
  \ set shiftwidth=4  |
  \ set noexpandtab   |
  \ set filetype=c    |
  \ set colorcolumn=100

" ##### journal files #####
au BufNewFile,BufRead *.jo
  \ set wrap |
  \ set cc=0 |
  \ set nonumber

" ##### test/status files #####
au BufNewFile,BufRead *.txt
  \ set cc=0    |
  \ set autoread

" ##### logfiles #####
au BufNewFile,BufRead *.log
  \ set cc=0
  \ set foldlevel = 1

Add automatic change to directory in log file augroup.

" Cameron Rossington File definition vimscript
" created 170605

" ##### Python #####
au BufNewFile,BufRead *.py,*.pyw  "PEP8 style settings
  \ set tabstop=4       |
  \ set softtabstop=4   |
  \ set shiftwidth=4    |
  \ set expandtab       |
  \ set autoindent      |
  \ set fileformat=unix |
  \ setlocal colorcolumn=100

" ##### Web Files #####
au BufNewFile,BufRead *.js,*.css,*.htm,*.html,*.php
  \ set tabstop=2     |
  \ set softtabstop=2 |
  \ set shiftwidth=2  |
  \ set noexpandtab   |
  \ set autoindent    |
  \ set fileformat=unix

" ##### C files #####
au BufNewFile,BufRead *.c,*.h
  \ set tabstop=4     |
  \ set softtabstop=4 |
  \ set shiftwidth=4  |
  \ set noexpandtab   |
  \ set filetype=c    |
  \ set colorcolumn=100

" ##### journal files #####
au BufNewFile,BufRead *.jo
  \ set wrap |
  \ set cc=0 |
  \ set nonumber

" ##### test/status files #####
au BufNewFile,BufRead *.txt
  \ set cc=0    |
  \ set autoread

" ##### logfiles #####
au BufNewFile,BufRead *.log
  \ set cc=0
  \ set foldlevel = 1
  \ if @% =~ "status" | cd %:p:h | endif " changes cwd to current file


if exists('g:loaded_nvim_go')
  finish
endif
let g:loaded_nvim_go = 1

let g:go#def#filer = get(g:, 'go#def#filer', 'Explore')
let g:go#guru#reflection = get(g:, 'go#guru#reflection', 0)
let g:go#fmt#async = get(g:, 'go#fmt#async', 0)

let s:plugin_name = 'nvim-go'
let s:goos = $GOOS
let s:goarch = $GOARCH
let s:plugin_path = fnamemodify(resolve(expand('<sfile>:p')), ':h:h') . '/bin/' . s:plugin_name . '-' . s:goos . '-' . s:goarch

" function! s:RequireNvimGo(host) abort
"     return rpcstart(s:plugin_path, ['plugin'])
" endfunction

function! s:RequireNvimGo(host) abort
  let args = []
  try
    for plugin in remote#host#PluginsForHost(a:host.name)
        call add(args, plugin.path)
    endfor
    return rpcstart(s:plugin_path, args)
  catch
    echomsg v:exception
  endtry
  throw 'Failed to load ' . s:plugin_name . ' host'.
endfunction

call remote#host#Register('go/' . s:plugin_name, '*', function('s:RequireNvimGo'))

Fix register rplugin vim script

if exists('g:loaded_nvim_go')
  finish
endif
let g:loaded_nvim_go = 1

let g:go#def#filer = get(g:, 'go#def#filer', 'Explore')
let g:go#guru#reflection = get(g:, 'go#guru#reflection', 0)
let g:go#fmt#async = get(g:, 'go#fmt#async', 0)

let s:plugin_name = 'nvim-go'
let s:goos = $GOOS
let s:goarch = $GOARCH
let s:plugin_path = fnamemodify(resolve(expand('<sfile>:p')), ':h:h') . '/bin/' . s:plugin_name . '-' . s:goos . '-' . s:goarch

function! s:RequireNvimGo(host) abort
  " Collect registered Go plugins into args
  let args = []
  let go_plugins = remote#host#PluginsForHost(a:host.name)

  for plugin in go_plugins
    call add(args, plugin.path)
  endfor

  try
    let channel_id = rpcstart(s:plugin_path, args)

    return channel_id
  catch
    echomsg v:throwpoint
    echomsg v:exception
  endtry

  throw remote#host#LoadErrorForHost(a:host.orig_name, '$NVIM_GO_LOG_FILE')
endfunction

call remote#host#Register('go/' . s:plugin_name, '*', function('s:RequireNvimGo'))


set background=dark

colorscheme hybrid

" 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

Switch colorscheme from Hybrid to jellybeans

set background=dark
colorscheme jellybeans


if did_filetype() " filetype already set..
  finish          " ..don't do these checks
endif
if getline(1) =~ '^#!/bin/\(ba\)?sh'
  setfiletype sh
elseif getline(1) =~ '^#!/usr/bin/env awesome-bash'
  setfiletype sh
elseif getline(2) =~ '^Index: '
  setfiletype diff
endif

Replace vim shell file type recognition using one regex

if did_filetype() " filetype already set..
  finish          " ..don't do these checks
endif
if getline(1) =~ '^#\!\(\/usr\)\{0,1\}\/bin\/\(env \)\{0,1\}\(awesome-\)\{0,1\}\(ba\)\{0,1\}sh'
  " recognize /usr/bin/env bash and /usr/bin/env sh
  " recognize /bin/bash
  " recognize /usr/bin/env awesome-bash (https://github.com/antontsv/awesome-shell)
  setfiletype sh
elseif getline(2) =~ '^Index: '
  setfiletype diff
endif


" for crontab editing
au! FileType crontab setlocal bkc=yes

au! BufNewFile,BufRead *.phl,*.pht,.php_cs      set filetype=php
au! BufNewFile,BufRead *.sql,*.SQL              set filetype=pgsql
au! BufNewFile,BufRead *.tpl,*.tmpl,*.xml.dist  set filetype=xml
au! BufNewFile,BufRead *.md                     set filetype=markdown
au! BufNewFile,BufRead composer.lock            set filetype=json
au! BufNewFile,BufRead docker-compose.yml.*     set filetype=yaml
au! BufNewFile,BufRead .env.*                   set filetype=sh

au FileType php let b:syntastic_php_phpmd_args =
    \ @% . ' text /home/sol/.vim/php/phpmd.xml'

au FileType tagbar,nerdtree setlocal signcolumn=no

au FileType yaml setlocal ts=2 sw=2
au FileType html setlocal ts=2 sw=2

Set tab=2 spaces for yaml, html and JS in vim

" for crontab editing
au! FileType crontab setlocal bkc=yes

au! BufNewFile,BufRead *.phl,*.pht,.php_cs      set filetype=php
au! BufNewFile,BufRead *.sql,*.SQL              set filetype=pgsql
au! BufNewFile,BufRead *.tpl,*.tmpl,*.xml.dist  set filetype=xml
au! BufNewFile,BufRead *.md                     set filetype=markdown
au! BufNewFile,BufRead composer.lock            set filetype=json
au! BufNewFile,BufRead docker-compose.yml.*     set filetype=yaml
au! BufNewFile,BufRead .env.*                   set filetype=sh

au FileType php let b:syntastic_php_phpmd_args =
    \ @% . ' text /home/sol/.vim/php/phpmd.xml'

au FileType tagbar,nerdtree setlocal signcolumn=no

au FileType yaml        setlocal ts=2 sw=2
au FileType html        setlocal ts=2 sw=2
au FileType javascript  setlocal ts=2 sw=2


if has('python')
python << EOF
import os, vim
items = set(os.listdir('.'))
items -= {'.git', 'lib'}
vim.command('nnoremap <leader>k :silent !git difftool -d ' + ' '.join(items) + ' -d &<CR>')
EOF
endif

set wildignore+=*.pyj-cached
set wildignore+=node_modules

Fix simple diff failling because of un-escaped = character in filename

if has('python')
python << EOF
import os, vim
items = {x.replace('=', r'\=') for x in os.listdir('.')}
items -= {'.git', 'lib'}
vim.command('nnoremap <leader>k :silent !git difftool -d ' + ' '.join(items) + ' -d &<CR>')
EOF
endif

set wildignore+=*.pyj-cached
set wildignore+=node_modules


set omnifunc=csscomplete#CompleteCSS

set textwidth=130
set nowrap

" use TAB character when TAb is pressed
set noexpandtab

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

" number of spaces for indent when indenting with >>
set shiftwidth=4

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

set smartindent
set smartcase
set noincsearch

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

" F2 uncomment line
map <F2> :s/\/\*//<enter>:s/\*\///<enter>:noh<enter>j
imap <F2> <esc>:s/\/\*//<enter>:s/\*\///<enter>:noh<enter>j

" F4 header
map <F4> <esc>1GO/*<return> * Creation Date: <esc>:r! LC_TIME=us date "+\%Y.\%m.\%d"<return><esc><esc>kJo* Author: Fernando L. Canizo - http://flc.muriandre.com/<return>*/<esc>o<return>

Change CSS header, leave only creation date

set omnifunc=csscomplete#CompleteCSS

set textwidth=130
set nowrap

" use TAB character when TAb is pressed
set noexpandtab

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

" number of spaces for indent when indenting with >>
set shiftwidth=4

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

set smartindent
set smartcase
set noincsearch

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

" F2 uncomment line
map <F2> :s/\/\*//<enter>:s/\*\///<enter>:noh<enter>j
imap <F2> <esc>:s/\/\*//<enter>:s/\*\///<enter>:noh<enter>j

" F4 header
map <F4> <esc>1GO/* Creation Date: <esc>:r! LC_TIME=us date "+\%Y.\%m.\%d"<return>kJA */<esc>o<return>


" Turn on syntax folding in ruby files
let ruby_fold=1
" Open all folds when a ruby file is opened (otherwise, the file starts folded)
autocmd FileType ruby set foldlevel=99
" Turn on syntax highlighting for ruby operators (==, ||, &&, etc)
let ruby_operators=1

Disable folding in Ruby due to performance issues


autocmd FileType css set shiftwidth=4
autocmd FileType scss set shiftwidth=4
autocmd FileType sass set shiftwidth=4
autocmd FileType less set shiftwidth=4

Use two spaces for indentation

autocmd FileType css set shiftwidth=2
autocmd FileType scss set shiftwidth=2
autocmd FileType sass set shiftwidth=2
autocmd FileType less set shiftwidth=2


function! Load_Rainbow()
    call rainbow_parentheses#load(0)
    call rainbow_parentheses#load(1)
    call rainbow_parentheses#load(2)
    call rainbow_parentheses#load(3)
    call rainbow_parentheses#activate()
endfunction

augroup TasteTheRainbow
    autocmd!
    autocmd VimEnter,BufRead,BufWinEnter,BufNewFile * call Load_Rainbow()
augroup END

Disable rainbow colouring of <> brackets.

function! Load_Rainbow()
    call rainbow_parentheses#load(0)
    call rainbow_parentheses#load(1)
    call rainbow_parentheses#load(2)
    call rainbow_parentheses#activate()
endfunction

augroup TasteTheRainbow
    autocmd!
    autocmd VimEnter,BufRead,BufWinEnter,BufNewFile * call Load_Rainbow()
augroup END


" Set maximum terminal color space.
set t_Co=256

" Disable Powerline.
let g:powerline_loaded = 1

" Use Powerline fonts for vim-airline.
let g:airline_powerline_fonts = 1

" Set promptline.vim theme.
let g:promptline_theme = 'airline'

" Set colorscheme.
if has('gui_running')
  let g:airline#extensions#tmuxline#enabled = 0
  colorscheme molokai
  set background=dark
else
  set background=dark
  colorscheme solarized
endif

" Set font.
if has('gui_running')
  set guifont=Inconsolata\-g\ 11
endif

Set larger font for Gungnir.

" Set maximum terminal color space.
set t_Co=256

" Disable Powerline.
let g:powerline_loaded = 1

" Use Powerline fonts for vim-airline.
let g:airline_powerline_fonts = 1

" Set promptline.vim theme.
let g:promptline_theme = 'airline'

" Set colorscheme.
if has('gui_running')
  let g:airline#extensions#tmuxline#enabled = 0
  colorscheme molokai
  set background=dark
else
  set background=dark
  colorscheme solarized
endif

" Set font.
if has('gui_running')
  set guifont=Inconsolata\-g\ 11

  if hostname() == 'Gungnir'
    set guifont=Inconsolata\-g\ 18
  endif
endif


map <Enter> <Plug>(expand_region_expand)
map <S-Enter> <Plug>(expand_region_shrink)

call expand_region#custom_text_objects({
      \ 'a]' :1,
      \ 'ab' :1,
      \ 'aB' :1,
      \ 'ii' :0,
      \ 'ai' :0,
      \ })

Fix quickfix not opening files on enter

map ,<CR> <Plug>(expand_region_expand)
map ,<S-CR> <Plug>(expand_region_shrink)

call expand_region#custom_text_objects({
      \ 'a]' :1,
      \ 'ab' :1,
      \ 'aB' :1,
      \ 'ii' :0,
      \ 'ai' :0,
      \ })


let g:ale_sign_error=''
let g:ale_sign_style_error=''
let g:ale_sign_warning=''
let g:ale_sign_style_warning=''
let g:ale_sign_info=''

augroup LightLineALEUpdate
    autocmd!
    autocmd User ALELint call lightline#update()
augroup END

" Press `K` to view the type in the gutter
nnoremap <silent> K :ALEHover<CR>
" Type `gd` to go to definition
nnoremap <silent> gd :ALEGoToDefinition<CR>
" gk shows more details about an error
nnoremap <silent> gk :ALEDetail<CR>
" Find references for a function/variable
map <leader>u :ALEFindReferences<CR>
" Meta-click (command-click) to go to definition
nnoremap <M-LeftMouse> <LeftMouse>:ALEGoToDefinition<CR>

" Message format
let g:ale_echo_msg_format = "[%linter%]%[ code]% %s"

" Autoformat
let g:ale_fixers = { '*': ['remove_trailing_lines', 'trim_whitespace'] }
let g:ale_fix_on_save = 1
noremap <leader>ff :ALEFix<CR>

Add more mappings for ALE go to definition

let g:ale_sign_error=''
let g:ale_sign_style_error=''
let g:ale_sign_warning=''
let g:ale_sign_style_warning=''
let g:ale_sign_info=''

augroup LightLineALEUpdate
    autocmd!
    autocmd User ALELint call lightline#update()
augroup END

" Press `K` to view the type in the gutter
nnoremap <silent> K :ALEHover<CR>
" Type `gd` to go to definition
nnoremap <silent> gd :ALEGoToDefinition<CR>
nnoremap <silent> gsd :ALEGoToDefinitionInSplit<CR>
nnoremap <silent> gvd :ALEGoToDefinitionInVSplit<CR>
nnoremap <silent> gtd :ALEGoToDefinitionTab<CR>
" gk shows more details about an error
nnoremap <silent> gk :ALEDetail<CR>
" Find references for a function/variable
map <leader>u :ALEFindReferences<CR>
" Meta-click (command-click) to go to definition
nnoremap <M-LeftMouse> <LeftMouse>:ALEGoToDefinition<CR>

" Message format
let g:ale_echo_msg_format = "[%linter%]%[ code]% %s"

" Autoformat
let g:ale_fixers = { '*': ['remove_trailing_lines', 'trim_whitespace'] }
let g:ale_fix_on_save = 1
noremap <leader>ff :ALEFix<CR>


"
" DevIcons
"

" Enable folder/directory glyph flag (disabled by default with 0)
let g:WebDevIconsUnicodeDecorateFolderNodes = 1

" Enable open and close folder/directory glyph flags (disabled by default with 0)
let g:DevIconsEnableFoldersOpenClose = 1

"
" For powerline:
"

set rtp+=$HOME/.local/lib/python2.7/site-packages/powerline/bindings/vim/

" Always show statusline
set laststatus=2

" Use 256 colours (Use this setting only if your terminal supports 256 colours)
set t_Co=256

" NOTE: Necessary for proper integration with vim-airline
" let g:airline_powerline_fonts = 1

Disable powerline settings since we're using airline

"
" DevIcons
"

" Enable folder/directory glyph flag (disabled by default with 0)
let g:WebDevIconsUnicodeDecorateFolderNodes = 1

" Enable open and close folder/directory glyph flags (disabled by default with 0)
let g:DevIconsEnableFoldersOpenClose = 1

"
" For Powerline:
"

" set runtimepath+=$HOME/.local/lib/python2.7/site-packages/powerline/bindings/vim/

" " Always show statusline
" set laststatus=2

" " Use 256 colours (Use this setting only if your terminal supports 256 colours)
" set t_Co=256


" Plugins (vim-plug)
call plug#begin('~/.local/share/nvim/plugged')
Plug 'chriskempson/base16-vim'
Plug 'itchyny/lightline.vim'
Plug 'daviesjamie/vim-base16-lightline'
Plug 'editorconfig/editorconfig-vim'
Plug 'christoomey/vim-tmux-navigator'
call plug#end()

" set colorscheme to match terminal
if filereadable(expand("~/.vimrc_background"))
  let base16colorspace=256
  source ~/.vimrc_background
endif

" set lightline theme
let g:lightline = { 'colorscheme': 'base16' }

" show line numbers
set relativenumber

" list settings
nmap <leader>l :set list!<CR>
set list listchars=tab:\¦\ ,eol:¬,trail:.

" break bad habits
noremap <Up> <nop>
noremap <Down> <nop>
noremap <Left> <nop>
noremap <Right> <nop>

" remap Escape key
inoremap jj <Esc>

" easier split navigation
nnoremap <C-j> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

Remove nvim relative line numbering

" Plugins (vim-plug)
call plug#begin('~/.local/share/nvim/plugged')
Plug 'chriskempson/base16-vim'
Plug 'itchyny/lightline.vim'
Plug 'daviesjamie/vim-base16-lightline'
Plug 'editorconfig/editorconfig-vim'
Plug 'christoomey/vim-tmux-navigator'
call plug#end()

" set colorscheme to match terminal
if filereadable(expand("~/.vimrc_background"))
  let base16colorspace=256
  source ~/.vimrc_background
endif

" set lightline theme
let g:lightline = { 'colorscheme': 'base16' }

" show line numbers
set number

" list settings
nmap <leader>l :set list!<CR>
set list listchars=tab:\¦\ ,eol:¬,trail:.

" break bad habits
noremap <Up> <nop>
noremap <Down> <nop>
noremap <Left> <nop>
noremap <Right> <nop>

" remap Escape key
inoremap jj <Esc>

" easier split navigation
nnoremap <C-j> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>


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

Plug 'chriskempson/base16-vim'                                          " base16 themes
Plug 'tpope/vim-fugitive', {'for': []}                                  " git <3
Plug 'scrooloose/syntastic'                                             " syntax checking
Plug 'editorconfig/editorconfig-vim'
Plug 'ctrlpvim/ctrlp.vim'                                               " fuzzy searching
Plug 'airblade/vim-gitgutter'                                           " show what lines have changed when inside a git repo
Plug 'valloric/youcompleteme', {'do': './install.py --clang-completer'} " completion
Plug 'haya14busa/incsearch.vim'                                         " a better insearch
Plug 'junegunn/vim-easy-align'                                          " easy align text
Plug 'jamessan/vim-gnupg', {'for': []}                                  " transparent editing of gpg files
Plug 'plasticboy/vim-markdown', {'for': 'markdown'}                     " Markdown vim mode
Plug 'mhinz/vim-startify'                                               " the fancy start screen for vim
Plug 'tpope/vim-eunuch'                                                 " helpers for UNIX
Plug 'easymotion/vim-easymotion'                                        " Vim motions on speed

" Add plugins to &runtimepath
call plug#end()

Use PGP for GPG files

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

Plug 'chriskempson/base16-vim'                                          " base16 themes
Plug 'tpope/vim-fugitive', {'for': []}                                  " git <3
Plug 'scrooloose/syntastic'                                             " syntax checking
Plug 'editorconfig/editorconfig-vim'
Plug 'ctrlpvim/ctrlp.vim'                                               " fuzzy searching
Plug 'airblade/vim-gitgutter'                                           " show what lines have changed when inside a git repo
Plug 'valloric/youcompleteme', {'do': './install.py --clang-completer'} " completion
Plug 'haya14busa/incsearch.vim'                                         " a better insearch
Plug 'junegunn/vim-easy-align'                                          " easy align text
Plug 'jamessan/vim-gnupg' " transparent editing of gpg files
Plug 'plasticboy/vim-markdown', {'for': 'markdown'}                     " Markdown vim mode
Plug 'mhinz/vim-startify'                                               " the fancy start screen for vim
Plug 'tpope/vim-eunuch'                                                 " helpers for UNIX
Plug 'easymotion/vim-easymotion'                                        " Vim motions on speed

" Add plugins to &runtimepath
call plug#end()


function! s:MarkQF() abort
  if !qf#IsQfWindowOpen()
    let g:quickfix_pending = 1
  endif
endfunction

function! s:UnmarkQF() abort
  if qf#IsQfWindow(winnr()) && exists('g:quickfix_pending')
    unlet g:quickfix_pending
  endif
endfunction

augroup QfAfter
  autocmd!

  autocmd QuickFixCmdPost [^l]* call s:MarkQF()
  autocmd WinEnter * call s:UnmarkQF()
augroup END

Make s:UnmarkQF() rely on Filetype instead

function! s:MarkQF() abort
  if !qf#IsQfWindowOpen()
    let g:quickfix_pending = 1
  endif
endfunction

function! s:UnmarkQF() abort
  if exists('g:quickfix_pending')
    unlet g:quickfix_pending
  endif
endfunction

augroup QfAfter
  autocmd!

  autocmd QuickFixCmdPost [^l]* call s:MarkQF()
  autocmd Filetype qf call s:UnmarkQF()
augroup END


" 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:
" - Get dirvish to refresh
" - q mapping
" - Mapping to open 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(?)

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

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

" Create a new note.
function! CreateNote()
  call inputsave()
  let l:note_name = input('Note name: ')
  call inputrestore()
  execute ':split ~/Dropbox/Notes/' . join(split(tolower(l:note_name)), '-') . '.md'
  call setline(1, '# ' . l:note_name)
  call setline(2, '')
  execute ':write'
endfunction
nnoremap <leader>n :call CreateNote()<CR>

Add todo item to naive note plugin

" 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:
" - Get dirvish to refresh
" - q mapping
" - Mapping to open archive
" - Consistent interface (NaiveNote new, NaiveNote list, etc)
" - 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(?)

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

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

" Create a new note.
function! CreateNote()
  call inputsave()
  let l:note_name = input('Note name: ')
  call inputrestore()
  execute ':split ~/Dropbox/Notes/' . join(split(tolower(l:note_name)), '-') . '.md'
  call setline(1, '# ' . l:note_name)
  call setline(2, '')
  execute ':write'
endfunction
nnoremap <leader>n :call CreateNote()<CR>


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 the Q letter to hard-wrapping specific sections
map Q gq

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

" Special overrides for specific filetypes
autocmd FileType yaml setlocal tabstop=2 softtabstop=2 shiftwidth=2 expandtab
autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab

Add indentation controls based on style guides

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 the Q letter to hard-wrapping specific sections
map Q gq

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

" Special overrides for specific filetypes
autocmd FileType yaml   setlocal tabstop=2 softtabstop=2 shiftwidth=2 expandtab  " based on http://yaml.org/spec/1.2/2009-07-21/spec.html#id2576668
autocmd FileType php    setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab  " based on http://www.php-fig.org/psr/psr-2/#indenting
autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab  " based on https://www.python.org/dev/peps/pep-0008/#indentation


" Text indentation, special chars, wrapping
set shiftwidth=4
set softtabstop=4
set tabstop=4

" Some file types use real tabs
au FileType {make,gitconfig} set noexpandtab sw=4

set splitright " Vertical split on right
set splitbelow " Horizontal split on below
set showtabline=2 " Always display tabline > prevents window resizing when closing down to just one tab

set relativenumber

Make diffs vertical by default

" Text indentation, special chars, wrapping
set shiftwidth=4
set softtabstop=4
set tabstop=4

" Some file types use real tabs
au FileType {make,gitconfig} set noexpandtab sw=4

set splitright " Vertical split on right
set splitbelow " Horizontal split on below
set showtabline=2 " Always display tabline > prevents window resizing when closing down to just one tab

set relativenumber
set diffopt+=vertical


" Vim plugin file
" Language:    JS Lib syntax loader
" Maintainer:  othree <othree@gmail.com>
" Last Change: 2013/02/24
" Version:     0.3
" URL:         https://github.com/othree/javascript-libraries-syntax.vim

let s:libs = [
  \ 'jquery',
  \ 'underscore',
  \ 'backbone',
  \ 'prelude',
  \ 'angularjs',
  \ 'requirejs'
  \ ]

let s:path = expand('<sfile>:p:h')

function! jslibsyntax#load()
  if exists('b:javascript_libraries_syntax')
    return
  endif
  let b:javascript_libraries_syntax = 1

  if !exists('g:used_javascript_libs')
    let g:used_javascript_libs = join(s:libs, ',')
  endif

  let index = 0
  let loaded = 0
  while index < len(s:libs)
    let lib = s:libs[index]
    let use = g:used_javascript_libs =~ lib
    if exists('b:javascript_lib_use_'.lib)
      exec('let use = b:javascript_lib_use_'.lib)
    endif
    if use
      let fn = s:path.'/syntax/'.lib.'.'.&filetype.'.vim'
      if filereadable(fn)
        exe('source '.fn)
        let loaded = loaded + 1
      endif
    endif
    let index = index + 1
  endwhile
  if loaded > 0
    exe('source '.s:path.'/syntax/postprocess.'.&filetype.'.vim')
  endif
endfunction

Remove load protect, since syntax will be cleanup when set filetype

" Vim plugin file
" Language:    JS Lib syntax loader
" Maintainer:  othree <othree@gmail.com>
" Last Change: 2013/02/24
" Version:     0.3
" URL:         https://github.com/othree/javascript-libraries-syntax.vim

let s:libs = [
  \ 'jquery',
  \ 'underscore',
  \ 'backbone',
  \ 'prelude',
  \ 'angularjs',
  \ 'requirejs'
  \ ]

let s:path = expand('<sfile>:p:h')

function! jslibsyntax#load()
  if !exists('g:used_javascript_libs')
    let g:used_javascript_libs = join(s:libs, ',')
  endif

  let index = 0
  let loaded = 0
  while index < len(s:libs)
    let lib = s:libs[index]
    let use = g:used_javascript_libs =~ lib
    if exists('b:javascript_lib_use_'.lib)
      exec('let use = b:javascript_lib_use_'.lib)
    endif
    if use
      let fn = s:path.'/syntax/'.lib.'.'.&filetype.'.vim'
      if filereadable(fn)
        exe('source '.fn)
        let loaded = loaded + 1
      endif
    endif
    let index = index + 1
  endwhile
  if loaded > 0
    exe('source '.s:path.'/syntax/postprocess.'.&filetype.'.vim')
  endif
endfunction


" --------------------------------------------------------------------------
" Dusk Colour Scheme
" --------------------------------------------------------------------------

hi clear

if exists("syntax_on")
    syntax reset
endif

let colors_name = "dusk"

hi Comment      ctermfg=8
hi Normal       ctermfg=none        ctermbg=none
hi NonText      ctermfg=none        ctermbg=none
hi LineNr       ctermfg=8
hi CursorLineNr ctermfg=8
hi String       ctermfg=3
hi Keyword      ctermfg=2
hi Statement    ctermfg=2
hi Function     ctermfg=4
hi PreProc      ctermfg=5
hi Constant     ctermfg=6
hi Character    ctermfg=6
hi Number       ctermfg=6

Add selection styles to vim colorscheme

" --------------------------------------------------------------------------
" Dusk Colour Scheme
" --------------------------------------------------------------------------

hi clear

if exists("syntax_on")
    syntax reset
endif

let colors_name = "dusk"

hi Comment      ctermfg=8
hi Normal       ctermfg=none        ctermbg=none
hi NonText      ctermfg=none        ctermbg=none
hi LineNr       ctermfg=8
hi CursorLineNr ctermfg=8
hi String       ctermfg=3
hi Keyword      ctermfg=2
hi Statement    ctermfg=2
hi Function     ctermfg=4
hi PreProc      ctermfg=5
hi Constant     ctermfg=6
hi Character    ctermfg=6
hi Number       ctermfg=6
hi Visual                           ctermbg=235


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
"highlight CursorLine guibg=#073642 guifg=#839496

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

Add gracefull fallback for non-truecolor terminals

set mouse=a
syntax on

set colorcolumn=81 cursorline
set ruler showcmd title showmode modeline

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

if ! has("gui_running")
	" Use a transparent background in neosolarized when in terminal
	let g:neosolarized_termtrans=1
endif

" Detect if display used has support for "true" colors
if has("gui_running") || &t_Co >= 256
	let truecolor = 1
else
	let truecolor = 0
endif

if truecolor == 1
	" Use gui colors even in terminal mode
	set termguicolors

	" Use dark colors always, never light background
	set background=dark

	colorscheme NeoSolarized

	" 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
endif


" CtrlP
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
let g:ctrlp_prompt_mappings = {
    \ 'AcceptSelection("e")': ['<c-t>'],
    \ 'AcceptSelection("t")': ['<cr>', '<2-LeftMouse>'],
    \ }

" Set ts
function! SetIndent(size)
  let &ts=a:size
  let &sw=a:size
  let &sts=a:size
endfunction
call SetIndent(2)
command! -nargs=1 Ts call SetIndent(<f-args>)

" Sets
set cursorline
set colorcolumn=80

" Mouse setting
set mouse=nicr

" Colorscheme
colorscheme gruvbox
set background=dark
hi Comment cterm=None

" xterm settings
set term=xterm-256color
set t_Co=256
set t_ut=

" 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>

Add a line to render gruvbox correctly.

" CtrlP
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
let g:ctrlp_prompt_mappings = {
    \ 'AcceptSelection("e")': ['<c-t>'],
    \ 'AcceptSelection("t")': ['<cr>', '<2-LeftMouse>'],
    \ }

" Set ts
function! SetIndent(size)
  let &ts=a:size
  let &sw=a:size
  let &sts=a:size
endfunction
call SetIndent(2)
command! -nargs=1 Ts call SetIndent(<f-args>)

" Sets
set cursorline
set colorcolumn=80

" Mouse setting
set mouse=nicr

" Colorscheme
colorscheme gruvbox
set background=dark
hi Comment cterm=None
silent !~/.vim/bundle/gruvbox/gruvbox_256palette_osx.sh

" xterm settings
set term=xterm-256color
set t_Co=256
set t_ut=

" 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>


" --------------------------------
"  Function(s)
" --------------------------------
function! VimBootstrapUpdate()
   let langs = join(split(g:vim_bootstrap_langs, ','), '&langs=')
   let frams = join(split(g:vim_bootstrap_frams, ','), '&frameworks=')
   let editor = g:vim_bootstrap_editor
   let theme = g:vim_bootstrap_theme
   let path = $MYVIMRC
   let data = 'langs='.langs.'&editor='.editor.'&theme='.theme.'&frameworks='.frams
   silent exec '!curl -fLso '.path.' http://vim-bootstrap.com/generate.vim --data "'.data.'"' | redr!
   echo path.' sucesfully updated! '
endfunction

" --------------------------------
"  Expose our commands to the user
" --------------------------------
command! VimBootstrapUpdate call VimBootstrapUpdate()

Use https instead of http avoiding bug

" --------------------------------
"  Function(s)
" --------------------------------
function! VimBootstrapUpdate()
   let langs = join(split(g:vim_bootstrap_langs, ','), '&langs=')
   let frams = join(split(g:vim_bootstrap_frams, ','), '&frameworks=')
   let editor = g:vim_bootstrap_editor
   let theme = g:vim_bootstrap_theme
   let path = $MYVIMRC
   let data = 'langs='.langs.'&editor='.editor.'&theme='.theme.'&frameworks='.frams
   silent exec '!curl -fLso '.path.' https://vim-bootstrap.com/generate.vim --data "'.data.'"' | redr!
   echo path.' sucesfully updated! '
endfunction

" --------------------------------
"  Expose our commands to the user
" --------------------------------
command! VimBootstrapUpdate call VimBootstrapUpdate()


let g:syntastic_enable_signs=1
autocmd FileType javascript let b:syntastic_checkers = findfile('.jscsrc', '.;') != '' ? ['jscs'] : ['jshint']

Use eslint if .eslintrc is present

let g:syntastic_enable_signs=1
autocmd FileType javascript let b:syntastic_checkers = findfile('.eslintrc', '.;') != '' ? ['eslint'] : (findfile('.jscsrc', '.;') != '' ? ['jscs'] : ['jshint'])


" vundle.vim
" note: comments after Bundle commands are not allowed.

filetype off                  " required!
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
" Bundle foo

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ

Use Vundle for solarized theme

" vundle.vim
" note: comments after Bundle commands are not allowed.

filetype off                  " required!
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" Start bundle list -----------------------------

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
Bundle 'altercation/vim-colors-solarized'

" End bundle list -------------------------------

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ


" Language:    CoffeeScript
" Maintainer:  Mick Koch <kchmck@gmail.com>
" URL:         http://github.com/kchmck/vim-coffee-script
" License:     WTFPL

if exists("b:did_ftplugin")
  finish
endif

let b:did_ftplugin = 1

setlocal formatoptions-=t formatoptions+=croql
setlocal comments=f:###,:#
setlocal commentstring=#\ %s

" Fold by indentation, but only if enabled.
setlocal foldmethod=indent

if !exists("coffee_folding")
  setlocal nofoldenable
endif

" Compile some CoffeeScript.
command! -range=% CoffeeCompile <line1>,<line2>:w !coffee -scb

" Compile the current file on write.
if exists("coffee_compile_on_save")
  autocmd BufWritePost,FileWritePost *.coffee silent !coffee -c <afile> &
endif

Indent two spaces after starting a block comment

" Language:    CoffeeScript
" Maintainer:  Mick Koch <kchmck@gmail.com>
" URL:         http://github.com/kchmck/vim-coffee-script
" License:     WTFPL

if exists("b:did_ftplugin")
  finish
endif

let b:did_ftplugin = 1

setlocal formatoptions-=t formatoptions+=croql
setlocal comments=f-1:###,:#
setlocal commentstring=#\ %s

" Fold by indentation, but only if enabled.
setlocal foldmethod=indent

if !exists("coffee_folding")
  setlocal nofoldenable
endif

" Compile some CoffeeScript.
command! -range=% CoffeeCompile <line1>,<line2>:w !coffee -scb

" Compile the current file on write.
if exists("coffee_compile_on_save")
  autocmd BufWritePost,FileWritePost *.coffee silent !coffee -c <afile> &
endif


Given:
  a
  b
  c
  d

Execute (Update one line using `$_`):
  2rubydo $_.upcase!

Expect:
  a
  B
  c
  d

Execute (Update a range of lines using `$_`):
  2,3rubydo $_.upcase!

Expect:
  a
  B
  C
  d

Execute (Update all lines using `$_`):
  %rubydo $_.upcase!

Execute (Raise a Ruby standard error):
  try
    1rubydo raise "BOOM"
  catch /BOOM/
  endtry

  1rubydo $_.replace("still works")

Expect:
  still works
  b
  c
  d

Execute (Raise a Ruby syntax error):
  try
    1rubydo puts[
  catch /SyntaxError/
  endtry

  1rubydo $_.replace("still works")

Expect:
  still works
  b
  c
  d

Given:
  x

Execute (Add a large number of lines):
  1yank
  silent normal 6000p
  %rubydo $_.succ!

  AssertEqual "y", getline(1)
  AssertEqual "y", getline(6001)
  AssertEqual "", getline(6002)

Add missing acceptance test assertion

Given:
  a
  b
  c
  d

Execute (Update one line using `$_`):
  2rubydo $_.upcase!

Expect:
  a
  B
  c
  d

Execute (Update a range of lines using `$_`):
  2,3rubydo $_.upcase!

Expect:
  a
  B
  C
  d

Execute (Update all lines using `$_`):
  %rubydo $_.upcase!

Expect:
  A
  B
  C
  D

Execute (Raise a Ruby standard error):
  try
    1rubydo raise "BOOM"
  catch /BOOM/
  endtry

  1rubydo $_.replace("still works")

Expect:
  still works
  b
  c
  d

Execute (Raise a Ruby syntax error):
  try
    1rubydo puts[
  catch /SyntaxError/
  endtry

  1rubydo $_.replace("still works")

Expect:
  still works
  b
  c
  d

Given:
  x

Execute (Add a large number of lines):
  1yank
  silent normal 6000p
  %rubydo $_.succ!

  AssertEqual "y", getline(1)
  AssertEqual "y", getline(6001)
  AssertEqual "", getline(6002)


" Mark syntax errors with :signs
let g:syntastic_enable_signs=1

" Automatically jump to the error when saving the file
let g:syntastic_auto_jump=0

" Show the error list automatically
let g:syntastic_auto_loc_list=1

" Syntax checkers
let g:syntastic_ruby_checkers=['rubocop', 'mri']
let g:syntastic_python_checkers=['pep8', 'pylint', 'python']
let g:syntastic_javascript_checkers=['jshint']
let g:syntastic_scala_checkers=['scalac', 'scalastyle']

let g:syntastic_scala_scalastyle_jar='/usr/local/Cellar/scalastyle/0.6.0/libexec/scalastyle_2.10-0.6.0-batch.jar'

Add eslint to js syntax checkers

" Mark syntax errors with :signs
let g:syntastic_enable_signs=1

" Automatically jump to the error when saving the file
let g:syntastic_auto_jump=0

" Show the error list automatically
let g:syntastic_auto_loc_list=1

" Syntax checkers
let g:syntastic_ruby_checkers=['rubocop', 'mri']
let g:syntastic_python_checkers=['pep8', 'pylint', 'python']
let g:syntastic_javascript_checkers=['jshint', 'eslint']
let g:syntastic_scala_checkers=['scalac', 'scalastyle']

let g:syntastic_scala_scalastyle_jar='/usr/local/Cellar/scalastyle/0.6.0/libexec/scalastyle_2.10-0.6.0-batch.jar'


" specify 2-space indent for Ruby files
setlocal expandtab
setlocal tabstop=2 shiftwidth=2 softtabstop=2

" Don't automatically comment the next/previous line after hitting 'o' or 'O'
setlocal formatoptions-=o

" highlight ruby whitespace errors
let ruby_space_errors = 1
let g:rubycomplete_buffer_loading = 1
let g:rubycomplete_classes_in_global = 1

" set the 'foldmethod' option to 'syntax' and allow folding of
" classes, modules, methods, code blocks, heredocs and comments.
let ruby_fold = 1

" Gary Bernhardt's hashrocket
inoremap <c-l> <space>=><space>

" Use v or # to get a variable interpolation (inside of a string)}
" ysiw#   Wrap the token under the cursor in #{}
" v...s#  Wrap the selection in #{}
let b:surround_118 = "#{ \r }"    " v
let b:surround_35  = "#{ \r }"    " #

" Select text in an ERb file with visual mode and then press s- or s=
" Or yss- to do entire line.
let b:surround_45 = "<% \r -%>"   " -
let b:surround_61 = "<%= \r %>"   " =

" The compiler plugins contain instructions which allow Vim to run the
" specified source file with an appropriate executable, parse any errors, and
" jump to the corresponding error location if required.
compiler ruby

Remove Ruby-specific 2-space indent; since it's set globally


" Indenting
set autoindent smartindent              " turn on auto/smart indenting
set smarttab                            " make <tab> and <backspace> smarter
set backspace=eol,start,indent          " allow backspacing over indent, eol, & start
set textwidth=118                       " screen in 120 columns wide, wrap at 118
filetype plugin indent on

" Syntax matching
syntax on
highlight ExtraWhitespace ctermbg=darkgreen

set formatoptions=tcqlron

map <C-I> :py3f ~/bin/clang-format.py<cr>
imap <C-I> <c-o>:py3f ~/bin/clang-format.py<cr>
function! ClangFormatFile()
  let l:lines="all"
  py3f ~/bin/clang-format.py
endfunction
map <C-K> :.call ClangFormatFile()<cr>

if filereadable(".kernel")
    source ~/.vim/tab/tab.vim
else
    if filereadable(".3space")
        source ~/.vim/tab/3space.vim
    else
        if filereadable(".2space")
            source ~/.vim/tab/2space.vim
        else
            if filereadable(".garbage")
                source ~/.vim/tab/garbage.vim
            else
                source ~/.vim/tab/4space.vim
                "#autocmd BufWritePre *.h,*.cc,*.cpp call ClangFormatFile()
            endif
        endif
    endif
endif

Use ctrl-f instead of i

" Indenting
set autoindent smartindent              " turn on auto/smart indenting
set smarttab                            " make <tab> and <backspace> smarter
set backspace=eol,start,indent          " allow backspacing over indent, eol, & start
set textwidth=118                       " screen in 120 columns wide, wrap at 118
filetype plugin indent on

" Syntax matching
syntax on
highlight ExtraWhitespace ctermbg=darkgreen

set formatoptions=tcqlron

map <C-F> :py3f ~/bin/clang-format.py<cr>
imap <C-F> <c-o>:py3f ~/bin/clang-format.py<cr>
function! ClangFormatFile()
  let l:lines="all"
  py3f ~/bin/clang-format.py
endfunction
map <C-K> :.call ClangFormatFile()<cr>

if filereadable(".kernel")
    source ~/.vim/tab/tab.vim
else
    if filereadable(".3space")
        source ~/.vim/tab/3space.vim
    else
        if filereadable(".2space")
            source ~/.vim/tab/2space.vim
        else
            if filereadable(".garbage")
                source ~/.vim/tab/garbage.vim
            else
                source ~/.vim/tab/4space.vim
                "#autocmd BufWritePre *.h,*.cc,*.cpp call ClangFormatFile()
            endif
        endif
    endif
endif


" BEGIN
if exists("g:loaded_pivo") || &cp
  finish
endif
let g:loaded_pivo = 1
let s:keepcpo     = &cpo
set cpo&vim

let PivoBufferName = "__Pivotal__"

function! s:PivoBufferOpen()
    " Check whether the buffer is already created
    let pivo_bufnum = bufnr(g:PivoBufferName)
    if pivo_bufnum == -1
        " open a new buffer
        exe "new " . g:PivoBufferName
    else
        " Pivo buffer is already created,
        " check whether it is open in one of the windows.
        let pivo_winnum = bufwinnr(pivo_bufnum)
        if pivo_winnum != -1
            " Jump to the window which has the buffer if we are not
            " already in that window
            if winnr() != pivo_winnum
                exe pivo_winnum . "wincmd w"
            endif
        else
            " Create a new Pivo buffer
            exe "split +buffer" . pivo_bufnum
        endif
    endif
endfunction

command! -nargs=0 Pivo call s:PivoBufferOpen()

" END
let &cpo= s:keepcpo
unlet s:keepcpo

Quit from Pivo buffer on 'q'

" BEGIN
if exists("g:loaded_pivo") || &cp
  finish
endif
let g:loaded_pivo = 1
let s:keepcpo     = &cpo
set cpo&vim

let PivoBufferName = "__Pivotal__"

function! s:PivoBufferOpen()
    " Check whether the buffer is already created
    let pivo_bufnum = bufnr(g:PivoBufferName)
    if pivo_bufnum == -1
        " open a new buffer
        exe "new " . g:PivoBufferName
    else
        " Pivo buffer is already created,
        " check whether it is open in one of the windows.
        let pivo_winnum = bufwinnr(pivo_bufnum)
        if pivo_winnum != -1
            " Jump to the window which has the buffer if we are not
            " already in that window
            if winnr() != pivo_winnum
                exe pivo_winnum . "wincmd w"
            endif
        else
            " Create a new Pivo buffer
            exe "split +buffer" . pivo_bufnum
        endif
    endif
endfunction

function! s:SetPivoBuffer()
    nnoremap <buffer> q :quit<CR>
endfunction
autocmd BufNewFile __Pivotal__ call s:SetPivoBuffer()

command! -nargs=0 Pivo call s:PivoBufferOpen()

" END
let &cpo= s:keepcpo
unlet s:keepcpo


" Hide the vim splash screen
set shortmess+=I

" Set terminal title bar
set title

" Use hidden buffers
set hidden

" Don't wrap lines
set nowrap

" Let cursor keys wrap around lines
set whichwrap+=<,>,h,l,[,]

" Always show line numbers
set number

" Highlight right gutter at 80 characters
set colorcolumn=80

" Highlight the current cursor line
set cursorline

" Set show matching parenthesis
set showmatch

" Remove the noise in the vertical divider between splits
:set fillchars+=vert:\

" Limit completion popup menu height
set pumheight =15

" ==========================================
" Code folding

" Fold based on indent
set foldmethod=indent

" Set the deepest fold is 10 levels
set foldnestmax=10

" Don't fold code by default
set nofoldenable

" ==========================================
" Color scheme settings

set background=light
set t_Co=256
colorscheme solarized

Remove obsolete color scheme settings