" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

autocmd BufNewFile,BufRead,BufReadPre *.coffee set filetype=coffee

augroup fileTypeIndent
    autocmd!
    autocmd BufNewFile,BufRead *.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.coffee setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.rkt setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.py setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.js setlocal tabstop=2 shiftwidth=2 softtabstop=2
augroup END

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

augroup fileTypeListChars
    autocmd!
    autocmd BufNewFile,BufRead *.go setlocal nolist
augroup END

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~
source $VIMRUNTIME/macros/matchit.vim

" spell check
set spell
set spelllang=en,cjk

" conceal
set conceallevel=0

Change tab space of yaml to 2-spaces

" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

autocmd BufNewFile,BufRead,BufReadPre *.coffee set filetype=coffee

augroup fileTypeIndent
    autocmd!
    autocmd BufNewFile,BufRead *.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.coffee setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.rkt setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.py setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.js setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.yml setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.yaml setlocal tabstop=2 shiftwidth=2 softtabstop=2
augroup END

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

augroup fileTypeListChars
    autocmd!
    autocmd BufNewFile,BufRead *.go setlocal nolist
augroup END

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~
source $VIMRUNTIME/macros/matchit.vim

" spell check
set spell
set spelllang=en,cjk

" conceal
set conceallevel=0


" Set up ALE (linting)
let g:airline#extensions#ale#enabled = 1
let g:ale_sign_column_always = 1
let g:ale_linters = {
\   'bash': ['shellcheck', 'bashate'],
\   'javascript': ['eslint'],
\   'html': ['alex'],
\   'mail': ['alex'],
\   'markdown': ['alex'],
\   'python': ['flake8', 'isort', 'mypy'],
\   'yaml': ['yamllint'],
\}

let g:neoformat_enabled_rust = ['rustfmt']
let g:neoformat_enabled_python = ['isort', 'black']
let g:neoformat_enabled_sql = ['sqlfmt']
let g:neoformat_sql_sqlfmt = {
\   'exe': 'sqlfmt',
\   'args': ['--align full', '--use-spaces'],
\   'stdin': 1,
\}
let g:neoformat_enabled_html = ['html-beautify']
let g:neoformat_run_all_formatters = 1
let g:neoformat_enabled_terraform = ['terraform']
command F :Neoformat

Add linter for docker files

" Set up ALE (linting)
let g:airline#extensions#ale#enabled = 1
let g:ale_sign_column_always = 1
let g:ale_linters = {
\   'bash': ['shellcheck', 'bashate'],
\   'docker': ['hadolint'],
\   'javascript': ['eslint'],
\   'html': ['alex'],
\   'mail': ['alex'],
\   'markdown': ['alex'],
\   'python': ['flake8', 'isort', 'mypy'],
\   'yaml': ['yamllint'],
\}

let g:neoformat_enabled_rust = ['rustfmt']
let g:neoformat_enabled_python = ['isort', 'black']
let g:neoformat_enabled_sql = ['sqlfmt']
let g:neoformat_sql_sqlfmt = {
\   'exe': 'sqlfmt',
\   'args': ['--align full', '--use-spaces'],
\   'stdin': 1,
\}
let g:neoformat_enabled_html = ['html-beautify']
let g:neoformat_run_all_formatters = 1
let g:neoformat_enabled_terraform = ['terraform']
command F :Neoformat


" Run the current file in a ConqueTerm, great for ruby tests
let g:ConqueTerm_InsertOnEnter = 0
let g:ConqueTerm_CWInsert = 1
let g:ConqueTerm_Color = 2

" Open up a variety of commands in the ConqueTerm
nmap <silent> <Leader>cc :execute 'ConqueTermSplit script/console --irb=pry'<CR>
nmap <silent> <Leader>pp :execute 'ConqueTermSplit pry'<CR>
nmap <silent> <Leader>zz :execute 'ConqueTermSplit zsh'<CR>

let g:ConqueTerm_SendVisKey = '<Leader>e'

Make conqueTerm behave nicer when running long running commands inside it

let g:ConqueTerm_InsertOnEnter = 1
let g:ConqueTerm_CWInsert = 1
let g:ConqueTerm_Color = 2
let g:ConqueTerm_ReadUnfocused = 1 " update conqueterm buffer while we're not looking (for running tests)

" Open up a variety of commands in the ConqueTerm
nmap <silent> <Leader>cc :execute 'ConqueTermSplit script/console --irb=pry'<CR>
nmap <silent> <Leader>pp :execute 'ConqueTermSplit pry'<CR>
nmap <silent> <Leader>zz :execute 'ConqueTermSplit zsh'<CR>

let g:ConqueTerm_SendVisKey = '<Leader>e'


" abbreviations
iab fis for (int i = 0; i < .size(); ++i) {<CR>}<ESC>-f.i
iab ato atoi(.c_str())<ESC>F.i
iab vs vector<string>
iab AC accumulate(.begin(), .end(), 0);<ESC>2F.i

" make commands
map <F5> <ESC>:wa!<cr>:make run<cr>
map <F6> <ESC>:wa!<cr>:make test<cr>
map <F7> <ESC>:wa!<cr>:make<cr>
map! <F5> <ESC>:wa!<cr>:make run<cr>
map! <F6> <ESC>:wa!<cr>:make test<cr>
map! <F7> <ESC>:wa!<cr>:make<cr>

Add Vim abbreviations for vectors

" abbreviations
iab fis for (int i = 0; i < .size(); ++i) {<CR>}<ESC>-f.i
iab ato atoi(.c_str())<ESC>F.i
iab vs vector<string>
iab vi vector<int>
iab vll vector<long long>
iab vb vector<bool>
iab AC accumulate(.begin(), .end(), 0);<ESC>2F.i

" make commands
map <F5> <ESC>:wa!<cr>:make run<cr>
map <F6> <ESC>:wa!<cr>:make test<cr>
map <F7> <ESC>:wa!<cr>:make<cr>
map! <F5> <ESC>:wa!<cr>:make run<cr>
map! <F6> <ESC>:wa!<cr>:make test<cr>
map! <F7> <ESC>:wa!<cr>:make<cr>


" Author: Peter Renström <renstrom.peter@gmail.com>
" Description: Fixing C/C++ files with clang-format.

call ale#Set('c_clangformat_executable', 'clang-format')
call ale#Set('c_clangformat_use_global', 0)
call ale#Set('c_clangformat_options', '')

function! ale#fixers#clangformat#GetExecutable(buffer) abort
    return ale#node#FindExecutable(a:buffer, 'c_clangformat', [
    \   'clang-format',
    \])
endfunction

function! ale#fixers#clangformat#Fix(buffer) abort
    let l:options = ale#Var(a:buffer, 'c_clangformat_options')

    return {
    \   'command': ale#Escape(ale#fixers#clangformat#GetExecutable(a:buffer))
    \       . ' ' . l:options,
    \}
endfunction

Add a missing scriptencoding line

scriptencoding utf-8
" Author: Peter Renström <renstrom.peter@gmail.com>
" Description: Fixing C/C++ files with clang-format.

call ale#Set('c_clangformat_executable', 'clang-format')
call ale#Set('c_clangformat_use_global', 0)
call ale#Set('c_clangformat_options', '')

function! ale#fixers#clangformat#GetExecutable(buffer) abort
    return ale#node#FindExecutable(a:buffer, 'c_clangformat', [
    \   'clang-format',
    \])
endfunction

function! ale#fixers#clangformat#Fix(buffer) abort
    let l:options = ale#Var(a:buffer, 'c_clangformat_options')

    return {
    \   'command': ale#Escape(ale#fixers#clangformat#GetExecutable(a:buffer))
    \       . ' ' . l:options,
    \}
endfunction


" 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> :pyf ~/bin/clang-format.py<cr>
imap <C-I> <c-o>:pyf ~/bin/clang-format.py<cr>
function! ClangFormatFile()
  let l:lines="all"
  pyf ~/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 py3f to better support newer systems

" 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


if has ('vim_starting')
    set nocompatible

    if has ('nvim')
        set runtimepath+=~/.config/nvim/bundle/neobundle.vim/
    else
        set runtimepath+=~/.vim/bundle/neobundle.vim/
    endif

    if has ('nvim')
        let $NVIM_TUI_ENABLE_CURSOR_SHAPE=1
    endif

    let mapleader = " "
endif

if has ('nvim')
    call neobundle#begin(expand('~/.config/nvim/bundle/'))
else
    call neobundle#begin(expand('~/.vim/bundle/'))
endif

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim

Enable NeoVIM's true color support unless tmux is running.

if has ('vim_starting')
    set nocompatible

    if has ('nvim')
        set runtimepath+=~/.config/nvim/bundle/neobundle.vim/
    else
        set runtimepath+=~/.vim/bundle/neobundle.vim/
    endif

    if has ('nvim')
        let $NVIM_TUI_ENABLE_CURSOR_SHAPE=1
        if !exists ('$TMUX')
            let $NVIM_TUI_ENABLE_TRUE_COLOR=1
        endif
    endif

    let mapleader = " "
endif

if has ('nvim')
    call neobundle#begin(expand('~/.config/nvim/bundle/'))
else
    call neobundle#begin(expand('~/.vim/bundle/'))
endif

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim


map <F7> Ofrom ipdb import set_trace; set_trace(); # TODO<esc>
map <F8> Oimport traceback, sys; traceback.print_exception(*sys.exc_info()); # TODO<esc>

map <Leader>r :w\|:!python %:p<CR>

Use regular old pdb, not ipdb.

map <F7> Ofrom pdb import set_trace; set_trace(); # TODO<esc>
map <F8> Oimport traceback, sys; traceback.print_exception(*sys.exc_info()); # TODO<esc>

map <Leader>r :w\|:!python %:p<CR>


" ==========================================
" Window split key bindings
" See http://technotales.wordpress.com/2010/04/29/vim-splits-a-guide-to-doing-exactly-what-you-want/

" window
nmap \<left>  :topleft  vnew<CR>
nmap \<right> :botright vnew<CR>
nmap \<up>    :topleft  new<CR>
nmap \<down>  :botright new<CR>

" buffer
nmap <leader><left>   :leftabove  vnew<CR>
nmap <leader><right>  :rightbelow vnew<CR>
nmap <leader><up>     :leftabove  new<CR>
nmap <leader><down>   :rightbelow new<CR>

" new window splits gain focus
nnoremap <C-w>s <C-w>s<C-w>w
nnoremap <C-w>v <C-w>v<C-w>w

Add workaround for neovim behavior

" ==========================================
" Window split key bindings
" See http://technotales.wordpress.com/2010/04/29/vim-splits-a-guide-to-doing-exactly-what-you-want/

" window
nmap \<left>  :topleft  vnew<CR>
nmap \<right> :botright vnew<CR>
nmap \<up>    :topleft  new<CR>
nmap \<down>  :botright new<CR>

" buffer
nmap <leader><left>   :leftabove  vnew<CR>
nmap <leader><right>  :rightbelow vnew<CR>
nmap <leader><up>     :leftabove  new<CR>
nmap <leader><down>   :rightbelow new<CR>

" new window splits gain focus
nnoremap <C-w>s <C-w>s<C-w>w
nnoremap <C-w>v <C-w>v<C-w>w

nnoremap <silent> <BS> :TmuxNavigateLeft<cr>


Plug 'vim-test/vim-test'

function! InteractiveZshTransform(cmd) abort
    return 'zsh -ic "'.a:cmd.'"'
endfunction

let g:test#custom_transformations = {
    \ 'zsh': function('InteractiveZshTransform')
\ }

let test#strategy = "neovim"
let g:test#transformation = 'zsh'
let test#php#phpunit#executable = 'phpunit'

nmap <leader>tn :TestNearest<CR>
nmap <leader>tf :TestFile<CR>
nmap <leader>ts :TestSuite<CR>
nmap <leader>tl :TestLast<CR>
nmap <leader>tv :TestVisit<CR>

augroup AutoDeleteTestTermBuffers
    autocmd!
    autocmd BufLeave term://*artisan\stest* bdelete!
    autocmd BufLeave term://*phpunit* bdelete!
augroup END

Use deliver instead of zsh-artisan for test dispatching

Plug 'vim-test/vim-test'

"let test#strategy = "neovim"
"let g:test#transformation = 'zsh'
let test#php#phpunit#executable = 'deliver vendor/bin/phpunit'

nmap <leader>tn :TestNearest<CR>
nmap <leader>tf :TestFile<CR>
nmap <leader>ts :TestSuite<CR>
nmap <leader>tl :TestLast<CR>
nmap <leader>tv :TestVisit<CR>

augroup AutoDeleteTestTermBuffers
    autocmd!
    autocmd BufLeave term://*artisan\stest* bdelete!
    autocmd BufLeave term://*phpunit* bdelete!
augroup END


let mapleader = ','

nmap <leader>f :Neoformat<cr>

" Map the Q letter to hard-wrapping specific sections
nnoremap Q gq

" Map the terminal escape to normal vim bindings
tnoremap <leader><esc> <C-\><C-n>

