let b:splitjoin_split_callbacks = [
      \ 'sj#js#SplitObjectLiteral',
      \ 'sj#js#SplitArray',
      \ ]

let b:splitjoin_join_callbacks = [
      \ 'sj#js#JoinArray',
      \ 'sj#js#JoinObjectLiteral',
      \ ]

Disable trailing commas for JSON

let b:splitjoin_split_callbacks = [
      \ 'sj#js#SplitObjectLiteral',
      \ 'sj#js#SplitArray',
      \ ]

let b:splitjoin_join_callbacks = [
      \ 'sj#js#JoinArray',
      \ 'sj#js#JoinObjectLiteral',
      \ ]

" JSON does not support trailing commas
let b:splitjoin_trailing_comma = 0


let s:python = executable('python3') ? 'python3' : 'python'
let s:script = resolve(expand('<sfile>:h:h')) . '/termedit.py'
let $EDITOR = s:python . ' ' . s:script

function s:term_release()
  if exists('b:termedit')
    call rpcnotify(b:termedit, 'release')
  endif
endfunction
command! TermRelease call s:term_release()

Use function! to prevent errors when updating

let s:python = executable('python3') ? 'python3' : 'python'
let s:script = resolve(expand('<sfile>:h:h')) . '/termedit.py'
let $EDITOR = s:python . ' ' . s:script

function! s:term_release()
  if exists('b:termedit')
    call rpcnotify(b:termedit, 'release')
  endif
endfunction
command! TermRelease call s:term_release()


" Vim filetype plugin
" Language:              [ba]sh script
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

if exists('b:undo_ftplugin')
  let b:undo_ftplugin .= ' | '
else
  let b:undo_ftplugin = ''
endif

xnoremap <buffer> <silent> iv :<C-u>call sh#in_parameter_expansion()<CR>
onoremap <buffer> <silent> iv :<C-u>call sh#in_parameter_expansion()<CR>

if !exists("*MyShPEFtpluginUndo")
  function MyShPEFtpluginUndo()
    silent! xunmap <buffer> iv
    silent! ounmap <buffer> iv
  endfunction
endif

let b:undo_ftplugin .= 'call MyShPEFtpluginUndo()'

Add "quote variable" mapping to sh ftplugin

" Vim filetype plugin
" Language:              [ba]sh script
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

if exists('b:undo_ftplugin')
  let b:undo_ftplugin .= ' | '
else
  let b:undo_ftplugin = ''
endif

xnoremap <buffer> <silent> iv :<C-u>call sh#in_parameter_expansion()<CR>
onoremap <buffer> <silent> iv :<C-u>call sh#in_parameter_expansion()<CR>

" Relies on surround.vim and custom text object above
nmap <buffer> <silent> <LocalLeader>qv ysiv"

if !exists("*MyShPEFtpluginUndo")
  function MyShPEFtpluginUndo()
    silent! xunmap <buffer> iv
    silent! ounmap <buffer> iv
    silent! ounmap <buffer> <LocalLeader>qv
  endfunction
endif

let b:undo_ftplugin .= 'call MyShPEFtpluginUndo()'


autocmd FileType go set noexpandtab
autocmd FileType go set nolist

let g:go_fmt_command = "goimports"

Add GoDef and GoRun shortcuts

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>


set foldmethod=marker

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

" Neovim theme
Plug 'morhetz/gruvbox'

"{{{ Language specific plugins
Plug 'dag/vim-fish', { 'for': 'fish' }
Plug 'rhysd/vim-crystal', { 'for': 'crystal' }
Plug 'pangloss/vim-javascript', { 'for': 'javascript' }
Plug 'leafgarland/typescript-vim', { 'for': 'typescript' }
"}}}

call plug#end()
"}}}

" Use 2 spaces instead of tab
set tabstop=2 shiftwidth=2 softtabstop=2 expandtab

" Show line numbers
set number

" Enable 24-bit colour
set termguicolors

" Set maxwidth of 80
set colorcolumn=81
set wrap

set background=dark
colorscheme gruvbox

cabbrev vsf vert sfind

Include rust plugin for neovim

set foldmethod=marker

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

" Neovim theme
Plug 'morhetz/gruvbox'

"{{{ Language specific plugins
Plug 'dag/vim-fish', { 'for': 'fish' }
Plug 'rhysd/vim-crystal', { 'for': 'crystal' }
Plug 'pangloss/vim-javascript', { 'for': 'javascript' }
Plug 'leafgarland/typescript-vim', { 'for': 'typescript' }
Plug 'rust-lang/rust.vim', { 'for': 'rust' }
"}}}

call plug#end()
"}}}

" Use 2 spaces instead of tab
set tabstop=2 shiftwidth=2 softtabstop=2 expandtab

" Show line numbers
set number

" Enable 24-bit colour
set termguicolors

" Set maxwidth of 80
set colorcolumn=81
set wrap

set background=dark
colorscheme gruvbox

cabbrev vsf vert sfind

let g:rustfmt_autosave = 1


highlight ColorColumn ctermbg=DarkGray
set cursorline

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

Change vim column color pattern

highlight ColorColumn ctermbg=DarkGray
set cursorline

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


autocmd BufEnter * call execute('CocDisable')
autocmd BufEnter *.tsx,*.ts call execute("CocEnable")

" TypeScript
" npm install -g typescript typescript-language-server
" And then run :CocInstall coc-tsserver in Neovim
autocmd FileType typescriptreact,typescript,typescript.tsx nmap <silent> gd <Plug>(coc-definition)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>ft <Plug>(coc-type-definition)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fi <Plug>(coc-implementation)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fu <Plug>(coc-references)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>nm <Plug>(coc-rename)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> gj <Plug>(coc-diagnostic-next)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> gk <Plug>(coc-diagnostic-prev)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fl :CocList outline<cr>

Disable asyncomplete popup for TypeScript-CoC

autocmd BufEnter * call execute('CocDisable')
autocmd BufEnter *.tsx,*.ts call execute('CocEnable')

autocmd BufEnter * let g:asyncomplete_auto_popup = 1
autocmd BufEnter *.tsx,*.ts let g:asyncomplete_auto_popup = 0

" TypeScript
" npm install -g typescript typescript-language-server
" And then run :CocInstall coc-tsserver in Neovim
autocmd FileType typescriptreact,typescript,typescript.tsx nmap <silent> gd <Plug>(coc-definition)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>ft <Plug>(coc-type-definition)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fi <Plug>(coc-implementation)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fu <Plug>(coc-references)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>nm <Plug>(coc-rename)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> gj <Plug>(coc-diagnostic-next)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> gk <Plug>(coc-diagnostic-prev)
autocmd FileType typescriptreact,typescript,typescript.tsx map <silent> <leader>fl :CocList outline<cr>


command! -nargs=* GoGuruCallees      call Go Guru('callees', <f-args>)
command! -nargs=* GoGuruCallers      call Go Guru('callers', <f-args>)
command! -nargs=* GoGuruCallstack    call Go Guru('callstack', <f-args>)
command! -nargs=* GoGuruDefinition   call Go Guru('definition', <f-args>)
command! -nargs=* GoGuruDescribe     call Go Guru('describe', <f-args>)
command! -nargs=* GoGuruFreevars     call Go Guru('freevars', <f-args>)
command! -nargs=* GoGuruImplements   call Go Guru('implements', <f-args>)
command! -nargs=* GoGuruPeers        call Go Guru('peers', <f-args>)
command! -nargs=* GoGuruChannelPeers call Go Guru('peers', <f-args>)
command! -nargs=* GoGuruPointsto     call Go Guru('pointsto', <f-args>)
command! -nargs=* GoGuruReferrers    call Go Guru('referrers', <f-args>)
command! -nargs=* GoGuruWhicherrs    call Go Guru('whicherrs', <f-args>)

Fix wrong guru function name

command! -nargs=* GoGuruCallees      call GoGuru('callees', <f-args>)
command! -nargs=* GoGuruCallers      call GoGuru('callers', <f-args>)
command! -nargs=* GoGuruCallstack    call GoGuru('callstack', <f-args>)
command! -nargs=* GoGuruDefinition   call GoGuru('definition', <f-args>)
command! -nargs=* GoGuruDescribe     call GoGuru('describe', <f-args>)
command! -nargs=* GoGuruFreevars     call GoGuru('freevars', <f-args>)
command! -nargs=* GoGuruImplements   call GoGuru('implements', <f-args>)
command! -nargs=* GoGuruPeers        call GoGuru('peers', <f-args>)
command! -nargs=* GoGuruChannelPeers call GoGuru('peers', <f-args>)
command! -nargs=* GoGuruPointsto     call GoGuru('pointsto', <f-args>)
command! -nargs=* GoGuruReferrers    call GoGuru('referrers', <f-args>)
command! -nargs=* GoGuruWhicherrs    call GoGuru('whicherrs', <f-args>)


" File type detection is On.
filetype on

" C/C++, Java
autocmd FileType c,cpp,java setl cindent
autocmd FileType c,cpp,java setl expandtab tabstop=4 shiftwidth=4 softtabstop=4 shiftround

" JavaScript
autocmd FileType javascript setl autoindent
autocmd FileType javascript setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround

" Ruby [2010-05-07]
autocmd FileType ruby setl smartindent
autocmd FileType ruby setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround
autocmd FileType ruby inoremap # X#

" Python
autocmd FileType python setl smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
autocmd FileType python setl expandtab tabstop=4 shiftwidth=4 softtabstop=4 shiftround
autocmd FileType python inoremap # X#

" HTML
autocmd FileType html setl autoindent
autocmd FileType html setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround

Add FileType settings for ERB and SCSS

" File type detection is On.
filetype on

" C/C++, Java
autocmd FileType c,cpp,java setl cindent
autocmd FileType c,cpp,java setl expandtab tabstop=4 shiftwidth=4 softtabstop=4 shiftround

" JavaScript
autocmd FileType javascript setl autoindent
autocmd FileType javascript setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround

" Ruby, eruby (ERB)
autocmd FileType ruby,eruby setl smartindent
autocmd FileType ruby,eruby setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround
autocmd FileType ruby,eruby inoremap # X#

" Python
autocmd FileType python setl smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
autocmd FileType python setl expandtab tabstop=4 shiftwidth=4 softtabstop=4 shiftround
autocmd FileType python inoremap # X#

" HTML, CSS, SCSS
autocmd FileType html,css,scss setl autoindent
autocmd FileType html,css,scss setl expandtab tabstop=2 shiftwidth=2 softtabstop=2 shiftround


" Refresh Ctags
map <Leader>rtt :!ctags --extra=+f -R *<CR><CR>
map <Leader>rt :TagbarToggle<CR><CR>

Secure my twitter credentials in another file, source it in config and gitignore it.

" Refresh Ctags
map <Leader>rt :!ctags --extra=+f -R *<CR><CR>
map <Leader>rtt :TagbarToggle<CR><CR>

" Set NERDTreeToggle to leader p
map <Leader>p :NERDTreeToggle<CR><CR>

" Twitvim setup
source ~/.vim/.twitter_user_and_password.vim
nnoremap <F8> :FriendsTwitter<cr>
nnoremap <S-F8> :UserTwitter<cr>


" Variables
let s:no_python_support = "Vim is compiled without python support"
let s:no_ruby_support = "Vim is compiled without ruby support"

