function! tmuxcomplete#words(scrollback)
    let capture_args = '-J -S -' . a:scrollback
    return tmuxcomplete#completions('', capture_args)
endfunction

function! tmuxcomplete#completions(base, capture_args)
    let script       = expand('<sfile>:h:h') . "/sh/tmuxwords.sh"
    let base_pattern = '^' . escape(a:base, '*^$][.\') . '.'
    let list_args    = get(g:, 'tmux_complete_list_args', '-a')

    let command  = 'sh ' . shellescape(script)
    let command .=   ' ' . shellescape(base_pattern)
    let command .=   ' ' . shellescape(list_args)
    let command .=   ' ' . shellescape(a:capture_args)

    let completions = system(command)
    return split(completions)
endfunction

Fix shell script path detection

function! tmuxcomplete#words(scrollback)
    let capture_args = '-J -S -' . a:scrollback
    return tmuxcomplete#completions('', capture_args)
endfunction

let s:script = expand('<sfile>:h:h') . "/sh/tmuxwords.sh"

function! tmuxcomplete#completions(base, capture_args)
    let base_pattern = '^' . escape(a:base, '*^$][.\') . '.'
    let list_args    = get(g:, 'tmux_complete_list_args', '-a')

    let command  = 'sh ' . shellescape(s:script)
    let command .=   ' ' . shellescape(base_pattern)
    let command .=   ' ' . shellescape(list_args)
    let command .=   ' ' . shellescape(a:capture_args)

    let completions = system(command)
    return split(completions)
endfunction


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

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

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

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

Remove rustc linter from ALE config

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

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

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

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


autocmd BufNewFile,BufRead *.swift setfiletype swift

Read first line for shebang

autocmd BufNewFile,BufRead *.swift setfiletype swift
autocmd BufRead * call s:Swift()
function! s:Swift()
  if !empty(&filetype)
    return
  endif

  let line = getline(1)
  if line =~ "^#!.*swift"
    setfiletype swift
  endif
endfunction


augroup CB2Abbreviations
  au!
  au User AfterBundles Abolish absense absence
  au User AfterBundles Abolish adddress address
  au User AfterBundles Abolish adress address
  au User AfterBundles Abolish asesment assessment
  au User AfterBundles Abolish asessment assessment
  au User AfterBundles Abolish assesment assessment
  au User AfterBundles Abolish dentifer identifier
  au User AfterBundles Abolish eligibilty eligibility
  au User AfterBundles Abolish eligiblity eligibility
  au User AfterBundles Abolish famly family
  au User AfterBundles Abolish referal referral
  au User AfterBundles Abolish residental residential
  au User AfterBundles Abolish resouce resource
  au User AfterBundles Abolish specifed specified
  au User AfterBundles Abolish unkown unknown

  au User BufEnterRails Rabbrev E:: Eligibility
  au User BufEnterRails Rabbrev RL:: RemovalLocation
augroup END

" Edit crontab in-place
au FileType crontab set nobackup nowritebackup

Remove shortcuts for typing model names

augroup CB2Abbreviations
  au!
  au User AfterBundles Abolish absense absence
  au User AfterBundles Abolish adddress address
  au User AfterBundles Abolish adress address
  au User AfterBundles Abolish asesment assessment
  au User AfterBundles Abolish asessment assessment
  au User AfterBundles Abolish assesment assessment
  au User AfterBundles Abolish dentifer identifier
  au User AfterBundles Abolish eligibilty eligibility
  au User AfterBundles Abolish eligiblity eligibility
  au User AfterBundles Abolish famly family
  au User AfterBundles Abolish referal referral
  au User AfterBundles Abolish residental residential
  au User AfterBundles Abolish resouce resource
  au User AfterBundles Abolish specifed specified
  au User AfterBundles Abolish unkown unknown
augroup END

" Edit crontab in-place
au FileType crontab set nobackup nowritebackup


" 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

Revert "vim: Maintain VISUAL selection while indenting/dedenting"


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

if !has('python')
  echo 'Python required'
  finish
endif

let repo_root = expand("<sfile>:p:h:h")
let main_py_file = repo_root . '/lib/main.py'
execute 'pyfile ' . main_py_file

" Find the path of the require statement on the same line as the cursor. Returns the text value
fu! Find_in_current_line()
  let current_line = getline('.')
  if current_line !~# 'require\(.*\)'
    echom 'Current line does not contain a require statement'
    return
  endif
  let current_buffer_path = expand('%:p')

python << EOF
path = find_in_require_stmt(vim.eval('current_buffer_path'), vim.eval('current_line'))
vim.command('return "{}"'.format(path))
EOF
endfu

" Declare a function that can autoload this file
fu! require#Load()
endfu

Return path if not None otherwise warn

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

if !has('python')
  echo 'Python required'
  finish
endif

let repo_root = expand("<sfile>:p:h:h")
let main_py_file = repo_root . '/lib/main.py'
execute 'pyfile ' . main_py_file

" Find the path of the require statement on the same line as the cursor. Returns the text value
fu! require#find_in_current_line()
  let current_line = getline('.')
  if current_line !~# 'require\(.*\)'
    echom 'Current line does not contain a require statement'
    return
  endif
  let current_buffer_path = expand('%:p')
  let path = ''
python << EOF
path = find_in_require_stmt(vim.eval('current_buffer_path'), vim.eval('current_line'))
vim.command('let path = "{}"'.format(path))
EOF
if path == 'None'
  echom 'No path found...Report this'
else
  return path
endif
endfu

" Declare a function that can autoload this file
fu! require#Load()
endfu


"
" Adaptations for shell scripts
"
"
" Keyboard
"
" down through functions
"
noremap <leader><up> jzOk
noremap <leader><down> jzOw
noremap <up> ?^[^{} \t#]<cr>jzOk
noremap <down> /^[^{} \t#]<cr>jzOk
" to function start/end
noremap [d ?^[^{} \t#]<cr>
noremap ]d /^[^{} \t#]<cr>
"
" introduce variable
"
noremap <leader>v mvO<c-r>.=<c-r>"<esc>`v
"
" debugging
"
noremap <F8> Oset -x<esc>joset +x<esc>k
noremap <F7> gg/^\s*set..x$<cr>:noremap <F7> ddn<cr>

let g:syntastic_sh_checkers=['bashate', 'checkbashisms', 'shellcheck']

" Fold on indentation
set foldmethod=indent
"
" Start with closed folds
"
set foldlevel=0

Reset folds when leaving a method

"
" Adaptations for shell scripts
"
"
" Keyboard
"
" down through functions
"
noremap <leader><up> jzOk
noremap <leader><down> jzOw
noremap <up> zx?^[^{} \t#]<cr>jzOk
noremap <down> zx/^[^{} \t#]<cr>jzOk
" to function start/end
noremap [d ?^[^{} \t#]<cr>
noremap ]d /^[^{} \t#]<cr>
"
" introduce variable
"
noremap <leader>v mvO<c-r>.=<c-r>"<esc>`v
"
" debugging
"
noremap <F8> Oset -x<esc>joset +x<esc>k
noremap <F7> gg/^\s*set..x$<cr>:noremap <F7> ddn<cr>

let g:syntastic_sh_checkers=['bashate', 'checkbashisms', 'shellcheck']

" Fold on indentation
set foldmethod=indent
"
" Start with closed folds
"
set foldlevel=0


let g:SuperTabDefaultCompletionType = 'context'
let g:SuperTabContextDefaultCompletionType = '<c-n>'
let g:SuperTabCompletionContexts = ['s:ContextMarkup']
" reset default completion type after leaving 'insert' mode
let g:SuperTabRetainCompletionType = 2
inoremap <C-t> <C-v><Tab>

Add `<Ctrl-Tab>` as literal tab key

let g:SuperTabDefaultCompletionType = 'context'
let g:SuperTabContextDefaultCompletionType = '<c-n>'
let g:SuperTabCompletionContexts = ['s:ContextMarkup']
" reset default completion type after leaving 'insert' mode
let g:SuperTabRetainCompletionType = 2
inoremap <C-t> <C-v><Tab>
ino <C-Tab> <C-v><Tab>


noremap <expr> <buffer> k v:count == 0 ? 'gk' : 'k'
noremap <expr> <buffer> j v:count == 0 ? 'gj' : 'j'
noremap <expr> <buffer> 0 'g0'
noremap <expr> <buffer> $ 'g$'
setlocal linebreak
setlocal colorcolumn=0
setlocal shiftwidth=2 softtabstop=2 tabstop=2 expandtab
setlocal spell spelllang=en_ca spellcapcheck=

" Don't complain about 1. 2. 3. instead of 1. 1. 1. for ordered lists
let b:ale_markdown_mdl_options = '--style ordered'

Update mdl vim config setting

noremap <expr> <buffer> k v:count == 0 ? 'gk' : 'k'
noremap <expr> <buffer> j v:count == 0 ? 'gj' : 'j'
noremap <expr> <buffer> 0 'g0'
noremap <expr> <buffer> $ 'g$'
setlocal linebreak
setlocal colorcolumn=0
setlocal shiftwidth=2 softtabstop=2 tabstop=2 expandtab
setlocal spell spelllang=en_ca spellcapcheck=

" Path to mdl style file
let b:ale_markdown_mdl_options = '--style ~/.config/mdl/style.rb'


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

  " SETTINGS {{{
    let g:LanguageClient_autoStart = 1

    let g:LanguageClient_rootMarkers = {
        \ 'go': ['.git', 'go.mod'],
        \ }

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

  " MAPPINGS {{{
    nnoremap <silent> K :call LanguageClient_textDocument_hover()<CR>
    nnoremap <silent> gd :call LanguageClient_textDocument_definition()<cr>
    nnoremap <silent> lf :call LanguageClient_textDocument_formatting()<cr>
    nnoremap <silent> lr :call LanguageClient_textDocument_rename()<CR>
    nnoremap <silent> l# :call LanguageClient_textDocument_references()<CR>
    nnoremap <silent> lf :call LanguageClient_textDocument_documentSymbol()<CR>
    nnoremap <silent> lm :call LanguageClient_contextMenu()<CR>
    nnoremap <silent> le :call LanguageClient#explainErrorAtPoint()<CR>
  " }}}
end

Fix typo in golanguage server name

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

  " SETTINGS {{{
    let g:LanguageClient_autoStart = 1

    let g:LanguageClient_rootMarkers = {
        \ 'go': ['.git', 'go.mod'],
        \ }

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

  " MAPPINGS {{{
    nnoremap <silent> K :call LanguageClient_textDocument_hover()<CR>
    nnoremap <silent> gd :call LanguageClient_textDocument_definition()<cr>
    nnoremap <silent> lf :call LanguageClient_textDocument_formatting()<cr>
    nnoremap <silent> lr :call LanguageClient_textDocument_rename()<CR>
    nnoremap <silent> l# :call LanguageClient_textDocument_references()<CR>
    nnoremap <silent> lf :call LanguageClient_textDocument_documentSymbol()<CR>
    nnoremap <silent> lm :call LanguageClient_contextMenu()<CR>
    nnoremap <silent> le :call LanguageClient#explainErrorAtPoint()<CR>
  " }}}
end


function! sj#vim#Split()
  if sj#BlankString(getline('.'))
    return 0
  endif

  let new_line = sj#GetMotion('vg_')

  if sj#BlankString(new_line)
    return 0
  else
    let new_line = "\n\\ ".new_line
    call sj#ReplaceMotion('vg_', new_line)
    s/\s\+$//e

    return 1
  endif
endfunction

function! sj#vim#Join()
  let continuation_pattern = '^\s*\\'
  let current_lineno       = line('.')
  let next_lineno          = current_lineno + 1
  let next_line            = getline(next_lineno)

  if next_lineno > line('$') || next_line !~ continuation_pattern
    return 0
  else
    exe next_lineno.'s/'.continuation_pattern.'//'
    exe current_lineno.','.next_lineno.'join'

    if g:splitjoin_normalize_whitespace
      call sj#CompressWhitespaceOnLine()
    endif

    return 1
  endif
endfunction

Trim split line in Vimscript as well

function! sj#vim#Split()
  if sj#BlankString(getline('.'))
    return 0
  endif

  let new_line = sj#GetMotion('vg_')

  if sj#BlankString(new_line)
    return 0
  else
    let new_line = "\n\\ ".sj#Trim(new_line)
    call sj#ReplaceMotion('vg_', new_line)
    s/\s\+$//e

    return 1
  endif
endfunction

function! sj#vim#Join()
  let continuation_pattern = '^\s*\\'
  let current_lineno       = line('.')
  let next_lineno          = current_lineno + 1
  let next_line            = getline(next_lineno)

  if next_lineno > line('$') || next_line !~ continuation_pattern
    return 0
  else
    exe next_lineno.'s/'.continuation_pattern.'//'
    exe current_lineno.','.next_lineno.'join'

    if g:splitjoin_normalize_whitespace
      call sj#CompressWhitespaceOnLine()
    endif

    return 1
  endif
endfunction


" Make it beautiful - colors and fonts

if has("gui_running")
  "tell the term has 256 colors
  set t_Co=256

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

  set lines=60
  set columns=190

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

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

colorscheme solarized
" set background=dark
set background=light

Update vim colorscheme for linux

" Make it beautiful - colors and fonts

if has("gui_running")
  "tell the term has 256 colors
  set t_Co=256

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

  set lines=60
  set columns=190

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

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

set background=dark

if system('uname')=~'Darwin'
    colorscheme solarized
    set background=light
endif


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

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

Revert "Merge two autocmds into one"

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

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


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

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

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

augroup AutoSyntastic
    autocmd!
    autocmd BufWritePost *.c,*.cpp,*.js,*.php call CheckSyntax()
augroup END

Update lightline syntax flag after saving any file

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

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

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

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


if findfile('.eslintrc', '.;') != ''
    let b:syntastic_checkers = ['eslint']
endif

Use eslint_d or local eslint if available

if findfile('.eslintrc', '.;') != ''
    let b:syntastic_checkers = ['eslint']
    let b:syntastic_javascript_eslint_exec =
        \ split(system('PATH=$(npm bin):$PATH which eslint_d eslint'), '\n')[0]
endif


" Vim compiler file
" Language:		RSpec
" Maintainer:		Tim Pope <vimNOSPAM@tpope.org>
" URL:			https://github.com/vim-ruby/vim-ruby
" Anon CVS:		See above site
" Release Coordinator:	Doug Kearns <dougkearns@gmail.com>

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

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=spec

CompilerSet errorformat=
    \%+W'%.%#'\ FAILED,
    \%+I'%.%#'\ FIXED,
    \%-Cexpected:%.%#,
    \%-C\ \ \ \ \ got:%.%#,
    \%E%.%#:in\ `load':\ %f:%l:%m,
    \%C%f:%l:,
    \%W%f:%l:\ warning:\ %m,
    \%E%f:%l:in\ %*[^:]:\ %m,
    \%E%f:%l:\ %m,
    \%-Z%\tfrom\ %f:%l,
    \%-Z%p^%.%#,
    \%-C%.%#,
    \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save

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

Switch compiler to RSpec 2

" Vim compiler file
" Language:		RSpec
" Maintainer:		Tim Pope <vimNOSPAM@tpope.org>
" URL:			https://github.com/vim-ruby/vim-ruby
" Anon CVS:		See above site
" Release Coordinator:	Doug Kearns <dougkearns@gmail.com>

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

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=rspec

CompilerSet errorformat=
    \%f:%l:\ %tarning:\ %m,
    \%E%.%#:in\ `load':\ %f:%l:%m,
    \%E%f:%l:in\ `%*[^']':\ %m,
    \%-Z\ \ \ \ \ \#\ %f:%l:%.%#,
    \%E\ \ %\\d%\\+)%.%#,
    \%C\ \ \ \ \ %m,
    \%-G%.%#

let &cpo = s:cpo_save
unlet s:cpo_save

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


" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

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

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

" My bundles
Bundle 'altercation/vim-colors-solarized'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'digitaltoad/vim-jade'
Bundle 'wavded/vim-stylus'

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

filetype plugin indent on     " required!

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

Add vim plugins for JSHint and for fixing whitespace in vim

" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

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

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

" My bundles
Bundle 'altercation/vim-colors-solarized'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'digitaltoad/vim-jade'
Bundle 'wavded/vim-stylus'
Bundle 'walm/jshint.vim'
Bundle 'eyuelt/vim-whitespace'

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

filetype plugin indent on     " required!

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


" Ignore case if search pattern is all lowercase, case-sensitive otherwise
set smartcase

" Ignore case when searching
set ignorecase

" Highlight search terms
set hlsearch

" Show search matches as you type
set incsearch

" Use Ack instead of grep
set grepprg=ack

" ==========================================
" Search in project/directory

" Search current word in project/directory
" With or without word boundaries
function! SearchInProject()
  let word = expand("<cword>")
  let @/=word
  set hls
  exec "Ag " . word
endfunction

function! SearchWordInProject()
  let word = expand("<cword>")
  let @/='\<' . word . '\>'
  set hls
  exec "Ag '\\b" . word . "\\b'"
endfunction

Replace grepprg with ag if it exists

" Ignore case if search pattern is all lowercase, case-sensitive otherwise
set smartcase

" Ignore case when searching
set ignorecase

" Highlight search terms
set hlsearch

" Show search matches as you type
set incsearch

" ==========================================
" Search in project/directory

" Search current word in project/directory
" With or without word boundaries
function! SearchInProject()
  let word = expand("<cword>")
  let @/=word
  set hls
  exec "Ag " . word
endfunction

function! SearchWordInProject()
  let word = expand("<cword>")
  let @/='\<' . word . '\>'
  set hls
  exec "Ag '\\b" . word . "\\b'"
endfunction

if executable('ag')
  " Note we extract the column as well as the file and line number
  set grepprg=ag\ --nogroup\ --nocolor\ --column
  set grepformat=%f:%l:%c%m
endif


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

let g:ale_linters = {
	\ 'typescript': ['tslint', 'tsserver']
\ }

let g:ale_fixers = {
  \ '*': ['remove_trailing_lines', 'trim_whitespace'],
  \ 'ruby': ['rubocop']
\ }

let g:ale_ruby_rubocop_executable = 'bin/rubocop'
let g:ale_haml_hamllint_executable = 'bin/haml-lint'

Add tslint to vim ALE linters for typescript

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

let g:ale_linters = {
	\ 'typescript': ['eslint', 'tslint', 'tsserver']
\ }

let g:ale_fixers = {
  \ '*': ['remove_trailing_lines', 'trim_whitespace'],
  \ 'ruby': ['rubocop']
\ }

let g:ale_ruby_rubocop_executable = 'bin/rubocop'
let g:ale_haml_hamllint_executable = 'bin/haml-lint'


"
" Python configuration
"

" Enable auto indenting
au FileType python let g:pymode_indent = 0

" Disable automatic folding
au FileType python let g:pymode_folding = 0

" Disable rope code completion
au FileType python let g:pymode_rope_lookup_project = 0
au FileType python let g:pymode_rope_completion = 1
au FileType python let g:pymode_rope_complete_on_dot = 1

" Documentation
au FileType python let g:pymode_doc = 0
au FileType python let g:pymode_doc_bind = 'K'

Add pylint support for Python files

"
" Python configuration
"

" Enable auto indenting
au FileType python let g:pymode_indent = 1

" Enable pymode lint checking
au FileType python let g:pymode_lint = 1
au FileType python let g:pymode_lint_on_write = 1
au FileType python let g:pymode_lint_checkers = ['pylint', 'pep8']

" Disable automatic folding
au FileType python let g:pymode_folding = 0

" Disable rope code completion
au FileType python let g:pymode_rope_lookup_project = 0
au FileType python let g:pymode_rope_completion = 1
au FileType python let g:pymode_rope_complete_on_dot = 1

" Documentation
au FileType python let g:pymode_doc = 0
au FileType python let g:pymode_doc_bind = 'K'


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


" disable for vimshell
let g:better_whitespace_filetypes_blacklist=['vimshell']

" jellyx colors
highlight ExtraWhitespace ctermbg=89 guibg=#87005f

Disable whitespace highlights for help files

" disable whitespace highlights for specified filetypes
let g:better_whitespace_filetypes_blacklist=['help', 'vimshell']

" jellyx colors
highlight ExtraWhitespace ctermbg=89 guibg=#87005f


" do some snippets magic on code placeholders.
let g:clang_snippets = 1
" preview window will be closed automatically after a completion.
let g:clang_close_preview = 1
" use libclang directly.
let g:clang_use_library = 1
" absolute path where libclang is available.
let g:clang_library_path = "/usr/lib/llvm/"
" complete preprocessor macros and constants.
let g:clang_complete_macros = 1
" complete code patterns.
let g:clang_complete_patterns = 1
" let neocomplete manage completion.
let g:clang_complete_auto = 0

Fix path to libclang on gentoo

" do some snippets magic on code placeholders.
let g:clang_snippets = 1
" preview window will be closed automatically after a completion.
let g:clang_close_preview = 1
" use libclang directly.
let g:clang_use_library = 1
" absolute path where libclang is available.
let g:clang_library_path = "/usr/lib/"
" complete preprocessor macros and constants.
let g:clang_complete_macros = 1
" complete code patterns.
let g:clang_complete_patterns = 1
" let neocomplete manage completion.
let g:clang_complete_auto = 0


"
" vim-json configuration
"

" Disable concealing
let g:vim_json_syntax_conceal = 0

" Enable syntax folding for javascript files
au FileType json setlocal foldmethod=syntax

Fix tabstop and shiftwidth for JSON

"
" vim-json configuration
"

" Disable concealing
let g:vim_json_syntax_conceal = 0

" Enable syntax folding for javascript files
au FileType json setlocal foldmethod=syntax

au FileType json set expandtab
au FileType json set shiftwidth=2
au FileType json set tabstop=2
au FileType json set softtabstop=2


setlocal commentstring=//\ %s
setlocal iskeyword+=?,!
setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4

Add basic syntax completion with Ctrl-x Ctrl-u

setlocal commentstring=//\ %s
setlocal iskeyword+=?,!
setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
setlocal completefunc=syntaxcomplete#Complete


function! s:buf_total_num()
  return len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
endfunction

function! s:file_size(f)
  let l:size = getfsize(expand(a:f))
  if l:size == 0 || l:size == -1 || l:size == -2
    return ''
  endif
  if l:size < 1024
    return l:size.'bytes'
  elseif l:size < 1024*1024
    return printf('%.1f', l:size/1024.0).'K'
  elseif l:size < 1024*1024*1024
    return printf('%.1f', l:size/1024.0/1024.0) . 'M'
  else
    return printf('%.1f', l:size/1024.0/1024.0/1024.0) . 'G'
  endif
endfunction

function! spacevim#vim#file#CtrlG() abort
  redir => file
  :silent f!
  redir END
  let l:msg = join([file[2:], 'Cursor '.line('.').':'.col('.'), s:file_size(@%), 'TOT:'.s:buf_total_num(), '['.&ft.']'], ' ')
  call spacevim#vim#cursor#TruncatedEcho(l:msg)
endfunction

Make the cursor info more explicit

function! s:buf_total_num()
  return len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
endfunction

function! s:file_size(f)
  let l:size = getfsize(expand(a:f))
  if l:size == 0 || l:size == -1 || l:size == -2
    return ''
  endif
  if l:size < 1024
    return l:size.'bytes'
  elseif l:size < 1024*1024
    return printf('%.1f', l:size/1024.0).'K'
  elseif l:size < 1024*1024*1024
    return printf('%.1f', l:size/1024.0/1024.0) . 'M'
  else
    return printf('%.1f', l:size/1024.0/1024.0/1024.0) . 'G'
  endif
endfunction

function! spacevim#vim#file#CtrlG() abort
  redir => file
  :silent f!
  redir END
  let l:msg = join([file[2:], 'Cursor line:'.line('.').',col:'.col('.'), s:file_size(@%), 'TOT:'.s:buf_total_num(), '['.&filetype.']'], ' ')
  call spacevim#vim#cursor#TruncatedEcho(l:msg)
endfunction


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

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

Switch to Underlined instead of VisualNOS

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

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


let g:pylint_onwrite = 0
let g:pylint_show_rate = 0
let g:pylint_cwindow = 1
compiler pylint

Add Python debugging shortcuts to VIM.

let g:pylint_onwrite = 0
let g:pylint_show_rate = 0
let g:pylint_cwindow = 1
compiler pylint

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


" ALE
let g:ale_fixers = {'*': ['remove_trailing_lines', 'trim_whitespace']}
let g:ale_fixers.python = ['black']
let g:ale_fixers.rust = ['rustfmt']

" asyncomplete
let g:asyncomplete_remove_duplicates = 1
let g:asyncomplete_smart_completion = 1
let g:asyncomplete_auto_popup = 1

" autopairs
let g:AutoPairsMapCR=0

" nerdtree
let NERDTreeIgnore=['\.pyc$','\.pyo$','__pycache__','\.o$']

" LanguageClient-neovim
let g:LanguageClient_serverCommands = {}
let g:LanguageClient_serverCommands.python = ['pyls']
let g:LanguageClient_serverCommands.rust = ['rustup', 'run', 'stable', 'rls']

" supertab
let g:SuperTabDefaultCompletionType = "<c-n>"

" vim-airline
let g:airline_powerline_fonts=1

" UltiSnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
let g:UltiSnipsEditSplit="vertical"

" vim-airline-themes
let g:airline_theme='papercolor'

Use only ALE for syntax

" ALE
let g:ale_sign_column_always = 1
let g:ale_sign_error = '🔴'
let g:ale_sign_warning = '⚠'
let g:ale_sign_info = 'i'
let g:ale_fixers = {'*': ['remove_trailing_lines', 'trim_whitespace']}
let g:ale_fixers.python = ['black']
let g:ale_fixers.rust = ['rustfmt']

" asyncomplete
let g:asyncomplete_remove_duplicates = 1
let g:asyncomplete_smart_completion = 1
let g:asyncomplete_auto_popup = 1

" autopairs
let g:AutoPairsMapCR=0

" nerdtree
let NERDTreeIgnore=['\.pyc$','\.pyo$','__pycache__','\.o$']

" LanguageClient-neovim
let g:LanguageClient_diagnosticsEnable = 0
let g:LanguageClient_serverCommands = {}
let g:LanguageClient_serverCommands.python = ['pyls']
let g:LanguageClient_serverCommands.rust = ['rustup', 'run', 'stable', 'rls']

" supertab
let g:SuperTabDefaultCompletionType = "<c-n>"

" vim-airline
let g:airline_powerline_fonts=1

" UltiSnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
let g:UltiSnipsEditSplit="vertical"

" vim-airline-themes
let g:airline_theme='papercolor'


set nocompatible " not vi compatible

set background=dark
colorscheme solarized

"------------------
" Syntax and indent
"------------------
syntax enable " turn on syntax highlighting
set showmatch " show matching braces when text indicator is over them

filetype on
filetype plugin indent on " enable file type detection
set autoindent

"---------------------
" Basic editing config
"---------------------
set tags=tags;/ " recursively search parent directory for tags
set list
set listchars=tab:\|\ ,trail:●,extends:>,precedes:<,nbsp:+

set backspace=indent,eol,start " allow backspacing over everything

set incsearch " incremental search (as string is being typed)
set hlsearch " highlight search

set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]

set showcmd
set number " number lines

" Ignore case when doing regex searches, except if you capitalize explicitly
set ignorecase
set smartcase

set runtimepath^=~/.vim/bundle/ctrlp.vim
set autoread

set complete+=kspell
autocmd filetype crontab setlocal nobackup nowritebackup

Use spaces instead of tabs

set nocompatible " not vi compatible

set background=dark
colorscheme solarized

"------------------
" Syntax and indent
"------------------
syntax enable " turn on syntax highlighting
set showmatch " show matching braces when text indicator is over them

filetype on
filetype plugin indent on " enable file type detection
set autoindent

"---------------------
" Basic editing config
"---------------------
set tags=tags;/ " recursively search parent directory for tags
set list
set listchars=tab:\|\ ,trail:●,extends:>,precedes:<,nbsp:+

set backspace=indent,eol,start " allow backspacing over everything

set incsearch " incremental search (as string is being typed)
set hlsearch " highlight search

set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]

" Make all spaces size 4, use spaces instead of tabs
set tabstop=4 shiftwidth=4 expandtab smarttab

set showcmd
set number " number lines

" Ignore case when doing regex searches, except if you capitalize explicitly
set ignorecase
set smartcase

set runtimepath^=~/.vim/bundle/ctrlp.vim
set autoread

set complete+=kspell
autocmd filetype crontab setlocal nobackup nowritebackup


" How to: Type the letters then hit space

" General
iabbrev fsl # frozen_string_literal: true

" debugging
iabbrev bpry binding.pry
iabbrev bpid binding.pry if Rails.env.development?
iabbrev bpit binding.pry if Rails.env.test?
iabbrev brp binding.remote_pry
iabbrev brpid binding.remote_pry if Rails.env.development?
iabbrev brpit binding.remote.pry if Rails.env.test?

" RSpec
iabbrev af :aggregate_failures

Add bb shortcut in vim

" How to: Type the letters then hit space

" General
iabbrev fsl # frozen_string_literal: true

" pry
iabbrev bpry binding.pry
iabbrev bpid binding.pry if Rails.env.development?
iabbrev bpit binding.pry if Rails.env.test?
iabbrev brp binding.remote_pry
iabbrev brpid binding.remote_pry if Rails.env.development?
iabbrev brpit binding.remote.pry if Rails.env.test?

" byebug
iabbrev bb byebug

" RSpec
iabbrev af :aggregate_failures


" after/ftplugin/javascript.vim
"
" @file Configuration applied for javascript files

" Auto format the current file using eslint
if executable('eslint')
  nnoremap <silent><special><buffer>
        \ <Leader>=
        \ :silent !eslint --fix -- %<CR>:checktime<CR>
endif

Use project specific eslint config

" after/ftplugin/javascript.vim
"
" @file Configuration applied for javascript files

" All linters are disabled by default
let b:neomake_enabled_makers = []

" Use eslint if the current project has a local configuration file
let s:eslintrc = dw#project#FindFile(['.eslintrc.yml', '.eslintrc.json'])

if filereadable(s:eslintrc)
  let b:neomake_enabled_makers += ['eslint']
  let b:neomake_javascript_eslint_exe = dw#node#FindPackage('eslint')
endif

" Auto format the current file using eslint
if executable('eslint')
  nnoremap <silent><special><buffer>
        \ <Leader>=
        \ :silent !eslint --fix -- %<CR>:checktime<CR>
endif


""""""""""""""
" HTML Setup "
""""""""""""""

" tabbing, spacing, and nesting
set tabstop=4       " 4 spaces to a tab
set shiftwidth=4    " 4 spaces for indentation

Update vim to default to 2 tabs

""""""""""""""
" HTML Setup "
""""""""""""""

" tabbing, spacing, and nesting
set tabstop=2       " 2 spaces to a tab
set shiftwidth=2    " 2 spaces for indentation


" put \begin{} \end{} tags tags around the current word
function! s:ExpandTexEnv()
    let l:cword = expand("<cWORD>")
    execute "normal! YpkI\\begin{\<esc>A}\<esc>jI\\end{\<esc>A}\<esc>k$"
    if l:cword ==# "equation"
        execute "normal! o\\label{eq:}\<esc>k$"
    elseif l:cword ==# "figure"
        execute "normal! o\\includegraphics{}\<cr>\\caption{}\<cr>\\label{fig:}\<esc>2k$h"
    elseif l:cword ==# "frame"
        execute "normal! o\\frametitle{}\<esc>2k$h"
    elseif l:cword ==# "minipage"
        execute "normal! A{\\textwidth}\<esc>%"
    endif
endfunction

nnoremap <F5> :call <SID>ExpandTexEnv()<CR>a
inoremap <F5> <ESC>:call <SID>ExpandTexEnv()<CR>a

Fix cursor pos when expanding frame environment

" put \begin{} \end{} tags tags around the current word
function! s:ExpandTexEnv()
    let l:cword = expand("<cWORD>")
    execute "normal! YpkI\\begin{\<esc>A}\<esc>jI\\end{\<esc>A}\<esc>k$"
    if l:cword ==# "equation"
        execute "normal! o\\label{eq:}\<esc>k$"
    elseif l:cword ==# "figure"
        execute "normal! o\\includegraphics{}\<cr>\\caption{}\<cr>\\label{fig:}\<esc>2k$h"
    elseif l:cword ==# "frame"
        execute "normal! o\\frametitle{}\<esc>h"
    elseif l:cword ==# "minipage"
        execute "normal! A{\\textwidth}\<esc>%"
    endif
endfunction

nnoremap <F5> :call <SID>ExpandTexEnv()<CR>a
inoremap <F5> <ESC>:call <SID>ExpandTexEnv()<CR>a


"" show a vertical bar at 80 characters
set colorcolumn=80
set clipboard=unnamedplus
"" hide the buffers in the background, but don't close them
set hidden
set expandtab
set shiftwidth=4
set scrolloff=8
"" automatically indent at the same lvl as the previous
set smartindent
set softtabstop=4
set tabstop=4
"" prevent copying of line numbers when using a mouse
set mouse+=a
"" prevent the bells when things go wrong
set noerrorbells
"" let me be free and the text go as far and I want it to
set nowrap
set number
set signcolumn=yes
set termguicolors

let g:gruvbox_italic=1
let $NVIM_TUI_ENABLE_TRUE_COLOR=1

"" The plugins begin
call plug#begin('~/.vim/plugged')
  Plug 'gruvbox-community/gruvbox'
  Plug 'eraserhd/parinfer-rust', {'do': 'cargo build --release'}
call plug#end()

colorscheme gruvbox
set bg=dark

fun! TrimWhitespace()
    let l:save = winsaveview()
    keeppatterns %s/\s+$//e
    call winrestview(l:save)
endfun

augroup THOMAS
    autocmd!
    autocmd BufWritePre * :call TrimWhitespace()
augroup END

Update nvim - remap Esc to jk

"" show a vertical bar at 80 characters
set colorcolumn=80
set clipboard=unnamedplus
"" hide the buffers in the background, but don't close them
set hidden
set expandtab
set shiftwidth=4
set scrolloff=8
"" automatically indent at the same lvl as the previous
set smartindent
set softtabstop=4
set tabstop=4
"" prevent copying of line numbers when using a mouse
set mouse+=a
"" prevent the bells when things go wrong
set noerrorbells
"" let me be free and the text go as far and I want it to
set nowrap
set number
set signcolumn=yes
set termguicolors

"" escape using jk which feels more ergonomic
inoremap jk <ESC>

let g:gruvbox_italic=1
let $NVIM_TUI_ENABLE_TRUE_COLOR=1

"" The plugins begin
call plug#begin('~/.vim/plugged')
  Plug 'gruvbox-community/gruvbox'
  Plug 'eraserhd/parinfer-rust', {'do': 'cargo build --release'}
call plug#end()

colorscheme gruvbox
set bg=dark

fun! TrimWhitespace()
    let l:save = winsaveview()
    keeppatterns %s/\s+$//e
    call winrestview(l:save)
endfun

augroup THOMAS
    autocmd!
    autocmd BufWritePre * :call TrimWhitespace()
augroup END


autocmd FileType go set noexpandtab
autocmd FileType go set nolist

let g:go_fmt_command = "goimports"
au Filetype go nnoremap <leader>d :vsp <CR>:exe "GoDef" <CR>
au Filetype go nnoremap <leader>r :GoRun %<CR>
au FileType go nmap <Leader>c <Plug>(go-coverage)

au FileType go nmap <Leader>s <Plug>(go-implements)
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)
au FileType go nmap <Leader>e <Plug>(go-rename)

Add g prefix to commands

autocmd FileType go set noexpandtab
autocmd FileType go set nolist

let g:go_fmt_command = "goimports"
au Filetype go nnoremap <leader>gd :vsp <CR>:exe "GoDef" <CR>
au Filetype go nnoremap <leader>gr :GoRun %<CR>
au FileType go nmap <Leader>gc <Plug>(go-coverage)

au FileType go nmap <Leader>gi <Plug>(go-implements)
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)
au FileType go nmap <Leader>ge <Plug>(go-rename)


set nocompatible

syntax on
filetype plugin indent on

source ~/.vim/bundles.vim

" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
autocmd BufReadPost *
  \ if line("'\"") > 0 && line("'\"") <= line("$") |
  \   exe "normal! g`\"" |
  \ endif

Stop trying to jump to last line on BufRead


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

"My color scheme
Plug 'agude/vim-eldar'
"VimCompletesMe
Plug 'ajh17/VimCompletesMe'
"Surround
Plug 'tpope/vim-surround'
"Repeat (lets you use . with surround)
Plug 'tpope/vim-repeat'
"Tagbar
Plug 'majutsushi/tagbar'
"ctrlp
Plug 'ctrlpvim/ctrlp.vim'
"Python Syntax Highlighting
Plug 'vim-python/python-syntax'
"Git support
Plug 'tpope/vim-fugitive'
" Better Diffing using git 1.8
Plug 'chrisbra/vim-diff-enhanced'
" PEP8 compliant indenting
Plug 'Vimjas/vim-python-pep8-indent'
" Jekyll Liquid syntax
Plug 'tpope/vim-liquid'
" Conky Syntax
Plug 'smancill/conky-syntax.vim'
" Mediawiki Syntax
Plug 'chikamichi/mediawiki.vim'

" Neovim only
if has("nvim")
    " Autocomplete
    function! DoRemote(arg)
        UpdateRemotePlugins
    endfunction
    Plug 'Shougo/deoplete.nvim', { 'do': function('DoRemote') }
    " Jedi autocomplete
    Plug 'zchee/deoplete-jedi'
endif

call plug#end()

Add `w0rp/ale` for linting in vim

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

"My color scheme
Plug 'agude/vim-eldar'
"VimCompletesMe
Plug 'ajh17/VimCompletesMe'
"Surround
Plug 'tpope/vim-surround'
"Repeat (lets you use . with surround)
Plug 'tpope/vim-repeat'
"Tagbar
Plug 'majutsushi/tagbar'
"ctrlp
Plug 'ctrlpvim/ctrlp.vim'
"Python Syntax Highlighting
Plug 'vim-python/python-syntax'
"Git support
Plug 'tpope/vim-fugitive'
" Better Diffing using git 1.8
Plug 'chrisbra/vim-diff-enhanced'
" PEP8 compliant indenting
Plug 'Vimjas/vim-python-pep8-indent'
" Jekyll Liquid syntax
Plug 'tpope/vim-liquid'
" Conky Syntax
Plug 'smancill/conky-syntax.vim'
" Mediawiki Syntax
Plug 'chikamichi/mediawiki.vim'

" Neovim only
if has("nvim")
    " Autocomplete
    function! DoRemote(arg)
        UpdateRemotePlugins
    endfunction
    Plug 'Shougo/deoplete.nvim', { 'do': function('DoRemote') }
    " Jedi autocomplete for Python
    Plug 'zchee/deoplete-jedi'
    " Asynchronous linting
    Plug 'w0rp/ale'
endif

call plug#end()


" Vim syntax file
" Language: Ansible YAML/Jinja templates
" Maintainer: Dave Honneffer <pearofducks@gmail.com>
" Last Change: 2015.09.06

if exists("b:current_syntax")
  finish
endif

if !exists("main_syntax")
  let main_syntax = 'jinja2'
endif

let b:current_syntax = ''
unlet b:current_syntax
runtime! syntax/jinja2.vim

let s:extra_syntax = split(g:ansible_extra_syntaxes)
for syntax_name in s:extra_syntax
  let b:current_syntax = ''
  unlet b:current_syntax
  execute 'runtime!' "syntax/" . syntax_name
endfor

let b:current_syntax = "ansible_template"

Fix a bug when g:ansible_extra_syntaxes isn't defined

" Vim syntax file
" Language: Ansible YAML/Jinja templates
" Maintainer: Dave Honneffer <pearofducks@gmail.com>
" Last Change: 2015.09.06

if exists("b:current_syntax")
  finish
endif

if !exists("main_syntax")
  let main_syntax = 'jinja2'
endif

let b:current_syntax = ''
unlet b:current_syntax
runtime! syntax/jinja2.vim

if exists("g:ansible_extra_syntaxes")
  let s:extra_syntax = split(g:ansible_extra_syntaxes)
  for syntax_name in s:extra_syntax
    let b:current_syntax = ''
    unlet b:current_syntax
    execute 'runtime!' "syntax/" . syntax_name
  endfor
endif

let b:current_syntax = "ansible_template"


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

"  Black (python formatting)
let g:neoformat_python_black = {
            \ 'exe': 'black',
            \ 'stdin': 1,
            \ 'args': ['--skip-string-normalization', '-q', '-'],
            \ }

let g:neoformat_enabled_python = ['isort', 'black']
let g:neoformat_enabled_sql = ['sqlfmt']
let g:neoformat_enabled_html = ['html-beautify']
let g:neoformat_run_all_formatters = 1
command F :Neoformat

Fix SQL formatting for neoformat

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

"  Black (python formatting)
let g:neoformat_python_black = {
            \ 'exe': 'black',
            \ 'stdin': 1,
            \ 'args': ['--skip-string-normalization', '-q', '-'],
            \ }

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
command F :Neoformat


" Vim filetype plugin
" Language              Markdown
" Maintainer            Ben Knoble <ben.knoble@gmail.com>

" Wrap at 80 characters
setlocal textwidth=80
" Spell check on
setlocal spell spelllang=en_us

function! UnderlineHeading(level)
  if a:level == 1
    normal! yypVr=
  elseif a:level == 2
    normal! yypVr-
  else
    execute "normal! I### "
  endif
endfunction

nnoremap <LocalLeader>u1 :call UnderlineHeading(1)<CR>
nnoremap <LocalLeader>u2 :call UnderlineHeading(2)<CR>
nnoremap <LocalLeader>u3 :call UnderlineHeading(3)<CR>

Add heading operator mappings for Markdown

" Vim filetype plugin
" Language              Markdown
" Maintainer            Ben Knoble <ben.knoble@gmail.com>

" Wrap at 80 characters
setlocal textwidth=80
" Spell check on
setlocal spell spelllang=en_us

function! UnderlineHeading(level)
  if a:level == 1
    normal! yypVr=
  elseif a:level == 2
    normal! yypVr-
  else
    execute "normal! I### "
  endif
endfunction

nnoremap <LocalLeader>u1 :call UnderlineHeading(1)<CR>
nnoremap <LocalLeader>u2 :call UnderlineHeading(2)<CR>
nnoremap <LocalLeader>u3 :call UnderlineHeading(3)<CR>

onoremap <buffer> ih= :<C-u>execute "normal! ?^==\\+$\r:nohlsearch\rkvg_"<CR>
onoremap <buffer> ih- :<C-u>execute "normal! ?^--\\+$\r:nohlsearch\rkvg_"<CR>
onoremap <buffer> i#1 :<C-u>execute "normal! ?^#\\s.?e\r:nohlsearch\rvg_"<CR>
onoremap <buffer> i#2 :<C-u>execute "normal! ?^##\\s.?e\r:nohlsearch\rvg_"<CR>
onoremap <buffer> i#3 :<C-u>execute "normal! ?^###\\s.?e\r:nohlsearch\rvg_"<CR>


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

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

function! EnterNormalModeHighlight()
    set colorcolumn=
    highlight CursorLineNr ctermfg=Yellow ctermbg=DarkGray
endfunction

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

call EnterNormalModeHighlight()

if &term =~ "xterm" || &term =~ "putty"
    set t_ZH=
    set t_ZR=
    highlight Comment cterm=Italic
endif

let g:loaded_matchparen = 0

Use bold line number in vim current line

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

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

function! EnterNormalModeHighlight()
    let &colorcolumn = ""
    highlight CursorLineNr cterm=Bold ctermfg=Yellow ctermbg=DarkGray
endfunction

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

call EnterNormalModeHighlight()

if &term =~ "xterm" || &term =~ "putty"
    set t_ZH=
    set t_ZR=
    highlight Comment cterm=Italic
endif

let g:loaded_matchparen = 0


" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

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

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

" split horizontally with h
nnoremap <C-w>h <C-w>s

" fly between buffers:
" http://of-vim-and-vigor.blogspot.ro/p/vim-vigor-comic.html
nnoremap <leader>l :ls<CR>:b<space>

" prepend leader to copy to null register
" http://unix.stackexchange.com/a/88755
nnoremap <leader>c "_c
nnoremap <leader>d "_d

" quick close buffer
cmap qq bd

Fix C-h navigation bug in neovim

" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

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

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

" split horizontally with h
nnoremap <C-w>h <C-w>s

" fly between buffers:
" http://of-vim-and-vigor.blogspot.ro/p/vim-vigor-comic.html
nnoremap <leader>l :ls<CR>:b<space>

" prepend leader to copy to null register
" http://unix.stackexchange.com/a/88755
nnoremap <leader>c "_c
nnoremap <leader>d "_d

" quick close buffer
cmap qq bd

" fix C-h navigation bug in neovim
" https://github.com/christoomey/vim-tmux-navigator/issues/71#issuecomment-202422963
if has('nvim')
    nmap <BS> :<C-u>TmuxNavigateLeft<CR>
else
    nmap <C-h> <C-w>h
endif


function! KillTrailingWhitespace(lines) " Kill trailing whitespace/lines.
  let l:search = @/
  let l:view = winsaveview()
  %s/\s\+$//e
  if a:lines
    %s/\($\n\s*\)\+\%$//e
  endif
  let @/ = l:search
  call winrestview(l:view)
endfunction

" kill trailing whitespace (bang for lines)
command! -bang -nargs=* KillTrailingWhitespace call KillTrailingWhitespace(<bang>0)
" ripgrep
command! -bang -nargs=* Rg call fzf#vim#grep('rg --column --line-number --no-heading --color=always '.shellescape(<q-args>).'| tr -d "\017"', 1, <bang>0)

Add rehash command for vim

function! KillTrailingWhitespace(lines) " Kill trailing whitespace/lines.
  let l:search = @/
  let l:view = winsaveview()
  execute '%s/\s\+$//e'
  if a:lines
    execute '%s/\($\n\s*\)\+\%$//e'
  endif
  let @/ = l:search
  call winrestview(l:view)
endfunction

" kill trailing whitespace (bang for lines)
command! -bang -nargs=* KillTrailingWhitespace call KillTrailingWhitespace(<bang>0)
" rehash configuration
command! -bang -nargs=* Rehash terminal fresh; nvr -c 'source \$MYVIMRC' -c Sayonara
" ripgrep
command! -bang -nargs=* Rg call fzf#vim#grep('rg --column --line-number --no-heading --color=always '.shellescape(<q-args>).'| tr -d "\017"', 1, <bang>0)


setlocal formatoptions+=n " Recognize numbered lists
setlocal spell

Handle bulleted lists in Git commit messages

setlocal formatoptions+=n " Recognize numbered lists
setlocal spell
setlocal comments=fb:*,fb:-,fb:+ " Indent bulleted lists


set nocompatible
filetype off

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

Bundle 'gmarik/vundle'
Bundle 'scrooloose/nerdtree'
Bundle 'scrooloose/syntastic'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'nathanaelkane/vim-indent-guides'
Bundle 'nathanaelkane/Command-T'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-cucumber'
Bundle 'tpope/vim-repeat'
Bundle 'vim-scripts/upAndDown'
Bundle 'mileszs/ack.vim'
Bundle 'tomtom/tcomment_vim'
Bundle 'twe4ked/vim-peepopen'
Bundle 'kana/vim-textobj-user'
Bundle 'nelstrom/vim-textobj-rubyblock'
Bundle 'Lokaltog/vim-powerline'

Bundle 'bufkill.vim'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'snipMate'
Bundle 'EasyMotion'

Bundle 'altercation/vim-colors-solarized'
Bundle 'nanotech/jellybeans.vim'

Add vim pasta for better paste indenting.

set nocompatible
filetype off

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

Bundle 'gmarik/vundle'
Bundle 'scrooloose/nerdtree'
Bundle 'scrooloose/syntastic'
Bundle 'nathanaelkane/vim-command-w'
Bundle 'nathanaelkane/vim-indent-guides'
Bundle 'nathanaelkane/Command-T'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-cucumber'
Bundle 'tpope/vim-repeat'
Bundle 'vim-scripts/upAndDown'
Bundle 'mileszs/ack.vim'
Bundle 'tomtom/tcomment_vim'
Bundle 'twe4ked/vim-peepopen'
Bundle 'kana/vim-textobj-user'
Bundle 'nelstrom/vim-textobj-rubyblock'
Bundle 'Lokaltog/vim-powerline'
Bundle 'sickill/vim-pasta'

Bundle 'bufkill.vim'
Bundle 'bufexplorer.zip'
Bundle 'vimwiki'
Bundle 'haml.zip'
Bundle 'snipMate'
Bundle 'EasyMotion'

Bundle 'altercation/vim-colors-solarized'
Bundle 'nanotech/jellybeans.vim'


" Ruby
au BufNewFile,BufRead *.rb,*.rbw,*.gem,*.gemspec	set filetype=ruby

" Ruby on Rails
au BufNewFile,BufRead *.builder,*.rxml,*.rjs		set filetype=ruby

" Bundler's Gemfile
au BufNewFile,BufRead Gemfile		set filetype=ruby

" Rakefile
au BufNewFile,BufRead [rR]akefile,*.rake		set filetype=ruby

" Rantfile
au BufNewFile,BufRead [rR]antfile,*.rant		set filetype=ruby

" IRB config
au BufNewFile,BufRead .irbrc,irbrc			set filetype=ruby

" eRuby
au BufNewFile,BufRead *.erb,*.rhtml			set filetype=eruby

Add more file type detection

" Ruby
au BufNewFile,BufRead *.rb,*.rbw,*.gem,*.gemspec	set filetype=ruby

" Ruby on Rails
au BufNewFile,BufRead *.builder,*.rxml,*.rjs		set filetype=ruby

" Rakefile
au BufNewFile,BufRead [rR]akefile,*.rake		set filetype=ruby

" Rantfile
au BufNewFile,BufRead [rR]antfile,*.rant		set filetype=ruby

" IRB config
au BufNewFile,BufRead .irbrc,irbrc			set filetype=ruby

" Rackup
au BufNewFile,BufRead *.ru				set filetype=ruby

" Capistrano
au BufNewFile,BufRead Capfile				set filetype=ruby

" Bundler
au BufNewFile,BufRead Gemfile				set filetype=ruby

" eRuby
au BufNewFile,BufRead *.erb,*.rhtml			set filetype=eruby


if exists("b:did_indent")
  finish
endif

let b:did_indent = 1

setlocal nolisp
setlocal autoindent
setlocal indentexpr=TerraformIndent(v:lnum)
setlocal indentkeys+=<:>,0=},0=)

if exists("*TerraformIndent")
  finish
endif

function! TerraformIndent(lnum)
  " previous non-blank line
  let prevlnum = prevnonblank(a:lnum-1)

  " beginning of file?
  if prevlnum == 0
    return 0
  endif

  " previous line without comments
  let prevline = substitute(getline(prevlnum), '//.*$', '', '')
  let previndent = indent(prevlnum)
  let thisindent = previndent

  " block open?
  if prevline =~ '[\[{]\s*$'
    let thisindent += &sw
  endif

  " current line without comments
  let thisline = substitute(getline(a:lnum), '//.*$', '', '')

  " block close?
  if thisline =~ '^\s*[\]}]'
    let thisindent -= &sw
  endif

  return thisindent
endfunction

Indent on newline in interpolation function argument

if exists("b:did_indent")
  finish
endif

let b:did_indent = 1

setlocal nolisp
setlocal autoindent
setlocal indentexpr=TerraformIndent(v:lnum)
setlocal indentkeys+=<:>,0=},0=)

if exists("*TerraformIndent")
  finish
endif

function! TerraformIndent(lnum)
  " previous non-blank line
  let prevlnum = prevnonblank(a:lnum-1)

  " beginning of file?
  if prevlnum == 0
    return 0
  endif

  " previous line without comments
  let prevline = substitute(getline(prevlnum), '//.*$', '', '')
  let previndent = indent(prevlnum)
  let thisindent = previndent

  " block open?
  if prevline =~ '[\[{\(]\s*$'
    let thisindent += &sw
  endif

  " current line without comments
  let thisline = substitute(getline(a:lnum), '//.*$', '', '')

  " block close?
  if thisline =~ '^\s*[\)\]}]'
    let thisindent -= &sw
  endif

  return thisindent
endfunction


" Vim syntax file

if exists("b:current_syntax")
  finish
endif

" Hide hacker news item id at end of main page lines
syn match Ignore /\s\[[0-9]\{3,}\]$/

" Remove emphesis from all components of main page item except title
syn match Comment /^\s*[0-9]\{1,2}\.\s/
syn match Comment /\s(.*\..*)/
syn match Comment /^.*ago\s|.*comments/

" Comment titles
syn match Comment /^\s*Comment.*$/

" Highlight links
syn region Constant start="\[http" end="\]"

" Highlight code blocks
syn region Statement start="^\s+ " end="^\s "

let b:current_syntax = "hackernews"

Fix syntax highlighting of domains on main page

" Vim syntax file

if exists("b:current_syntax")
  finish
endif

" Hide hacker news item id at end of main page lines
syn match Ignore /\s\[[0-9]\{3,}\]$/

" Remove emphesis from all components of main page item except title
syn match Comment /^\s*[0-9]\{1,2}\.\s/
syn match Comment /\s(\S\+\.\S\+)/
syn match Comment /^.*ago\s|.*comments/

" Comment titles
syn match Comment /^\s*Comment.*$/

" Highlight links
syn region Constant start="\[http" end="\]"

" Highlight code blocks
syn region Statement start="^\s+ " end="^\s "

let b:current_syntax = "hackernews"


set background=dark
silent! colorscheme solarized

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

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

Switch to base16-tomorrow color scheme

set background=dark
silent! colorscheme base16-tomorrow

" Feel free to override the colorscheme by adding a line to ~/.vimrc.local
" such as the following:
"
" colorscheme solarized


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

command! -buffer Fmt call s:GoFormat()

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

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

Send GoFmt errors to a location list

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

command! -buffer Fmt call s:GoFormat()

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

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


" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.dotfiles/vim/vim.symlink/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" Toggle tagbar {{{
  nmap <Leader>t :TagbarToggle<CR>
" }}}

" neocompcache {{{
  let g:neocomplcache_auto_completion_start_length = 3
  let g:neocomplcache_enable_at_startup = 1
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <Leader>a :AV<CR>
  nmap <C-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'
" }}}

Use default neocompcache start length

" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.dotfiles/vim/vim.symlink/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" Toggle tagbar {{{
  nmap <Leader>t :TagbarToggle<CR>
" }}}

" neocompcache {{{
  let g:neocomplcache_enable_at_startup = 1
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <Leader>a :AV<CR>
  nmap <C-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'
" }}}


" Fresh Syntax Vim
" Author : Quinten Palmer

highlight link freshStatement Statement
highlight link freshFunction Function
highlight link freshNumber Number
highlight link freshBool Number

hi def link freshBuiltin freshStatement
hi def link freshTokens freshStatement
hi def link freshExpressionDelimiter freshFunction
hi def link freshDec freshNumber

if exists("b:current_syntax")
	finish
endif

syn keyword freshBuiltin var type function lambda if not and or
syn match freshTokens "[*+><=]"
syn match freshExpressionDelimiter "[()\[\]]"
syn match freshDec "\<\d\+\>"

Include package and member in vim keywords

" Fresh Syntax Vim
" Author : Quinten Palmer

highlight link freshStatement Statement
highlight link freshFunction Function
highlight link freshNumber Number
highlight link freshBool Number

hi def link freshBuiltin freshStatement
hi def link freshTokens freshStatement
hi def link freshExpressionDelimiter freshFunction
hi def link freshDec freshNumber

if exists("b:current_syntax")
	finish
endif

syn keyword freshBuiltin var type function lambda if not and or package member
syn match freshTokens "[*+><=]"
syn match freshExpressionDelimiter "[()\[\]]"
syn match freshDec "\<\d\+\>"


" 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'   : '/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
" }}}

Use $TEMP as default cache directory if it exists

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


set encoding=utf-8 " default character encoding

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

filetype off
call plug#begin()

Plug 'tpope/vim-sensible'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-endwise'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'sheerun/vim-polyglot'
Plug 'plasticboy/vim-markdown'
Plug 'jgdavey/vim-blockle'
Plug 'neomake/neomake'
Plug 'itchyny/lightline.vim'
Plug 'tpope/vim-eunuch' " Syntax sugar for unix commands
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'jnurmine/Zenburn'
Plug 'sjl/gundo.vim'

call plug#end()

filetype plugin indent on

Add elixir plugins to vim

set encoding=utf-8 " default character encoding

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

filetype off
call plug#begin()

Plug 'tpope/vim-sensible'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-endwise'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'sheerun/vim-polyglot'
Plug 'plasticboy/vim-markdown'
Plug 'elixir-lang/vim-elixir'
Plug 'slashmili/alchemist.vim'
Plug 'jgdavey/vim-blockle'
Plug 'neomake/neomake'
Plug 'itchyny/lightline.vim'
Plug 'tpope/vim-eunuch' " Syntax sugar for unix commands
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'jnurmine/Zenburn'
Plug 'sjl/gundo.vim'

call plug#end()

filetype plugin indent on


lua << EOF
local null_ls = require("null-ls")
null_ls.setup({
      sources = {
            -- general
            null_ls.builtins.formatting.trim_newlines,
            null_ls.builtins.formatting.trim_whitespace,
            -- python
            null_ls.builtins.diagnostics.flake8,
            null_ls.builtins.formatting.black.with({
              extra_args = { "-l", "79" }
            }),
            null_ls.builtins.formatting.isort,
            -- javascript
            null_ls.builtins.code_actions.eslint,
            null_ls.builtins.diagnostics.eslint,
            null_ls.builtins.formatting.eslint,
            null_ls.builtins.formatting.prettier,
            -- shell
            null_ls.builtins.code_actions.shellcheck,
            null_ls.builtins.diagnostics.shellcheck,
            -- fish
            null_ls.builtins.diagnostics.fish,
            -- ruby
            null_ls.builtins.diagnostics.rubocop,
            -- go
            null_ls.builtins.formatting.gofmt,
      },
})
EOF

Make prettier not print semi-colons

lua << EOF
local null_ls = require("null-ls")
null_ls.setup({
      sources = {
            -- general
            null_ls.builtins.formatting.trim_newlines,
            null_ls.builtins.formatting.trim_whitespace,
            -- python
            null_ls.builtins.diagnostics.flake8,
            null_ls.builtins.formatting.black.with({
              extra_args = { "-l", "79" }
            }),
            null_ls.builtins.formatting.isort,
            -- javascript
            null_ls.builtins.code_actions.eslint,
            null_ls.builtins.diagnostics.eslint,
            null_ls.builtins.formatting.eslint,
            null_ls.builtins.formatting.prettier.with({
              extra_args = { "--no-semi" }
            }),
            -- shell
            null_ls.builtins.code_actions.shellcheck,
            null_ls.builtins.diagnostics.shellcheck,
            -- fish
            null_ls.builtins.diagnostics.fish,
            -- ruby
            null_ls.builtins.diagnostics.rubocop,
            -- go
            null_ls.builtins.formatting.gofmt,
      },
})
EOF


fun! TrimTrailingWhitespace(type, ...)
  if a:0  " from Visual mode
    let range = '`<' . a:type . '`>'
  elseif a:type == 'line'
    let range = "'[V']"
  elseif a:type == 'block'
    let range = "`[\<C-V>`]"
  else
    let range = '`[v`]'
  endif
  sil exe "normal! ".range."=\<CR>"
  let cmd = "normal! ".range.":s/\\s\\+$//e\<CR>"
  sil exe cmd
endf

nnoremap <silent> = :set opfunc=TrimTrailingWhitespace<CR>g@
vnoremap <silent> = :<C-U>call TrimTrailingWhitespace(visualmode(), 1)<CR>
nmap <silent> == =$

Remove superfluous `\<CR>` from Vim mappings

fun! TrimTrailingWhitespace(type, ...)
  if a:0  " from Visual mode
    let range = '`<' . a:type . '`>'
  elseif a:type == 'line'
    let range = "'[V']"
  elseif a:type == 'block'
    let range = "`[\<C-V>`]"
  else
    let range = '`[v`]'
  endif
  sil exe "normal! ".range."="
  let cmd = "normal! ".range.":s/\\s\\+$//e"
  sil exe cmd
endf

nnoremap <silent> = :set opfunc=TrimTrailingWhitespace<CR>g@
vnoremap <silent> = :<C-U>call TrimTrailingWhitespace(visualmode(), 1)<CR>
nmap <silent> == =$


set nocompatible  " no vi complatibility

" install plugins
call plug#begin()
" Main plugins
Plug 'w0rp/ale'
Plug 'jiangmiao/auto-pairs'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'junegunn/fzf', {'dir': '~/.fzf', 'do': './install --bin'}
Plug 'autozimu/LanguageClient-neovim', {'branch': 'next', 'do': 'bash install.sh'}
Plug 'scrooloose/nerdtree'
Plug 'altercation/vim-colors-solarized'
Plug 'ervandew/supertab'
Plug 'SirVer/ultisnips'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'

" Plugin extras
Plug 'junegunn/fzf.vim'
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'
runtime local.plug.vim
call plug#end()

" source config
runtime core.vim
runtime plugins.vim
runtime autocommands.vim
runtime functions.vim
runtime commands.vim
runtime remaps.vim

" source local config
runtime local.vim

" source project config
if filereadable(".vimlocal")
	source .vimlocal
endif

Rename local vim for better syntax highlighting

set nocompatible  " no vi complatibility

" install plugins
call plug#begin()
" Main plugins
Plug 'w0rp/ale'
Plug 'jiangmiao/auto-pairs'
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'junegunn/fzf', {'dir': '~/.fzf', 'do': './install --bin'}
Plug 'autozimu/LanguageClient-neovim', {'branch': 'next', 'do': 'bash install.sh'}
Plug 'scrooloose/nerdtree'
Plug 'altercation/vim-colors-solarized'
Plug 'ervandew/supertab'
Plug 'SirVer/ultisnips'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'

" Plugin extras
Plug 'junegunn/fzf.vim'
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'
runtime local.plug.vim
call plug#end()

" source config
runtime core.vim
runtime plugins.vim
runtime autocommands.vim
runtime functions.vim
runtime commands.vim
runtime remaps.vim

" source local config
runtime local.vim

" source project config
if filereadable(".local.vim")
	source .local.vim
endif


set number
set list
set colorcolumn=81

au BufRead,BufNewFile *.tsx setfiletype typescript
au BufRead,BufNewFile *.ts setfiletype typescript
autocmd Filetype typescript setlocal expandtab
autocmd Filetype typescript setlocal tabstop=2
autocmd Filetype typescript setlocal shiftwidth=2

au BufRead,BufNewFile *.yml setfiletype yaml
au BufRead,BufNewFile *.yml setfiletype yaml
autocmd Filetype yaml setlocal expandtab
autocmd Filetype yaml setlocal tabstop=2
autocmd Filetype yaml setlocal shiftwidth=2

Add config for .twig files

set number
set list
set colorcolumn=81

au BufRead,BufNewFile *.tsx setfiletype typescript
au BufRead,BufNewFile *.ts setfiletype typescript
autocmd Filetype typescript setlocal expandtab
autocmd Filetype typescript setlocal tabstop=2
autocmd Filetype typescript setlocal shiftwidth=2

au BufRead,BufNewFile *.yml setfiletype yaml
au BufRead,BufNewFile *.yml setfiletype yaml
autocmd Filetype yaml setlocal expandtab
autocmd Filetype yaml setlocal tabstop=2
autocmd Filetype yaml setlocal shiftwidth=2

au BufRead,BufNewFile *.twig setfiletype twig
autocmd Filetype twig setlocal expandtab
autocmd Filetype twig setlocal tabstop=2
autocmd Filetype twig setlocal shiftwidth=2


noremap <buffer> K :help <C-R><C-W><CR>
vnoremap <buffer> K "xy:help <C-R>x<CR>

Add missing n to nnoremap

nnoremap <buffer> K :help <C-R><C-W><CR>
vnoremap <buffer> K "xy:help <C-R>x<CR>


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

Update the wildignore variables to be more generic

" Ignore retarded directories
set wildignore+=**/bower_components/**
set wildignore+=**/node_modules/**
set wildignore+=**/build/**
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"


if has("gui_running")
  set guioptions=acei
  set background=dark
  colorscheme vividchalk
  set listchars=tab:→\ ,eol:¬
  set list
  set guifont=Monaco:h12
end

Fix vim font on linux systems

if has("gui_running")
  set guioptions=acei
  set background=dark
  colorscheme vividchalk
  set listchars=tab:→\ ,eol:¬
  set list
  if has("gui_macvim")
    set guifont=Monaco:h12
  else
    set guifont=Monaco\ 11,\ DejaVu\ Sans\ Mono\ 10
  end
end


let g:LatexBox_output_type = "pdf"
let g:LatexBox_quickfix = 2
let g:LatexBox_latexmk_preview_continuously = 1
let g:LatexBox_Folding = 1

Use zathura as LatexBox viewer

let g:LatexBox_output_type = "pdf"
let g:LatexBox_quickfix = 2
let g:LatexBox_latexmk_preview_continuously = 1
let g:LatexBox_Folding = 1
let g:LatexBox_viewer = 'zathura'


" Vundle
set nocompatible
filetype off
set rtp+=~/.config/nvim/bundle/Vundle.vim
call vundle#begin()
  Plugin 'VundleVim/Vundle.vim'
  Plugin 'chriskempson/base16-vim'
  Plugin 'ervandew/supertab'
  Plugin 'kien/ctrlp.vim'
  Plugin 'scrooloose/syntastic'
  Plugin 'tpope/vim-commentary'
  Plugin 'tpope/vim-markdown'
  Plugin 'lilydjwg/colorizer'
  Plugin 'vim-ruby/vim-ruby'
  Plugin 'tpope/vim-rails'
  Plugin 'sjl/badwolf'
call vundle#end()

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:ctrlp_show_hidden = 1
let g:ctrlp_custom_ignore = {
      \ 'dir': '\v[\/]\.(git|hg|svn)$',
      \ 'file': '\v\.(exe|so|dll|DS_Store|Trash)$',
      \ 'link': 'SOME_BAD_SYMBOLIC_LINKS'
      \ }

Remove base16-vim. A color scheme that's not used. Remove vim-markdown. Performance issues with large files. Added vim-fugitive. Git integration.

" Vundle
set nocompatible
filetype off
set rtp+=~/.config/nvim/bundle/Vundle.vim
call vundle#begin()
  Plugin 'VundleVim/Vundle.vim'
  Plugin 'ervandew/supertab'
  Plugin 'kien/ctrlp.vim'
  Plugin 'scrooloose/syntastic'
  Plugin 'tpope/vim-commentary'
  Plugin 'lilydjwg/colorizer'
  Plugin 'vim-ruby/vim-ruby'
  Plugin 'tpope/vim-rails'
  Plugin 'tpope/vim-fugitive'
  Plugin 'sjl/badwolf'
call vundle#end()

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:ctrlp_show_hidden = 1
let g:ctrlp_custom_ignore = {
      \ 'dir': '\v[\/]\.(git|hg|svn)$',
      \ 'file': '\v\.(exe|so|dll|DS_Store|Trash)$',
      \ 'link': 'SOME_BAD_SYMBOLIC_LINKS'
      \ }


" Personal vim configuration.
" Maintainer: Lorenzo Cabrini <lorenzo.cabrini@gmail.com>

" General options
set nocompatible
set backspace=indent,eol,start
set showcmd
set showmatch
set incsearch
set autowrite
set hidden
set history=50
set ruler

" Tabs and spaces
set tabstop=8
set expandtab
set shiftwidth=4
set softtabstop=4

" Settings for color terminals and in the GUI.
if &t_Co > 2 || has("gui_running")
  syntax on
  set background=dark
  colorscheme elflord
  set hlsearch
endif

" Enable filetype plugins
if has("autocmd")
  filetype plugin indent on
endif

" If lightline is installed
if isdirectory($HOME . "/.vim/pack/default/start/lightline.vim")
  set laststatus=2
  set noshowmode
endif

Add line numbers to Vim.

" Personal vim configuration.
" Maintainer: Lorenzo Cabrini <lorenzo.cabrini@gmail.com>

" General options
set nocompatible
set backspace=indent,eol,start
set showcmd
set showmatch
set incsearch
set autowrite
set hidden
set history=50
set ruler
set number

" Tabs and spaces
set tabstop=8
set expandtab
set shiftwidth=4
set softtabstop=4

" Settings for color terminals and in the GUI.
if &t_Co > 2 || has("gui_running")
  syntax on
  set background=dark
  colorscheme elflord
  set hlsearch
endif

" Enable filetype plugins
if has("autocmd")
  filetype plugin indent on
endif

" If lightline is installed
if isdirectory($HOME . "/.vim/pack/default/start/lightline.vim")
  set laststatus=2
  set noshowmode
endif


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

Make vim sh filetype recognition regex more compact

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


" Author: w0rp <devw0rp@gmail.com>
" Description: This file adds support for using the shellcheck linter with
"   shell scripts.

" This global variable can be set with a string of comma-seperated error
" codes to exclude from shellcheck. For example:
"
" let g:ale_linters_sh_shellcheck_exclusions = 'SC2002,SC2004'
if !exists('g:ale_linters_sh_shellcheck_exclusions')
    let g:ale_linters_sh_shellcheck_exclusions = ''
endif

if g:ale_linters_sh_shellcheck_exclusions !=# ''
    let s:exclude_option = '-e ' .  g:ale_linters_sh_shellcheck_exclusions
else
    let s:exclude_option = ''
endif

call ale#linter#Define('sh', {
\   'name': 'shellcheck',
\   'executable': 'shellcheck',
\   'command': 'shellcheck ' . s:exclude_option . ' -f gcc -',
\   'callback': 'ale#handlers#HandleGCCFormat',
\})

Choose shell dialect based on vim syntax

" Author: w0rp <devw0rp@gmail.com>
" Description: This file adds support for using the shellcheck linter with
"   shell scripts.

" This global variable can be set with a string of comma-seperated error
" codes to exclude from shellcheck. For example:
"
" let g:ale_linters_sh_shellcheck_exclusions = 'SC2002,SC2004'
if !exists('g:ale_linters_sh_shellcheck_exclusions')
    let g:ale_linters_sh_shellcheck_exclusions = ''
endif

if g:ale_linters_sh_shellcheck_exclusions !=# ''
    let s:exclude_option = '-e ' .  g:ale_linters_sh_shellcheck_exclusions
else
    let s:exclude_option = ''
endif

function! s:GetDialectArgument()
    if exists('b:is_bash') && b:is_bash
        return '-s bash'
    elseif exists('b:is_sh') && b:is_sh
        return '-s sh'
    elseif exists('b:is_kornshell') && b:is_kornshell
        return '-s ksh'
    endif

    return ''
endfunction

function! ale_linters#sh#shellcheck#GetCommand(buffer)
  return 'shellcheck ' . s:exclude_option . ' ' . s:GetDialectArgument() . ' -f gcc -'
endfunction

call ale#linter#Define('sh', {
\   'name': 'shellcheck',
\   'executable': 'shellcheck',
\   'command_callback': 'ale_linters#sh#shellcheck#GetCommand',
\   'callback': 'ale#handlers#HandleGCCFormat',
\})


if exists("*FollowLink")
    finish
endif

" --------------------------------
" Add plugin to the path
" --------------------------------
python import sys
python import vim
python sys.path.append(vim.eval('expand("<sfile>:h")'))

function! FollowLink()
python << endOfPython

from follow_markdown_links import follow_link
follow_link()

endOfPython
endfunction

command! FollowLink call FollowLink()
nnoremap <script> <CR> :FollowLink<CR>
nnoremap <script> <BS> :e#<CR>

Allow keyboard mapping for `markdown` type only

if exists("*FollowLink")
    finish
endif

" --------------------------------
" Add plugin to the path
" --------------------------------
python import sys
python import vim
python sys.path.append(vim.eval('expand("<sfile>:h")'))

function! FollowLink()
python << endOfPython

from follow_markdown_links import follow_link
follow_link()

endOfPython
endfunction

command! FollowLink call FollowLink()
autocmd FileType markdown nnoremap <script> <CR> :FollowLink<CR>
autocmd FileType markdown nnoremap <script> <BS> :e#<CR>


" Set the shell to bash so we inherit its path, to make sure
" we inherit its path. This affects :Rtags finding the right
" path to homebrewed ctags rather than the XCode version of ctags
set shell=bash\ -i

Remove setting which cause some plugins crashing mvim in iterm2

" Set the shell to bash so we inherit its path, to make sure
" we inherit its path. This affects :Rtags finding the right
" path to homebrewed ctags rather than the XCode version of ctags
"set shell=bash\ -i


" Double-tap leader to toggle folds.
map <leader><leader> za

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

" Double-tap backslash to write.
nnoremap <silent> \\ :<C-U>write<CR>

" Shortcut for update.
nnoremap <silent> <leader>w :<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

Use Q to toggle folds.

" Double-tap leader to open Command-line mode.
nnoremap <leader><leader> :

" Use : to open command-line window.
nnorema : q:

" Use Q to toggle folds.
nmap Q za

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

" Double-tap backslash to write.
nnoremap <silent> \\ :<C-U>write<CR>

" Shortcut for update.
nnoremap <silent> <leader>w :<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


" Plugin:      https://github.com/mhinz/vim-startify
" Description: Start screen displaying recently used stuff.
" Maintainer:  Marco Hinz <http://github.com/mhinz>
" Version:     1.6

if exists('g:loaded_startify') || &cp
  finish
endif
let g:loaded_startify = 1

augroup startify
  autocmd!
  autocmd VimEnter *
        \ if !argc() && (line2byte('$') == -1) && (v:progname =~? '^[gm]\=vim\%[\.exe]$') |
        \   call startify#insane_in_the_membrane() |
        \ endif
augroup END

command! -nargs=? -bar -complete=customlist,startify#session_list SSave   call startify#session_save(<f-args>)
command! -nargs=? -bar -complete=customlist,startify#session_list SLoad   call startify#session_load(<f-args>)
command! -nargs=? -bar -complete=customlist,startify#session_list SDelete call startify#session_delete(<f-args>)
command! -nargs=0 -bar Startify enew | call startify#insane_in_the_membrane()

" vim: et sw=2 sts=2

Remove VimEnter event after execution

" Plugin:      https://github.com/mhinz/vim-startify
" Description: Start screen displaying recently used stuff.
" Maintainer:  Marco Hinz <http://github.com/mhinz>
" Version:     1.6

if exists('g:loaded_startify') || &cp
  finish
endif
let g:loaded_startify = 1

augroup startify
  autocmd!
  autocmd startify VimEnter *
        \ if !argc() && (line2byte('$') == -1) && (v:progname =~? '^[gm]\=vim\%[\.exe]$') |
        \   call startify#insane_in_the_membrane() |
        \ endif |
        \ autocmd! startify VimEnter
augroup END

command! -nargs=? -bar -complete=customlist,startify#session_list SSave   call startify#session_save(<f-args>)
command! -nargs=? -bar -complete=customlist,startify#session_list SLoad   call startify#session_load(<f-args>)
command! -nargs=? -bar -complete=customlist,startify#session_list SDelete call startify#session_delete(<f-args>)
command! -nargs=0 -bar Startify enew | call startify#insane_in_the_membrane()

" vim: et sw=2 sts=2


" Tyep the letters then hit space
" Binding Pry All
iabbrev bpa binding.pry
" Binding Pry Except Test
iabbrev bpet binding.pry unless Rails.env.test?
" Aggregate failures
iabbrev af :aggregate_failures
iabbrev fsl # frozen_string_literal: true

Add ruby shortcut for remote_pry

" How to: Type the letters then hit space

# General
iabbrev fsl # frozen_string_literal: true

# debugging
iabbrev bpa binding.pry
iabbrev bput binding.pry unless Rails.env.test?
iabbrev brp binding.remote_pry
iabbrev brput binding.remote_pry unless Rails.env.test?

# RSpec
iabbrev af :aggregate_failures


" Author: w0rp <devw0rp@gmail.com>, KabbAmine <amine.kabb@gmail.com>
" Description: This file adds support for checking Vim code with Vint.

" This flag can be used to change enable/disable style issues.
let g:ale_vim_vint_show_style_issues =
\   get(g:, 'ale_vim_vint_show_style_issues', 1)

let s:warning_flag = g:ale_vim_vint_show_style_issues ? '-s' : '-w'
let s:enable_neovim = has('nvim') ? ' --enable-neovim ' : ''
let s:format = '-f "{file_path}:{line_number}:{column_number}: {severity}: {description} (see {reference})"'

call ale#linter#Define('vim', {
\   'name': 'vint',
\   'executable': 'vint',
\   'command': 'vint '
\       . s:warning_flag
\       . ' --no-color '
\       . s:enable_neovim
\       . s:format
\       . ' %t',
\   'callback': 'ale#handlers#HandleGCCFormat',
\})

Support older versions of Vint

" Author: w0rp <devw0rp@gmail.com>, KabbAmine <amine.kabb@gmail.com>
" Description: This file adds support for checking Vim code with Vint.

" This flag can be used to change enable/disable style issues.
let g:ale_vim_vint_show_style_issues =
\   get(g:, 'ale_vim_vint_show_style_issues', 1)

let s:warning_flag = g:ale_vim_vint_show_style_issues ? '-s' : '-w'
let s:vint_version = ale#semver#Parse(system('vint --version'))
let s:has_no_color_support = ale#semver#GreaterOrEqual(s:vint_version, [3, 0, 7])
let s:enable_neovim = has('nvim') ? ' --enable-neovim ' : ''
let s:format = '-f "{file_path}:{line_number}:{column_number}: {severity}: {description} (see {reference})"'

call ale#linter#Define('vim', {
\   'name': 'vint',
\   'executable': 'vint',
\   'command': 'vint '
\       . s:warning_flag . ' '
\       . (s:has_no_color_support ? '--no-color ' : '')
\       . s:enable_neovim
\       . s:format
\       . ' %t',
\   'callback': 'ale#handlers#HandleGCCFormat',
\})


setlocal tabstop=4
setlocal shiftwidth=4
setlocal softtabstop=4
setlocal noexpandtab

let g:go_fmt_command = "goimports"

let g:go_highlight_types = 1
let g:go_highlight_fields = 1
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_operators = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_build_constraints = 1

let g:go_template_autocreate = 0

let g:go_metalinter_autosave = 1
let g:go_metalinter_autosave_enabled = ['golint']
let g:go_metalinter_enabled = ['golint', 'errcheck']

Use camel casing when using GoAddTags

setlocal tabstop=4
setlocal shiftwidth=4
setlocal softtabstop=4
setlocal noexpandtab

let g:go_fmt_command = "goimports"

let g:go_highlight_types = 1
let g:go_highlight_fields = 1
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_operators = 1
let g:go_highlight_extra_types = 1
let g:go_highlight_build_constraints = 1

let g:go_template_autocreate = 0

let g:go_metalinter_autosave = 1
let g:go_metalinter_autosave_enabled = ['golint']
let g:go_metalinter_enabled = ['golint', 'errcheck']

let g:go_addtags_transform = 'camelcase'


" ===============================
" Setup:
" Include following line in ~/.vimrc:
"   source $PATH_TO_HERE/vim_config.vim
" Then run:
"   git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
"   vim +PluginInstall +qall

" ================================
" Vundle config
"
set nocompatible
filetype off

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

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

" Plugins
Plugin 'jelera/vim-javascript-syntax'
Plugin 'pangloss/vim-javascript'
Plugin 'nathanaelkane/vim-indent-guides'
Plugin 'Raimondi/delimitMate'

" Color Schemes
Plugin 'Lokaltog/vim-distinguished'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" ================================

set t_Co=256
syntax on
set background=dark
colorscheme distinguished

set hlsearch

set expandtab
set shiftwidth=2
set softtabstop=2

set textwidth=80
set colorcolumn=+1

set nobackup

" Strip trailing whitespace from all files on save
autocmd BufWritePre * :%s/\s\+$//e

Add supertab to vim config

" ===============================
" Setup:
" Include following line in ~/.vimrc:
"   source $PATH_TO_HERE/vim_config.vim
" Then run:
"   git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
"   vim +PluginInstall +qall

" ================================
" Vundle config
"
set nocompatible
filetype off

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

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

" Plugins
Plugin 'jelera/vim-javascript-syntax'
Plugin 'pangloss/vim-javascript'
Plugin 'nathanaelkane/vim-indent-guides'
Plugin 'Raimondi/delimitMate'
Plugin 'ervandew/supertab'

" Color Schemes
Plugin 'Lokaltog/vim-distinguished'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required
" ================================

set t_Co=256
syntax on
set background=dark
colorscheme distinguished

set hlsearch
set incsearch

set expandtab
set shiftwidth=2
set softtabstop=2

set textwidth=80
set colorcolumn=+1

set nobackup

" Strip trailing whitespace from all files on save
autocmd BufWritePre * :%s/\s\+$//e


" Enable true color mode.
set termguicolors

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

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

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

" Disable promptline and tmuxline extensions.
let g:airline#extensions#tmuxline#enabled = 0
let g:airline#extensions#promptline#enabled = 0

" Un-set promptline and tmuxline snapshot.
unlet g:airline#extensions#promptline#snapshot_file
unlet g:airline#extensions#tmuxline#snapshot_file

Check for GuiFont before using

" Enable true color mode.
set termguicolors

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

" Set font.
if exists('GuiFont')
  GuiFont Inconsolata-g for Powerline:h12
endif

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

" Disable promptline and tmuxline extensions.
let g:airline#extensions#tmuxline#enabled = 0
let g:airline#extensions#promptline#enabled = 0

" Un-set promptline and tmuxline snapshot.
unlet g:airline#extensions#promptline#snapshot_file
unlet g:airline#extensions#tmuxline#snapshot_file


" 2-space width tabs
set tabstop=2
set shiftwidth=2

" ics
autocmd BufNewFile,BufRead *.iced call SetICSOptions()
function SetICSOptions()
	setlocal filetype=coffee
	setlocal commentstring=#\ %s
	setlocal expandtab
endfunction

" js indentation
autocmd BufNewFile,BufRead *.coffee set expandtab
autocmd BufNewFile,BufRead *.js set expandtab
autocmd BufNewFile,BufRead *.json set expandtab

" assembly indentation
autocmd BufNewFile,BufRead *.s call SetAsmOptions()
autocmd BufNewFile,BufRead *.as call SetAsmOptions()
autocmd BufNewFile,BufRead *.asm call SetAsmOptions()
function SetAsmOptions()
	setlocal tabstop=8
	hi SpecialKey cterm=none ctermbg=none ctermfg=bg
endfunction

" whitespace highlighting
if !(&filetype == "txt")
	set list " show special characters
	set listchars=tab:→\ ,trail:·,extends:>,precedes:<,nbsp:‥
endif

Fix foreground in asm highlighting

" 2-space width tabs
set tabstop=2
set shiftwidth=2

" whitespace highlighting
if !(&filetype == "txt")
	set list " show special characters
	set listchars=tab:→\ ,trail:·,extends:>,precedes:<,nbsp:‥
endif

" ics
autocmd BufNewFile,BufRead *.iced call SetICSOptions()
function SetICSOptions()
	setlocal filetype=coffee
	setlocal commentstring=#\ %s
	setlocal expandtab
endfunction

" js indentation
autocmd BufNewFile,BufRead *.coffee set expandtab
autocmd BufNewFile,BufRead *.js set expandtab
autocmd BufNewFile,BufRead *.json set expandtab

" assembly indentation
autocmd BufNewFile,BufRead *.s call SetAsmOptions()
autocmd BufNewFile,BufRead *.as call SetAsmOptions()
autocmd BufNewFile,BufRead *.asm call SetAsmOptions()
function SetAsmOptions()
	setlocal tabstop=8
	setlocal nolist
endfunction


set background=dark
silent! colorscheme base16-tomorrow

" Feel free to override the colorscheme by adding a line to ~/.vimrc.local
" such as the following:
"
" colorscheme solarized

Switch to regular Tomorrow Night theme

set background=dark
silent! colorscheme Tomorrow-Night

" Feel free to override the colorscheme by adding a line to ~/.vimrc.local
" such as the following:
"
" colorscheme solarized


" Turn off default key mappings
let g:multi_cursor_use_default_mapping=0

" Switch to multicursor mode with ,mc
let g:multi_cursor_start_key=',mc'

" Ctrl-n, Ctrl-p, Ctrl-x, and <Esc> are mapped in the special multicursor
" mode once you've added at least one virtual cursor to the buffer
let g:multi_cursor_next_key='<C-n>'
let g:multi_cursor_prev_key='<C-p>'
let g:multi_cursor_skip_key='<C-x>'
let g:multi_cursor_quit_key='<Esc>'

Change comma to just <leader>

" Turn off default key mappings
let g:multi_cursor_use_default_mapping=0

" Switch to multicursor mode with ,mc
let g:multi_cursor_start_key='<leader>mc'

" Ctrl-n, Ctrl-p, Ctrl-x, and <Esc> are mapped in the special multicursor
" mode once you've added at least one virtual cursor to the buffer
let g:multi_cursor_next_key='<C-n>'
let g:multi_cursor_prev_key='<C-p>'
let g:multi_cursor_skip_key='<C-x>'
let g:multi_cursor_quit_key='<Esc>'


setlocal makeprg=flake8\ %
setlocal errorformat=%f:%l:%c:\ %m
setlocal foldmethod=indent

Use autopep8 for Python formatting.

setlocal makeprg=flake8\ %
setlocal errorformat=%f:%l:%c:\ %m
setlocal foldmethod=indent
setlocal formatprg=autopep8\ -


autocmd BufNewFile,BufRead *.cu set cindent

autocmd BufNewFile,BufRead *.cc,*.cpp,*.cu,*.h,*.hpp,*.c set ft=cpp.doxygen

set cinoptions=>s,e0,n0,f0,{0,}0,^0,L-1,:0,=s,l0,b0,g0,hs,N-s,ps,ts,is,+s,c3,C0,/0,(2s,us,U0,w0,W0,k0,m0,j0,J0,)20,*70,#0
nmap <Leader>k :tabe %<CR>g]

Remove some c family configurations