" Better navigation in splits
nnoremap <leader>% :vsp<cr>
nnoremap <leader>" :sp<cr>

nnoremap <leader>h <C-W><C-H>
nnoremap <leader>j <C-W><C-J>
nnoremap <leader>k <C-W><C-K>
nnoremap <leader>l <C-W><C-L>

" Yank and paste to clipboard
function! ClipboardYank()
	call system('xclip -i -selection clipboard', @@)
endfunction
function! ClipboardPaste()
	let @@ = system('xclip -o -selection clipboard')
endfunction

nnoremap <leader>y :call ClipboardYank()<cr>
nnoremap <leader>p :call ClipboardPaste()<cr>

Remove duplicate function, add term binds

let mapleader = ','

nmap <leader>f :Neoformat<cr>

" Map the Q letter to hard-wrapping specific sections
nnoremap Q gq

" Better navigation in splits
nnoremap <leader>% :vsp<cr>
nnoremap <leader>$ :sp<cr>

nnoremap <leader>h <c-W><c-H>
nnoremap <leader>j <c-W><c-J>
nnoremap <leader>k <c-W><c-K>
nnoremap <leader>l <c-W><c-L>

" Map the terminal escape to normal vim bindings
tnoremap <leader><esc> <c-\><c-n>

" Map split movements to terminal mode
tnoremap <leader>h <c-\><c-n><c-W><c-H>
tnoremap <leader>j <c-\><c-n><c-W><c-J>
tnoremap <leader>k <c-\><c-n><c-W><c-K>
tnoremap <leader>l <c-\><c-n><c-W><c-L>

" Map tab movements to terminal mode
tnoremap <leader>gt <c-\><c-n>gt
tnoremap <leader>gT <c-\><c-n>gT

nnoremap <leader>y :call ClipboardYank()<cr>
nnoremap <leader>p :call ClipboardPaste()<cr>


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>

Add vim binding to toggle 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>

" this is hacky, but it works
let s:coq_running = 0
function! CoqToggle()
    if s:coq_running == 1
        execute "CoqKill"
        let s:coq_running = 0
    else
        execute "CoqLaunch"
        let s:coq_running = 1
    endif
endfunction
nnoremap <buffer> <Leader>c :call CoqToggle()<CR>


" Powerline - The ultimate statusline utility
"
" Author: Kim Silkebækken <kim.silkebaekken+vim@gmail.com>
" Source repository: https://github.com/Lokaltog/vim-powerline

" Script initialization {{{
	if exists('g:Powerline_loaded') || &compatible || version < 702
		finish
	endif

	let g:Powerline_loaded = 1
" }}}
" Set default options {{{
	function! s:InitOptions(options) " {{{
		for [key, value] in items(a:options)
			if ! exists('g:Powerline_' . key)
				exec printf('let g:Powerline_%s = %s', key, string(value))
			endif
		endfor
	endfunction " }}}
	call s:InitOptions({
	\   'theme'        : 'distinguished'
	\ , 'symbols'      : 'compatible'
	\ , 'cache_file'   : (exists('$TEMP') && ! empty($TEMP) ? $TEMP : '/tmp') . '/Powerline.cache'
	\ })
" }}}
" Autocommands {{{
	augroup Powerline
		autocmd!

		" Reload statuslines when changing color scheme
		au ColorScheme *
			\ call Pl#Load()

		au BufEnter,WinEnter,FileType,BufUnload *
			\ call Pl#UpdateStatusline(1)

		au BufLeave,WinLeave *
			\ call Pl#UpdateStatusline(0)
	augroup END
" }}}

Update option setting in plugin file

" Powerline - The ultimate statusline utility
"
" Author: Kim Silkebækken <kim.silkebaekken+vim@gmail.com>
" Source repository: https://github.com/Lokaltog/vim-powerline

" Script initialization {{{
	if exists('g:Powerline_loaded') || &compatible || version < 702
		finish
	endif

	let g:Powerline_loaded = 1
" }}}
" Set default options {{{
	for [key, value] in items({
		\   'theme'        : 'distinguished'
		\ , 'colorscheme'  : 'distinguished'
		\ , 'symbols'      : 'compatible'
		\ , 'cache_file'   : (exists('$TEMP') && ! empty($TEMP) ? $TEMP : '/tmp') . '/Powerline.cache'
		\ , 'cache_enable' : 1
		\ })

		if ! exists('g:Powerline_' . key)
			exec printf('let g:Powerline_%s = %s', key, string(value))
		endif
	endfor
" }}}
" Autocommands {{{
	augroup Powerline
		autocmd!

		" Reload statuslines when changing color scheme
		au ColorScheme *
			\ call Pl#Load()

		au BufEnter,WinEnter,FileType,BufUnload *
			\ call Pl#UpdateStatusline(1)

		au BufLeave,WinLeave *
			\ call Pl#UpdateStatusline(0)
	augroup END
" }}}


" //TODO Review Neobundle vs Vundle vs whatever and review/update/replace this

" Load all the plugins automatically on startup
filetype off
filetype plugin indent off

" Increase timeout for YouCompleteMe
let g:neobundle#install_process_timeout=300

if has('vim_starting')
  set nocompatible
  set runtimepath+=~/.vim/bundle/neobundle.vim/
  set runtimepath+=~/.vim/rc/plugins/
endif

call neobundle#begin(expand('~/.vim/bundle/'))

NeoBundleFetch 'Shougo/neobundle.vim'

runtime! rc/plugins/*.vim

call neobundle#end()

filetype plugin indent on
syntax on

NeoBundleCheck

Swap from Neobundle to Vundle; more TODOs

" //TODO Review Neobundle vs Vundle vs whatever and review/update/replace this

" Load all the plugins automatically on startup
filetype off
filetype plugin indent off

" TODO
" Increase timeout for YouCompleteMe
let g:neobundle#install_process_timeout=300

if has('vim_starting')
  set nocompatible
  set runtimepath+=~/.vim/bundle/neobundle.vim/
  set runtimepath+=~/.vim/rc/plugins/
endif

" set the runtime path to include Vundle and initialize
" TODO set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line

syntax on

NeoBundleCheck


set guifont=Iosevka\ Term:h16

if exists('g:fvim_loaded')
	FVimCursorSmoothBlink v:true
	FVimCursorSmoothMove v:true
	FVimCustomTitleBar v:false
endif

Set font to JetBrains Mono

set guifont=JetBrains\ Mono:h13

if exists('g:fvim_loaded')
	FVimCursorSmoothBlink v:true
	FVimCursorSmoothMove v:true
	FVimCustomTitleBar v:false
endif


" 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

Remove cucumber step and support nav commands

" Cucumber navigation commands {{{
  Rnavcommand feature features                  -suffix=.feature
" }}}

" 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


if exists("b:current_syntax")
    finish
endif

syntax case match

syntax match paketDepsKeyword /^redirects/
syntax match paketDepsKeyword /^source/
syntax match paketDepsKeyword /^nuget/
syntax match paketDepsKeyword /^http/
syntax match paketDepsKeyword /^github/

syntax match paketDepsSymbol />=/
syntax match paketDepsSymbol /:\_s/

syntax match paketDepsVersion /\d\(\.\d\)\+/

syntax match paketDepsOption /\<on\>/

" Source: https://gist.github.com/tobym/584909
syntax match paketDepsUrl /https\?:\/\/\(\w\+\(:\w\+\)\?@\)\?\([A-Za-z][-_0-9A-Za-z]*\.\?\)\{1,}\(\w\{2,}\.\?\)\{1,}\(:[0-9]\{1,5}\)\?\S*/

highlight link paketDepsKeyword Keyword
highlight link paketDepsSymbol Operator
highlight link paketDepsVersion Float
highlight link paketDepsOption Boolean
highlight link paketDepsUrl String

let b:current_syntax = "paketdeps"

Support dependency groups in Paket highlighting

if exists("b:current_syntax")
    finish
endif

syntax case match

syntax match paketDepsKeyword /^\s*redirects/
syntax match paketDepsKeyword /^\s*source/
syntax match paketDepsKeyword /^\s*nuget/
syntax match paketDepsKeyword /^\s*http/
syntax match paketDepsKeyword /^\s*github/
syntax match paketDepsKeyword /^\s*group/

syntax match paketDepsSymbol />=/
syntax match paketDepsSymbol /:\_s/

syntax match paketDepsVersion /\d\(\.\d\)\+/

syntax match paketDepsOption /\<on\>/

" Source: https://gist.github.com/tobym/584909
syntax match paketDepsUrl /https\?:\/\/\(\w\+\(:\w\+\)\?@\)\?\([A-Za-z][-_0-9A-Za-z]*\.\?\)\{1,}\(\w\{2,}\.\?\)\{1,}\(:[0-9]\{1,5}\)\?\S*/

highlight link paketDepsKeyword Keyword
highlight link paketDepsSymbol Operator
highlight link paketDepsVersion Float
highlight link paketDepsOption Boolean
highlight link paketDepsUrl String

let b:current_syntax = "paketdeps"


" Show current file directory in current window
au BufEnter * if !exists("b:NERDTreeType") | nnoremap <buffer> <silent> - :EditCurrentDir<CR> |
au BufLeave * if !exists("b:NERDTreeType") | let w:nerdtree_previous_file = expand("%:p") . '' |

call NERDTreeAddKeyMap({
        \ 'key': '-',
        \ 'callback': 'NERDTreeBackToPreviousFile',
        \ 'quickhelpText': 'If activated inside a buffer (like netrw), gets back to the "calling" file' })

function! NERDTreeBackToPreviousFile()
  if exists("w:nerdtree_previous_file")
    execute 'edit ' . w:nerdtree_previous_file
  endif
endfunction

Fix in which filetypes the '-' key will be mapped

function! CurrentBufferEditable()
  return !(&readonly || &ft ==? 'nerdtree' || &ft ==? 'qf')
endfunction

" Show current file directory in current window
au BufEnter * if CurrentBufferEditable() | nnoremap <buffer> <silent> - :EditCurrentDir<CR> |
au BufLeave * if CurrentBufferEditable() | let w:nerdtree_previous_file = expand("%:p") . '' |

call NERDTreeAddKeyMap({
        \ 'key': '-',
        \ 'callback': 'NERDTreeBackToPreviousFile',
        \ 'quickhelpText': 'If activated inside a buffer (like netrw), gets back to the "calling" file' })

function! NERDTreeBackToPreviousFile()
  if exists("w:nerdtree_previous_file")
    execute 'edit ' . w:nerdtree_previous_file
  endif
endfunction


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

Make vim Coq bindings work in insert mode

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>


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

" Glorious technicolour!
set termguicolors
colorscheme base16-materia-meshy
" colorscheme base16-mexico-light
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

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

Use light theme for vim

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

" 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

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


" Set leader key
let mapleader = ","

" Highlight search matches
set hls

" Enable incremental search
set is

" Put swap files outside project dir to keep it clean
set swapfile
set dir=~/tmp

" Automatically change dir when switching files.
" This enables :compl-filename to give me proper relative filenames.
set autochdir

" Use 2 spaces for indentation
set ts=2
set et
set sw=2

" Enable autoindent
set autoindent
set smartindent

" allow the . to execute once for each line of a visual selection
vnoremap . :normal .<CR>

" Configure colors
set t_Co=256
set term=xterm-256color

" Sources the current vimscript
nnoremap <leader>sop :source %<cr>

" Set Chrome as the default brower
let g:netrw_browsex_viewer='google-chrome'

" Open image in gwenview
nnoremap <leader>i :!gwenview <cfile><cr><cr>

" Swaps paste mode
set pastetoggle=<F3>

Set backup file folder to ~/tmp

" Set leader key
let mapleader = ","

" Highlight search matches
set hls

" Enable incremental search
set is

" Put swap and backup files outside project dir to keep it clean
set swapfile
set dir=~/tmp
set backup
set backupdir=~/tmp

" Automatically change dir when switching files.
" This enables :compl-filename to give me proper relative filenames.
set autochdir

" Use 2 spaces for indentation
set ts=2
set et
set sw=2

" Enable autoindent
set autoindent
set smartindent

" allow the . to execute once for each line of a visual selection
vnoremap . :normal .<CR>

" Configure colors
set t_Co=256
set term=xterm-256color

" Sources the current vimscript
nnoremap <leader>sop :source %<cr>

" Set Chrome as the default brower
let g:netrw_browsex_viewer='google-chrome'

" Open image in gwenview
nnoremap <leader>i :!gwenview <cfile><cr><cr>

" Swaps paste mode
set pastetoggle=<F3>


function! Cdfile()
    cd %:h
    pwd
endfunction

" cd to the root of the current file's git directory
function! Cdroot()
    cd %:h
    exec "cd " . Trim(system("git rev-parse --show-toplevel"))
    pwd
endfunction

Make Cdf and Cdr no-ops when not in a file

function! Cdfile()
    if expand('%') != ''
        cd %:h
    else
        echom "Not currently in a file."
    endif
endfunction