" Plugins that requires python support
if !has("python")
  call janus#disable_plugin("gundo", s:no_python_support)
  call janus#disable_plugin("pep8", s:no_python_support)
endif

" Plugins that requires ruby support
if !has("ruby")
  call janus#disable_plugin("command-t", s:no_ruby_support)
  call janus#disable_plugin("ruby", s:no_ruby_support)
endif

" Pep8 requires pep8 installed
if !executable("pep8")
  call janus#disable_plugin("pep8", "The pep8 program is not installed")
endif

" Ack requires ack command
if !executable("ack")
  call janus#disable_plugin("ack", "The ack program is not installed")
endif

" Gist-vim requires curl
if !executable("curl")
  call janus#disable_plugin("gist", "The curl program is not installed")
endif

Disable nodejs if DetectNode() is defined

" Variables
let s:no_python_support = "Vim is compiled without python support"
let s:no_ruby_support = "Vim is compiled without ruby support"

" Plugins that requires python support
if !has("python")
  call janus#disable_plugin("gundo", s:no_python_support)
  call janus#disable_plugin("pep8", s:no_python_support)
endif

" Plugins that requires ruby support
if !has("ruby")
  call janus#disable_plugin("command-t", s:no_ruby_support)
  call janus#disable_plugin("ruby", s:no_ruby_support)
endif

" Pep8 requires pep8 installed
if !executable("pep8")
  call janus#disable_plugin("pep8", "The pep8 program is not installed")
endif

" Ack requires ack command
if !executable("ack")
  call janus#disable_plugin("ack", "The ack program is not installed")
endif

" Gist-vim requires curl
if !executable("curl")
  call janus#disable_plugin("gist", "The curl program is not installed")
endif

" nodejs does not protect itself
" See #336
if exists("*DetectNode")
  call janus#disable_plugin("nodejs", "Nodejs already exists on your system.")
endif


let g:LanguageClient_serverCommands = {
\   'go': ['bingo', '-mode', 'stdio'],
\   'rust': ['rustup', 'run', 'nightly', 'rls'],
\   'yaml': ['yaml-language-server', '--stdio'],
\ }
let g:LanguageClient_loadSettings = 1
let g:LanguageClient_settingsPath = '~/.config/nvim/plugins/language-client-settings.json'

augroup LanguageClient_config
  autocmd!
  autocmd BufWritePre *.yaml,*.yml,*.go,*.rs :call LanguageClient#textDocument_formatting_sync()
augroup END

noremap <silent> <C-]> :call LanguageClient#textDocument_definition()<CR>
noremap <silent> <C-t> <C-o>

Use async format in LaunguageClient-neovim

let g:LanguageClient_serverCommands = {
\   'go': ['bingo', '-mode', 'stdio'],
\   'rust': ['rustup', 'run', 'nightly', 'rls'],
\   'yaml': ['yaml-language-server', '--stdio'],
\ }
let g:LanguageClient_loadSettings = 1
let g:LanguageClient_settingsPath = '~/.config/nvim/plugins/language-client-settings.json'

augroup LanguageClient_config
  autocmd!
  autocmd BufWritePre *.yaml,*.yml,*.go,*.rs :call LanguageClient#textDocument_formatting()
augroup END

noremap <silent> <C-]> :call LanguageClient#textDocument_definition()<CR>
noremap <silent> <C-t> <C-o>


" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)

" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)

Add leader command to align markdown table

" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)

" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)

" Automatically align a Markdown table
nmap <Leader>at gaip*<Bar>


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

set history=50
set undolevels=1000
set ruler      " show the cursor position all the time
set showcmd    " display incomplete commands
set incsearch
set hlsearch
set number     " line numbers
set nobackup
set wrap
set autoread
set smartcase

set shortmess=imrx
set cmdheight=2

set scrolloff=10
set sidescrolloff=10

" Autoindent and Smartindent on
set autoindent
set smartindent

" Tab settings
set expandtab
set tabstop=2
set shiftwidth=2
set smarttab

" Setup the menu stuff
set wildmenu
set wildmode=list:longest,full

" Have swapfiles in a separate directory
set dir=~/.vim/tmp

Add a sane max height for CommandT

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

set history=50
set undolevels=1000
set ruler      " show the cursor position all the time
set showcmd    " display incomplete commands
set incsearch
set hlsearch
set number     " line numbers
set nobackup
set wrap
set autoread
set smartcase

set shortmess=imrx
set cmdheight=2

set scrolloff=10
set sidescrolloff=10

" Autoindent and Smartindent on
set autoindent
set smartindent

" Tab settings
set expandtab
set tabstop=2
set shiftwidth=2
set smarttab

" Setup the menu stuff
set wildmenu
set wildmode=list:longest,full

" Have swapfiles in a separate directory
set dir=~/.vim/tmp

let g:CommandTMaxHeight=20


let g:conjure_log_direction = "horizontal"
let g:conjure_log_auto_open = ["up", "status", "out", "tap", "doc", "test"]

Tweak Conjure configuration to a blacklist

let g:conjure_log_direction = "horizontal"
let g:conjure_log_blacklist = ["up", "ret", "ret-multiline", "load-file", "eval"]


" Equip with css completions
source ~/.vim/bundle/cssautocomplete/ftplugin/css_autocomplete.vim

" Set omnifunction same as css files
setlocal omnifunc=csscomplete#CompleteCSS

" Don't pair {
let b:AutoPairs = {'(':')', '[':']',"'":"'",'"':'"', '`':'`'}

" Also consider - as keyword
setlocal iskeyword+=-

Correct css completion file path

" Equip with css completions
source ~/.vim/plugged-local/cssautocomplete/ftplugin/css_autocomplete.vim

" Set omnifunction same as css files
setlocal omnifunc=csscomplete#CompleteCSS

" Don't pair {
let b:AutoPairs = {'(':')', '[':']',"'":"'",'"':'"', '`':'`'}

" Also consider - as keyword
setlocal iskeyword+=-


set background=dark
colorscheme solarized

" textwidth < 81 please
set colorcolumn=81

" Medium Menlo
set guifont=Menlo:h15

Switch from Menlo to Consolas in VIM

set background=dark
colorscheme solarized

" textwidth < 81 please
set colorcolumn=81

" Medium Menlo
set guifont=Consolas:h16


autocmd BufNewFile,BufRead *.coffee set filetype=coffee

Add preamble to ftdetect plugin

" Language:    CoffeeScript
" Maintainer:  Mick Koch <kchmck@gmail.com>
" URL:         http://github.com/kchmck/vim-coffee-script
" Filenames:   *.coffee
" Version:     1.0
" Last Change: 2010-01-20

autocmd BufNewFile,BufRead *.coffee set filetype=coffee


source plugin/increment_activator.vim

describe 'default increment'
  after
    " Delete all line
    execute 'normal 1GdG'
  end

  it 'can increment weekday of currently word'
    put! = 'monday'
    call increment_activator#increment()
    Expect getline(1) == 'tuesday'
  end

  it 'can decrement weekday of currently word'
    put! = 'sunday'
    call increment_activator#decrement()
    Expect getline(1) == 'saturday'
  end

  it 'can increment/decrement number by the default vim behavior'
    execute 'normal I1'
    execute "normal \<C-a>"
    Expect getline(1) == '2'

    execute "normal \<C-x>"
    execute "normal \<C-x>"
    execute "normal \<C-x>"
    Expect getline(1) == '-1'
  end
end

Use defined key mappings for tests

source plugin/increment_activator.vim

describe 'default increment'
  after
    " Delete all line
    execute 'normal 1GdG'
  end

  it 'can increment weekday of currently word'
    put! = 'monday'
    execute "normal \<C-a>"
    Expect getline(1) == 'tuesday'
  end

  it 'can decrement weekday of currently word'
    put! = 'sunday'
    execute "normal \<C-x>"
    Expect getline(1) == 'saturday'
  end

  it 'can increment/decrement number by the default vim behavior'
    execute 'normal I1'
    execute "normal \<C-a>"
    Expect getline(1) == '2'

    execute "normal \<C-x>"
    execute "normal \<C-x>"
    execute "normal \<C-x>"
    Expect getline(1) == '-1'
  end
end


autocmd FileType go set noexpandtab
autocmd FileType go set nolist

Use goimports as the default formatting

autocmd FileType go set noexpandtab
autocmd FileType go set nolist

let g:go_fmt_command = "goimports"


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

set relativenumber
set number

set background=dark
let g:gruvbox_bold=0
" let g:gruvbox_termcolors=256
colorscheme gruvbox

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

Change default indent to 2 spaces.

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

set relativenumber
set number

set background=dark
let g:gruvbox_bold=0
" let g:gruvbox_termcolors=256
colorscheme gruvbox

set ts=2 sw=2 et
autocmd FileType cpp setlocal ts=2 sw=2 et
autocmd FileType c setlocal ts=2 sw=2 et
autocmd FileType fortran setlocal ts=3 sw=3 et


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

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

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

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

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

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

Update Copy maps to work in more modes.

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

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

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

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

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

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


let g:airline_theme='base16_spacemacs'

Hide some pointless airline stuff

let g:airline_theme='base16_spacemacs'
let g:airline_detect_spell=1
let g:airline#parts#ffenc#skip_expected_string='utf-8[unix]'


let b:ale_fixers = ['remove_trailing_lines', 'rubocop', 'trim_whitespace']

Format Ruby files with prettier

let b:ale_fixers = ['remove_trailing_lines', 'rubocop', 'trim_whitespace']

augroup Prettier
  autocmd!
  if get(g:, 'prettier#autoformat')
    autocmd BufWritePre *.ruby call prettier#Autoformat()
  endif
augroup end


" 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

Add json highlighting for 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'
Bundle 'elzr/vim-json'

" 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


autocmd BufWritePre <buffer> :call StripTrailingWhitespaces()
set foldmethod=syntax
set noballooneval

Check availability of noballooneval option before using it

autocmd BufWritePre <buffer> :call StripTrailingWhitespaces()
set foldmethod=syntax

if exists('+noballooneval')
  set noballooneval
endif


set nocompatible

let g:CommandTMaxHeight=20

source ~/.vim/bundles.vim

syntax on
filetype plugin indent on

" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78

" 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