" cd to the root of the current file's git directory
function! Cdroot()
    call Cdfile()
    exec "cd " . Trim(system("git rev-parse --show-toplevel"))
    echom expand('.')
endfunction


" Hide ignored files from CtrlP.
let g:ctrlp_user_command = {
  \ 'types': {
    \ 1: ['.git', 'cd %s && git ls-files --cached --exclude-standard --others'],
    \ 2: ['.hg', 'hg --cwd %s locate -I .'],
    \ },
  \ 'fallback': 'find %s -type f'
  \ }

" Disable caching in CtrlP.
let g:ctrlp_use_caching = 0

Use "fd" as a CtrlP command fallback if available

" Hide ignored files from CtrlP.
let g:ctrlp_user_command = {
  \ 'types': {
    \ 1: ['.git', 'cd %s && git ls-files --cached --exclude-standard --others'],
    \ 2: ['.hg', 'hg --cwd %s locate -I .'],
    \ },
  \ 'fallback': 'find %s -type f'
  \ }

" Use `fd` as a fallback if available (faster and supports 'ignore' files).
if executable('fd')
  let g:ctrlp_user_command['fallback'] = 'fd --type f --color never . %s'
endif

" Disable caching in CtrlP.
let g:ctrlp_use_caching = 0


syntax on

" Fix syntax coloring for sign and fold column.
highlight clear SignColumn
highlight clear FoldColumn
set signcolumn=yes

" Waiting for alacritty merge.
" highlight IndentBlanklineContextStart guisp=#00FF00 gui=underline

lua<<EOF
local async = require("plenary.async")
async.run(function ()
	local pipe = io.popen('grep -P "^colors: \\*light" ~/.config/alacritty/alacritty.yml')
	local output = pipe:read('*all')
	print(output)
	if output == "" then
		--	colorscheme badwolf
		print('dark')
		vim.o.background = "dark"
		vim.cmd('highlight IndentBlanklineChar guifg=#444444 gui=nocombine')
		vim.cmd('colorscheme ayu')
	else
		print('light')
		vim.o.background = "light"
		vim.cmd('let ayucolor="light"')
		vim.cmd('highlight IndentBlanklineChar guifg=#dddddd gui=nocombine')
		vim.cmd('colorscheme ayu')
		vim.cmd('highlight Todo guibg=#e03050')
		-- vim.cmd('highlight Todo guibg=#efdfaf')
		vim.cmd('highlight SignatureMarkText guifg=#0f3f3f gui=bold')
	end
end)
EOF

" TODO

Remove debug prints from colorscheme

syntax on

" Fix syntax coloring for sign and fold column.
highlight clear SignColumn
highlight clear FoldColumn
set signcolumn=yes

" Waiting for alacritty merge.
" highlight IndentBlanklineContextStart guisp=#00FF00 gui=underline

lua<<EOF
local async = require("plenary.async")
async.run(function ()
	local pipe = io.popen('grep -P "^colors: \\*light" ~/.config/alacritty/alacritty.yml')
	local output = pipe:read('*all')
	if output == "" then
		--	colorscheme badwolf
		vim.o.background = "dark"
		vim.cmd('highlight IndentBlanklineChar guifg=#444444 gui=nocombine')
		vim.cmd('colorscheme ayu')
	else
		vim.o.background = "light"
		vim.cmd('let ayucolor="light"')
		vim.cmd('highlight IndentBlanklineChar guifg=#dddddd gui=nocombine')
		vim.cmd('colorscheme ayu')
		vim.cmd('highlight Todo guibg=#e03050')
		-- vim.cmd('highlight Todo guibg=#efdfaf')
		vim.cmd('highlight SignatureMarkText guifg=#0f3f3f gui=bold')
	end
end)
EOF

" TODO


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

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

" registers = cr
" marks = c'

Remove \cf mapping for Ctrl-P

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

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

" registers = cr
" marks = c'


let s:save_cpo = &cpo
set cpo&vim
if exists('g:javaunit_util_loaded')
    finish
endif
let g:javaunit_util_loaded = 1

function! s:OSX()
    return has('macunix')
endfunction
function! s:LINUX()
    return has('unix') && !has('macunix') && !has('win32unix')
endfunction
function! s:WINDOWS()
    return (has('win16') || has('win32') || has('win64'))
endfunction

function! javaunit#util#Fsep() abort
    if s:WINDOWS()
        return '\'
    else
        return '/'
    endif
endfunction

function! javaunit#util#Psep() abort
    if s:WINDOWS()
        return ';'
    else
        return ':'
    endif
endfunction

function! javaunit#util#ExecCMD(cmd)
    if exists(':Unite')
        call unite#start([['output/shellcmd', s:EscapeCMD(a:cmd)]], {'log': 1, 'wrap': 1,'start_insert':0})
    else
        call javaunit#win#OpenWin(a:cmd)
    endif
endfunction

function! s:EscapeCMD(cmd)
    if s:WINDOWS()
        return a:cmd
    else
        return a:cmd
    endif
endfunction

let &cpo = s:save_cpo
unlet s:save_cpo

Use SpaceVim runner by default

let s:save_cpo = &cpo
set cpo&vim
if exists('g:javaunit_util_loaded')
    finish
endif
let g:javaunit_util_loaded = 1

function! s:OSX()
    return has('macunix')
endfunction
function! s:LINUX()
    return has('unix') && !has('macunix') && !has('win32unix')
endfunction
function! s:WINDOWS()
    return (has('win16') || has('win32') || has('win64'))
endfunction

function! javaunit#util#Fsep() abort
    if s:WINDOWS()
        return '\'
    else
        return '/'
    endif
endfunction

function! javaunit#util#Psep() abort
    if s:WINDOWS()
        return ';'
    else
        return ':'
    endif
endfunction

function! javaunit#util#ExecCMD(cmd)
    if exists('g:spacevim_version')
        call SpaceVim#plugins#runner#open(a:cmd)
    elseif exists(':Unite')
        call unite#start([['output/shellcmd', s:EscapeCMD(a:cmd)]], {'log': 1, 'wrap': 1,'start_insert':0})
    else
        call javaunit#win#OpenWin(a:cmd)
    endif
endfunction

function! s:EscapeCMD(cmd)
    if s:WINDOWS()
        return a:cmd
    else
        return a:cmd
    endif
endfunction

let &cpo = s:save_cpo
unlet s:save_cpo


colorscheme wal
highlight CursorLine ctermbg=7

" NERDTree Key
nnoremap <leader>n :NERDTreeToggle<CR>

" Neomake
augroup neomake_lint
    autocmd!
    autocmd BufWritePost * Neomake
augroup END

Fix cursor line killing the cursor

colorscheme wal
highlight CursorLine ctermbg=11

" NERDTree Key
nnoremap <leader>n :NERDTreeToggle<CR>

" Neomake
augroup neomake_lint
    autocmd!
    autocmd BufWritePost * Neomake
augroup END


" Aliases
cab W w
cab Q q
cab Qa! qa!
cab Qa qa
cab Wa! wa!
cab Wa wa
cab wQ wq
cab Wq wq
cab WQ wq
cab Wqa wqa
cab WQa wqa
cab WQA wqa
cab E e
cab ag Rg
cab Ag Rg
cab ack Rg
cab rg Rg
cab TAbnew tabnew
cab Tabnew tabnew
cab REname Rename
cab Renaem Rename
cab REnaem Rename
cab gblame Gblame
cab GBlame Gblame
ab bp require 'pry'; binding.pry
ab sos save_and_open_screenshot <esc>
ab sop save_and_open_page <esc>

Drop require from binding.pry alias

" Aliases
cab W w
cab Q q
cab Qa! qa!
cab Qa qa
cab Wa! wa!
cab Wa wa
cab wQ wq
cab Wq wq
cab WQ wq
cab Wqa wqa
cab WQa wqa
cab WQA wqa
cab E e
cab ag Rg
cab Ag Rg
cab ack Rg
cab rg Rg
cab TAbnew tabnew
cab Tabnew tabnew
cab REname Rename
cab Renaem Rename
cab REnaem Rename
cab gblame Gblame
cab GBlame Gblame
ab bp binding.pry
ab sos save_and_open_screenshot <esc>
ab sop save_and_open_page <esc>


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

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

" Default size
set lines=40
set columns=120

Hide gvim toolbar by default

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

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

" Remove toolbar
set guioptions-=T

" Default size
set lines=40
set columns=120


function! RunInTerminal(file)
  if match(a:file, '_spec\.rb') != -1
    let l:command = 'bundle exec rspec --tty'
  elseif match(a:file, '\.rb') != -1
    let l:command = 'ruby'
  endif

  if exists("l:command")
    let l:run_script = "!osascript ~/.vim/tools/run_terminal_command.applescript"
    let l:run_dir = getcwd()
    silent execute ":up"
    silent execute l:run_script . " 'cd " . l:run_dir . " && " . l:command . " " . a:file . "' 'Ruby Tests'"
    silent execute ":redraw!"
  else
    echo "This file does not appear to be a ruby file "
  end
endfunction

function! RunRubyFileInTerminal()
  call RunInTerminal(expand("%") . ":" . line("."))
endfunction

command! RunRubyFileInTerminal call RunRubyFileInTerminal()

Use Zeus by default for specs

function! RunInTerminal(file)
  if match(a:file, '_spec\.rb') != -1
    let l:command = 'zeus rspec --tty'
  elseif match(a:file, '\.rb') != -1
    let l:command = 'ruby'
  endif

  if exists("l:command")
    let l:run_script = "!osascript ~/.vim/tools/run_terminal_command.applescript"
    let l:run_dir = getcwd()
    silent execute ":up"
    silent execute l:run_script . " 'cd " . l:run_dir . " && " . l:command . " " . a:file . "' 'Ruby Tests'"
    silent execute ":redraw!"
  else
    echo "This file does not appear to be a ruby file "
  end
endfunction

function! RunRubyFileInTerminal()
  call RunInTerminal(expand("%") . ":" . line("."))
endfunction

command! RunRubyFileInTerminal call RunRubyFileInTerminal()


" Better key maps for switching between controller and view
nnoremap ,vv :Rview<cr>
nnoremap ,cc :Rcontroller<cr>

Fix shortcuts for deprecated Rails.vim commands

" Better key maps for switching between controller and view
nnoremap ,vv :Eview<cr>
nnoremap ,cc :Econtroller<cr>


" Vim compiler file
" Language:             Scala SBT (http://www.scala-sbt.org/)
" Maintainer:           Derek Wyatt
" URL:                  https://github.com/derekwyatt/vim-scala
" License:              Apache 2
" ----------------------------------------------------------------------------

if exists('current_compiler')
  finish
endif
let current_compiler = 'sbt'

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=sbt\ -Dsbt.log.noformat=true\ compile

CompilerSet errorformat=
      \%E\ %#[error]\ %f:%l:\ %m,%C\ %#[error]\ %p^,%-C%.%#,%Z,
      \%W\ %#[warn]\ %f:%l:\ %m,%C\ %#[warn]\ %p^,%-C%.%#,%Z,
      \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save

" vim:set sw=2 sts=2 ts=8 et:

Add column number into errorformat

" Vim compiler file
" Language:             Scala SBT (http://www.scala-sbt.org/)
" Maintainer:           Derek Wyatt
" URL:                  https://github.com/derekwyatt/vim-scala
" License:              Apache 2
" ----------------------------------------------------------------------------

if exists('current_compiler')
  finish
endif
let current_compiler = 'sbt'

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=sbt\ -Dsbt.log.noformat=true\ compile

CompilerSet errorformat=
      \%E\ %#[error]\ %f:%l:%c:\ %m,%C\ %#[error]\ %p^,%-C%.%#,%Z,
      \%W\ %#[warn]\ %f:%l:%c:\ %m,%C\ %#[warn]\ %p^,%-C%.%#,%Z,
      \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save

" vim:set sw=2 sts=2 ts=8 et:


" Ignore retarded directories
set wildignore+=build/*
set wildignore+=public/build/*
set wildignore+=exam/*
set wildignore+=*.pyc

let g:CommandTCancelMap=['<ESC>','<C-c>']
let g:CommandTMaxFiles=999999
let g:CommandTMaxDepth=999999
let g:CommandTMaxCachedDirectories=10

Make Command-T not use the current scm root as the pwd.

" Ignore retarded directories
set wildignore+=build/*
set wildignore+=public/build/*
set wildignore+=exam/*
set wildignore+=*.pyc

let g:CommandTCancelMap=['<ESC>','<C-c>']
let g:CommandTMaxFiles=999999
let g:CommandTMaxDepth=999999
let g:CommandTMaxCachedDirectories=10
let g:CommandTTraverseSCM="pwd"


au BufWritePost *.rs silent!make ctags > /dev/null 2>&1
let g:syntastic_rust_rustc_fname = "src/lib.rs"

Use more useful rustc args for syntastic.

au BufWritePost *.rs silent!make ctags > /dev/null 2>&1
let g:syntastic_rust_rustc_fname = "src/lib.rs"
let g:syntastic_rust_rustc_args = "--no-trans"


"
" Limelight
"

FIX Goyo x Limelight integration

"
" Limelight
"

autocmd! User GoyoEnter Limelight
autocmd! User GoyoLeave Limelight!

" https://github.com/junegunn/limelight.vim/issues/27#issuecomment-160692583
let g:limelight_conceal_ctermfg = 245  " Solarized Base1
let g:limelight_conceal_guifg = '#8a8a8a'  " Solarized Base1


if has ('vim_starting')
    set nocompatible

    if has ('nvim')
        set runtimepath+=~/.config/nvim/bundle/neobundle.vim/
    else
        set runtimepath+=~/.vim/bundle/neobundle.vim/
    endif

    if has ('nvim')
        let $NVIM_TUI_ENABLE_CURSOR_SHAPE=1
        let $NVIM_TUI_ENABLE_TRUE_COLOR=1
    endif

    let mapleader = " "
endif

if has ('nvim')
    call neobundle#begin(expand('~/.config/nvim/bundle/'))
else
    call neobundle#begin(expand('~/.vim/bundle/'))
endif

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim

Reorder statements to reduce branching.

if has ('vim_starting')
    if has ('nvim')
        let $NVIM_TUI_ENABLE_CURSOR_SHAPE=1
        let $NVIM_TUI_ENABLE_TRUE_COLOR=1

        set runtimepath+=~/.config/nvim/bundle/neobundle.vim/
    else
        set nocompatible

        set runtimepath+=~/.vim/bundle/neobundle.vim/
    endif

    let mapleader = " "
endif

if has ('nvim')
    call neobundle#begin(expand('~/.config/nvim/bundle/'))
else
    call neobundle#begin(expand('~/.vim/bundle/'))
endif

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim


" Set up Vim to edit Katasemeion biblical text files
" Author: Kazark

if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

let s:save_cpo = &cpo
set cpo&vim

setlocal textwidth=80
setlocal spell
" Disable automatic comment continuations to the next line... doesn't apply
" here and could make Vim insert unnecessary characters
setlocal formatoptions-=c
setlocal formatoptions-=o
setlocal formatoptions-=q
setlocal formatoptions-=r
setlocal comments-=:%

let &cpo = s:save_cpo

Build to HTML from Vim with :make

" Set up Vim to edit Katasemeion biblical text files
" Author: Kazark

if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

let s:save_cpo = &cpo
set cpo&vim

setlocal textwidth=80
setlocal spell
" Disable automatic comment continuations to the next line... doesn't apply
" here and could make Vim insert unnecessary characters
setlocal formatoptions-=c
setlocal formatoptions-=o
setlocal formatoptions-=q
setlocal formatoptions-=r
setlocal comments-=:%

" Build to HTML with :make
let &l:makeprg="katasemeion " . expand('%') . " > output/" . expand('%:t:r') . ".html"

let &cpo = s:save_cpo


" Vim indent file
" Language:	Roy
" Maintainer:	Bill Casarin <bill@casarin.ca>
" Last Change:	April 24, 2012
" Notes:        based on Bram Moneaar's indent file for vim

"set nocindent
"set smartindent
set autoindent

setlocal indentexpr=GetRoyIndent()
setlocal indentkeys+==end,=else,=catch,=}

" Only define the function onceo
if exists("*GetRoyIndent")
endif

function! GetRoyIndent()
  " Find a non-blank line above the current line.
  let lnum = prevnonblank(v:lnum - 1)

  " At the start of the file use zero indent.
  if lnum == 0
    return 0
  endif

  " Add a 'shiftwidth' after matched strings
  let ind = indent(lnum)
  let line = getline(lnum)

  let i = match(line, '\.*\(if\)\.*')
  if i >= 0
    let ind = i + &sw
  endif

  if match(line, '\.*{\s*$') >= 0
    let ind += &sw
  endif

  if match(line, '\.*=\s*$') >= 0
    let ind += &sw
  endif

  let i = match(line, '^\s*\(where\|else\|do\)')
  if i >= 0
    let ind += &sw
  endif

  " Subtract a 'shiftwidth' on a end, catch, else and elseif
  if getline(v:lnum) =~ '^\s*\(else\|}\)'
    let ind -= &sw
  endif

  return ind
endfunction

Remove possibly buggy indent rule

" Vim indent file
" Language:	Roy
" Maintainer:	Bill Casarin <bill@casarin.ca>
" Last Change:	April 24, 2012
" Notes:        based on Bram Moneaar's indent file for vim

"set nocindent
"set smartindent
set autoindent

setlocal indentexpr=GetRoyIndent()
setlocal indentkeys+==end,=else,=catch,=}

" Only define the function onceo
if exists("*GetRoyIndent")
endif

function! GetRoyIndent()
  " Find a non-blank line above the current line.
  let lnum = prevnonblank(v:lnum - 1)

  " At the start of the file use zero indent.
  if lnum == 0
    return 0
  endif

  " Add a 'shiftwidth' after matched strings
  let ind = indent(lnum)
  let line = getline(lnum)

  if match(line, '\.*{\s*$') >= 0
    let ind += &sw
  endif

  if match(line, '\.*=\s*$') >= 0
    let ind += &sw
  endif

  let i = match(line, '^\s*\(if\|where\|else\|do\)')
  if i >= 0
    let ind += &sw
  endif

  " Subtract a 'shiftwidth' on a end, catch, else and elseif
  if getline(v:lnum) =~ '^\s*\(else\|}\)'
    let ind -= &sw
  endif

  return ind
endfunction


au BufRead,BufNewFile /etc/nginx/conf/* set ft=nginx

Add json file type for vim

au BufRead,BufNewFile /etc/nginx/conf/* set ft=nginx
au! BufRead,BufNewFile *.json set ft=json


function autocmd#setup()
  set autoread

  " Filetypes
  au BufRead,BufNewFile *.rb,*.rabl,*.json.jbuilder,Capfile,Vagrantfile setf ruby
  au BufRead,BufNewFile *.htm.erb setf html.eruby
  au BufRead,BufNewFile *.json.erb setf javascript.eruby
  au BufRead,BufNewFile *.json,*.ejson,*.ehs,*.es6 setf javascript
  au BufRead,BufNewFile *.go setf go

  " Emmet file types
  au FileType html,html.eruby,css,haml,eruby,handlebars,liquid EmmetInstall

  " File types that require tabs, not spaces
  au FileType make set noexpandtab

  " Manage whitespace on save, maintaining cursor position
  au FileType vim,ruby,haml,eruby,javascript,coffee,css,scss,lua,handlebars,python,yaml
        \au BufWritePre <buffer> call functions#ClearTrailingWhitespace()

  " Remember last location in file, but not for commit messages. (see :help last-position-jump)
  au BufReadPost * if &filetype !~ '^git\c' && line("'\"") > 0 && line("'\"") <= line("$") | exe "normal! g`\"" | endif

  " Close when NERDTree is the last open buffer
  au bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
endfunc

Fix issue with command across multiple lines

function autocmd#setup()
  set autoread

  " Filetypes
  au BufRead,BufNewFile *.rb,*.rabl,*.json.jbuilder,Capfile,Vagrantfile setf ruby
  au BufRead,BufNewFile *.htm.erb setf html.eruby
  au BufRead,BufNewFile *.json.erb setf javascript.eruby
  au BufRead,BufNewFile *.json,*.ejson,*.ehs,*.es6 setf javascript
  au BufRead,BufNewFile *.go setf go

  " Emmet file types
  au FileType html,html.eruby,css,haml,eruby,handlebars,liquid EmmetInstall

  " File types that require tabs, not spaces
  au FileType make set noexpandtab

  " Manage whitespace on save, maintaining cursor position
  au FileType vim,ruby,haml,eruby,javascript,coffee,css,scss,lua,handlebars,python,yaml
        \ au BufWritePre <buffer> call functions#ClearTrailingWhitespace()

  " Remember last location in file, but not for commit messages. (see :help last-position-jump)
  au BufReadPost * if &filetype !~ '^git\c' && line("'\"") > 0 && line("'\"") <= line("$") | exe "normal! g`\"" | endif

  " Close when NERDTree is the last open buffer
  au bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
endfunc


if has("gui_macvim")
  map <D-/> <plug>NERDCommenterToggle<CR>
  imap <D-/> <Esc><plug>NERDCommenterToggle<CR>i
endif

Add mappings for non-osx systems.

if has("gui_macvim")
  map <D-/> <plug>NERDCommenterToggle<CR>
  imap <D-/> <Esc><plug>NERDCommenterToggle<CR>i
else
  map <leader>/ <plug>NERDCommenterToggle<CR>
  imap <leader>/ <Esc><plug>NERDCommenterToggle<CR>i
endif


" Turn on spell checking.
setlocal spell

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

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

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

Remove git commit buffer save

" Turn on spell checking.
setlocal spell

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

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


" Plugin settings

nmap <leader>t :PickerEdit<CR>
nmap <leader><S-t> :PickerBuffer<CR>
nmap <leader>l :FSHere<CR>
nmap <leader><S-l> :split<CR> :FSBelow<CR>
nmap <leader>p :Welcome<CR>
nmap <leader>n :SimplenoteList

set laststatus=2
set noshowmode
let g:lightline = {
      \ 'colorscheme': 'wombat',
      \ 'active': {
      \   'left': [ [ 'mode', 'paste' ], [ 'fugitive', 'filename', 'modified'] ],
      \   'right': [ [ 'syntastic', 'lineinfo' ], ['percent'] ]
      \ },
      \ 'inactive': {
      \   'left': [ [ 'filename', 'modified'] ],
      \   'right': [ [ 'syntastic', 'lineinfo' ], ['percent'] ]
      \ },
      \ 'component': {
      \   'modified': '%{&filetype=="help"?"":&modified?"+":&modifiable?"":"-"}',
      \ },
      \ 'component_function': {
      \   'fugitive': 'MyFugitive',
      \ },
      \ }
function! MyFugitive()
  try
    if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head')
      let _ = fugitive#head()
      return strlen(_) ? '<'._.'>' : ''
    endif
  catch
  endtry
  return ''
endfunction

Use fzf.vim for searching files and buffers

" Plugin settings

nmap <leader>t :Files<CR>
nmap <leader><S-t> :Buffers<CR>
nmap <leader>l :FSHere<CR>
nmap <leader><S-l> :split<CR> :FSBelow<CR>
nmap <leader>p :Welcome<CR>
nmap <leader>n :SimplenoteList

set laststatus=2
set noshowmode
let g:lightline = {
      \ 'colorscheme': 'wombat',
      \ 'active': {
      \   'left': [ [ 'mode', 'paste' ], [ 'fugitive', 'filename', 'modified'] ],
      \   'right': [ [ 'syntastic', 'lineinfo' ], ['percent'] ]
      \ },
      \ 'inactive': {
      \   'left': [ [ 'filename', 'modified'] ],
      \   'right': [ [ 'syntastic', 'lineinfo' ], ['percent'] ]
      \ },
      \ 'component': {
      \   'modified': '%{&filetype=="help"?"":&modified?"+":&modifiable?"":"-"}',
      \ },
      \ 'component_function': {
      \   'fugitive': 'MyFugitive',
      \ },
      \ }
function! MyFugitive()
  try
    if expand('%:t') !~? 'Tagbar\|Gundo\|NERD' && &ft !~? 'vimfiler' && exists('*fugitive#head')
      let _ = fugitive#head()
      return strlen(_) ? '<'._.'>' : ''
    endif
  catch
  endtry
  return ''
endfunction


" ruby_spin.vim
"
" Author: David Vollbracht <david@flipstone.com>
" Version: 1.0 for Vim 7.3
" Last Change:  2012 5/16
" Licence: Public Domain
"
" Description:
"
if exists("g:loaded_ruby_spin")
  finish
endif
let g:loaded_ruby_spin = 1

let s:files = ""

function! s:SpinAddCurrent()
  let s:files = s:files . " " . @%
  call s:Spin()
endfunction

function! s:SpinClear()
  let s:files = ""
endfunction

function! s:Spin()
  call system("spin push " . s:files)
endfunction

command! -nargs=0 SpinAdd :call s:SpinAddCurrent()
command! -nargs=0 SpinClear :call s:SpinClear()
command! -nargs=0 Spin :call s:Spin()

Add Spin commands for enabling/disabling automatic spin on buf post write

" ruby_spin.vim
"
" Author: David Vollbracht <david@flipstone.com>
" Version: 1.0 for Vim 7.3
" Last Change:  2012 5/16
" Licence: Public Domain
"
" Description:
"
if exists("g:loaded_ruby_spin")
  finish
endif
let g:loaded_ruby_spin = 1

let s:files = ""

function! s:SpinAddCurrent()
  let s:files = s:files . " " . @%
  call s:Spin()
endfunction

function! s:SpinClear()
  let s:files = ""
endfunction

function! s:Spin()
  call system("spin push " . s:files)
endfunction

augroup Spin

command! -nargs=0 SpinAdd :call s:SpinAddCurrent()
command! -nargs=0 SpinClear :call s:SpinClear()
command! -nargs=0 Spin :call s:Spin()
command! -nargs=0 AutoSpin :autocmd Spin BufWritePost * Spin
command! -nargs=0 NoAutoSpin :autocmd! Spin BufWritePost *


" MIT License. Copyright (c) 2013 Bailey Ling.
" vim: et ts=2 sts=2 sw=2

if !exists(':ProjectCreate')
  finish
endif

function! airline#extensions#eclim#get_warnings()
  let eclimList = eclim#display#signs#GetExisting()
  if !empty(eclimList)
    let errorsLine = eclimList[0]['line']
    let errorsNumber = len(eclimList)
    let errors = "[Eclim: line:".string(errorsLine)." (".string(errorsNumber).")]"
    if !exists(':SyntasticStatuslineFlag') || SyntasticStatuslineFlag() == ''
      return errors.(g:airline_symbols.space)
    endif
  endif
  return ''
endfunction

function! airline#extensions#eclim#init(ext)
  call airline#parts#define_function('eclim', 'airline#extensions#eclim#get_warnings')
endfunction

Fix a wrong determines order name. It should be ':SyntasticCheck' not ':SyntasticStatuslineFlag'.

" MIT License. Copyright (c) 2013 Bailey Ling.
" vim: et ts=2 sts=2 sw=2

if !exists(':ProjectCreate')
  finish
endif

function! airline#extensions#eclim#get_warnings()
  let eclimList = eclim#display#signs#GetExisting()
  if !empty(eclimList)
    let errorsLine = eclimList[0]['line']
    let errorsNumber = len(eclimList)
    let errors = "[Eclim: line:".string(errorsLine)." (".string(errorsNumber).")]"
    if !exists(':SyntasticCheck') || SyntasticStatuslineFlag() == ''
      return errors.(g:airline_symbols.space)
    endif
  endif
  return ''
endfunction

function! airline#extensions#eclim#init(ext)
  call airline#parts#define_function('eclim', 'airline#extensions#eclim#get_warnings')
endfunction


Bundle 'The-NERD-tree'
Bundle 'Command-T'
Bundle 'Indent-Guides'
Bundle 'trailing-whitespace'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'ack.vim'
Bundle 'snipMate'
Bundle 'tComment'
Bundle 'git://github.com/nathanaelkane/snipmate-snippets.git'

Update various vim plugins to use github repos.

Bundle 'scrooloose/nerdtree'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'nathanaelkane/snipmate-snippets'
Bundle 'nathanaelkane/vim-indent-guides'
Bundle 'wincent/Command-T'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'ack.vim'
Bundle 'snipMate'
Bundle 'tomtom/tcomment_vim'


call plug#begin()
Plug 'airblade/vim-gitgutter'
Plug 'altercation/vim-colors-solarized'
Plug 'jalvesaq/R-Vim-runtime'
Plug 'jalvesaq/Nvim-R'
Plug 'kien/ctrlp.vim'
Plug 'klmr/vim-snakemake'
Plug 'micha/vim-colors-solarized'
Plug 'moby/moby' , {'rtp': '/contrib/syntax/vim/'}
Plug 'plasticboy/vim-markdown'
Plug 'raghur/vim-ghost', {'do': ':GhostInstall'}
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'vim-airline/vim-airline'
Plug 'w0rp/ale'
call plug#end()

let g:ale_sign_error = '❌ '
let g:ale_sign_warning = '⚠ '

Remove problematic Unicode gutter signs


augroup vimtss
	autocmd!
	autocmd BufReadPost *.ts,*.tsx call tss#openFile(expand('<afile>'))
	autocmd BufDelete *.ts,*.tsx call tss#closeFile(expand('<afile>'))
augroup END

" The job ID of the currently running tss server
let g:tss_server_id = 0

" If non-zero, display debug messages
let g:tss_verbose = 0

Check for option values before setting

" If non-zero, display debug messages
if !exists('g:tss_verbose')
	let g:tss_verbose = 0
endif

augroup vimtss
	autocmd!
	autocmd BufReadPost *.ts,*.tsx call tss#openFile(expand('<afile>'))
	autocmd BufDelete *.ts,*.tsx call tss#closeFile(expand('<afile>'))
augroup END

" The job ID of the currently running tss server
let g:tss_server_id = 0


" on startup, open NERDTree w/ files, goto (last window)
autocmd VimEnter * NERDTree
autocmd VimEnter * wincmd p

" on startup, open NERDTree if no files are specified
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif

" close Vim if only window open is NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

" keymap to show/hide NERDTree
map <C-n> :NERDTreeToggle<cr>

" Make nerdtree look nice
let NERDTreeMinimalUI = 1

" helper function to detect NERDTree window
function! NERDTreeInFocus()
   if matchstr(expand("%"), 'NERD') == 'NERD'
      return 1
   else
      return 0
endfunction

Improve NERDTree buffer name match

" on startup, open NERDTree w/ files, goto (last window)
autocmd VimEnter * NERDTree
autocmd VimEnter * wincmd p

" on startup, open NERDTree if no files are specified
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif

" close Vim if only window open is NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif

" keymap to show/hide NERDTree
map <C-n> :NERDTreeToggle<cr>

" make nerdtree look nice
let NERDTreeMinimalUI = 1

" set default width
let NERDTreeWinSize = 22

" helper function to detect NERDTree window
function! NERDTreeInFocus()
   return matchstr(expand("%"), 'NERD_tree_') == 'NERD_tree_'
endfunction


command! Wq wq
command! Sudow w !sudo tee %
command! Q q

Remove annoying W command that closes the buffer

command! Wq wq
command! Sudow w !sudo tee %
command! Q q
command! W w


" You can make commands run after plugins are loaded from the .vimrc (and
" init/ directory) like so:
"
"   autocmd User AfterBundles SomePluginCommand
"
" This lets you use commands defined in plugins, which haven't been created at
" .vimrc-time.

doautocmd User AfterBundles

Use silent doautocmd for after bundles

" You can make commands run after plugins are loaded from the .vimrc (and
" init/ directory) like so:
"
"   autocmd User AfterBundles SomePluginCommand
"
" This lets you use commands defined in plugins, which haven't been created at
" .vimrc-time.

silent doautocmd User AfterBundles


" Autocompletion via neco-ghc
let g:haskellmode_completion_ghc = 0
setlocal omnifunc=necoghc#omnifunc

nnoremap <buffer> <silent> <F8> :wa<CR>:NeomakeProject stackbuild<CR>

" ghc-mod mappings
nnoremap <silent> <leader>ht :GhcModType!<CR>
nnoremap <silent> <leader>hI :GhcModTypeInsert!<CR>
nnoremap <silent> <leader>hl :GhcModTypeClear<CR>
nnoremap <silent> <leader>hi :GhcModInfo!<CR>

" Auto-sort imports
autocmd BufWritePre <buffer> HaskellSortImport

Use Intero for go to definition

" Autocompletion via neco-ghc
let g:haskellmode_completion_ghc = 0
setlocal omnifunc=necoghc#omnifunc

nnoremap <buffer> <silent> <F8> :wa<CR>:NeomakeProject stackbuild<CR>

" ghc-mod mappings
nnoremap <silent> <leader>ht :GhcModType!<CR>
nnoremap <silent> <leader>hI :GhcModTypeInsert!<CR>
nnoremap <silent> <leader>hl :GhcModTypeClear<CR>
nnoremap <silent> <leader>hi :GhcModInfo!<CR>

" Replace tags with Intero
nnoremap <silent> <C-]> :InteroGoToDef<CR>

" Auto-sort imports
autocmd BufWritePre <buffer> HaskellSortImport


if exists("g:loaded_tmux_complete") || &cp || v:version < 700
    finish
endif
let g:loaded_tmux_complete = '0.0.1' " version number
let s:save_cpoptions = &cpoptions
set cpo&vim

" Deprecated completion function
" use tmuxcomplete#complete
function! CompleteScript(findstart, base)
    return tmuxcomplete#complete(a:findstart, a:base)
endfun

set completefunc=tmuxcomplete#complete

let &cpoptions = s:save_cpoptions
unlet s:save_cpoptions

Remove function CompleteScript and cpoptions

if exists("g:loaded_tmux_complete") || &cp || v:version < 700
    finish
endif
let g:loaded_tmux_complete = '0.0.1' " version number

set completefunc=tmuxcomplete#complete


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

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

" Some keyboards are inclined to this
iabbrev SOn Son
iabbrev GOd God
iabbrev ANd And
iabbrev FOr For
iabbrev HIm Him

Add abbreviation for JOb -> Job

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

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

" Some keyboards are inclined to this
iabbrev SOn Son
iabbrev GOd God
iabbrev ANd And
iabbrev FOr For
iabbrev HIm Him
iabbrev JOb Job
iabbrev OUr Our


" FUNCTIONS {{{
  " fuzzy serach buffers
  command! FZFBuffers call fzf#run({
    \ 'source':  BuffersList(),
    \ 'sink':    'e ',
    \ 'tmux_height': '30%'
  \})

  " fuzzy search most recently opened files
  command! FZFMru call fzf#run({
    \'source': v:oldfiles,
    \'sink' : 'e ',
    \ 'tmux_height': '30%'
  \})
" }}}

" SETTINGS {{{
" }}}

" MAPPINGS {{{
  nnoremap <leader>f :FZF<cr>
  nnoremap <leader>fb :FZFBuffers<cr>
  nnoremap <leader>fm :FZFMru<cr>
" }}}

Add FZF command to search git files

" FUNCTIONS {{{
  " fuzzy serach buffers
  command! FZFBuffers call fzf#run({
    \ 'source':  BuffersList(),
    \ 'sink':    'e ',
    \ 'tmux_height': '30%'
  \})

  " fuzzy search most recently opened files
  command! FZFMru call fzf#run({
    \'source': v:oldfiles,
    \'sink' : 'e ',
    \ 'tmux_height': '30%'
  \})

  function! FZFGit()
    " Remove trailing new line to make it work with tmux splits
    let directory = substitute(system('git rev-parse --show-toplevel'), '\n$', '', '')
    if !v:shell_error
      call fzf#run({'sink': 'e', 'dir': directory, 'source': 'git ls-files', 'tmux_height': '40%'})
    else
      FZF
    endif
  endfunction
  command! FZFGit call FZFGit()
" }}}

" SETTINGS {{{
" }}}

" MAPPINGS {{{
  nnoremap <leader>f :FZF<cr>
  nnoremap <leader>fg :FZFGit<cr>
  nnoremap <leader>fb :FZFBuffers<cr>
  nnoremap <leader>fm :FZFMru<cr>
" }}}


" Enable spellchecking
setlocal spell

" Automatically wrap at 80 characters
setlocal textwidth=80

" Limelight settings
let g:limelight_paragraph_span = 1
let g:limelight_priority = -1

" Set fullscreen and linespace when entering goyo
function! s:goyo_enter()
  if has('gui_running')
    set fullscreen
    set linespace=7
  endif
  Limelight
endfunction

" Reset fullscreen and linespace when leaving goyo
function! s:goyo_leave()
  if has('gui_running')
    set nofullscreen
    set linespace=0
  endif
  Limelight!
endfunction

autocmd! User GoyoEnter nested call <SID>goyo_enter()
autocmd! User GoyoLeave nested call <SID>goyo_leave()

" Toggle goyo
nnoremap <leader>G :Goyo<CR>

Remove going fullscreen when running Goyo

" Enable spellchecking
setlocal spell

" Automatically wrap at 80 characters
setlocal textwidth=80

" Limelight settings
let g:limelight_paragraph_span = 1
let g:limelight_priority = -1

" Set fullscreen and linespace when entering goyo
function! s:goyo_enter()
  if has('gui_running')
    set linespace=7
  endif
  Limelight
endfunction

" Reset fullscreen and linespace when leaving goyo
function! s:goyo_leave()
  if has('gui_running')
    set linespace=0
  endif
  Limelight!
endfunction

autocmd! User GoyoEnter nested call <SID>goyo_enter()
autocmd! User GoyoLeave nested call <SID>goyo_leave()

" Toggle goyo
nnoremap <Leader>G :Goyo<CR>


" set background=light " light theme
set background=dark " dark theme
colorscheme solarized

highlight clear IncSearch
highlight IncSearch term=reverse cterm=reverse ctermfg=7 ctermbg=0 guifg=Black guibg=Yellow
highlight VertSplit ctermbg=NONE guibg=NONE

function! GitBranch()
  return system("git rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
endfunction

function! StatuslineGit()
  let l:branchname = GitBranch()
  return strlen(l:branchname) > 0?'  '.l:branchname.' ':''
endfunction

" Always show statusline
set laststatus=2

" Statusline appearance
set statusline=
set statusline+=%#PmenuSel#
set statusline+=%{StatuslineGit()}
set statusline+=%#LineNr#
set statusline+=%<
set statusline+=\ %f
set statusline+=%=
set statusline+=%#CursorColumn#
set statusline+=\ %y
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
set statusline+=\[%{&fileformat}\]
set statusline+=\ %P
set statusline+=\ %l:%c
set statusline+=\
set statusline+=%m%h%r

" Vim Conflicted
set statusline+=%{ConflictedVersion()}

Add extra modified symbol in center of statusline.

" set background=light " light theme
set background=dark " dark theme
colorscheme solarized

highlight clear IncSearch
highlight IncSearch term=reverse cterm=reverse ctermfg=7 ctermbg=0 guifg=Black guibg=Yellow
highlight VertSplit ctermbg=NONE guibg=NONE

function! GitBranch()
  return system("git rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
endfunction

function! StatuslineGit()
  let l:branchname = GitBranch()
  return strlen(l:branchname) > 0?'  '.l:branchname.' ':''
endfunction

" Always show statusline
set laststatus=2

" Statusline appearance
set statusline=
set statusline+=%#PmenuSel#
set statusline+=%{StatuslineGit()}
set statusline+=%#LineNr#
set statusline+=%<
set statusline+=\ %f
set statusline+=%m
set statusline+=%=
set statusline+=%#CursorColumn#
set statusline+=\ %y
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
set statusline+=\[%{&fileformat}\]
set statusline+=\ %P
set statusline+=\ %l:%c
set statusline+=\
set statusline+=%m%h%r

" Vim Conflicted
set statusline+=%{ConflictedVersion()}


function! s:SetUpLoupeHighlight()
  highlight! link Search Underlined
endfunction

if has('autocmd')
  augroup WincentLoupe
    autocmd!
    autocmd ColorScheme * call s:SetUpLoupeHighlight()
  augroup END
endif

Make Search highlighting bold like it was before

function! s:SetUpLoupeHighlight()
  highlight! clear Search
  execute 'highlight! Search ' . pinnacle#embolden('Underlined')
endfunction

if has('autocmd')
  augroup WincentLoupe
    autocmd!
    autocmd ColorScheme * call s:SetUpLoupeHighlight()
  augroup END
endif


if has ('vim_starting')
    set nocompatible

    set runtimepath+=~/.vim/bundle/neobundle.vim/

    let mapleader = " "
endif

call neobundle#begin(expand('~/.vim/bundle/'))

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim

Use different runtimepaths for NeoVim and VIm.

if has ('vim_starting')
    set nocompatible

    if has ('nvim')
        set runtimepath+=~/.config/nvim/bundle/neobundle.vim/
    else
        set runtimepath+=~/.vim/bundle/neobundle.vim/
    endif

    let mapleader = " "
endif

if has ('nvim')
    call neobundle#begin(expand('~/.config/nvim/bundle/'))
else
    call neobundle#begin(expand('~/.vim/bundle/'))
endif

runtime! bundles.vim

call neobundle#end()

NeoBundleCheck

" delegate configuration to files in config/
runtime! config/**/*.vim