if exists('g:loaded_fugitive') || &cp
  set statusline=%{fugitive#statusline()}\ %<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
else
  set statusline=restart\ vim!\ %<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
endif

Solve fugitive loading problems. Thanks, @mbadran!

set nocompatible

let g:CommandTMaxHeight=20

source ~/.vim/bundles.vim

syntax on
filetype plugin indent on

" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78

" 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

function! GitStatusLine()
  if exists('g:loaded_fugitive')
    return fugitive#statusline()
  endif
  return "(fugitive not loaded)"
endfunction

set statusline=%{GitStatusLine()}\ %<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P


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

Set bundle to update itself.

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

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


let g:neomake_ruby_enabled_makers = ['mri', 'rubocop']

augroup rubycomplete
  if !exists('ruby_completion_loaded')
    let g:ruby_completion_loaded = 1
    autocmd! FileType ruby,eruby setl ofu=rubycomplete#Complete
  endif
augroup END

Format Ruby files on save

let g:neomake_ruby_enabled_makers = ['mri', 'rubocop']

augroup rubycomplete
  if !exists('ruby_completion_loaded')
    let g:ruby_completion_loaded = 1
    autocmd! FileType ruby,eruby setl ofu=rubycomplete#Complete
  endif
augroup END

augroup fmt
  autocmd!
  autocmd BufWritePre *.rb Neoformat
augroup END


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

hi clear

if exists("syntax_on")
    syntax reset
endif

let colors_name = "dusk"

hi Comment          ctermfg=8
hi Normal           ctermfg=none        ctermbg=none
hi NonText          ctermfg=none        ctermbg=none
hi LineNr           ctermfg=8
hi CursorLineNr     ctermfg=8
hi String           ctermfg=3
hi Keyword          ctermfg=2
hi Statement        ctermfg=2
hi Function         ctermfg=4
hi PreProc          ctermfg=5
hi Constant         ctermfg=6
hi Character        ctermfg=6
hi Number           ctermfg=6
hi Visual                               ctermbg=235
hi Search                               ctermbg=237
hi MatchParen                           ctermbg=none        cterm=underline
hi StatusLine       ctermfg=244         ctermbg=0

Update vim visual mode highlight color

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

hi clear

if exists("syntax_on")
    syntax reset
endif

let colors_name = "dusk"

hi Comment          ctermfg=8
hi Normal           ctermfg=none        ctermbg=none
hi NonText          ctermfg=none        ctermbg=none
hi LineNr           ctermfg=8
hi CursorLineNr     ctermfg=8
hi String           ctermfg=3
hi Keyword          ctermfg=2
hi Statement        ctermfg=2
hi Function         ctermfg=4
hi PreProc          ctermfg=5
hi Constant         ctermfg=6
hi Character        ctermfg=6
hi Number           ctermfg=6
hi Visual                               ctermbg=237
hi Search                               ctermbg=237
hi MatchParen                           ctermbg=none        cterm=underline
hi StatusLine       ctermfg=244         ctermbg=0


nnoremap <buffer> <silent> P :Pick<CR>
nnoremap <buffer> <silent> S :Squash<CR>
nnoremap <buffer> <silent> E :Edit<CR>
nnoremap <buffer> <silent> R :Reword<CR>
nnoremap <buffer> <silent> F :Fixump<CR>

Fix spelling of :Fixup command

nnoremap <buffer> <silent> P :Pick<CR>
nnoremap <buffer> <silent> S :Squash<CR>
nnoremap <buffer> <silent> E :Edit<CR>
nnoremap <buffer> <silent> R :Reword<CR>
nnoremap <buffer> <silent> F :Fixup<CR>


" Vim syntax file
" Language: Mario rules
" Maintainer: Damir Jelić
" Latest Revision: 26 March 2015

if exists("b:current_syntax")
  finish
endif

" Keywords
syn region marioRuleName start="^\s*\[" end="\]"
syn keyword marioMatchObjects kind data arg nextgroup=marioMatchVerbs
syn keyword marioKinds raw url
syn keyword marioMatchVerbs is istype matches rewrite
syn keyword marioActionObjects plumb nextgroup=marioActionVerbs
syn keyword marioActionVerbs download run
syn region marioVariable start="{" end="}"

syn match marioComment "#.*$"

hi def link marioComment       Comment
hi def link marioRuleName      Title
hi def link marioVariable      Type

hi def link marioMatchObjects  Keyword
hi def link marioMatchVerbs    Function

hi def link marioActionObjects Keyword
hi def link marioActionVerbs   Function

let b:current_syntax = "plumb"

Set comment options in vim syntax file.

" Vim syntax file
" Language: Mario rules
" Maintainer: Damir Jelić
" Latest Revision: 26 March 2015

if exists("b:current_syntax")
  finish
endif

" Keywords
syn region marioRuleName start="^\s*\[" end="\]"
syn keyword marioMatchObjects kind data arg nextgroup=marioMatchVerbs
syn keyword marioKinds raw url
syn keyword marioMatchVerbs is istype matches rewrite
syn keyword marioActionObjects plumb nextgroup=marioActionVerbs
syn keyword marioActionVerbs download run
syn region marioVariable start="{" end="}"

syn match marioComment "#.*$"

hi def link marioComment       Comment
hi def link marioRuleName      Title
hi def link marioVariable      Type

hi def link marioMatchObjects  Keyword
hi def link marioMatchVerbs    Function

hi def link marioActionObjects Keyword
hi def link marioActionVerbs   Function

set commentstring=#%s
set comments=b:#

let b:current_syntax = "plumb"


" Vim syntax file for tetra code
" place (or symlink) in .vim/syntax/
" also place 'au BufRead,BufNewFile *.ttr set filetype=tetra' in vimrc
" this is very basic for now

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

" keywords
syn keyword tetraKeyword if elif else for in parallel while continue break def
syn keyword tetraKeyword or and not pass return background lock constant global
syn keyword tetraKeyword declare open import
syn keyword tetraType int real string bool mutex task none

" comments and TODOs
syn keyword tetraTodo contained TODO FIXME
syn match tetraComment "#.*$" contains=tetraTodo
syn match tetraError '\t'

" values
syn keyword tetraValue true false
syn match tetraValue '\d\+'
syn match tetraValue '[-+]\d\+'
syn match tetraValue '\d\+\.\d*'
syn match tetraValue '[-+]\d\+\.\d*'
syn region tetraValue start='"' end='"' skip='\\"'

" hook it up
hi def link tetraKeyword Keyword
hi def link tetraType Type
hi def link tetraValue Constant
hi def link tetraComment Comment
hi def link tetraTodo Todo
hi def link tetraError Error

let b:current_syntax = "tetra"

Add more keywords to .vim.

" Vim syntax file for tetra code
" place (or symlink) in .vim/syntax/
" also place 'au BufRead,BufNewFile *.ttr set filetype=tetra' in vimrc
" this is very basic for now

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

" keywords
syn keyword tetraKeyword if elif else for in parallel while continue break def
syn keyword tetraKeyword or and not pass return background lock constant global
syn keyword tetraKeyword declare open import lambda wait self class
syn keyword tetraKeyword init
syn keyword tetraType int real string bool mutex task none

" comments and TODOs
syn keyword tetraTodo contained TODO FIXME
syn match tetraComment "#.*$" contains=tetraTodo
syn match tetraError '\t'

" values
syn keyword tetraValue true false
syn match tetraValue '\d\+'
syn match tetraValue '[-+]\d\+'
syn match tetraValue '\d\+\.\d*'
syn match tetraValue '[-+]\d\+\.\d*'
syn region tetraValue start='"' end='"' skip='\\"'

" hook it up
hi def link tetraKeyword Keyword
hi def link tetraType Type
hi def link tetraValue Constant
hi def link tetraComment Comment
hi def link tetraTodo Todo
hi def link tetraError Error

let b:current_syntax = "tetra"


" backups and swap config
" Author: Viacheslav Lotsmanov
" License: MIT https://raw.githubusercontent.com/unclechu/neovimrc/master/LICENSE

set backup
set undofile

let s:my_backup_dir = $HOME . '/.vim_backup'
if !isdirectory(s:my_backup_dir) | call mkdir(s:my_backup_dir) | endif
let &backupdir = s:my_backup_dir . ',.,/tmp'

let s:my_swap_dir = $HOME . '/.vim_swap'
if !isdirectory(s:my_swap_dir) | call mkdir(s:my_swap_dir) | endif
let &directory = s:my_swap_dir . ',.,/tmp'

let s:my_undo_dir = $HOME . '/.vim_undo'
if !isdirectory(s:my_undo_dir) | call mkdir(s:my_undo_dir) | endif
let &undodir = s:my_undo_dir . ',.,/tmp'

" vim: set noet :

Use “//” for swap dir in order to expand full paths

" backups and swap config
" Author: Viacheslav Lotsmanov
" License: MIT https://raw.githubusercontent.com/unclechu/neovimrc/master/LICENSE

set backup
set undofile

let s:my_backup_dir = $HOME . '/.vim_backup//'
if !isdirectory(s:my_backup_dir) | call mkdir(s:my_backup_dir) | endif
let &backupdir = s:my_backup_dir . ',.//,/tmp//'

let s:my_swap_dir = $HOME . '/.vim_swap//'
if !isdirectory(s:my_swap_dir) | call mkdir(s:my_swap_dir) | endif
let &directory = s:my_swap_dir . ',.//,/tmp//'

let s:my_undo_dir = $HOME . '/.vim_undo//'
if !isdirectory(s:my_undo_dir) | call mkdir(s:my_undo_dir) | endif
let &undodir = s:my_undo_dir . ',.//,/tmp//'

" vim: set noet :


" JavaScript
autocmd FileType javascript.jsx set shiftwidth=4

" TypeScript
autocmd FileType typescript set shiftwidth=4

" JSON
autocmd FileType json set shiftwidth=4

Use four spaces for indentation in TSX files

" JavaScript
autocmd FileType javascript.jsx set shiftwidth=4

" TypeScript
autocmd FileType typescript set shiftwidth=4
autocmd FileType typescript.tsx set shiftwidth=4

" JSON
autocmd FileType json set shiftwidth=4


setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

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

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

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

Allow multiple writable search windows

setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

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

autocmd BufWriteCmd <buffer> call writable_search#Update()

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


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

let PivoBufferName = "__Pivotal__"

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

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

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

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

Add project ID and API token set to false

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

let PivoBufferName = "__Pivotal__"
let PivoProjectId  = 0
let PivoApiToken   = 0

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

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

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

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


filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" Plugins {{{
Plugin 'gmarik/Vundle.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'kien/ctrlp.vim'
Plugin 'mattn/emmet-vim'
Plugin 'tpope/vim-surround'
Plugin 'Raimondi/delimitMate'
Plugin 'airblade/vim-gitgutter'
Plugin 'christoomey/vim-tmux-navigator'
Plugin 'godlygeek/csapprox'
" }}}
" Syntax {{{
Plugin 'cakebaker/scss-syntax.vim'
Plugin 'jelera/vim-javascript-syntax'
Plugin 'zaiste/tmux.vim'
Plugin 'StanAngeloff/php.vim'
" }}}
" Colorschemes {{{
Plugin 'wombat256.vim'
Plugin 'summerfruit256.vim'
" }}}

call vundle#end()

Add vim-javascript for additional js support

filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" Plugins {{{
Plugin 'gmarik/Vundle.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'kien/ctrlp.vim'
Plugin 'mattn/emmet-vim'
Plugin 'tpope/vim-surround'
Plugin 'Raimondi/delimitMate'
Plugin 'airblade/vim-gitgutter'
Plugin 'christoomey/vim-tmux-navigator'
Plugin 'godlygeek/csapprox'
" }}}
" Syntax {{{
Plugin 'cakebaker/scss-syntax.vim'
Plugin 'jelera/vim-javascript-syntax'
Plugin 'pangloss/vim-javascript'
Plugin 'zaiste/tmux.vim'
Plugin 'StanAngeloff/php.vim'
" }}}
" Colorschemes {{{
Plugin 'wombat256.vim'
Plugin 'summerfruit256.vim'
" }}}

call vundle#end()


echo "Starting CMake.nvim"
let g:neomake_cmpcmddb_maker = { 'exe': CMakeCompDB, 'args': [''] }
noremap <unique> <Plug>NeomakeCompDB :Neomake! cmpcmddb<CR>
function DoItVimL()
    echo "hello from DoItVimL"
endfunction

Fix 'exe' argument in neomake maker.

echo "Starting CMake.nvim"
let g:neomake_cmpcmddb_maker = {
    \ 'exe': 'CMakeCompDB',
    \ 'args': ['']
    \ }
noremap <unique> <Plug>NeomakeCompDB :Neomake! cmpcmddb<CR>
function DoItVimL()
    echo "hello from DoItVimL"
endfunction


" Reload
map <silent> <Leader>r :source ~/.config/nvim/init.vim<CR>:echo "NVIM Reloaded"<CR>

" Keybindings
nnoremap <silent> <F2> :bp<CR>
nnoremap <silent> <F3> :bn<CR>
nnoremap <silent> <leader>ws :split<CR>
nnoremap <silent> <leader>wv :vsplit<CR>
nnoremap <silent> <leader>wS :split<CR><C-W>w
nnoremap <silent> <leader>wV :vsplit<CR><C-W>w
nnoremap <silent> <leader>wd <C-W>q
nnoremap <silent> <leader>w <C-W>

nnoremap <silent> <C-P> :Files<CR>
nnoremap <silent> <leader>e :Files <C-R>=expand('%:h')<CR><CR>
nnoremap <silent> <leader>b :Buffers<CR>
nnoremap <silent> <leader>s :Rg<CR>
nnoremap <silent> <leader>l :BLines<CR>
" nnoremap <silent> <leader>e :Explore<CR>

nnoremap <silent> <leader><tab> :b#<CR>

nnoremap <silent> <leader>gd <Plug>(coc-definition)
nnoremap <silent> <leader>gr <Plug>(coc-references)
nnoremap <silent> <leader>gi <Plug>(coc-implementation)

Add :GFiles shortcut to nvim config

" Reload
map <silent> <Leader>r :source ~/.config/nvim/init.vim<CR>:echo "NVIM Reloaded"<CR>

" Keybindings
nnoremap <silent> <F2> :bp<CR>
nnoremap <silent> <F3> :bn<CR>
nnoremap <silent> <leader>ws :split<CR>
nnoremap <silent> <leader>wv :vsplit<CR>
nnoremap <silent> <leader>wS :split<CR><C-W>w
nnoremap <silent> <leader>wV :vsplit<CR><C-W>w
nnoremap <silent> <leader>wd <C-W>q
nnoremap <silent> <leader>w <C-W>

nnoremap <silent> <C-P> :Files<CR>
nnoremap <silent> <leader>p :GFiles<CR>
nnoremap <silent> <leader>e :Files <C-R>=expand('%:h')<CR><CR>
nnoremap <silent> <leader>b :Buffers<CR>
nnoremap <silent> <leader>s :Rg<CR>
nnoremap <silent> <leader>l :BLines<CR>
" nnoremap <silent> <leader>e :Explore<CR>

nnoremap <silent> <leader><tab> :b#<CR>

nnoremap <silent> <leader>gd <Plug>(coc-definition)
nnoremap <silent> <leader>gr <Plug>(coc-references)
nnoremap <silent> <leader>gi <Plug>(coc-implementation)


source plugin/jedi.vim

describe 'documentation docstrings'
    before
        set filetype=python
    end

    after
        bd!
        bd!
    end

    it 'simple'
        put = 'ImportError'
        normal GK
        Expect bufname('%') == "'__doc__'"
        Expect &filetype == 'rst'
        let content = join(getline(1,'$'), "\n")
        Expect stridx(content, "Import can't find module") > 0
        normal K
        Expect bufname('%') == ''
    end

    it 'no documentation'
        put = 'x = 2'
        normal o<ESC>GK
        Expect bufname('%') == ''
    end
end

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

Test if this helps fixing the online tests that are not working.

source plugin/jedi.vim

describe 'documentation docstrings'
    before
        bd!
        set filetype=python
    end

    after
        bd!
        bd!
    end

    it 'simple'
        put = 'ImportError'
        normal GK
        Expect bufname('%') == "'__doc__'"
        Expect &filetype == 'rst'
        let content = join(getline(1,'$'), "\n")
        Expect stridx(content, "Import can't find module") > 0
        normal K
        Expect bufname('%') == ''
    end

    it 'no documentation'
        put = 'x = 2'
        normal o<ESC>GK
        Expect bufname('%') == ''
    end
end

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


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

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

Configure neoformat to format Rust files

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

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


if exists("g:loaded_hindent") || !executable("hindent")
    finish
endif
let g:loaded_hindent = 1

if !exists("g:hindent_style")
    let g:hindent_style = "fundamental"
endif

if has("autocmd")
  let hindent = "hindent --style " . g:hindent_style
  autocmd FileType haskell setlocal formatexpr=FormatprgLocal(hindent)
endif

Make vim code work (define the formatexpr function)

if exists("g:loaded_hindent") || !executable("hindent")
    finish
endif
let g:loaded_hindent = 1

if !exists("g:hindent_style")
    let g:hindent_style = "fundamental"
endif

function! FormatHaskell()
    if !empty(v:char)
        return 1
    else
        let l:filter = "hindent --style " . g:hindent_style
        let l:command = v:lnum.','.(v:lnum+v:count-1).'!'.l:filter
        execute l:command
    endif
endfunction

if has("autocmd")
  autocmd FileType haskell setlocal formatexpr=FormatHaskell()
endif


if !exists('g:maccopy')
    let g:maccopy = 1
    command -range=% Copy call g:MacCopy(<count>)
endif

function! s:CopyThruExFile(lines)
    " open exeternal file may failed
    let tempfile = tempname()
    call writefile(a:lines, tempfile)
    call system('pbcopy < '.tempfile)
    call system('rm '.tempfile)
endfunc

func! g:MacCopy(number)
    if a:number == -1
        call system('pbcopy < '.expand('%'))
    else
        "y
        "echoerr getpos("'<")[1]
        "x
        "echoerr getpos("'<")[2]
        "join(getline("'<", "'>"), "\n")
        let sx = getpos("'<")[2]
        let sy = getpos("'<")[1]
        let dx = getpos("'>")[2]
        let dy = getpos("'>")[1]
        if dy < sy
            let tmp = sx
            let sx = dx
            let dx = tmp
            let tmp = sy
            let sy = dy
            let dy = tmp
        endif

        if sy == dy
            if sx > dx
                let tmp = sx
                let sx = dx
                let dx = tmp
            endif
            let output = [getline(sy)[sx-1:dx-1]]
        else
            let output = [getline(sy)[sx-1:]]
            for i in range(sy+1, dy-1)
                let output = add(output, getline(i))
            endfor
            let output = add(output, getline(sy)[:dx-1])
        endif
        call s:CopyThruExFile(output)
    endif
endfunc

Delete tempfile with build-in func

if !exists('g:maccopy')
    let g:maccopy = 1
    command -range=% Copy call g:MacCopy(<count>)
endif

function! s:CopyThruExFile(lines)
    " open exeternal file may failed
    let tempfile = tempname()
    call writefile(a:lines, tempfile)
    call system('pbcopy < '.tempfile)
    call delete(tempfile)
endfunc

func! g:MacCopy(number)
    if a:number == -1
        call system('pbcopy < '.expand('%'))
    else
        "y
        "echoerr getpos("'<")[1]
        "x
        "echoerr getpos("'<")[2]
        "join(getline("'<", "'>"), "\n")
        let sx = getpos("'<")[2]
        let sy = getpos("'<")[1]
        let dx = getpos("'>")[2]
        let dy = getpos("'>")[1]
        if dy < sy
            let tmp = sx
            let sx = dx
            let dx = tmp
            let tmp = sy
            let sy = dy
            let dy = tmp
        endif

        if sy == dy
            if sx > dx
                let tmp = sx
                let sx = dx
                let dx = tmp
            endif
            let output = [getline(sy)[sx-1:dx-1]]
        else
            let output = [getline(sy)[sx-1:]]
            for i in range(sy+1, dy-1)
                let output = add(output, getline(i))
            endfor
            let output = add(output, getline(sy)[:dx-1])
        endif
        call s:CopyThruExFile(output)
    endif
endfunc


" set key code delay to 10ms
" only wait a very short time for terminal key codes
" these aren't used by modern terminals
" This prevents delays when pressing ESC
set ttimeoutlen=10

" change leader key from \ to space
let mapleader=' '

" map space-e to open the file explorer
map <leader>e :Explore<cr>
map <leader><S-E> :Rexplore<cr>

" map space-j and space-k to next and previous buffers
map <leader>j :bnext<cr>
map <leader>k :bprevious<cr>

" Map unmapped easymotion commands
map <Plug>(easymotion-prefix)l <Plug>(easymotion-lineforward)
map <Plug>(easymotion-prefix)h <Plug>(easymotion-linebackward)
map <Plug>(easymotion-prefix)/ <Plug>(easymotion-sn)
omap <Plug>(easymotion-prefix)/ <Plug>(easymotion-tn)

Fix backspace behavior in vim for mac

" set key code delay to 10ms
" only wait a very short time for terminal key codes
" these aren't used by modern terminals
" This prevents delays when pressing ESC
set ttimeoutlen=10

" change leader key from \ to space
let mapleader=' '

" change backspace behavior to be more like a typical editor
set backspace=indent,eol,start

" map space-e to open the file explorer
map <leader>e :Explore<cr>
map <leader><S-E> :Rexplore<cr>

" map space-j and space-k to next and previous buffers
map <leader>j :bnext<cr>
map <leader>k :bprevious<cr>

" Map unmapped easymotion commands
map <Plug>(easymotion-prefix)l <Plug>(easymotion-lineforward)
map <Plug>(easymotion-prefix)h <Plug>(easymotion-linebackward)
map <Plug>(easymotion-prefix)/ <Plug>(easymotion-sn)
omap <Plug>(easymotion-prefix)/ <Plug>(easymotion-tn)


let s:lib_path = getcwd() . "/../../lib/"
let s:bin_path = getcwd() . "/../../bin/neovim-ruby-host"
let g:ruby_host_prog = printf("ruby -I %s %s", s:lib_path, s:bin_path)

set rtp=./runtime,./runtime/vader.vim,$VIMRUNTIME

ruby << EOS
require "rspec"

if ENV["REPORT_COVERAGE"]
  require "coveralls"
  Coveralls.wear_merged!
  SimpleCov.merge_timeout 3600
  SimpleCov.command_name "spec:acceptance:#{Process.pid}"
end
EOS

function! RunSuite() abort
  ruby $output = ENV["RSPEC_OUTPUT_FILE"]
  ruby $result = RSpec::Core::Runner.run([], $output, $output)
  ruby Vim.command($result == 0 ? "qa!" : "cq!")
endfunction

Move neovim require after coveralls loading in acceptance specs

let s:lib_path = getcwd() . "/../../lib/"
let s:bin_path = getcwd() . "/../../bin/neovim-ruby-host"
let g:ruby_host_prog = printf("ruby -I %s %s", s:lib_path, s:bin_path)

set rtp=./runtime,./runtime/vader.vim,$VIMRUNTIME

ruby << EOS
require "rspec"

if ENV["REPORT_COVERAGE"]
  require "coveralls"
  Coveralls.wear_merged!
  SimpleCov.merge_timeout 3600
  SimpleCov.command_name "spec:acceptance:#{Process.pid}"
end

$:.unshift File.expand_path("../../../lib", __FILE__)
require "neovim"
EOS

function! RunSuite() abort
  ruby $output = ENV["RSPEC_OUTPUT_FILE"]
  ruby $result = RSpec::Core::Runner.run([], $output, $output)
  ruby Vim.command($result == 0 ? "qa!" : "cq!")
endfunction


" key mappings for Git Fugitive plugin
"
" some mappings 'g' mappings are used by Vim and should not be remapped:
"
"  gq<text obj>      format text
"  gg                go to top
"  g]                ctag jump

noremap <C-g>  :call ToggleGStatus()<cr>
noremap gww    :Gwrite<cr>
noremap gbl    :Gblame<cr>
noremap gcm    :Gcommit<cr>
noremap gd     :Gdiff<cr>
noremap gmv    :Gmove<space>
noremap grm    :Gremove<cr>
noremap grr    :Gread<cr>

" diff options (use dp and do builtins)
set diffopt=filler,vertical

" helper to detect a fugitive diff buffer
function! FugitiveDiffInFocus()
   return matchstr(expand("%"), 'fugitive:///') == 'fugitive:///'
endfunction

" helper to detect a fugitive diff buffer
function! FugitiveStatusInFocus()
   return matchstr(expand("%"), '.git/index') == '.git/index'
endfunction

" toggle the GStatus window (https://gist.github.com/actionshrimp/6493611)
function! ToggleGStatus()
   if buflisted(bufname('.git/index'))
      bd .git/index
   else
      Gstatus
   endif
endfunction

Set 'git commit' vim mapping to 'gcc'

" key mappings for Git Fugitive plugin
"
" some mappings 'g' mappings are used by Vim and should not be remapped:
"
"  gq<text obj>      format text
"  gg                go to top
"  g]                ctag jump

noremap <C-g>  :call ToggleGStatus()<cr>
noremap gww    :Gwrite<cr>
noremap gbl    :Gblame<cr>
noremap gcc    :Gcommit<cr>
noremap gd     :Gdiff<cr>
noremap gmv    :Gmove<space>
noremap grm    :Gremove<cr>
noremap grr    :Gread<cr>

" diff options (use dp and do builtins)
set diffopt=filler,vertical

" helper to detect a fugitive diff buffer
function! FugitiveDiffInFocus()
   return matchstr(expand("%"), 'fugitive:///') == 'fugitive:///'
endfunction

" helper to detect a fugitive diff buffer
function! FugitiveStatusInFocus()
   return matchstr(expand("%"), '.git/index') == '.git/index'
endfunction

" toggle the GStatus window (https://gist.github.com/actionshrimp/6493611)
function! ToggleGStatus()
   if buflisted(bufname('.git/index'))
      bd .git/index
   else
      Gstatus
   endif
endfunction


" Backspace is managed by vim-sensible, but I need it here too because some
" plugins depend on it during start up.
set backspace=indent,eol,start

" Enable invisible characters.
set list

" More natural splitting.
set splitbelow
set splitright

" Enable mouse. Great for resizing windows and keeping co-workers sane.
set mouse=a

" Disable swap files.
set noswapfile

" Write files as they are, don't mess with line endings etc.
set binary

" Disable the completion preview window.
set completeopt-=preview

" Make session files minimal.
set sessionoptions=blank,curdir,folds,help,tabpages,winsize

Revert "My default indent was breaking vim-sleuth"

" Backspace is managed by vim-sensible, but I need it here too because some
" plugins depend on it during start up.
set backspace=indent,eol,start

" Enable invisible characters.
set list

" More natural splitting.
set splitbelow
set splitright

" Set a default indent, but vim-sleuth should adjust it.
set tabstop=4
set shiftwidth=4
set expandtab

" Enable mouse. Great for resizing windows and keeping co-workers sane.
set mouse=a

" Disable swap files.
set noswapfile

" Write files as they are, don't mess with line endings etc.
set binary

" Disable the completion preview window.
set completeopt-=preview

" Make session files minimal.
set sessionoptions=blank,curdir,folds,help,tabpages,winsize


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

" highlight ruby whitespace errors
let ruby_space_errors = 1

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

" Activate Ruby.vim's tooltips for Ruby keywords
setlocal ballooneval

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

Add options for better Ruby omnicompletion

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

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

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

" Activate Ruby.vim's tooltips for Ruby keywords
setlocal ballooneval

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


" ------------------------------------------------------------------------------
" NERDTree and related config
" ------------------------------------------------------------------------------
" Enable line numbers
let g:NERDTreeShowLineNumbers = 1
" Make sure relative line numbers are used.
autocmd FileType nerdtree setlocal relativenumber
" Make sure relative numbers re-appear when switching back to NERDTree
" from other windows.
autocmd BufEnter NERD_* setlocal rnu
" Display hidden files by default
let NERDTreeShowHidden=1

Add case-sensitive file name sorting in NERDTree

" ------------------------------------------------------------------------------
" NERDTree and related config
" ------------------------------------------------------------------------------
" Make sure relative line numbers are used.
autocmd FileType nerdtree setlocal relativenumber
" Make sure relative numbers re-appear when switching back to NERDTree
" from other windows.
autocmd BufEnter NERD_* setlocal rnu
" Enable line numbers
let g:NERDTreeShowLineNumbers = 1
" Display hidden files by default
let NERDTreeShowHidden = 1
" Case-sensitive sorting of filenames
let NERDTreeCaseSensitiveSort = 1


" load plugins
call plug#begin()

" colorscheme
Plug 'morhetz/gruvbox'

" sensible defaults
Plug 'pbrisbin/vim-mkdir'
Plug 'tpope/vim-repeat'
Plug 'vim-scripts/replacewithregister'
Plug 'vim-scripts/visualrepeat'
Plug 'wincent/terminus'

" cosmetic enhancements
Plug 'junegunn/goyo.vim' " distraction-free mode

" language support
Plug 'baskerville/vim-sxhkdrc'
Plug 'cespare/vim-toml'
Plug 'lervag/vimtex'
Plug 'wlangstroth/vim-racket'

" new features
Plug 'junegunn/fzf.vim'
Plug 'mhinz/vim-signify'
Plug 'tpope/vim-abolish'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-surround'
Plug 'junegunn/vim-easy-align'

call plug#end()

" override vim-sensible settings by default
runtime! plugin/sensible.vim

Add back in vim-local fzf installation

" load plugins
call plug#begin()

" colorscheme
Plug 'morhetz/gruvbox'

" sensible defaults
Plug 'pbrisbin/vim-mkdir'
Plug 'tpope/vim-repeat'
Plug 'vim-scripts/replacewithregister'
Plug 'vim-scripts/visualrepeat'
Plug 'wincent/terminus'

" cosmetic enhancements
Plug 'junegunn/goyo.vim' " distraction-free mode

" language support
Plug 'baskerville/vim-sxhkdrc'
Plug 'cespare/vim-toml'
Plug 'lervag/vimtex'
Plug 'wlangstroth/vim-racket'

" new features
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'mhinz/vim-signify'
Plug 'tpope/vim-abolish'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-surround'
Plug 'junegunn/vim-easy-align'

call plug#end()

" override vim-sensible settings by default
runtime! plugin/sensible.vim


augroup set_filetype_group
  autocmd!
  autocmd BufNewFile,BufRead Guardfile set filetype=ruby
  autocmd BufNewFile,BufRead *.md set filetype=markdown
  autocmd BufNewFile,BufRead *.pde set filetype=processing
  autocmd BufRead,BufNewFile *.scss set filetype=scss.css
augroup END

Use correct filetype for Vagrantfile and .jshintrc

augroup set_filetype_group
  autocmd!
  autocmd BufNewFile,BufRead Guardfile set filetype=ruby
  autocmd BufNewFile,BufRead Vagrantfile set filetype=ruby
  autocmd BufNewFile,BufRead .jshintrc set filetype=javascript
  autocmd BufNewFile,BufRead *.md set filetype=markdown
  autocmd BufNewFile,BufRead *.pde set filetype=processing
  autocmd BufRead,BufNewFile *.scss set filetype=scss.css
augroup END


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

" Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
Plug 'junegunn/vim-easy-align'

" On-demand loading
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }

" Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
Plug 'fatih/vim-go', { 'tag': '*' }

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

Add jedi-vim and some settings

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

" Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
Plug 'junegunn/vim-easy-align'

" On-demand loading
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }

" Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
Plug 'fatih/vim-go', { 'tag': '*' }

" Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }

" vim-jedi
" https://github.com/davidhalter/jedi-vim
Plug 'davidhalter/jedi-vim'

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

"
set background=dark
set t_Co=256 " make sure our terminal use 256 color
let g:solarized_termcolors = 256

" colorscheme solarized


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

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

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

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

Make ALE show additional details with gk

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

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

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

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


" My filetypes
if exists("did_load_filetypes")
   finish
endif

augroup filetypedetect
   autocmd BufNewFile,BufRead *.shlib set filetype=sh
   autocmd BufNewFile,BufRead *.json set filetype=json
   autocmd BufNewFile,BufRead Jamfile,Jamroot,*.jam set filetype=jam
   autocmd BufNewFile,BufRead *.bb,*.inc,*.conf set filetype=bitbake
   autocmd BufNewFile,BufRead *.ino set filetype=c
   autocmd BufNewFile,BufRead *.tpp set filetype=cpp
   autocmd BufNewFile,BufRead CMakeLists.txt set filetype=cmake
augroup END