let b:splitjoin_split_callbacks = [
      \ 'sj#html#SplitTags',
      \ 'sj#html#SplitAttributes',
      \ 'sj#js#SplitArray',
      \ 'sj#js#SplitObjectLiteral',
      \ 'sj#js#SplitFunction',
      \ 'sj#js#SplitOneLineIf',
      \ 'sj#js#SplitArgs'
      \ ]

let b:splitjoin_join_callbacks = [
      \ 'sj#html#JoinAttributes',
      \ 'sj#html#JoinTags',
      \ 'sj#js#JoinArray',
      \ 'sj#js#JoinArgs',
      \ 'sj#js#JoinFunction',
      \ 'sj#js#JoinOneLineIf',
      \ 'sj#js#JoinObjectLiteral',
      \ ]

Include fat arrow function handling in jsx as well

let b:splitjoin_split_callbacks = [
      \ 'sj#html#SplitTags',
      \ 'sj#html#SplitAttributes',
      \ 'sj#js#SplitFatArrowFunction',
      \ 'sj#js#SplitArray',
      \ 'sj#js#SplitObjectLiteral',
      \ 'sj#js#SplitFunction',
      \ 'sj#js#SplitOneLineIf',
      \ 'sj#js#SplitArgs'
      \ ]

let b:splitjoin_join_callbacks = [
      \ 'sj#html#JoinAttributes',
      \ 'sj#html#JoinTags',
      \ 'sj#js#JoinFatArrowFunction',
      \ 'sj#js#JoinArray',
      \ 'sj#js#JoinArgs',
      \ 'sj#js#JoinFunction',
      \ 'sj#js#JoinOneLineIf',
      \ 'sj#js#JoinObjectLiteral',
      \ ]