Set position to 0,0 for git commits

" My filetypes
if exists("did_load_filetypes")
   finish
endif

augroup filetypedetect
   autocmd BufNewFile,BufRead *.shlib set filetype=sh
   autocmd BufNewFile,BufRead *.json set filetype=json
   autocmd BufNewFile,BufRead Jamfile,Jamroot,*.jam set filetype=jam
   autocmd BufNewFile,BufRead *.bb,*.inc,*.conf set filetype=bitbake
   autocmd BufNewFile,BufRead *.ino set filetype=c
   autocmd BufNewFile,BufRead *.tpp set filetype=cpp
   autocmd BufNewFile,BufRead CMakeLists.txt set filetype=cmake
   autocmd BufEnter COMMIT_EDITMSG set filetype=gitcommit
   autocmd BufEnter git-rebase-todo call setpos('.', [0, 1, 1, 0])
augroup END


autocmd FileType c,cpp,css,java,javascript,perl,php,jade,matlab nmap <silent> <Leader>; <Plug>(cosco-commaOrSemiColon)
autocmd FileType c,cpp,css,java,javascript,perl,php,jade,matlab imap <silent> <Leader>; <c-o><Plug>(cosco-commaOrSemiColon)

Add cosco ignore comments option

autocmd FileType c,cpp,css,java,javascript,perl,php,jade,matlab nmap <silent> <Leader>; <Plug>(cosco-commaOrSemiColon)
autocmd FileType c,cpp,css,java,javascript,perl,php,jade,matlab imap <silent> <Leader>; <c-o><Plug>(cosco-commaOrSemiColon)

let g:cosco_ignore_comment_lines = 1


" GOLANG

let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_structs = 1

au FileType go nmap <Leader>ti <Plug>(go-implements)
au FileType go nmap <Leader>i <Plug>(go-info)

au FileType go nmap <Leader>gd <Plug>(go-doc)
au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)

au FileType go nmap <leader>r <Plug>(go-run)
au FileType go nmap <leader>b <Plug>(go-build)
au FileType go nmap <leader>t <Plug>(go-test)
au FileType go nmap <leader>c <Plug>(go-coverage)

function GoToggleAlternate()
  let path = expand('%:r')
  if path =~ ".*_test$"
    " From *_test.go to *.go
    let impl_path = fnamemodify(path, ":s?_test?.go?")
    if filereadable(impl_path)
      execute "e " . impl_path
    endif
  else
    " From *.go to *_test.go
    let test_path = path . "_test.go"
    if filereadable(test_path)
      execute "e " . test_path
    endif
  endif
endfunction

au FileType go nnoremap <leader>a :call GoToggleAlternate()<CR>

Use gd-like GOPATH in vim

" GOLANG

let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_structs = 1

au FileType go nmap <Leader>ti <Plug>(go-implements)
au FileType go nmap <Leader>i <Plug>(go-info)

au FileType go nmap <Leader>gd <Plug>(go-doc)
au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)

au FileType go nmap <leader>r <Plug>(go-run)
au FileType go nmap <leader>b <Plug>(go-build)
au FileType go nmap <leader>t <Plug>(go-test)
au FileType go nmap <leader>c <Plug>(go-coverage)

function GoToggleAlternate()
  let path = expand('%:r')
  if path =~ ".*_test$"
    " From *_test.go to *.go
    let impl_path = fnamemodify(path, ":s?_test?.go?")
    if filereadable(impl_path)
      execute "e " . impl_path
    endif
  else
    " From *.go to *_test.go
    let test_path = path . "_test.go"
    if filereadable(test_path)
      execute "e " . test_path
    endif
  endif
endfunction

au FileType go nnoremap <leader>a :call GoToggleAlternate()<CR>

let $GOPATH = $HOME . "/Projects/go:" . fnamemodify('.', ':p') . ':' . fnamemodify('./vendor', ':p')


filetype off

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

" ESLint
Plug 'scrooloose/syntastic'

" Languages
Plug 'elmcast/elm-vim'
Plug 'ingydotnet/yaml-vim'
Plug 'mitsuhiko/vim-json'
Plug 'mxw/vim-jsx'
Plug 'pangloss/vim-javascript'

" Themes
Plug 'lifepillar/vim-wwdc16-theme'
Plug 'mhartington/oceanic-next'
Plug 'w0ng/vim-hybrid'

" Toolbelt
Plug 'adonis0147/prettyGuides'
Plug 'bling/vim-airline'
Plug 'chrisbra/vim-show-whitespace'
Plug 'christoomey/vim-system-copy'
Plug 'editorconfig/editorconfig-vim'
Plug 'luochen1990/rainbow'
Plug 'raimondi/delimitmate'
Plug 'scrooloose/nerdtree'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-sensible'
Plug 'umutcoskun/vim-whitespaces'
Plug 'vim-airline/vim-airline-themes'

call plug#end()

filetype plugin indent on

Add commentary plugin to vim

filetype off

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

" ESLint
Plug 'scrooloose/syntastic'

" Languages
Plug 'elmcast/elm-vim'
Plug 'ingydotnet/yaml-vim'
Plug 'mitsuhiko/vim-json'
Plug 'mxw/vim-jsx'
Plug 'pangloss/vim-javascript'

" Themes
Plug 'lifepillar/vim-wwdc16-theme'
Plug 'mhartington/oceanic-next'
Plug 'w0ng/vim-hybrid'

" Toolbelt
Plug 'adonis0147/prettyGuides'
Plug 'bling/vim-airline'
Plug 'chrisbra/vim-show-whitespace'
Plug 'christoomey/vim-system-copy'
Plug 'editorconfig/editorconfig-vim'
Plug 'luochen1990/rainbow'
Plug 'raimondi/delimitmate'
Plug 'scrooloose/nerdtree'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-sensible'
Plug 'umutcoskun/vim-whitespaces'
Plug 'vim-airline/vim-airline-themes'

call plug#end()

filetype plugin indent on


nnoremap <Leader>ga :Gwrite<CR>
nnoremap <Leader>gb :Git blame<CR>
nnoremap <Leader>gc :vert :Git commit -v<CR>
nnoremap <Leader>gd :Gvdiffsplit<CR>
nnoremap <Leader>gp :Git push<CR>
nnoremap <Leader>gs :Git<CR>

nnoremap <Leader>gh :Gbrowse<CR>
xnoremap <Leader>gh :Gbrowse<CR>

Add leader mapping for quick commits to wiki

nnoremap <Leader>ga :Gwrite<CR>
nnoremap <Leader>gb :Git blame<CR>
nnoremap <Leader>gc :vert :Git commit -v<CR>
nnoremap <Leader>gd :Gvdiffsplit<CR>
nnoremap <Leader>gp :Git push<CR>
nnoremap <Leader>gs :Git<CR>

nnoremap <Leader>gh :Gbrowse<CR>
xnoremap <Leader>gh :Gbrowse<CR>

" Quickly commit the current file in the wiki
nnoremap <Leader>gw :Gwrite<CR>:Git commit -m "Update <C-R>=strftime('%F %T')<CR>"<CR>


" plugin/ultisnips.plugin.vim

" Load custom snippets from the following directory.
" Note: Directories named `snippets` are reserved for SnipMate
let g:UltiSnipsSnippetDirectories = [ g:vim_home_dir . '/usnippets' ]

" Ignore snipmate snippets. I only want to provide my custom snippets.
let g:UltiSnipsEnableSnipMate = 0

Customize the directory for custom snippets

" plugin/ultisnips.plugin.vim

" Directory of private snippet definition files.
" Note: Directories named `snippets` are reserved for SnipMate.
let g:UltiSnipsSnippetsDir = g:vim_home_dir . '/usnippets'

" Load snippets only from the private directory.
let g:UltiSnipsSnippetDirectories = [ g:UltiSnipsSnippetsDir ]

" Ignore snipmate snippets. I only want to provide my custom snippets.
let g:UltiSnipsEnableSnipMate = 0


Plug 'vim-test/vim-test'

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

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

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

Tidy up vim test config

Plug 'vim-test/vim-test'

let test#php#phpunit#executable = 'deliver vendor/bin/phpunit'

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

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


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

if !exists("g:deoplete#sources#go#align_class")
  let g:deoplete#sources#go#align_class = 0
endif

if !exists("g:deoplete#sources#go#gocode_binary")
  let g:deoplete#sources#go#gocode_binary = ''
endif

if !exists("g:deoplete#sources#go#package_dot")
  let g:deoplete#sources#go#package_dot = 0
endif

if !exists("g:deoplete#sources#go#sort_class")
  let g:deoplete#sources#go#sort_class = []
endif

Fix set default values to use vim's 'get'

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

let g:deoplete#sources#go#align_class =
      \ get( g:, 'deoplete#sources#go#align_class', 0 )

let g:deoplete#sources#go#gocode_binary =
      \ get( g:, 'deoplete#sources#go#gocode_binary', '' )

let g:deoplete#sources#go#package_dot =
      \ get( g:, 'deoplete#sources#go#package_dot', 0 )

let g:deoplete#sources#go#sort_class =
      \ get( g:, 'deoplete#sources#go#sort_class', [] )