"
" Airline Themes
"

" Set the theme to use
let g:airline_theme='solarized'

Set dark background for solarized theme

"
" Airline Themes
" https://github.com/vim-airline/vim-airline
"

" Set the theme to use
let g:airline_theme='solarized'
let g:airline_solarized_bg='dark'


" Bind Ctrl-S to update.
nnoremap <silent> <C-S> :<C-U>update<CR>

" Close the buffer but not the window.
nnoremap <silent> <C-W> :<C-U>BD<CR>

" Clear highlighting until next search.
nnoremap <silent> <C-I> :<C-U>nohlsearch<CR>

" Toggle highlighting.
nnoremap <silent> <leader>h :<C-U>set hlsearch!<CR>

" Copy to system clipboard.
map <leader>c "+y
map <leader>cc "+yy
map <silent> <leader>ca :<C-U>%y+<CR>

" Paste from system clipboard.
nnoremap <leader>p "+p
nnoremap <leader>P "+P

Add shortcuts to open split.

" Shortcuts to open splits.
nnoremap <silent> ,s :<C-U>split<CR>
nnoremap <silent> ,v :<C-U>vsplit<CR>

" Bind Ctrl-S to update.
nnoremap <silent> <C-S> :<C-U>update<CR>

" Close the buffer but not the window.
nnoremap <silent> <C-W> :<C-U>BD<CR>

" Clear highlighting until next search.
nnoremap <silent> <C-I> :<C-U>nohlsearch<CR>

" Toggle highlighting.
nnoremap <silent> <leader>h :<C-U>set hlsearch!<CR>

" Copy to system clipboard.
map <leader>c "+y
map <leader>cc "+yy
map <silent> <leader>ca :<C-U>%y+<CR>

" Paste from system clipboard.
nnoremap <leader>p "+p
nnoremap <leader>P "+P


" Keep more lines of context around where I'm working.
set sidescrolloff=5
set scrolloff=8

" Scroll the viewport faster.
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>

Update number of screen lines to keep around the cursor

" Keep more lines of context around where I'm working.
set sidescrolloff=5
set scrolloff=5

" Scroll the viewport faster.
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>


let g:syntastic_ruby_checkers = ['flog', 'reek', 'rubylint']
let g:syntastic_haml_checkers = ['haml_lint']

Add additional configuration to syntastic

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

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

let g:syntastic_ruby_checkers = ['flog', 'reek', 'rubylint']
let g:syntastic_haml_checkers = ['haml_lint']


setlocal expandtab
setlocal shiftwidth=2
setlocal tabstop=2

Use prettier as fixer for CSS

let b:ale_fixers = ['prettier']
setlocal expandtab
setlocal shiftwidth=2
setlocal tabstop=2


let test#strategy = "neovim"
let test#neovim#term_position = "vert botright"

nmap <silent> <leader>st :TestNearest<CR>
nmap <silent> <leader>sT :TestFile<CR>
nmap <silent> <leader>sa :TestSuite<CR>
nmap <silent> <leader>sl :TestLast<CR>
nmap <silent> <leader>ss :TestVisit<CR>

Add shortcut for test current file

let test#strategy = "neovim"
let test#neovim#term_position = "vert botright"

nmap <silent> <leader>st :TestNearest<CR>
nmap <silent> <leader>sT :TestFile<CR>
nmap <silent> <LocalLeader>t :TestFile<CR>
nmap <silent> <leader>sa :TestSuite<CR>
nmap <silent> <leader>sl :TestLast<CR>
nmap <silent> <leader>ss :TestVisit<CR>


" Vim syntax file
" Language: Simio I/O Automata
" Maintainer: Jon Gjengset
" Latest Revision: 4 December 2014

if exists("b:current_syntax")
  finish
endif

syn include @Python syntax/python.vim

" Keywords
syn match Comment /^#.*/
syn match sectionKeywords /^\(Name\|Signature-\(Input\|Output\)\|Tasks\)/
syn match sectionKeywords /^Transition-Name/
syn match executableKeywords /^\(State\|\(Transition-\(Precondition\|Output\|Effect\)\)\)/ contained
hi def link executableKeywords Identifier
hi def link sectionKeywords Identifier

syn region stateRegion start=/^State:/ end=/^\ze[^ \t]/ contains=executableKeywords,@Python
syn region transitionRegion start=/^Transition-\(Precondition\|Output\|Effect\):/ end=/^\ze[^ \t]/ contains=executableKeywords,@Python

let b:current_syntax = "simio"

Update vim syntax to handle new vars

" Vim syntax file
" Language: Simio I/O Automata
" Maintainer: Jon Gjengset
" Latest Revision: 4 December 2014

if exists("b:current_syntax")
  finish
endif

syn include @Python syntax/python.vim

" Keywords
syn match Comment /^\s*#.*$/
syn match sectionKeywords /^\(Name\|Signature-\(Input\|Output\)\|Tasks\)/
syn match sectionKeywords /^Transition-Name/
syn match executableKeywords /^\(State\|\(Transition-\(Precondition\|Output\|Effect\)\)\)/ contained
syn match specialVariables /\<self\.\(i\|weights\|nbrs\)\>/ contained
syn match specialVariables /\<\(to\|from\)\>/ contained
syn match globalVariables /\<N\>/ contained
hi def link executableKeywords Identifier
hi def link sectionKeywords Identifier
hi def link specialVariables Special
hi def link globalVariables Define

syn match connectKeyword /\<connect\>/ contained
hi def link connectKeyword Keyword

syn region sigOutRegion start=/^Signature-Output:/ end=/^\ze[^ \t]/ contains=sectionKeywords,connectKeyword,Comment
syn region stateRegion start=/^State:/ end=/^\ze[^ \t]/ contains=executableKeywords,@Python,specialVariables,globalVariables
syn region transitionRegion start=/^Transition-\(Precondition\|Output\|Effect\):/ end=/^\ze[^ \t]/ contains=executableKeywords,@Python,specialVariables,globalVariables

let b:current_syntax = "simio"


inoremap <buffer> --- —
inoremap <buffer> -- –
setlocal spell
setlocal nojoinspaces
setlocal textwidth=80
setlocal colorcolumn=80
setlocal softtabstop=2
setlocal formatoptions+=n " Recognize numbered lists

Use Limelight and HardPencil in Markdown files

inoremap <buffer> --- —
inoremap <buffer> -- –
setlocal spell
setlocal nojoinspaces
setlocal textwidth=80
setlocal colorcolumn=80
setlocal softtabstop=2
setlocal formatoptions+=n " Recognize numbered lists
silent! Limelight
silent! HardPencil


" Always display and search dotfiles/dotdirectories
let g:CommandTAlwaysShowDotFiles = 1
let g:CommandTScanDotDirectores = 1

" Show the match window at the top of the screen rather than the bottom
let g:CommandTMatchWindowAtTop = 1

" Don't show any more than 25 matches at once
let g:CommandTMaxHeight=25

noremap <leader>N <Esc>:CommandTFlush<CR>

Change ,N to ,T for CommandTFlush

" Always display and search dotfiles/dotdirectories
let g:CommandTAlwaysShowDotFiles = 1
let g:CommandTScanDotDirectores = 1

" Show the match window at the top of the screen rather than the bottom
let g:CommandTMatchWindowAtTop = 1

" Don't show any more than 25 matches at once
let g:CommandTMaxHeight=25

noremap <leader>T <Esc>:CommandTFlush<CR>


" Fast saving
nmap <leader>w :w!<CR>

" Fast saving & exiting
nmap <leader>x :x<CR>

nmap <leader>qa :qall<CR>

" Smart-insert semicolon
inoremap <leader>; <C-o>A;<Esc>:w<CR>
nnoremap <leader>; A;<Esc>:w<CR>

Make Y consistent with C and D

" Fast saving
nmap <leader>w :w!<CR>

" Fast saving & exiting
nmap <leader>x :x<CR>

nmap <leader>qa :qall<CR>

" Smart-insert semicolon
inoremap <leader>; <C-o>A;<Esc>:w<CR>
nnoremap <leader>; A;<Esc>:w<CR>

" Make Y consistent with C and D
nnoremap Y y$


call plug#begin('~/.local/share/nvim/plugged')

" Colourscheme
Plug 'AlessandroYorba/Despacio'

" File management
Plug 'scrooloose/nerdtree'
"Plug '/usr/bin/fzf'
"Plug 'junegunn/fzf.vim'
Plug 'Shougo/denite.nvim', { 'do': ':UpdateRemotePlugins' }

" Airline
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'

" Git
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'
Plug 'airblade/vim-gitgutter'

" Autocomplete
Plug 'neoclide/coc.nvim', {'branch': 'release'}