function! TestUriEncode() abort
  call assert_equal('foo/bar%20baz', lsc#uri#encodeFilePath('foo/bar baz'))
  call assert_equal('foo/bar%23baz', lsc#uri#encodeFilePath('foo/bar#baz'))
endfunction

function! TestUriDecode() abort
  call assert_equal('foo/bar baz', lsc#uri#decodeFilePath('foo/bar%20baz'))
  call assert_equal('foo/bar#baz', lsc#uri#decodeFilePath('foo/bar%23baz'))
endfunction

function! s:RunTest(test)
  let v:errors = []
  silent! call lsc#uri#not_a_function()

  call function(a:test)()

  if len(v:errors) > 0
    for error in v:errors
      echoerr error
    endfor
  else
    echom 'No errors in: '.a:test
  endif
endfunction!

function! s:RunTests(...)
  for test in a:000
    call s:RunTest(test)
  endfor
endfunction

call s:RunTests('TestUriEncode', 'TestUriDecode')

Fix tests for URI encoding

function! TestUriEncode() abort
  call assert_equal('file://foo/bar%20baz', lsc#uri#documentUri('foo/bar baz'))
  call assert_equal('file://foo/bar%23baz', lsc#uri#documentUri('foo/bar#baz'))
endfunction

function! TestUriDecode() abort
  call assert_equal('foo/bar baz', lsc#uri#documentPath('file://foo/bar%20baz'))
  call assert_equal('foo/bar#baz', lsc#uri#documentPath('file://foo/bar%23baz'))
endfunction

function! s:RunTest(test)
  let v:errors = []
  silent! call lsc#uri#not_a_function()

  call function(a:test)()

  if len(v:errors) > 0
    for error in v:errors
      echoerr error
    endfor
  else
    echom 'No errors in: '.a:test
  endif
endfunction!

function! s:RunTests(...)
  for test in a:000
    call s:RunTest(test)
  endfor
endfunction

call s:RunTests('TestUriEncode', 'TestUriDecode')


" Contains custom filetype declarations
"

" Flex, The Fast Lexical Analyzer
au BufNewFile,BufRead *.flex set filetype=lex

" ASP.NET ASMX
au BufNewFile,BufRead *.asmx set filetype=cs

" Markdown (auto-detected as Modula 2)
au BufNewFile,BufRead *.md set filetype=markdown

" Localfile formats
au BufNewFile,BufRead .bashlocal set filetype=sh
au BufNewFile,BufRead .vimlocal set filetype=vim

" Filetype-specific configs
"
au FileType ruby setlocal sw=2 ts=2 sts=2
au FileType yaml setlocal sw=2 ts=2 sts=2

au FileType glsl setlocal formatoptions+=roq

au FileType make setlocal noexpandtab  " Makefiles *require* tabs

au FileType markdown vnoremap <leader><Bslash> :EasyAlign*<Bar><CR>

au FileType typescript nnoremap <silent> <buffer> <leader>h :echo tsuquyomi#hint()<CR>
au FileType typescript setlocal completeopt+=menu,preview

" Non-work configs
if !filereadable(expand('~/.atwork'))
    augroup autoformat_settings
        autocmd FileType bzl AutoFormatBuffer buildifier
        autocmd FileType c,cpp,proto,javascript,typescript AutoFormatBuffer clang-format
        autocmd FileType glsl,vert,frag AutoFormatBuffer clang-format
        autocmd FileType python AutoFormatBuffer yapf
    augroup END
endif

Clean up unnecessary vim config.

" Contains custom filetype declarations
"

" Markdown (auto-detected as Modula 2)
au BufNewFile,BufRead *.md set filetype=markdown

" Localfile formats
au BufNewFile,BufRead .bashlocal set filetype=sh
au BufNewFile,BufRead .vimlocal set filetype=vim

" Filetype-specific configs
"
au FileType yaml setlocal sw=2 ts=2 sts=2

au FileType glsl setlocal formatoptions+=roq

au FileType make setlocal noexpandtab  " Makefiles *require* tabs

au FileType markdown vnoremap <leader><Bslash> :EasyAlign*<Bar><CR>

au FileType typescript nnoremap <silent> <buffer> <leader>h :echo tsuquyomi#hint()<CR>
au FileType typescript setlocal completeopt+=menu,preview

" Non-work configs
if !filereadable(expand('~/.atwork'))
    augroup autoformat_settings
        autocmd FileType bzl AutoFormatBuffer buildifier
        autocmd FileType c,cpp,proto,javascript,typescript AutoFormatBuffer clang-format
        autocmd FileType glsl,vert,frag AutoFormatBuffer clang-format
        autocmd FileType python AutoFormatBuffer yapf
    augroup END
endif


let s:save_cpo = &cpo
set cpo&vim

if exists('g:markdown_pl_loaded')
    finish
endif

let g:markdown_pl_home = fnamemodify(expand('<sfile>'), ':p:h:h:gs?\\?/?')

command! -nargs=0 MarkDownPreview call MarkDownPreview()

function! MarkDownPreview()
    let s:fileName = expand("%:p:r").'.html'
    silent exec '!'.g:markdown_pl_home.'/bin/markdown.pl % >  '.s:fileName
    call system('xdg-open file://'.s:fileName)
    call system('rm '.s:fileName)
endf

let g:markdown_pl_loaded = 1

let &cpo = s:save_cpo
unlet s:save_cpo

Change sleep time to 1s

let s:save_cpo = &cpo
set cpo&vim

if exists('g:markdown_pl_loaded')
    finish
endif

let g:markdown_pl_home = fnamemodify(expand('<sfile>'), ':p:h:h:gs?\\?/?')

command! -nargs=0 MarkDownPreview call MarkDownPreview()

function! MarkDownPreview()
    let s:fileName = expand("%:p:r").'.html'
    silent exec '!'.g:markdown_pl_home.'/bin/markdown.pl % >  '.s:fileName
    call system('xdg-open file://'.s:fileName)
    call system('sleep 1')
    call system('rm '.s:fileName)
endf

let g:markdown_pl_loaded = 1

let &cpo = s:save_cpo
unlet s:save_cpo


nnoremap <Leader>t :CtrlP<cr>

" Mimic Command-T behaviour
let g:ctrlp_working_path_mode = 0
let g:ctrlp_match_window_reversed = 0
let g:ctrlp_clear_cache_on_exit=0

if executable('ag')
  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
endif

Add most recently opened files quicksearch shortcut

nnoremap <Leader>t :CtrlP<cr>
nnoremap <Leader>r :CtrlPMRUFiles<cr>

" Mimic Command-T behaviour
let g:ctrlp_working_path_mode = 0
let g:ctrlp_match_window_reversed = 0
let g:ctrlp_clear_cache_on_exit=0

if executable('ag')
  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
endif


let b:ale_fixers = ['remove_trailing_lines', 'trim_whitespace']

Format c++ code with clang-format

let b:ale_fixers = ['clang-format']
let b:ale_c_clangformat_options = '--style="{BasedOnStyle: google}"'
setlocal expandtab
setlocal tabstop=2
setlocal shiftwidth=2


if !has('python')
    echoerr "This plugin requires python."
    finish
endif

if exists('vim_c_grayout_loaded')
    finish
else
    let g:vim_c_grayout_loaded = 1
    let g:grayout_debug = 0
    let g:grayout_debug_logfile = 0
    let g:grayout_debug_compiler_inout = 0
    let g:grayout_cmd_line = 'clang -x c++ -E -'

    highlight PreprocessorGrayout cterm=italic gui=italic ctermfg=DarkGray guifg=DarkGray
    sign define PreprocessorGrayout linehl=PreprocessorGrayout

    python import sys
endif

function! UpdateGrayout()
    if !exists("b:num_grayout_lines")
        let b:num_grayout_lines = 0
    endif

    if !exists('b:grayout_cmd_line')
        call s:LoadConfig()
    endif

    python sys.argv = ["grayout"]
    pyfile grayout.py
endfunction

function! s:LoadConfig()
    python sys.argv = ["config"]
    pyfile grayout.py
endfunction

Add function to clear grayouts from buffer

if !has('python')
    echoerr "This plugin requires python."
    finish
endif

if exists('vim_c_grayout_loaded')
    finish
else
    let g:vim_c_grayout_loaded = 1
    let g:grayout_debug = 0
    let g:grayout_debug_logfile = 0
    let g:grayout_debug_compiler_inout = 0
    let g:grayout_cmd_line = 'clang -x c++ -E -'

    highlight PreprocessorGrayout cterm=italic gui=italic ctermfg=DarkGray guifg=DarkGray
    sign define PreprocessorGrayout linehl=PreprocessorGrayout

    python import sys
endif

function! UpdateGrayout()
    if !exists("b:num_grayout_lines")
        let b:num_grayout_lines = 0
    endif

    if !exists('b:grayout_cmd_line')
        call s:LoadConfig()
    endif

    python sys.argv = ["grayout"]
    pyfile grayout.py
endfunction

function! ClearGrayout()
    python sys.argv = ["clear"]
    pyfile grayout.py
endfunction

function! s:LoadConfig()
    python sys.argv = ["config"]
    pyfile grayout.py
endfunction


" Authentication
let g:github_dashboard = { 'username': 'you', 'password': $GITHUB_TOKEN }

let g:github_dashboard['position'] = 'tab'
let g:github_dashboard['emoji'] = 1
let g:github_dashboard['statusline'] = 0

Add username for github dashboard

" Authentication
let g:github_dashboard = { 'username': 'felixjung', 'password': $GITHUB_TOKEN }

let g:github_dashboard['position'] = 'tab'
let g:github_dashboard['emoji'] = 1
let g:github_dashboard['statusline'] = 0


" This callback will be executed when the entire command is completed
function! OnPushed(channel)
  unlet g:asyncPushOutput
  " clear status line
  echo ""
endfunction

function! AsyncPush()
  " Make sure we're running VIM version 8 or higher.
  if v:version < 800
    echoerr 'asyncPush requires VIM version 8 or higher'
    return
  endif

  if exists('g:asyncPushOutput')
    echo 'Already running task in background'
  else
    echo 'pushing changes…'
    " Launch the job.
    " Notice that we're only capturing out, and not err here. This is because, for some reason, the callback
    " will not actually get hit if we write err out to the same file. Not sure if I'm doing this wrong or?
    let g:asyncPushOutput = tempname()
    call job_start('git push', {'close_cb': 'OnPushed', 'out_io': 'file', 'out_name': g:asyncPushOutput})
  endif
endfunction

:command! -buffer W  execute "silent Gwrite | silent Gcommit -a -m 'update'" | call AsyncPush()
:command! -buffer WQ execute "Gwrite | Gcommit -a -m 'update'" | Gpush | q

Upgrade to new vim-fugitive syntax

" This callback will be executed when the entire command is completed
function! OnPushed(channel)
  unlet g:asyncPushOutput
  " clear status line
  echo ""
endfunction

function! AsyncPush()
  " Make sure we're running VIM version 8 or higher.
  if v:version < 800
    echoerr 'asyncPush requires VIM version 8 or higher'
    return
  endif

  if exists('g:asyncPushOutput')
    echo 'Already running task in background'
  else
    echo 'pushing changes…'
    " Launch the job.
    " Notice that we're only capturing out, and not err here. This is because, for some reason, the callback
    " will not actually get hit if we write err out to the same file. Not sure if I'm doing this wrong or?
    let g:asyncPushOutput = tempname()
    call job_start('git push', {'close_cb': 'OnPushed', 'out_io': 'file', 'out_name': g:asyncPushOutput})
  endif
endfunction

:command! -buffer W  execute "silent Gwrite | silent Git commit -a -m 'update'" | call AsyncPush()
:command! -buffer WQ execute "Gwrite | Git commit -a -m 'update'" | Gpush | q


" Set the leader key.
let mapleader=","

" Faster saving.
nmap <Leader>w :w!<CR>

Add moving around Vim windows with `Ctrl + hjkl`

" Window movement shortcuts.
"
" Move to the window in the direction shown, or create a new window.
"
" Credit: https://github.com/nicknisi/dotfiles/blob/master/config/nvim/autoload/functions.vim
function! WinMove(key)
    let t:curwin = winnr()

    exec "wincmd ".a:key

    if (t:curwin == winnr())
        if (match(a:key,'[jk]'))
            wincmd v
        else
            wincmd s
        endif

        exec "wincmd ".a:key
    endif
endfunction

" Set the leader key.
let mapleader=","

" Faster saving.
nmap <Leader>w :w!<CR>

" Move around the windows with `Ctrl + hjkl`.
map <silent> <C-h> :call WinMove('h')<cr>
map <silent> <C-j> :call WinMove('j')<cr>
map <silent> <C-k> :call WinMove('k')<cr>
map <silent> <C-l> :call WinMove('l')<cr>


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

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

Add new config variables to updater

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

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


let g:rainbow#pairs = [['(', ')'], ['[', ']'], ['{', '}'], ['<', '>']]
call rainbow_parentheses#activate()

Remove <> from rain parens

let g:rainbow#pairs = [['(', ')'], ['[', ']'], ['{', '}']]
call rainbow_parentheses#activate()


" some people don't like auto-formatting
" augroup cpp_autocmd
	" autocmd!
	" autocmd BufWritePost <buffer> silent AsyncRun! -strip
				" \ clang-format -i $(VIM_FILEPATH) &&
				" \ clang --config ./.clang --analyze $(VIM_FILEPATH)
" augroup END

Make something useful out of CPP

" some people don't like auto-formatting
" \ clang-format -i $(VIM_FILEPATH) &&
augroup cpp_autocmd
	autocmd!
	autocmd BufWritePost <buffer> silent AsyncRun! -strip
				\ clang --config ./.clang --analyze $(VIM_FILEPATH)
augroup END


" To get syntax highlighting and tab settings for gyp(i) files, add the
" following to your .vimrc file:
"     so /path/to/src/vim/filetypes.vim

augroup filetype
        au! BufRead,BufNewFile *.gyp    set filetype=python expandtab tabstop=2 shiftwidth=2
        au! BufRead,BufNewFile *.gypi   set filetype=python expandtab tabstop=2 shiftwidth=2
augroup END

Add vim filetype settings for DEPS.

" To get syntax highlighting and tab settings for gyp(i) and DEPS files,
" add the following to your .vimrc file:
"     so /path/to/src/tools/vim/filetypes.vim

augroup filetype
        au! BufRead,BufNewFile *.gyp    set filetype=python expandtab tabstop=2 shiftwidth=2
        au! BufRead,BufNewFile *.gypi   set filetype=python expandtab tabstop=2 shiftwidth=2
        au! BufRead,BufNewFile DEPS     set filetype=python expandtab tabstop=2 shiftwidth=2
augroup END


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

" Navigation
nnoremap j gj
nnoremap k gk

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

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

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

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

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

Add hotkey for repeat last command

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

" Navigation
nnoremap j gj
nnoremap k gk

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

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

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

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

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

" Command
" Repeat last command
nnoremap <leader>k :<Up><CR>


filetype off " required!

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

" GitHub
Bundle 'ap/vim-css-color'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'ecomba/vim-ruby-refactoring'
Bundle 'ervandew/supertab'
Bundle 'godlygeek/tabular'
Bundle 'kana/vim-scratch'
Bundle 'michaeljsmith/vim-indent-object'
Bundle 'mileszs/ack.vim'
Bundle 'othree/html5-syntax.vim'
Bundle 'pangloss/vim-javascript'
Bundle 'spiiph/vim-space'
Bundle 'tpope/vim-cucumber'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-haml'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-surround'
Bundle 'vim-ruby/vim-ruby'
Bundle 'xolox/vim-easytags'
Bundle 'xolox/vim-notes'

" vim-scripts
Bundle 'JSON.vim'
Bundle 'UltiSnips'
Bundle 'netrw.vim'
Bundle 'zoomwin'
Bundle 'Rename'
Bundle 'ruby-matchit'

" other Git
Bundle 'git://git.wincent.com/command-t.git'

" Should I still keep these?
Bundle 'mexpolk/vim-taglist'
Bundle 'scrooloose/nerdtree'

filetype plugin indent on " required!

Fix name of "ZoomWin" bundle

filetype off " required!

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

" GitHub
Bundle 'ap/vim-css-color'
Bundle 'bronson/vim-trailing-whitespace'
Bundle 'ecomba/vim-ruby-refactoring'
Bundle 'ervandew/supertab'
Bundle 'godlygeek/tabular'
Bundle 'kana/vim-scratch'
Bundle 'michaeljsmith/vim-indent-object'
Bundle 'mileszs/ack.vim'
Bundle 'othree/html5-syntax.vim'
Bundle 'pangloss/vim-javascript'
Bundle 'spiiph/vim-space'
Bundle 'tpope/vim-cucumber'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-haml'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-surround'
Bundle 'vim-ruby/vim-ruby'
Bundle 'xolox/vim-easytags'
Bundle 'xolox/vim-notes'

" Mirror needed since VBA from original source does not seem to install
Bundle 'vim-scripts/ZoomWin'

" vim-scripts
Bundle 'JSON.vim'
Bundle 'Rename'
Bundle 'UltiSnips'
Bundle 'netrw.vim'
Bundle 'ruby-matchit'

" other Git
Bundle 'git://git.wincent.com/command-t.git'

" Should I still keep these?
Bundle 'mexpolk/vim-taglist'
Bundle 'scrooloose/nerdtree'

filetype plugin indent on " required!


" enable quick comment toggles
"
" comment + <motion> (e.g. toggle line with <leader>t_)
map <leader>t        <plug>TComment_gc
" toggle line or paragraph
nmap <leader>tt      :TComment<cr>
nmap <leader>tp      <leader>_p
" block toggle line
nmap <leader>tb      :TCommentBlock<cr>

" visual toggle comment
vmap <leader>b       :TCommentBlock<cr>

Set vim comment command to <leader>d

" comment + <motion> (e.g. toggle line with <leader>d_)
nmap     <leader>d         <plug>TComment_gc
vmap     <leader>d         <plug>TComment_gc

" toggle line or paragraph
nnoremap <leader>dd        :TComment<cr>
nmap <leader>dp            <plug>TComment_<c-_>p

" toggle right of cursor
nnoremap <leader>dr        :TCommentRight<cr>

" block toggle line
nmap <leader>db            <plug>TComment_Commentb
vnoremap <leader>b         :TCommentBlock<cr>


" Cycle through relativenumber + number, number (only), and no numbering.
function! wincent#mappings#leader#cycle_numbering() abort
  if exists('+relativenumber')
    execute {
          \ '00': 'set relativenumber   | set number',
          \ '01': 'set norelativenumber | set number',
          \ '10': 'set norelativenumber | set nonumber',
          \ '11': 'set norelativenumber | set number' }[&number . &relativenumber]
  else
    " No relative numbering, just toggle numbers on and off.
    set number!<CR>
  endif
endfunction

function! wincent#mappings#leader#matchparen() abort
  " Preserve current window becaus {Do,No}MatchParen cycle with :windo.
  let l:currwin=winnr()
  if exists('g:loaded_matchparen')
    NoMatchParen
  else
    DoMatchParen
  endif
  execute l:currwin . 'wincmd w'
endfunction

" Zap trailing whitespace.
function! wincent#mappings#leader#zap() abort
  let l:pos=getcurpos()
  let l:search=@/
  keepjumps %substitute/\s\+$//e
  let @/=l:search
  nohlsearch
  call setpos('.', l:pos)
endfunction

Drop an unnecessary <CR> suffix

" Cycle through relativenumber + number, number (only), and no numbering.
function! wincent#mappings#leader#cycle_numbering() abort
  if exists('+relativenumber')
    execute {
          \ '00': 'set relativenumber   | set number',
          \ '01': 'set norelativenumber | set number',
          \ '10': 'set norelativenumber | set nonumber',
          \ '11': 'set norelativenumber | set number' }[&number . &relativenumber]
  else
    " No relative numbering, just toggle numbers on and off.
    set number!
  endif
endfunction

function! wincent#mappings#leader#matchparen() abort
  " Preserve current window becaus {Do,No}MatchParen cycle with :windo.
  let l:currwin=winnr()
  if exists('g:loaded_matchparen')
    NoMatchParen
  else
    DoMatchParen
  endif
  execute l:currwin . 'wincmd w'
endfunction

" Zap trailing whitespace.
function! wincent#mappings#leader#zap() abort
  let l:pos=getcurpos()
  let l:search=@/
  keepjumps %substitute/\s\+$//e
  let @/=l:search
  nohlsearch
  call setpos('.', l:pos)
endfunction


autocmd FileType clojure nnoremap <buffer> <localleader>fe :Eval<cr>
autocmd FileType clojure vnoremap <buffer> <localleader>fe :Eval<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fE :%Eval<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fr :Require<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fR :Require!<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>ft :RunTests<cr>
nnoremap <localleader>fc :FireplaceConnect<cr>

Add a fireplace last binding

autocmd FileType clojure nnoremap <buffer> <localleader>fe :Eval<cr>
autocmd FileType clojure vnoremap <buffer> <localleader>fe :Eval<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fE :%Eval<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fr :Require<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fR :Require!<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>ft :RunTests<cr>
autocmd FileType clojure nnoremap <buffer> <localleader>fl :Last<cr>
nnoremap <localleader>fc :FireplaceConnect<cr>


" Plugin settings

nmap <leader>t :Files<CR>
nmap <leader><S-t> :Tags<CR>
nmap <leader>b :Buffers<CR>
nmap <leader>f :Rg
nmap <leader><S-f> :Rg <C-r><C-w><CR>
nmap <leader>l :FSHere<CR>
nmap <leader><S-l> :split<CR> :FSBelow<CR>
nmap <leader>p :Welcome<CR>

Use branch names instead of hashes for vim-gh-line

" Plugin settings

nmap <leader>t :Files<CR>
nmap <leader><S-t> :Tags<CR>
nmap <leader>b :Buffers<CR>
nmap <leader>f :Rg
nmap <leader><S-f> :Rg <C-r><C-w><CR>
nmap <leader>l :FSHere<CR>
nmap <leader><S-l> :split<CR> :FSBelow<CR>
nmap <leader>p :Welcome<CR>

" vim-gh-line: use branch names instead of hashes in URL
let g:gh_use_canonical = 0


" plugin/plugin.investigate.vim

" Use dash if available on the current system
let g:investigate_use_dash = has('mac')

" Custom keybinding to open documentation pages
nnoremap <leader>K :call investigate#Investigate('n')<CR>
vnoremap <leader>K :call investigate#Investigate('v')<CR>

Use macOS dictionary as keywordprg in markdown/gitcommits

" plugin/plugin.investigate.vim

" Open macOS specific application using vim investigate
if has('mac')

  " Use dash on macOS
  let g:investigate_use_dash = 1

  " Look up word in macOS dictionary when editing markdown files
  let g:investigate_use_url_for_markdown = 1
  let g:investigate_url_for_markdown = 'dict://^x'

  " Look up word in macOS dictionary when editing markdown files
  let g:investigate_use_url_for_gitcommit = 1
  let g:investigate_url_for_gitcommit = 'dict://^x'

endif

" Custom keybinding to open documentation pages
nnoremap <leader>K :call investigate#Investigate('n')<CR>
vnoremap <leader>K :call investigate#Investigate('v')<CR>

" Rebind normal mode `K` only if `&keywordprg` is different to
" its default value `man -s`
function! s:RunExprIfDefault(cmd)
  if &keywordprg =~# '^man'
    return a:cmd
  endif
  return 'K'
endfunction

nnoremap <expr> K <SID>RunExprIfDefault(':call investigate#Investigate("n")<CR>')


"autostart syntax checking when vim opens to a compatible filetype (default: 0)
if !exists("g:autostartchecker") || &diff
    let g:autostartchecker = 0
endif

"start ale if autostartchecker is true
let g:ale_enabled = g:autostartchecker

"always show the sign column when ale is running
if g:autostartchecker
    set scl=yes
else
    set scl=auto
endif

"don't open the error list when detected (hitting leader twice will do this)
let g:ale_open_list = 0

"don't fix on save
let g:ale_fix_on_save = 0

"configure when to lint
let g:ale_lint_on_text_changed = 'normal'
let g:ale_lint_on_enter = 1
let g:ale_lint_on_filetype_changed = 1
let g:ale_lint_on_save = 1
let g:ale_lint_on_insert_leave = 1

"list of ale fixers
let g:ale_fixers = {
    \     'javascript': [ 'eslint' ]
    \ }

"don't run ale on minified files
let g:ale_pattern_options = {
    \     '\.min\.[^\.]*$': { 'ale_linters': [], 'ale_fixers': [] },
    \ }

Allow eslint to be used to fix vue files

"autostart syntax checking when vim opens to a compatible filetype (default: 0)
if !exists("g:autostartchecker") || &diff
    let g:autostartchecker = 0
endif

"start ale if autostartchecker is true
let g:ale_enabled = g:autostartchecker

"always show the sign column when ale is running
if g:autostartchecker
    set scl=yes
else
    set scl=auto
endif

"don't open the error list when detected (hitting leader twice will do this)
let g:ale_open_list = 0

"don't fix on save
let g:ale_fix_on_save = 0

"configure when to lint
let g:ale_lint_on_text_changed = 'normal'
let g:ale_lint_on_enter = 1
let g:ale_lint_on_filetype_changed = 1
let g:ale_lint_on_save = 1
let g:ale_lint_on_insert_leave = 1

"list of ale fixers
let g:ale_fixers = {
    \     'javascript': [ 'eslint' ],
    \     'vue': [ 'eslint' ]
    \ }

"don't run ale on minified files
let g:ale_pattern_options = {
    \     '\.min\.[^\.]*$': { 'ale_linters': [], 'ale_fixers': [] },
    \ }


" Contains custom filetype declarations
"

" Flex, The Fast Lexical Analyzer
au BufNewFile,BufRead *.flex set filetype=lex

" ASP.NET ASMX
au BufNewFile,BufRead *.asmx set filetype=cs

" Markdown (auto-detected as Modula 2)
au BufNewFile,BufRead *.md set filetype=markdown

Add special-case configs for certain file types

" Contains custom filetype declarations
"

" Flex, The Fast Lexical Analyzer
au BufNewFile,BufRead *.flex set filetype=lex

" ASP.NET ASMX
au BufNewFile,BufRead *.asmx set filetype=cs

" Markdown (auto-detected as Modula 2)
au BufNewFile,BufRead *.md set filetype=markdown

" Filetype-specific configs
"
au FileType ruby setlocal sw=2 ts=2 sts=2
au FileType yaml setlocal sw=2 ts=2 sts=2


setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

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

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

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

Set a name for the buffer even if there's no b:command

setlocal buftype=acwrite
setlocal bufhidden=wipe
setlocal autoindent

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

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

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