" Syntax
Plug 'modille/groovy.vim'
Plug 'neovimhaskell/haskell-vim'

call plug#end()

Add typescript syntax to neovim

call plug#begin('~/.local/share/nvim/plugged')

" Colourscheme
Plug 'AlessandroYorba/Despacio'

" File management
Plug 'scrooloose/nerdtree'
"Plug '/usr/bin/fzf'
"Plug 'junegunn/fzf.vim'
Plug 'Shougo/denite.nvim', { 'do': ':UpdateRemotePlugins' }

" Airline
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'

" Git
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-rhubarb'
Plug 'airblade/vim-gitgutter'

" Autocomplete
Plug 'neoclide/coc.nvim', {'branch': 'release'}

" Syntax
Plug 'modille/groovy.vim'
Plug 'neovimhaskell/haskell-vim'
Plug 'leafgarland/typescript-vim'

call plug#end()


set nocompatible
filetype off

filetype plugin indent on

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

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

Bundle 'tpope/vim-fugitive'
Bundle 'maksimr/vim-jsbeautify'
Bundle 'juvenn/mustache.vim'
Bundle 'groenewege/vim-less'
Bundle 'saltstack/salt-vim'
Bundle 'tpope/vim-markdown'
Bundle 'editorconfig/editorconfig-vim'
Bundle 'majutsushi/tagbar'
Bundle 'scrooloose/nerdtree'
Bundle 'klen/python-mode'
Bundle 'einars/js-beautify'
Bundle 'Lokaltog/vim-powerline'
Bundle 'aaronj1335/underscore-templates.vim'

filetype plugin indent on

Add Erik Zaadi's excellent autoinstall tweak

set nocompatible
filetype off

filetype plugin indent on

" Setting up Vundle - the vim plugin bundler
let iCanHazVundle=1
let vundle_readme=expand('~/.vim/bundle/vundle/README.md')
if !filereadable(vundle_readme)
    echo "Installing Vundle.."
    echo ""
    silent !mkdir -p ~/.vim/bundle
    silent !git clone https://github.com/gmarik/vundle ~/.vim/bundle/vundle
    let iCanHazVundle=0
endif

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

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

Bundle 'tpope/vim-fugitive'
Bundle 'maksimr/vim-jsbeautify'
Bundle 'juvenn/mustache.vim'
Bundle 'groenewege/vim-less'
Bundle 'saltstack/salt-vim'
Bundle 'tpope/vim-markdown'
Bundle 'editorconfig/editorconfig-vim'
Bundle 'majutsushi/tagbar'
Bundle 'scrooloose/nerdtree'
Bundle 'klen/python-mode'
Bundle 'einars/js-beautify'
Bundle 'Lokaltog/vim-powerline'
Bundle 'aaronj1335/underscore-templates.vim'

if iCanHazVundle == 0
    echo "Installing Bundles, please ignore key map error messages"
    echo ""
    :BundleInstall
endif
" Setting up Vundle - the vim plugin bundler end

filetype plugin indent on


highlight! ZettelLinkHeader cterm=underline,bold ctermfg=97
highlight! ZettelLink cterm=underline ctermfg=97

Tweak highlighting in md files

highlight! ZettelLinkHeader cterm=underline,bold ctermfg=97
highlight! ZettelLink cterm=underline ctermfg=97
highlight clear SpellBad
highlight SpellBad ctermbg=53


" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" go.vim: Vim filetype plugin for Go.

if exists("b:did_ftplugin")
    finish
endif
let b:did_ftplugin = 1

setlocal formatoptions-=t

setlocal comments=s1:/*,mb:*,ex:*/,://
setlocal commentstring=//\ %s

let b:undo_ftplugin = "setl fo< com< cms<"

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

Add mappings to make [[, ]], etc. work when editing Go files in Vim.

" Copyright 2013 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" go.vim: Vim filetype plugin for Go.

if exists("b:did_ftplugin")
    finish
endif
let b:did_ftplugin = 1

setlocal formatoptions-=t

setlocal comments=s1:/*,mb:*,ex:*/,://
setlocal commentstring=//\ %s

let b:undo_ftplugin = "setl fo< com< cms<"

map <buffer> <silent> ]] :call search("^}$")<CR>
map <buffer> <silent> [[ :call search("^func", 'b')<CR>
map <buffer> <silent> ][ :call search("^func")<CR>
map <buffer> <silent> [] :call search("^}$", 'b')<CR>

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


" markdown filetype file
if exists("did\_load\_filetypes")
 finish
endif
 augroup markdown
  au! BufRead,BufNewFile *.markdown   setfiletype markdown
augroup END

Make sure vim realizes .md files are Markdown.

" markdown filetype file
if exists("did\_load\_filetypes")
 finish
endif
 augroup markdown
  au! BufRead,BufNewFile *.markdown   setfiletype markdown
  au! BufRead,BufNewFile *.md         setfiletype markdown
augroup END


" Visual mode mappings.

" Move between windows.
xnoremap <C-h> <C-w>h
xnoremap <C-j> <C-w>j
xnoremap <C-k> <C-w>k
xnoremap <C-l> <C-w>l

" Move VISUAL LINE selection within buffer.
xnoremap <silent> K :call wincent#mappings#visual#move_up()<CR>
xnoremap <silent> J :call wincent#mappings#visual#move_down()<CR>

Maintain VISUAL selection while indenting/dedenting

" Visual mode mappings.

" Move between windows.
xnoremap <C-h> <C-w>h
xnoremap <C-j> <C-w>j
xnoremap <C-k> <C-w>k
xnoremap <C-l> <C-w>l

" Move VISUAL LINE selection within buffer.
xnoremap <silent> K :call wincent#mappings#visual#move_up()<CR>
xnoremap <silent> J :call wincent#mappings#visual#move_down()<CR>
xnoremap < <gv
xnoremap > >gv


nnoremap <silent> <buffer> q :cclose<CR>
setlocal nocursorline
autocmd! CursorHold <buffer>

Remove quickfix from buffer list

nnoremap <silent> <buffer> q :cclose<CR>
setlocal nocursorline
setlocal nobuflisted
autocmd! CursorHold <buffer>


let g:yadr_disable_solarized_enhancements = 1
let g:hybrid_use_iTerm_colors = 1
colorscheme hybrid

Update hybrid settings due to vim-hybrid update

let g:yadr_disable_solarized_enhancements = 1
let g:hybrid_use_Xresources = 1

colorscheme hybrid


nmap <C-p> :tabprevious<CR>
nmap <C-n> :tabnext<CR>

nmap <Leader>x :close<CR>

nmap <Leader>sd :%s/\s\+$//g<CR>
nmap <Leader>ss /\s\+$<CR>

nmap <Leader>t~ :tabedit ~/<CR>
nmap <Leader>t. :tabedit .<CR>
nmap <Leader>tn :tabedit<CR>
nmap <Leader>tt :tabedit %<CR>
nmap <Leader>to :tabonly<CR>

nmap <Leader>h~ :split ~/<CR>
nmap <Leader>h. :split .<CR>
nmap <Leader>hh :split<CR>

nmap <Leader>v~ :vsplit ~/<CR>
nmap <Leader>v. :vsplit .<CR>
nmap <Leader>vv :vsplit<CR>

nmap <C-h> zh
nmap <C-L> zl

nmap <Up> 3<C-y>
nmap <Down> 3<C-e>
nmap <Left> 4zh
nmap <Right> 4zl

imap <C-f> <C-o>l
imap <C-b> <C-o>h

Set scrolloff option in vim

nmap <C-p> :tabprevious<CR>
nmap <C-n> :tabnext<CR>

nmap <Leader>x :close<CR>

nmap <Leader>sd :%s/\s\+$//g<CR>
nmap <Leader>ss /\s\+$<CR>

nmap <Leader>t~ :tabedit ~/<CR>
nmap <Leader>t. :tabedit .<CR>
nmap <Leader>tn :tabedit<CR>
nmap <Leader>tt :tabedit %<CR>
nmap <Leader>to :tabonly<CR>

nmap <Leader>h~ :split ~/<CR>
nmap <Leader>h. :split .<CR>
nmap <Leader>hh :split<CR>

nmap <Leader>v~ :vsplit ~/<CR>
nmap <Leader>v. :vsplit .<CR>
nmap <Leader>vv :vsplit<CR>

nmap <C-h> zh
nmap <C-L> zl

nmap <Up> 3<C-y>
nmap <Down> 3<C-e>
nmap <Left> 4zh
nmap <Right> 4zl

imap <C-f> <C-o>l
imap <C-b> <C-o>h

set scrolloff=8


" helper for below
function! MultilineString(...)
  return join(a:000, "\n")
endfunction

" function definition
Snippet 'fn', 'function'
Snippet 'function', 'function |() {}'

Snippet 'fb', '=> {|}'
Snippet 'af', '() => {|}'

SnippetComplete "require", 'require("|");'

Snippet 'cl',  'console.log('
Snippet 'ce',  'console.error('
Snippet 'ce*', 'console.error("**** |"'

Snippet 'le', 'logger.error({|}, "CONTEXT");'

Snippet 'for', 'for (let i = 0; i < |; i += 1) {'
Snippet 'fe',  'forEach'

SnippetComplete 'JSON.stringify(|, null, 2)'

SnippetComplete 'prototype'
SnippetComplete 'hasOwnProperty'
SnippetComplete 'setTimeout'
SnippetComplete 'addEventListener'
SnippetComplete 'preventDefault'
SnippetComplete 'stopPropagation'

SnippetComplete 'eslint', MultilineString("/* eslint-disable no-console */",
                                        \ "/* eslint-disable func-names, prefer-arrow-callback */")

Add no-usused-vars to eslint snippet

" helper for below
function! MultilineString(...)
  return join(a:000, "\n")
endfunction

" function definition
Snippet 'fn', 'function'
Snippet 'function', 'function |() {}'

Snippet 'fb', '=> {|}'
Snippet 'af', '() => {|}'

SnippetComplete "require", 'require("|");'

Snippet 'cl',  'console.log('
Snippet 'ce',  'console.error('
Snippet 'ce*', 'console.error("**** |"'

Snippet 'le', 'logger.error({|}, "CONTEXT");'

Snippet 'for', 'for (let i = 0; i < |; i += 1) {'
Snippet 'fe',  'forEach'

SnippetComplete 'JSON.stringify(|, null, 2)'

SnippetComplete 'prototype'
SnippetComplete 'hasOwnProperty'
SnippetComplete 'setTimeout'
SnippetComplete 'addEventListener'
SnippetComplete 'preventDefault'
SnippetComplete 'stopPropagation'

SnippetComplete 'eslint', MultilineString("/* eslint-disable no-console */",
                                        \ "/* eslint-disable func-names, prefer-arrow-callback */",
                                        \ '/* eslint no-unused-vars: ["error", { "args": "none" }] */')


let g:rainbow_active = 1
let g:clojure_special_indent_words = 'deftype,defrecord,reify,proxy,extend-type,extend-protocol,letfn,defcomponent'
setlocal lispwords+=go-loop

Add completion regex for Clojure

let g:rainbow_active = 1
let g:clojure_special_indent_words = 'deftype,defrecord,reify,proxy,extend-type,extend-protocol,letfn,defcomponent'
setlocal lispwords+=go-loop

let g:deoplete#keyword_patterns = {}
let g:deoplete#keyword_patterns.clojure = '[\w!$%&*+/:<=>?@\^_~\-\.#]*'


if has("persistent_undo")
    set undodir='$HOME/.vim/undotree'
    set undofile
endif

Fix leaving history files all over the place

if has("persistent_undo")
    set undodir=$HOME/.vim/undotree
    set undofile
endif


" Remaps <Esc> to exit terminal-mode
tnoremap <Esc> <C-\><C-n>

" Please also see the mappings for navigating out of a terminal window in
" plugin-tmux-navigator.vim file

Fix <Esc> mappings for terminal mode

" Remaps 2x <Esc> to exit terminal-mode
" - One <Esc> only will exit command line insert mode to command line normal
"   mode (Vim's window will still be in "terminal" mode)
" - Second <Esc> will exit "terminal" mode on that window and make the whole
"   window into normal mode.
tnoremap <Esc><Esc> <C-\><C-n>

" Please also see the mappings for navigating out of a terminal window in
" plugin-tmux-navigator.vim file


" Key mappings
"
" My personal mappings for various commands and key combinations

" Add a way to write a file as sudo
cmap w!! w !sudo tee > /dev/null %

" Remap Ctrl+C to be the same as escape without telling us to use :q to quit
nnoremap <C-c> <silent> <ESC>

" Disable EX mode
map Q <Nop>

""" Buffer Managment
nnoremap <silent>       <Tab>   :bnext<CR>
nnoremap <silent>       <S-Tab> :bprev<CR>
nnoremap <expr><silent> <C-q>   ':confirm'.(NoBuffersOpen() ? 'quit' : 'bdelete').'<CR>'

Fix quitting and buffer deletion confirmation

" Key mappings
"
" My personal mappings for various commands and key combinations

" Add a way to write a file as sudo
cmap w!! w !sudo tee > /dev/null %

" Remap Ctrl+C to be the same as escape without telling us to use :q to quit
nnoremap <C-c> <silent> <ESC>

" Disable EX mode
map Q <Nop>

""" Buffer Managment
nnoremap <silent>       <Tab>   :bnext<CR>
nnoremap <silent>       <S-Tab> :bprev<CR>
nnoremap <expr><silent> <C-q>   ':confirm '.(NoBuffersOpen() ? 'quit' : 'bdelete').'<CR>'


" libdnf
autocmd BufRead,BufNewFile */code/libdnf/*
    \ setlocal textwidth=99 colorcolumn=100

let g:ale_pattern_options = {
\   '\(libdnf\).*[hc]pp$': {
\       'ale_cpp_gcc_options': '-std=c++11 -Wmissing-declarations $(pkg-config --cflags glib-2.0)',
\   },
\}

" yum
let g:ale_pattern_options = {
\   '\(createrepo\|urlgrabber\|yum\).*py$': {
\       'ale_enabled': 0,
\   },
\}

Fix up vimrc for libdnf

" libdnf
autocmd BufRead,BufNewFile */code/libdnf/*
    \ setlocal textwidth=99 |
    \ let &colorcolumn=join(range(100, 999), ",")

let g:ale_pattern_options = {
\   '\(libdnf\).*[hc]pp$': {
\       'ale_cpp_gcc_options': '-std=c++11 -Wmissing-declarations $(pkg-config --cflags glib-2.0)',
\   },
\}

" yum
let g:ale_pattern_options = {
\   '\(createrepo\|urlgrabber\|yum\).*py$': {
\       'ale_enabled': 0,
\   },
\}


" Enable substitution operator.
nmap <silent> : <Plug>SubstituteOverMotionMap
nmap :: <Plug>SubstituteLine
xmap :s <Plug>XEasyClipPaste

Add mapping to toggle paste formatting

" Toggle paste formatting.
nmap <Leader>op <Plug>EasyClipToggleFormattedPaste

" Enable substitution operator.
nmap <silent> : <Plug>SubstituteOverMotionMap
nmap :: <Plug>SubstituteLine
xmap :s <Plug>XEasyClipPaste


if exists("b:current_syntax")
    finish
endif

syntax case match

syntax match paketDepsKeyword /^redirects/
syntax match paketDepsKeyword /^source/
syntax match paketDepsKeyword /^nuget/
syntax match paketDepsKeyword /^github/

syntax match paketDepsSymbol />=/
syntax match paketDepsSymbol /:\_s/

syntax match paketDepsVersion /\d\.\d/

syntax match paketDepsOption /\<on\>/

" Source: https://gist.github.com/tobym/584909
syntax match paketDepsUrl /https\?:\/\/\(\w\+\(:\w\+\)\?@\)\?\([A-Za-z][-_0-9A-Za-z]*\.\)\{1,}\(\w\{2,}\.\?\)\{1,}\(:[0-9]\{1,5}\)\?\S*/

highlight link paketDepsKeyword Keyword
highlight link paketDepsSymbol Operator
highlight link paketDepsVersion Float
highlight link paketDepsOption Boolean
highlight link paketDepsUrl String

let b:current_syntax = "paketdeps"

Improve Paket dependencies syntax highlighting

if exists("b:current_syntax")
    finish
endif

syntax case match

syntax match paketDepsKeyword /^redirects/
syntax match paketDepsKeyword /^source/
syntax match paketDepsKeyword /^nuget/
syntax match paketDepsKeyword /^http/
syntax match paketDepsKeyword /^github/

syntax match paketDepsSymbol />=/
syntax match paketDepsSymbol /:\_s/

syntax match paketDepsVersion /\d\(\.\d\)\+/

syntax match paketDepsOption /\<on\>/

" Source: https://gist.github.com/tobym/584909
syntax match paketDepsUrl /https\?:\/\/\(\w\+\(:\w\+\)\?@\)\?\([A-Za-z][-_0-9A-Za-z]*\.\?\)\{1,}\(\w\{2,}\.\?\)\{1,}\(:[0-9]\{1,5}\)\?\S*/

highlight link paketDepsKeyword Keyword
highlight link paketDepsSymbol Operator
highlight link paketDepsVersion Float
highlight link paketDepsOption Boolean
highlight link paketDepsUrl String

let b:current_syntax = "paketdeps"


function! Lines2arglocal() range
  let lines = map(range(a:firstline, a:lastline), 'getline(v:val)')
  execute "arglocal " . join(lines, " ")
endfunction
command -range Lines2arglocal <line1>,<line2>:call Lines2arglocal()

function! FPScratchy(...)
  call call(function("Scratchy"), a:000)
  setlocal cursorline
  nmap <buffer> <CR> 0gf
  vmap <buffer> <CR> :Lines2arglocal<CR>
  nmap <buffer> <ESC><CR> 0<c-w>f<c-w>w
endfunction
command -nargs=* FPScratchy :call FPScratchy(<args>)

" SCRATCHY MAPPINGS

" replace current buffer
nmap <ESC>h :FPScratchy "rg --files --no-ignore-parent --sort-files"<CR>

" textmate-like command-t
nmap <ESC>t :botright  new<CR><ESC>h
nmap <ESC>T :botright vnew<CR><ESC>h

Add Scratchy shortcut for cheatsheets

function! Lines2arglocal() range
  let lines = map(range(a:firstline, a:lastline), 'getline(v:val)')
  execute "arglocal " . join(lines, " ")
endfunction
command -range Lines2arglocal <line1>,<line2>:call Lines2arglocal()

function! FPScratchy(...)
  call call(function("Scratchy"), a:000)
  setlocal cursorline
  nmap <buffer> <CR> 0gf
  vmap <buffer> <CR> :Lines2arglocal<CR>
  nmap <buffer> <ESC><CR> 0<c-w>f<c-w>w
endfunction
command -nargs=* FPScratchy :call FPScratchy(<args>)

" SCRATCHY MAPPINGS

" replace current buffer
nmap <ESC>h :FPScratchy "rg --files --no-ignore-parent --sort-files"<CR>

" textmate-like command-t
nmap <ESC>t :botright  new<CR><ESC>h
nmap <ESC>T :botright vnew<CR><ESC>h

" cheatsheets
nmap <ESC>c :lcd $WIKI/reference/technical/cheats/<CR><ESC>h


function! ChompedSystem( ... )
	return substitute(call('system', a:000), '\n\+$', '', '')
endfunction

Add Redir command for saving command output in scratch window

function! ChompedSystem( ... )
	return substitute(call('system', a:000), '\n\+$', '', '')
endfunction

" Redirect the output of a Vim or external command into a scratch buffer
function! Redir(cmd) abort
    let output = execute(a:cmd)
    vnew
	let w:scratch = 1
    setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile
    call setline(1, split(output, "\n"))
endfunction
command! -nargs=1 Redir silent call Redir(<q-args>)


" The MIT License (MIT)
"
" Copyright (c) 2013 Evgeni Kolev

let s:simple_symbols = {
    \ 'left'           : '',
    \ 'right'          : '',
    \ 'left_alt'       : '|',
    \ 'right_alt'      : '|',
    \ 'dir_sep'        : ' / ',
    \ 'truncation' : '...',
    \ 'vcs_branch'     : '',
    \ 'space'          : ' '}

let s:powerline_symbols = extend(copy(s:simple_symbols), {
    \ 'left'           : '',
    \ 'right'          : '',
    \ 'left_alt'       : '',
    \ 'right_alt'      : '',
    \ 'dir_sep'        : '  ',
    \ 'truncation' : '⋯',
    \ 'vcs_branch'     : ' '})

fun! promptline#symbols#get()
  let use_powerline_symbols = get(g:, 'promptline_powerline_symbols', 1)
  let symbols = use_powerline_symbols ? s:powerline_symbols : s:simple_symbols
  return extend(symbols, get(g:, 'promptline_symbols', {}))
endfun

Fix bug which can modify the hard-coded separators

" The MIT License (MIT)
"
" Copyright (c) 2013 Evgeni Kolev

let s:simple_symbols = {
    \ 'left'           : '',
    \ 'right'          : '',
    \ 'left_alt'       : '|',
    \ 'right_alt'      : '|',
    \ 'dir_sep'        : ' / ',
    \ 'truncation' : '...',
    \ 'vcs_branch'     : '',
    \ 'space'          : ' '}

let s:powerline_symbols = extend(copy(s:simple_symbols), {
    \ 'left'           : '',
    \ 'right'          : '',
    \ 'left_alt'       : '',
    \ 'right_alt'      : '',
    \ 'dir_sep'        : '  ',
    \ 'truncation' : '⋯',
    \ 'vcs_branch'     : ' '})

fun! promptline#symbols#get()
  let use_powerline_symbols = get(g:, 'promptline_powerline_symbols', 1)
  let symbols = use_powerline_symbols ? s:powerline_symbols : s:simple_symbols
  return extend(copy(symbols), get(g:, 'promptline_symbols', {}))
endfun


" Vim syntax file
" Language:	Ceos
" Current Maintainer:	tadeuzagallo (https://github.com/tadeuzagallo)

syn keyword ceosLanguageKeywords if else interface implementation extern virtual type

syn keyword ceosTodo contained TODO NOTE
syn region	ceosComment	start="//" skip="\\$" end="$" keepend contains=ceosTodo
syn region ceosMultilineComment	start="/\*" end="\*/" contains=ceosTodo,@Spell extend

" Integer with - + or nothing in front
syn match ceosNumber '\d\+'
syn match ceosNumber '[-+]\d\+'

syn region ceosString	start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=@Spell extend
syn match	ceosChar "'[^']'"

syn match ceosTypePrefix "\v:\s*" nextgroup=ceosTypes

syn match ceosTypes contained "\v[A-Za-z]+"
syn region ceosTemplate start="<" end=">" keepend contains=ceosTypes
syn match ceosDecl /\v\([^:)']+\)\s*:/me=e-1 contains=ceosTypes

let b:current_syntax = "ceos"

hi def link ceosLanguageKeywords Statement
hi def link ceosTodo Todo
hi def link ceosMultilineComment Comment
hi def link ceosComment Comment
hi def link ceosTypes Identifier
hi def link ceosNumber Number
hi def link ceosString String
hi def link ceosChar Character
hi def link ceosOperator Operator

Fix syntax highlighting after adding operators

" Vim syntax file
" Language:	Ceos
" Current Maintainer:	tadeuzagallo (https://github.com/tadeuzagallo)

syn keyword ceosLanguageKeywords if else interface implementation extern virtual type

syn keyword ceosTodo contained TODO NOTE
syn region	ceosComment	start="//" skip="\\$" end="$" keepend contains=ceosTodo
syn region ceosMultilineComment	start="/\*" end="\*/" contains=ceosTodo,@Spell extend

" Integer with - + or nothing in front
syn match ceosNumber '\d\+'
syn match ceosNumber '[-+]\d\+'

syn region ceosString	start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=@Spell extend
syn match	ceosChar "'[^']'"

syn match ceosTypePrefix "\v:\s*" nextgroup=ceosTypes

syn match ceosTypes contained "\v[A-Za-z]+"
syn match ceosTemplate /\v\<([a-zA-Z],?\s*)+\>/ keepend contains=ceosTypes
syn match ceosDecl /\v\([^:)']+\)\s*:/me=e-1 contains=ceosTypes

let b:current_syntax = "ceos"

hi def link ceosLanguageKeywords Statement
hi def link ceosTodo Todo
hi def link ceosMultilineComment Comment
hi def link ceosComment Comment
hi def link ceosTypes Identifier
hi def link ceosNumber Number
hi def link ceosString String
hi def link ceosChar Character
hi def link ceosOperator Operator


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

function! s:new(args) abort
  let cmd = 'hmm'

  if !empty(a:args)
    let cmd .= ' ' . a:args
  endif

  let output = systemlist(cmd)

  if !(empty(bufname('%')) && line('$') == 1 && getline(1) == '')
    new
  endif

  let bname = bufname('%')

  setlocal filetype=markdown
  setlocal spell

  call appendbufline(bname, 0, output)
  call deletebufline(bname, line('$'))

  call cursor(0, 0)
endfunction

" TODO: :command-complete (customlist, dir, …?)
command! -nargs=* Hmm call s:new(<q-args>)

Fix cursor positioning in :Hmm command

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

function! s:new(args) abort
  let cmd = 'hmm'

  if !empty(a:args)
    let cmd .= ' ' . a:args
  endif

  let output = systemlist(cmd)

  if !(empty(bufname('%')) && line('$') == 1 && getline(1) == '')
    new
  endif

  let bname = bufname('%')

  setlocal filetype=markdown
  setlocal spell

  call appendbufline(bname, 0, output)
  call deletebufline(bname, line('$'))

  call cursor(1, 1)
endfunction

" TODO: :command-complete (customlist, dir, …?)
command! -nargs=* Hmm call s:new(<q-args>)