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

sign define pycheck_E text=E! texthl=Error
sign define pycheck_W text=W! texthl=Search

func s:CheckBuffer()
	" create custom detection by writing to b:pycheck_version in ftplugin
	let python_ver = exists('b:pycheck_version') ? b:pycheck_version : (exists('g:pycheck_default_version') ? g:pycheck_default_version : 2)

	let shebang = getline(1)
	if python_ver == 2
		if shebang =~# '^#!.*\(python\|pypy\)3'
			let python_ver = 3
		endif
	elseif python_ver == 3
		if shebang =~# '^#!.*\(python\|pypy\)\(2\|\>\)'
			let python_ver = 2
		endif
	endif

	" for checking the used python version
	let b:pycheck_detected_version = python_ver

	if python_ver == 3
		py3 import pycheck; pycheck.check_buffer()
	else
		py import pycheck; pycheck.check_buffer()
	endif
endf

au BufWritePost *.py call s:CheckBuffer()

Change default python version to 3

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

sign define pycheck_E text=E! texthl=Error
sign define pycheck_W text=W! texthl=WarningMsg

func s:CheckBuffer()
	" create custom detection by writing to b:pycheck_version in ftplugin
	let python_ver = exists('b:pycheck_version') ? b:pycheck_version : (exists('g:pycheck_default_version') ? g:pycheck_default_version : 3)

	let shebang = getline(1)
	if python_ver == 2
		if shebang =~# '^#!.*\(python\|pypy\)3'
			let python_ver = 3
		endif
	elseif python_ver == 3
		if shebang =~# '^#!.*\(python\|pypy\)\(2\|\>\)'
			let python_ver = 2
		endif
	endif

	" for checking the used python version
	let b:pycheck_detected_version = python_ver

	if python_ver == 3
		py3 import pycheck; pycheck.check_buffer()
	else
		py import pycheck; pycheck.check_buffer()
	endif
endf

au BufWritePost *.py call s:CheckBuffer()


" Markdown syntax highlighting
  augroup mkd
    autocmd BufRead *.mkd  set ai formatoptions=tcroqn2 comments=n:>
    autocmd BufRead *.md  set ai formatoptions=tcroqn2 comments=n:>
    autocmd BufRead *.markdown  set ai formatoptions=tcroqn2 comments=n:>
  augroup END

" Allow old-school vim directory exploring
let NERDTreeHijackNetrw = 0

" Add some alignment patterns for :Tabular
function! CustomTabularPatterns()
  AddTabularPattern!  symbols         / :/l0
  AddTabularPattern!  hash            /=>/
  AddTabularPattern!  chunks          / \S\+/l0
  AddTabularPattern!  assignment      /= /l1l0
endfunction
autocmd VimEnter * call CustomTabularPatterns()

let g:fuf_coveragefile_prompt = '>GoToFile[]>'
let g:fuf_coveragefile_exclude = '\v\~$|' .
\                                '\.(o|exe|dll|bak|swp|log|sqlite3|png|gif|jpg)$|' .
\                                '(^|[/\\])\.(hg|git|bzr|bundle)($|[/\\])|' .
\                                '(^|[/\\])(log|tmp|vendor|system|doc|coverage|build)($|[/\\])'

Add comma and colon tabular mappings

" Markdown syntax highlighting
  augroup mkd
    autocmd BufRead *.mkd  set ai formatoptions=tcroqn2 comments=n:>
    autocmd BufRead *.md  set ai formatoptions=tcroqn2 comments=n:>
    autocmd BufRead *.markdown  set ai formatoptions=tcroqn2 comments=n:>
  augroup END

" Allow old-school vim directory exploring
let NERDTreeHijackNetrw = 0

" Add some alignment patterns for :Tabular
function! CustomTabularPatterns()
  AddTabularPattern! symbols         / :/l0
  AddTabularPattern! hash            /=>/
  AddTabularPattern! chunks          / \S\+/l0
  AddTabularPattern! assignment      /= /l1l0
  AddTabularPattern! comma           /,\zs /l0
  AddTabularPattern! colon           /:\zs /l0
endfunction
autocmd VimEnter * call CustomTabularPatterns()

let g:fuf_coveragefile_prompt = '>GoToFile[]>'
let g:fuf_coveragefile_exclude = '\v\~$|' .
\                                '\.(o|exe|dll|bak|swp|log|sqlite3|png|gif|jpg)$|' .
\                                '(^|[/\\])\.(hg|git|bzr|bundle)($|[/\\])|' .
\                                '(^|[/\\])(log|tmp|vendor|system|doc|coverage|build)($|[/\\])'


augroup help_versions
  autocmd! FileType vim,help call helpful#setup()
augroup END

command! -nargs=+ -complete=help HelpfulVersion call helpful#lookup('<args>')

Use <q-args> instead of '<args>'

augroup help_versions
  autocmd! FileType vim,help call helpful#setup()
augroup END

command! -nargs=+ -complete=help HelpfulVersion call helpful#lookup(<q-args>)


set laststatus=2   " always display a status line

set statusline=%<%f\ %m%r%h%w\ %= " Filename [modified][readonly][help][preview]
set statusline+=%{rvm#statusline()}\%y[R%{v:register}] "[rvm][filetype][register]
set statusline+=%#warningmsg#%{SyntasticStatuslineFlag()}%* "[Warning on Syntax Error]
set statusline+=%([%l/%L,%v][%p%%]%) "[line#,col#][percent%]

Remove RVM and refactor register display properly

set laststatus=2   " always display a status line

function! Register()
  return substitute('[R'.v:register.']','^\[R\]$','','')
endfunction

set statusline=%<%f\ %m%r%h%w\ %= " Filename [modified][readonly][help][preview]
set statusline+=%#warningmsg#%{SyntasticStatuslineFlag()}%* "[Warning on Syntax Error]
set statusline+=%y%{Register()} "[filetype][register]
set statusline+=%([%l/%L,%v][%p%%]%) "[line#,col#][percent%]


if !has("gui_running")
  finish
endif

set guioptions=acei
set list

if has("gui_macvim")
  set guifont=Monaco:h12
  " Fullscreen takes up entire screen
  set fuoptions=maxhorz,maxvert

  set transparency=15
else
  set guifont=Monaco\ 9,\ DejaVu\ Sans\ Mono\ 9
endif

Use Menlo instead of Monaco

if !has("gui_running")
  finish
endif

set guioptions=acei
set list

if has("gui_macvim")
  set guifont=Menlo:h12
  " Fullscreen takes up entire screen
  set fuoptions=maxhorz,maxvert

  set transparency=15
else
  set guifont=Menlo\ 9,\ DejaVu\ Sans\ Mono\ 9
endif


" 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

Use "setfiletype" rather than "set filetype"

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


" plugin/restore-position.vim

" Jump to last known position
" @see help docs on last-position-jump

augroup vimrc_rlp

  au!

  au BufReadPost *
    \ if (&ft != 'gitcommit') && line("'\"") > 1 && line("'\"") <= line("$") |
    \   execute "normal! g`\"" |
    \ endif

augroup END

Fix restore of last cursor position in vim

" plugin/restore-position.vim

" Jump to last known position
" @see help docs on last-position-jump

augroup vimrc_rlp

  au!

  au BufReadPost *
    \ if (&ft !~ '^git\c') && line("'\"") > 1 && line("'\"") <= line("$") |
    \   execute "normal! g`\"" |
    \ endif

augroup END


" hide upper case marks
let g:SignatureIncludeMarks = 'abcdefghijklmnopqrstuvwxyz'

Fix highlight of sign text

" hide upper case marks
let g:SignatureIncludeMarks = 'abcdefghijklmnopqrstuvwxyz'

" highlight
let g:SignatureMarkTextHL = 'Statement'


" Name: SuperMan man pages
" Author: Jacob Zimmerman <jake@zimmerman.io>
" License: MIT License
"
" URL: <https://github.com/Z1MM32M4N/vim-superman>
"
" Created: Dec 20 2014
" Modified: Dec 20 2014

" Wrapper around man.vim's Man command
function! superman#SuperMan(...)
  " Needed to get access to Man
  source $VIMRUNTIME/ftplugin/man.vim

  " Build and pass off arguments to Man command
  execute 'Man' join(a:000, ' ')

  " Quit with error code if there is only one line in the buffer
  " (i.e., manpage not found)
  if line('$') == 1 | cquit | endif

  " Why :Man opens up in a split I shall never know
  only

  " Set options appropriate for viewing manpages
  setlocal readonly
  setlocal nomodifiable

  setlocal number

  setlocal noexpandtab
  setlocal tabstop=8
  setlocal softtabstop=8
  setlocal shiftwidth=8

  " To make us behave more like less
  noremap q :q<CR>
endfunction

" Command alias for our function
command! -nargs=+ SuperMan call superman#SuperMan(<f-args>)

Add nolist and remove colorcolumn from man pages

" Name: SuperMan man pages
" Author: Jacob Zimmerman <jake@zimmerman.io>
" License: MIT License
"
" URL: <https://github.com/Z1MM32M4N/vim-superman>
"
" Created: Dec 20 2014
" Modified: Dec 20 2014

" Wrapper around man.vim's Man command
function! superman#SuperMan(...)
  " Needed to get access to Man
  source $VIMRUNTIME/ftplugin/man.vim

  " Build and pass off arguments to Man command
  execute 'Man' join(a:000, ' ')

  " Quit with error code if there is only one line in the buffer
  " (i.e., manpage not found)
  if line('$') == 1 | cquit | endif

  " Why :Man opens up in a split I shall never know
  only

  " Set options appropriate for viewing manpages
  setlocal readonly
  setlocal nomodifiable

  setlocal number

  setlocal noexpandtab
  setlocal tabstop=8
  setlocal softtabstop=8
  setlocal shiftwidth=8
  setlocal nolist
  setlocal colorcolumn=0

  " To make us behave more like less
  noremap q :q<CR>
endfunction

" Command alias for our function
command! -nargs=+ SuperMan call superman#SuperMan(<f-args>)


let g:Powerline#Segments#fugitive#segments = Pl#Segment#Init('fugitive',
	\ (exists('g:loaded_fugitive') && g:loaded_fugitive == 1),
	\
	\ Pl#Segment#Create('branch', '%{Powerline#Functions#fugitive#GetBranch("$BRANCH")}'),
\ )

Remove extra comma from Fugitive segment definition

let g:Powerline#Segments#fugitive#segments = Pl#Segment#Init('fugitive',
	\ (exists('g:loaded_fugitive') && g:loaded_fugitive == 1),
	\
	\ Pl#Segment#Create('branch', '%{Powerline#Functions#fugitive#GetBranch("$BRANCH")}')
\ )


set directory=~/.vim/backup
set backupdir=~/.vim/backup

set t_Co=256

set smartindent
set tabstop=2
set shiftwidth=2
set expandtab

set ai
set number
set hlsearch
set ignorecase
set smartcase

set spell spelllang=en_us
set mousemodel=popup_setpos

filetype plugin on
set omnifunc=syntaxcomplete#Complete

set laststatus=2

let g:powerline_loaded = 1

let g:airline_powerline_fonts = 1

let g:NERDTreeChDirMode = 2

let g:DeleteTrailingWhitespace = 1
let g:DeleteTrailingWhitespace_Action = 'delete'

if has('gui_running')
  colorscheme molokai
  set background=dark
else
  set background=dark

  if strlen($TMUX)
    let g:airline_theme = 'solarized'
  endif
endif

if has('gui_running')
  set guifont=Inconsolata\ XL\ 10
endif

Fix how colorscheme is loaded.

set directory=~/.vim/backup
set backupdir=~/.vim/backup

set t_Co=256

set smartindent
set tabstop=2
set shiftwidth=2
set expandtab

set ai
set number
set hlsearch
set ignorecase
set smartcase

set spell spelllang=en_us
set mousemodel=popup_setpos

filetype plugin on
set omnifunc=syntaxcomplete#Complete

set laststatus=2

let g:powerline_loaded = 1

let g:airline_powerline_fonts = 1

let g:NERDTreeChDirMode = 2

let g:DeleteTrailingWhitespace = 1
let g:DeleteTrailingWhitespace_Action = 'delete'

let g:promptline_theme = 'airline'

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

if has('gui_running')
  set guifont=Inconsolata\ XL\ 10
endif


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

syn keyword ceosLanguageKeywords if else interface implementation extern

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

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

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

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

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

let b:current_syntax = "ceos"

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

Add syntax highlighting for virtual

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

syn keyword ceosLanguageKeywords if else interface implementation extern virtual

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

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

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

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

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

let b:current_syntax = "ceos"

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


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

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

if !exists("g:go_auto_type_info")
    let g:go_auto_type_info = 0
endif

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

setlocal noexpandtab

" use old regexpengine
set re=1

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

" Set gocode completion
setlocal omnifunc=go#complete#Complete

" GoInfo automatic update
if g:go_auto_type_info != 0
    setlocal updatetime=300
    au! CursorHold *.go nested call go#complete#Info()
endif

compiler go

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

Remove regexpengine settings, it's global

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

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

if !exists("g:go_auto_type_info")
    let g:go_auto_type_info = 0
endif

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

setlocal noexpandtab

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

" Set gocode completion
setlocal omnifunc=go#complete#Complete

" GoInfo automatic update
if g:go_auto_type_info != 0
    setlocal updatetime=300
    au! CursorHold *.go nested call go#complete#Info()
endif

compiler go

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


MP 'danro/rename.vim',               { 'on' : 'Rename' }

" Refer to https://github.com/junegunn/dotfiles  vimrc
MP 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
augroup nerd_loader
    autocmd!
    autocmd VimEnter * silent! autocmd! FileExplorer
    autocmd BufEnter,BufNew *
                \  if isdirectory(expand('<amatch>'))
                \|   call plug#load('nerdtree')
                \|   execute 'autocmd! nerd_loader'
                \| endif
augroup END

MP 'Xuyuanp/nerdtree-git-plugin',             { 'on': 'NERDTreeToggle' }
MP 'tiagofumo/vim-nerdtree-syntax-highlight', { 'on': 'NERDTreeToggle' }

Fix nerdtree issue when open directory.

MP 'danro/rename.vim',               { 'on' : 'Rename' }

" Refer to https://github.com/junegunn/dotfiles  vimrc
MP 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
augroup nerd_loader
    autocmd!
    autocmd VimEnter * silent! autocmd! FileExplorer
    autocmd BufEnter,BufNew *
                \  if isdirectory(expand('<amatch>'))
                \|   call plug#load('nerdtree')
                \|   call nerdtree#checkForBrowse(expand("<amatch>"))
                \| endif
augroup END

MP 'Xuyuanp/nerdtree-git-plugin',             { 'on': 'NERDTreeToggle' }
MP 'tiagofumo/vim-nerdtree-syntax-highlight', { 'on': 'NERDTreeToggle' }


""" Plugins

"" System
" dense-analysis/ale
let g:ale_fixers['css'] = ['stylelint']
let g:ale_linters['css'] = ['stylelint']

let g:ale_fixers['scss'] = g:ale_fixers['css']
let g:ale_linters['scss'] = g:ale_linters['css']

let g:ale_fixers['javascript'] = ['xo']
let g:ale_fixers['typescript'] = ['prettier']
let g:ale_javascript_eslint_suppress_missing_config = 1
let g:ale_linters['javascript'] = ['xo']

" let g:ale_fixers['rust'] = ['rustfmt']
" let g:ale_linters['rust'] = ['cargo', 'rustc']

let g:ale_fixers['sh'] = ['shfmt']
let g:ale_linters['sh'] = ['shellcheck']

Clean up js linter settings

""" Plugins

"" System
" dense-analysis/ale
let g:ale_fixers['css'] = ['stylelint']
let g:ale_linters['css'] = ['stylelint']

let g:ale_fixers['scss'] = g:ale_fixers['css']
let g:ale_linters['scss'] = g:ale_linters['css']

let g:ale_fixers['javascript'] = ['xo']
let g:ale_javascript_eslint_suppress_missing_config = 1
let g:ale_linters['javascript'] = g:ale_fixers['javascript']

" let g:ale_fixers['rust'] = ['rustfmt']
" let g:ale_linters['rust'] = ['cargo', 'rustc']

let g:ale_fixers['sh'] = ['shfmt']
let g:ale_linters['sh'] = ['shellcheck']


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

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

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

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

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

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

let &cpo = s:cpo_save
unlet s:cpo_save

Remove Version line from script.

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

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

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

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

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

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

let &cpo = s:cpo_save
unlet s:cpo_save


" Enable true color mode.
set termguicolors

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

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

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

" Set nvim-gtk settings.
if exists('g:GtkGuiLoaded')
  call rpcnotify(1, 'Gui', 'Font', 'Inconsolata-g for Powerline 14')
  call rpcnotify(1, 'Gui', 'Option', 'Tabline', 0)
endif

Use Fira Code for neovim-gtk

" Enable true color mode.
set termguicolors

" Disable visual bell.
set visualbell t_vb=

" Set focus to follow mouse.
set mousefocus

" Set right mouse button action.
set mousemodel=extend

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

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

" Set nvim-gtk settings.
if exists('g:GtkGuiLoaded')
  call rpcnotify(1, 'Gui', 'Font', 'Fira Code 13')
  call rpcnotify(1, 'Gui', 'Option', 'Tabline', 0)
endif


if exists("g:import_js_loaded") || &cp
  finish
endif
let g:import_js_loaded = 1

command ImportJSImport call importjs#ImportJSImport()
command ImportJSImportAll call importjs#ImportJSImportAll()

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

Add <leader>i shortcut for :ImportJSImportAll

if exists("g:import_js_loaded") || &cp
  finish
endif
let g:import_js_loaded = 1

command ImportJSImport call importjs#ImportJSImport()
command ImportJSImportAll call importjs#ImportJSImportAll()

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

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


augroup startup
    autocmd!
    autocmd BufNewFile,BufReadPost,FilterReadPost,FileReadPost * :set number            " Always show line number on new buffer
augroup end
set nowrap

set nobackup        " Don't use backup file

set cursorline
augroup CursorLine
    autocmd!
    autocmd VimEnter,WinEnter,BufWinEnter * setlocal cursorline
    autocmd WinLeave * setlocal nocursorline
augroup END

" Tab
set tabstop=4
set shiftwidth=0
set softtabstop=-1
set expandtab

" UTF-8
set encoding=utf-8
set termencoding=utf-8
set fileencoding=utf-8

" Scrolling
set scrolloff=5
set sidescrolloff=5
set lazyredraw

set magic             " Regular expressions

set autoread

set clipboard=unnamed,unnamedplus

let $VISUAL = 'nvr -cc split --remote-wait'         " Split instead of nested editor inside neovim terminal

set ignorecase
set smartcase

set exrc
set secure

augroup filetypedetect
    " Mail
    autocmd BufRead,BufNewFile *mutt-* setfiletype mail
augroup END

Add wrap for plain text files in Neovim

augroup startup
    autocmd!
    autocmd BufNewFile,BufReadPost,FilterReadPost,FileReadPost * :set number            " Always show line number on new buffer
augroup end
set nowrap

set nobackup        " Don't use backup file

set cursorline
augroup CursorLine
    autocmd!
    autocmd VimEnter,WinEnter,BufWinEnter * setlocal cursorline
    autocmd WinLeave * setlocal nocursorline
augroup END

" Tab
set tabstop=4
set shiftwidth=0
set softtabstop=-1
set expandtab

" UTF-8
set encoding=utf-8
set termencoding=utf-8
set fileencoding=utf-8

" Scrolling
set scrolloff=5
set sidescrolloff=5
set lazyredraw

set magic             " Regular expressions

set autoread

set clipboard=unnamed,unnamedplus

let $VISUAL = 'nvr -cc split --remote-wait'         " Split instead of nested editor inside neovim terminal

set ignorecase
set smartcase

set exrc
set secure

augroup filetypedetect
    " Mail
    autocmd BufRead,BufNewFile *mutt-* setfiletype mail
augroup END

autocmd FileType text setlocal wrap


" LuaTeX Syntax Highlighting {{{
if exists("b:current_syntax")
    unlet b:current_syntax
endif

syn include @LUA syntax/lua.vim

syn region LuaTeXSnippet matchgroup=LuaTeXIdentifier
    \ start='\\begin{\z(luacode\|luacode*\)}'
    \ end='\\end{\z1}'
    \ contains=@LUA

syn region LuaTeXSnippet matchgroup=LuaTeXIdentifier
    \ start='\\\(directlua\|luadirect\){'
    \ end='}'
    \ contains=@LUA

highlight link LuaTeXSnippet SpecialComment
" }}}

Fix the highlighting of matchgroup.

" LuaTeX Syntax Highlighting {{{
if exists("b:current_syntax")
    unlet b:current_syntax
endif

syn include @LUA syntax/lua.vim

syn region LuaTeXSnippet matchgroup=LuaTeXIdentifier
    \ start='\\begin{\z(luacode\|luacode*\)}'
    \ end='\\end{\z1}'
    \ contains=@LUA

syn region LuaTeXSnippet matchgroup=LuaTeXIdentifier
    \ start='\\\(directlua\|luadirect\){'
    \ end='}'
    \ contains=@LUA

highlight link LuaTeXIdentifier SpecialComment
" }}}


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

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

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

" Add line numbers
set relativenumber
set number

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

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

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

" Visual feedback on autocompleted commands
set wmnu

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

Add commented out theme to use in sunlight

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

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

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

" Add line numbers
set relativenumber
set number

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

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

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

" Visual feedback on autocompleted commands
set wmnu

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


set scrolloff=3   " context lines around cursor
set scrolljump=5  " minimum number of lines to scroll

" retain relative cursor position when paging
nnoremap <PageUp>   <C-U>
nnoremap <PageDown> <C-D>

Swap (j-gj) and (k-gk) movements.

set scrolloff=3   " context lines around cursor
set scrolljump=5  " minimum number of lines to scroll

" retain relative cursor position when paging
nnoremap <PageUp>   <C-U>
nnoremap <PageDown> <C-D>

" Swap (j-gj) and (k-gk) movements
noremap j gj
noremap k gk
noremap gj j
noremap gk k


if ! has('python')
	echohl ErrorMsg
	echomsg 'You need vim compiled with Python 2 support for Powerline to work. Please consult the documentation for more details.'
	echohl None
	finish
endif

python import sys, vim
python sys.path.append(vim.eval('expand("<sfile>:h:h:h:h")'))

exec 'source '. fnameescape(expand('<sfile>:h') . '/powerline.vim')

Use shorter and more readable form of :source

if ! has('python')
	echohl ErrorMsg
	echomsg 'You need vim compiled with Python 2 support for Powerline to work. Please consult the documentation for more details.'
	echohl None
	finish
endif

python import sys, vim
python sys.path.append(vim.eval('expand("<sfile>:h:h:h:h")'))

source <sfile>:h/powerline.vim


" Make it beautiful - colors and fonts
if has("gui_running")
  "tell the term has 256 colors
  set t_Co=256

  " http://ethanschoonover.com/solarized/vim-colors-solarized
  colorscheme solarized
  set background=dark

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

  set lines=60
  set columns=190

  set guifont=Inconsolata\ XL:h17,Inconsolata:h20,Monaco:h17
else
  "dont load csapprox if we no gui support - silences an annoying warning
  let g:CSApprox_loaded = 1
endif

Add solarized theme to console vim

" Make it beautiful - colors and fonts

" http://ethanschoonover.com/solarized/vim-colors-solarized
colorscheme solarized
set background=dark

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

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

  set lines=60
  set columns=190

  set guifont=Inconsolata\ XL:h17,Inconsolata:h20,Monaco:h17
else
  "dont load csapprox if we no gui support - silences an annoying warning
  let g:CSApprox_loaded = 1
endif


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

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

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

Remove npm stop nvim command

command NpmStart :call NpmStartFunc()

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


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

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

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

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

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

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

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

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

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

Remove grep current partial, doesn't work well

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

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

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

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

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

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

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


syntax on

set autoindent
set backspace=indent,eol,start
set cursorline
set expandtab
set hlsearch
set ignorecase
set incsearch
set number
set scrolloff=1
set shiftwidth=4
set smartcase
set tabstop=4
set termguicolors
set updatetime=1000

call plug#begin('~/.vim/plugged')
    Plug 'airblade/vim-gitgutter'
    Plug 'arcticicestudio/nord-vim'
    Plug 'editorconfig/editorconfig-vim'
    Plug 'jpalardy/vim-slime'
    Plug 'tpope/vim-surround'
call plug#end()

colorscheme nord

let g:slime_target='tmux'
let g:slime_default_config={'socket_name': get(split($TMUX, ","), 0), 'target_pane': ':.1'}
let g:slime_dont_ask_default=1

Support LSP and automatic completion

syntax on

set autoindent
set backspace=indent,eol,start
set cursorline
set expandtab
set hlsearch
set ignorecase
set incsearch
set number
set scrolloff=1
set shiftwidth=4
set smartcase
set tabstop=4
set termguicolors
set updatetime=1000

set completeopt=menuone,noinsert,noselect
set shortmess+=c

call plug#begin('~/.vim/plugged')
    Plug 'airblade/vim-gitgutter'
    Plug 'arcticicestudio/nord-vim'
    Plug 'editorconfig/editorconfig-vim'
    Plug 'jpalardy/vim-slime'
    Plug 'JuliaEditorSupport/julia-vim'
    Plug 'neovim/nvim-lspconfig'
    Plug 'nvim-lua/completion-nvim'
    Plug 'tpope/vim-surround'
call plug#end()

colorscheme nord

lua << EOF
    vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
        vim.lsp.diagnostic.on_publish_diagnostics, {
            virtual_text=false,
            signs=true,
            update_in_insert=true,
        }
    )
    local lspconfig = require'lspconfig'
    local on_attach_vim = function(client)
        require'completion'.on_attach(client)
    end
    lspconfig.julials.setup({on_attach=on_attach_vim})
EOF

let g:slime_target='tmux'
let g:slime_default_config={'socket_name': get(split($TMUX, ","), 0), 'target_pane': ':.1'}
let g:slime_dont_ask_default=1

let g:completion_timer_cycle=250
let g:completion_matching_ignore_case=1

inoremap <expr> <Tab> pumvisible() ? '\<C-n>' : '\<Tab>'
inoremap <expr> <S-Tab> pumvisible() ? '\<C-p>' : '\<S-Tab>'
imap <Tab> <Plug>(completion_smart_tab)
imap <S-Tab> <Plug>(completion_smart_s_tab)


let mapleader = ","
" Reload vimrc
nnoremap <C-c><C-e>e :edit $HOME/.vimrc<CR>
nnoremap <C-c><C-e>s :source $HOME/.vimrc<CR>
" Escape
inoremap jj <ESC>
" For US keyboard
nnoremap ; :
nnoremap : ;
" Tab操作を簡単に。
nnoremap <C-t>  <Nop>
nnoremap <C-t>n  :<C-u>tabnew<CR>
nnoremap <C-t>c  :<C-u>tabclose<CR>
nnoremap <C-t>l :<C-u>execute 'tabnext' 1 + (tabpagenr() + v:count1 - 1) % tabpagenr('$')<CR>
nnoremap <C-t>h  gT
" splitの移動を簡単に。ctrl押しながらhjkl
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" アクティブなファイルが含まれるディレクトリを展開
cnoremap <expr> %% getcmdtype() == ':' ? expand('%:h').'/' : '%%'

Change shortcut that open new tab

let mapleader = ","
" Reload vimrc
nnoremap <C-c><C-e>e :edit $HOME/.vimrc<CR>
nnoremap <C-c><C-e>s :source $HOME/.vimrc<CR>
" Escape
inoremap jj <ESC>
" For US keyboard
nnoremap ; :
nnoremap : ;
" Tab操作を簡単に。
nnoremap <C-t>  <Nop>
nnoremap <C-t>t  :<C-u>tabnew<CR>
nnoremap <C-t>c  :<C-u>tabclose<CR>
nnoremap <C-t>l :<C-u>execute 'tabnext' 1 + (tabpagenr() + v:count1 - 1) % tabpagenr('$')<CR>
nnoremap <C-t>h  gT
" splitの移動を簡単に。ctrl押しながらhjkl
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
" アクティブなファイルが含まれるディレクトリを展開
cnoremap <expr> %% getcmdtype() == ':' ? expand('%:h').'/' : '%%'


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++ -w -P -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

Define commands to access plugin functions

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++ -w -P -E -'

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

    command! GrayoutUpdate call s:UpdateGrayout()
    command! GrayoutClear call s:ClearGrayout()
    command! GrayoutReloadConfig call s:ReloadGrayoutConfig()

    python import sys
endif

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

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

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

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

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


" =========================================
" Commentary Settings

autocmd FileType tmux set commentstring=#\ %s
autocmd FileType moon set commentstring=--\ %s
autocmd FileType puppet set commentstring=#\ %s
autocmd FileType dockerfile set commentstring=#\ %s
autocmd FileType nginx set commentstring=#\ %s
autocmd FileType gitcommit set commentstring=#\ %s

Set comment string for yaml

" =========================================
" Commentary Settings

autocmd FileType tmux set commentstring=#\ %s
autocmd FileType eruby.yaml set commentstring=#\ %s
autocmd FileType moon set commentstring=--\ %s
autocmd FileType puppet set commentstring=#\ %s
autocmd FileType dockerfile set commentstring=#\ %s
autocmd FileType nginx set commentstring=#\ %s
autocmd FileType gitcommit set commentstring=#\ %s


function! sj#vue#SplitCssDefinition()
    if s:GetVueSection() != 'style'
        return 0
    endif
    return sj#css#SplitDefinition()
endfunction

function! sj#vue#JoinCssDefinition()
    if s:GetVueSection() != 'style'
        return 0
    endif
    return sj#css#JoinDefinition()
endfunction

function! sj#vue#SplitCssMultilineSelector()
    if s:GetVueSection() != 'style'
        return 0
    endif
    return sj#css#SplitMultilineSelector()
endfunction

function! sj#vue#JoinCssMultilineSelector()
    if s:GetVueSection() != 'style'
        return 0
    endif
    return sj#css#JoinMultilineSelector()
endfunction

function! s:GetVueSection()
  let l:startofsection = search('\v^\<(template|script|style)\>', 'bn')
  return substitute(getline(startofsection), '\v[<>]', '', 'g')
endfunction

Use 2 spaces for consistency with the codebase


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

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

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

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

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

Disable automatic line wrapping by textwidth.

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

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

setlocal formatoptions-=t

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

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

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


" Copyright Floobits Inc 2014

if !has('python')
   echomsg "Floobits requires python in nvim, please read :he nvim-python"
endif

if !exists("floo_log_level")
    let floo_log_level = "msg"
endif
if !exists("floo_delete_local_files")
    let floo_delete_local_files = 1
endif
if !exists("floo_show_highlights")
    let floo_show_highlights = 1
endif
if !exists("floo_sparse_mode")
    let floo_sparse_mode = 0
endif

function! g:FloobitsGetSelection()
    let m = tolower(mode())
    try
        if 'v' == m
            let pos = getpos("v")
            let line = pos[1]
            let col = pos[2]
            let start = line2byte(line) + col - 2
            let pos = getpos(".")
            let line = pos[1]
            let col = pos[2]
            let end = line2byte(line) + col - 2
            return [[start, end]]
        else
            let pos = line2byte(line(".")) + col(".") - 2
            return [[pos, pos]]
        endif
    catch a:exception
        return [[0, 0]]
    endtry
endfunction

Update copyright. Better error message with solution.

" Copyright 2014-2015 Floobits, Inc

if !has('python')
   echomsg "Floobits error: no nvim python module. Run `pip install nvim` to fix. For more info, :he nvim-python"
endif

if !exists("floo_log_level")
    let floo_log_level = "msg"
endif
if !exists("floo_delete_local_files")
    let floo_delete_local_files = 1
endif
if !exists("floo_show_highlights")
    let floo_show_highlights = 1
endif
if !exists("floo_sparse_mode")
    let floo_sparse_mode = 0
endif

function! g:FloobitsGetSelection()
    let m = tolower(mode())
    try
        if 'v' == m
            let pos = getpos("v")
            let line = pos[1]
            let col = pos[2]
            let start = line2byte(line) + col - 2
            let pos = getpos(".")
            let line = pos[1]
            let col = pos[2]
            let end = line2byte(line) + col - 2
            return [[start, end]]
        else
            let pos = line2byte(line(".")) + col(".") - 2
            return [[pos, pos]]
        endif
    catch a:exception
        return [[0, 0]]
    endtry
endfunction


" vim: set foldmethod=marker :

if has("nvim")
  set termguicolors
  let $NVIM_TUI_ENABLE_TRUE_COLOR=1
  set bg=dark

  " {{{ Terminal mode
  "
  " Escape to switch back to normal mode
  tnoremap <Esc> <C-\><C-n>
  " Control-V + Escape to insert Escape
  tnoremap <C-v><Esc> <Esc>

  " Highlight terminal mode cursor
  highlight! link TermCursor Cursor
  highlight! TermCursorNC guibg=red guifg=white ctermbg=1 ctermfg=15

  " Use neovim-remote to open main neovim sessions when launching neovim within
  " a neovim terminal session
  " Thanks to https://pragprog.com/book/modvim/modern-vim for the tip!
  "
  " see https://github.com/mhinz/neovim-remote
  " nvr is a tool that helps controlling nvim processes.
  "
  " It does two things:
  "   * adds back the --remote family of options (see man vim)
  "   * helps controlling the current nvim from within :terminal
  if executable('nvr')
    let $VISUAL="nvr -cc split --remote-wait +'set bufhidden=wipe'"
  endif
  " }}}

endif

Fix errors w/ kitty terminal

" vim: set foldmethod=marker :

if has("nvim")
  set termguicolors
  let $NVIM_TUI_ENABLE_TRUE_COLOR=1
  set bg=dark

  " Fix errors with kitty when termguicolors is set
  " see https://github.com/kovidgoyal/kitty/issues/160#issuecomment-341027936
  let &t_8f = '\e[38;2;%lu;%lu;%lum'
  let &t_8b = '\e[48;2;%lu;%lu;%lum'

  " {{{ Terminal mode
  "
  " Escape to switch back to normal mode
  tnoremap <Esc> <C-\><C-n>
  " Control-V + Escape to insert Escape
  tnoremap <C-v><Esc> <Esc>

  " Highlight terminal mode cursor
  highlight! link TermCursor Cursor
  highlight! TermCursorNC guibg=red guifg=white ctermbg=1 ctermfg=15

  " Use neovim-remote to open main neovim sessions when launching neovim within
  " a neovim terminal session
  " Thanks to https://pragprog.com/book/modvim/modern-vim for the tip!
  "
  " see https://github.com/mhinz/neovim-remote
  " nvr is a tool that helps controlling nvim processes.
  "
  " It does two things:
  "   * adds back the --remote family of options (see man vim)
  "   * helps controlling the current nvim from within :terminal
  if executable('nvr')
    let $VISUAL="nvr -cc split --remote-wait +'set bufhidden=wipe'"
  endif
  " }}}

endif


" Settings for Vundle

set nocompatible
filetype off

set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
    Plugin 'gmarik/vundle'
    Plugin 'altercation/vim-colors-solarized'
    Plugin 'croaker/mustang-vim'
    Plugin 'Lokaltog/vim-easymotion'
    Plugin 'tpope/vim-surround'
    Plugin 'tpope/vim-commentary'
    Plugin 'tpope/vim-repeat'
    Plugin 'kien/ctrlp.vim'
    Plugin 'kien/rainbow_parentheses.vim'
    Plugin 'Yggdroot/indentLine'
    Plugin 'bling/vim-airline'
    Plugin 'majutsushi/tagbar'
    Plugin 'scrooloose/syntastic'
    Plugin 'terryma/vim-expand-region'
    Plugin 'terryma/vim-multiple-cursors'
    Plugin 'terryma/vim-smooth-scroll'
    Plugin 'Valloric/YouCompleteMe'
    Plugin 'godlygeek/tabular'
    Plugin 'jnwhiteh/vim-golang'
call vundle#end()

Add PEP8-indent plugin for VIM

" Settings for Vundle

set nocompatible
filetype off

set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
    Plugin 'altercation/vim-colors-solarized'
    Plugin 'bling/vim-airline'
    Plugin 'gmarik/vundle'
    Plugin 'godlygeek/tabular'
    Plugin 'hynek/vim-python-pep8-indent'
    Plugin 'jnwhiteh/vim-golang'
    Plugin 'kien/ctrlp.vim'
    Plugin 'kien/rainbow_parentheses.vim'
    Plugin 'Lokaltog/vim-easymotion'
    Plugin 'majutsushi/tagbar'
    Plugin 'scrooloose/syntastic'
    Plugin 'terryma/vim-expand-region'
    Plugin 'terryma/vim-multiple-cursors'
    Plugin 'terryma/vim-smooth-scroll'
    Plugin 'tpope/vim-commentary'
    Plugin 'tpope/vim-repeat'
    Plugin 'tpope/vim-surround'
    Plugin 'Valloric/YouCompleteMe'
call vundle#end()


" Avoid excessive line length in commit comments
setlocal textwidth=70
" Highlight these lines
exec '2match Todo /\%>' .  &textwidth . 'v.\+/'
" Undo the match when leaving, and remove the hook then too.
augroup gitcommit
  au!
  au BufLeave * execute "2match none | augroup gitcommit | au!" | execute "augroup END"
augroup END

Make Vim do a spell check in git commit messages

" Avoid excessive line length in commit comments
setlocal textwidth=70
" Highlight these lines
exec '2match Todo /\%>' .  &textwidth . 'v.\+/'
" Undo the match when leaving, and remove the hook then too.
augroup gitcommit
  au!
  au BufLeave * execute "2match none | augroup gitcommit | au!" | execute "augroup END"
augroup END
" Do a spell check
set spell


func s:init_config()
  if !exists("g:cmake_cxx_compiler")
    let g:cmake_cxx_compiler = "clang++"
  endif

  if !exists("g:cmake_c_compiler")
    let g:cmake_c_compiler = "clang"
  endif

  if !exists("g:cmake_build_dirs")
    let g:cmake_build_dirs = [ "build" ]
  endif

  if !exists("g:cmake_build_type")
    let g:cmake_build_type = "Debug"
  endif

  if !exists("g:cmake_install_prefix")
    let g:cmake_install_prefix = "$HOME/.local"
  endif

  if !exists("g:cmake_build_shared_libs")
    let g:cmake_build_shared_libs = 1
  endif
endfunc

func s:init_commands()
  exe "command! -buffer -nargs=0 CMakeBuild :call cmake#commands#build()"
  exe "command! -buffer -nargs=0 CMakeInstall :call cmake#commands#install()"
  exe "command! -buffer -nargs=0 CMakeClean :call cmake#commands#install()"
  exe "command! -buffer -nargs=0 CMakeTest :call cmake#commands#test()"
  exe "command! -buffer -nargs=0 CMakeCreateBuild :call cmake#commands#create_build()"
  exe "command! -buffer -nargs=0 CMakeDeleteBuild :call cmake#commands#delete_build()"
endfunc

if !exists("g:cmake_init_loaded")
  let g:cmake_init_loaded=1
  call s:init_config()
  call s:init_commands()
endif

Set CMake to load in specific buffers.

func s:init_config()
  if !exists("g:cmake_cxx_compiler")
    let g:cmake_cxx_compiler = "clang++"
  endif

  if !exists("g:cmake_c_compiler")
    let g:cmake_c_compiler = "clang"
  endif

  if !exists("g:cmake_build_dirs")
    let g:cmake_build_dirs = [ "build" ]
  endif

  if !exists("g:cmake_build_type")
    let g:cmake_build_type = "Debug"
  endif

  if !exists("g:cmake_install_prefix")
    let g:cmake_install_prefix = "$HOME/.local"
  endif

  if !exists("g:cmake_build_shared_libs")
    let g:cmake_build_shared_libs = 1
  endif
endfunc

func s:init_commands()
  exe "command! -buffer -nargs=0 CMakeBuild :call cmake#commands#build()"
  exe "command! -buffer -nargs=0 CMakeInstall :call cmake#commands#install()"
  exe "command! -buffer -nargs=0 CMakeClean :call cmake#commands#install()"
  exe "command! -buffer -nargs=0 CMakeTest :call cmake#commands#test()"
  exe "command! -buffer -nargs=0 CMakeCreateBuild :call cmake#commands#create_build()"
  exe "command! -buffer -nargs=0 CMakeDeleteBuild :call cmake#commands#delete_build()"
endfunc

if !exists("b:cmake_loaded_plugin")
  let b:cmake_loaded_plugin
  call s:init_config()
  call s:init_commands()
endif


" We take care to preserve the user's fileencodings and fileformats,
" because those settings are global (not buffer local), yet we want
" to override them for loading Go files, which are defined to be UTF-8.
let s:current_fileformats = ''
let s:current_fileencodings = ''

" define fileencodings to open as utf-8 encoding even if it's ascii.
function! s:gofiletype_pre()
  let s:current_fileformats = &g:fileformats
  let s:current_fileencodings = &g:fileencodings
  set fileencodings=utf-8 fileformats=unix
  setlocal filetype=go
endfunction

" restore fileencodings as others
function! s:gofiletype_post()
  let &g:fileformats = s:current_fileformats
  let &g:fileencodings = s:current_fileencodings
endfunction

au BufNewFile *.go setlocal filetype=go fileencoding=utf-8 fileformat=unix
au BufRead *.go call s:gofiletype_pre()
au BufReadPost *.go call s:gofiletype_post()

Set .tmpl files' syntax to gohtmltmpl.

" We take care to preserve the user's fileencodings and fileformats,
" because those settings are global (not buffer local), yet we want
" to override them for loading Go files, which are defined to be UTF-8.
let s:current_fileformats = ''
let s:current_fileencodings = ''

" define fileencodings to open as utf-8 encoding even if it's ascii.
function! s:gofiletype_pre()
  let s:current_fileformats = &g:fileformats
  let s:current_fileencodings = &g:fileencodings
  set fileencodings=utf-8 fileformats=unix
  setlocal filetype=go
endfunction

" restore fileencodings as others
function! s:gofiletype_post()
  let &g:fileformats = s:current_fileformats
  let &g:fileencodings = s:current_fileencodings
endfunction

au BufNewFile *.go setlocal filetype=go fileencoding=utf-8 fileformat=unix
au BufRead *.go call s:gofiletype_pre()
au BufReadPost *.go call s:gofiletype_post()

au BufRead,BufNewFile *.tmpl set filetype=gohtmltmpl


" This loads after the yadr plugins so that plugin mappings can
" be overwritten.

if filereadable(expand("~/.yadr/vim/after/.vimrc.after"))
  source ~/.yadr/vim/after/.vimrc.after
endif

if filereadable(expand("~/.vimrc.after"))
  source ~/.vimrc.after
endif

" Track my after config
if filereadable(expand("~/.yadr/vim/after/vimrc_after.vim"))
  source ~/.yadr/vim/after/vimrc_after.vim
endif

Add cross on cursor on leader c

" This loads after the yadr plugins so that plugin mappings can
" be overwritten.

if filereadable(expand("~/.yadr/vim/after/.vimrc.after"))
  source ~/.yadr/vim/after/.vimrc.after
endif

if filereadable(expand("~/.vimrc.after"))
  source ~/.vimrc.after
endif

" Track my after config
if filereadable(expand("~/.yadr/vim/after/vimrc_after.vim"))
  source ~/.yadr/vim/after/vimrc_after.vim
endif

hi CursorLine   cterm=NONE ctermbg=235
hi CursorColumn cterm=NONE ctermbg=235
nnoremap <Leader>c :set cursorline! cursorcolumn!<CR>


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

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

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

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

function! javaunit#util#ExecCMD(cmd)
    call unite#start([['output/shellcmd', s:EscapeCMD(a:cmd)]], {'log': 1, 'wrap': 1})
endfunction

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

let &cpo = s:save_cpo
unlet s:save_cpo

Use normal mode for result

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

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

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

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

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

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

let &cpo = s:save_cpo
unlet s:save_cpo


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

" Ignore case when searching
set ignorecase

" Highlight search terms
set hlsearch

" Show search matches as you type
set incsearch

" Use Ack instead of grep
set grepprg=ack

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

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

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

nnoremap <leader>f :call SearchInProject()<CR>
nnoremap <leader>F :call SearchWordInProject()<CR>

Add ./ as an alias to Ag

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

" Ignore case when searching
set ignorecase

" Highlight search terms
set hlsearch

" Show search matches as you type
set incsearch

" Use Ack instead of grep
set grepprg=ack

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

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

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

nnoremap <leader>f :call SearchInProject()<CR>
nnoremap <leader>F :call SearchWordInProject()<CR>


set nocompatible
filetype off

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

" Make sure you use single quotes
" Plug 'ctrlpvim/ctrlp.vim'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'scrooloose/nerdtree'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'

Plug 'sheerun/vim-polyglot'
Plug 'andymass/vim-matchup'

Plug 'janko-m/vim-test'

" Initialize plugin system
call plug#end()

Add devicons for a more stylish nerdtree

set nocompatible
filetype off

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

" Make sure you use single quotes
Plug 'scrooloose/nerdtree'
Plug 'ryanoasis/vim-devicons'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'

Plug 'sheerun/vim-polyglot'
Plug 'andymass/vim-matchup'

Plug 'janko-m/vim-test'

" Initialize plugin system
call plug#end()


" 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

Add ballooneval to enable Ruby tooltips.

" 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

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


"============================================================================
"File:        zsh.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer:  Martin Grenfell <martin.grenfell at gmail dot com>
"License:     This program is free software. It comes without any warranty,
"             to the extent permitted by applicable law. You can redistribute
"             it and/or modify it under the terms of the Do What The Fuck You
"             Want To Public License, Version 2, as published by Sam Hocevar.
"             See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists("loaded_zsh_syntax_checker")
    finish
endif
let loaded_zsh_syntax_checker = 1

"bail if the user doesnt have zsh installed
if !executable("zsh")
    finish
endif

exec "runtime! syntax_checkers/sh.vim"

function! SyntaxCheckers_zsh_GetLocList()
    let makeprg = 'zsh -n ' . shellescape(expand('%'))
    let errorformat = '%f:%l: %m'
    return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat})
endfunction

Remove wrong call to runtime in wrong file

"============================================================================
"File:        zsh.vim
"Description: Syntax checking plugin for syntastic.vim
"Maintainer:  Martin Grenfell <martin.grenfell at gmail dot com>
"License:     This program is free software. It comes without any warranty,
"             to the extent permitted by applicable law. You can redistribute
"             it and/or modify it under the terms of the Do What The Fuck You
"             Want To Public License, Version 2, as published by Sam Hocevar.
"             See http://sam.zoy.org/wtfpl/COPYING for more details.
"
"============================================================================
if exists("loaded_zsh_syntax_checker")
    finish
endif
let loaded_zsh_syntax_checker = 1

"bail if the user doesnt have zsh installed
if !executable("zsh")
    finish
endif

function! SyntaxCheckers_zsh_GetLocList()
    let makeprg = 'zsh -n ' . shellescape(expand('%'))
    let errorformat = '%f:%l: %m'
    return SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat})
endfunction


" Plugin settings

nmap <leader>t :Files<CR>
nmap <leader><S-t> :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>
nmap <leader>n :SimplenoteList

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

Remove unused bindings and definitions


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

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

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

Remove custom Black formatting options

" Set up ALE (linting)
let g:airline#extensions#ale#enabled = 1
let g:ale_sign_column_always = 1
let g:ale_linters = {
\   'bash': ['shellcheck'],
\   'javascript': ['eslint'],
\   'html': ['alex'],
\   'mail': ['alex'],
\   'markdown': ['alex'],
\   'python': ['flake8', 'isort', '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
command F :Neoformat


if exists("b:current_syntax")
    finish
endif

syntax case match

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

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

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

syntax match paketDepsOption /\<on\>/

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

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

let b:current_syntax = "paketdeps"

Add syntax highlighting for framework versions

if exists("b:current_syntax")
    finish
endif

syntax case match

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

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

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

syntax match paketDepsOption /\<on\>/
syntax match paketDepsOption /\<net20\>/
syntax match paketDepsOption /\<net35\>/
syntax match paketDepsOption /\<net40\>/
syntax match paketDepsOption /\<net45\>/
syntax match paketDepsOption /\<net451\>/

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

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

let b:current_syntax = "paketdeps"


" ----------------------------------------------------------------------------
" Indentation
" ----------------------------------------------------------------------------
" Copy indent from current line when starting a new line
set autoindent

" Backspace deletes like most programs in insert mode
set backspace=indent,eol,start

" A <Tab> in front of a line inserts blanks according to 'shiftwidth'
set smarttab

" Tabs are spaces: shortcut for inserting 2 spaces
set expandtab

" Round indent to multiple of 'shiftwidth'
set shiftround

" Number of columns to use for text indenting
set shiftwidth=2

" Number of spaces in tab when editing
set softtabstop=2

" Number of visual spaces per TAB
set tabstop=2

" Fix code indentation
nnoremap <F7> mzgg=G`z

" Shortcut to rapidly toggle `set list`
nnoremap <Leader>l :set list!<CR>

" Display extra whitespace.
set list
set listchars=tab:»·,trail:·,nbsp:·

" Ident like most editors do.
" Note: In insert mode, you can just use Ctrl-t and Ctrl-d to indent/dedent.
nnoremap <TAB> >>
nnoremap <S-TAB> <<
vnoremap <TAB> >gv
vnoremap <S-TAB> <gv

Remove unneeded map to toggle `set list`

" ----------------------------------------------------------------------------
" Indentation
" ----------------------------------------------------------------------------
" Copy indent from current line when starting a new line
set autoindent

" Backspace deletes like most programs in insert mode
set backspace=indent,eol,start

" A <Tab> in front of a line inserts blanks according to 'shiftwidth'
set smarttab

" Tabs are spaces: shortcut for inserting 2 spaces
set expandtab

" Round indent to multiple of 'shiftwidth'
set shiftround

" Number of columns to use for text indenting
set shiftwidth=2

" Number of spaces in tab when editing
set softtabstop=2

" Number of visual spaces per TAB
set tabstop=2

" Fix code indentation
nnoremap <F7> mzgg=G`z

" Display extra whitespace.
set list
set listchars=tab:»·,trail:·,nbsp:·

" Ident like most editors do.
" Note: In insert mode, you can just use Ctrl-t and Ctrl-d to indent/dedent.
nnoremap <TAB> >>
nnoremap <S-TAB> <<
vnoremap <TAB> >gv
vnoremap <S-TAB> <gv


" Vim syntax file
" Language: Ansible hosts files
" Maintainer: Dave Honneffer <pearofducks@gmail.com>
" Last Change: 2015.09.23

if exists("b:current_syntax")
  finish
endif

syn case ignore
syn match hostsFirstWord      "\v^\S+"
syn match hostsAttributes     "\v\S*\="
syn region hostsHeader        start="^\s*\[" end="\]"
syn keyword hostsHeaderSpecials children vars containedin=hostsHeader contained
syn match  hostsComment       "^[#;].*$"

highlight link hostsFirstWord        Label
highlight link hostsHeader           Define
highlight link hostsComment          Comment
highlight link hostsHeaderSpecials   Identifier
highlight link hostsAttributes       Structure

if exists("g:ansible_attribute_highlight")
  if a:attributes =~ 'n'
    highlight link hostsAttributes NONE
  elseif a:attributes =~ 'd'
    highlight link hostsAttributes Comment
  endif
endif

let b:current_syntax = "ansible_hosts"

Align two regexes to standards

" Vim syntax file
" Language: Ansible hosts files
" Maintainer: Dave Honneffer <pearofducks@gmail.com>
" Last Change: 2015.09.23

if exists("b:current_syntax")
  finish
endif

syn case ignore
syn match hostsFirstWord      "\v^\S+"
syn match hostsAttributes     "\v\S*\="
syn region hostsHeader        start="\v^\s*\[" end="\v\]"
syn keyword hostsHeaderSpecials children vars containedin=hostsHeader contained
syn match  hostsComment       "\v^[#;].*$"

highlight link hostsFirstWord        Label
highlight link hostsHeader           Define
highlight link hostsComment          Comment
highlight link hostsHeaderSpecials   Identifier
highlight link hostsAttributes       Structure

if exists("g:ansible_attribute_highlight")
  if a:attributes =~ 'n'
    highlight link hostsAttributes NONE
  elseif a:attributes =~ 'd'
    highlight link hostsAttributes Comment
  endif
endif

let b:current_syntax = "ansible_hosts"


" Description: Search Dash.app from vim
" Author: Zeh Rizzatti <zehrizzatti@gmail.com>
" License: MIT

let s:save_cpoptions = &cpoptions
set cpoptions&vim

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

function! dash#check_app_presence()
  if exists('s:dash_present')
    return s:dash_present
  endif
  let script = s:script
  call system(script)
  let s:dash_present = v:shell_error
endfunction

function! dash#run(word, bang)
  if !dash#check_app_presence()
    redraw
    echohl WarningMsg
    echomsg 'dash.vim: Dash.app does not seem to be installed.'
    echohl None
    return
  endif
  call dash#search(a:word, a:bang ==# '!' ? 1 : 0)
endfunction

function! dash#search(word, global)
  let filetype = ''
  if !a:global
    let filetype = &filetype . ':'
  endif
  silent execute '!open dash://' . filetype . a:word
endfunction

let &cpoptions = s:save_cpoptions
unlet s:save_cpoptions

Fix error on 1st attempt to run Dash

" Description: Search Dash.app from vim
" Author: Zeh Rizzatti <zehrizzatti@gmail.com>
" License: MIT

let s:save_cpoptions = &cpoptions
set cpoptions&vim

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

function! dash#check_app_presence()
  if exists('s:dash_present')
    return s:dash_present
  endif
  let script = s:script
  call system(script)
  let s:dash_present = v:shell_error
  return s:dash_present
endfunction

function! dash#run(word, bang)
  if !dash#check_app_presence()
    redraw
    echohl WarningMsg
    echomsg 'dash.vim: Dash.app does not seem to be installed.'
    echohl None
    return
  endif
  call dash#search(a:word, a:bang ==# '!' ? 1 : 0)
endfunction

function! dash#search(word, global)
  let filetype = ''
  if !a:global
    let filetype = &filetype . ':'
  endif
  silent execute '!open dash://' . filetype . a:word
endfunction

let &cpoptions = s:save_cpoptions
unlet s:save_cpoptions


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

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

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

au FileType tagbar,nerdtree setlocal signcolumn=no

au FileType yaml setlocal ts=2 sw=2 expandtab

"autocmd FileType php LanguageClientStart

Set vim indent in HTML to 2 spaces

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

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

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

au FileType tagbar,nerdtree setlocal signcolumn=no

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


" set default key/cmd mapping
let g:ctrlp_map = '<C-o>'
let g:ctrlp_cmd = 'CtrlP'

" set the local working dir
"     r = nearest repo
"     a = shorter of CWD or dir of current file
let g:ctrlp_working_path_mode = 'ra'

" ignore temp and binary files
set wildignore +=*/tmp/*,*.so,*.swp,*.zip,*.class
set wildignore +=*\\tmp\\*,*.zip,*.exe

" ignore gitignore files
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']

" typing delay in miliseconds before update
let g:ctrlp_lazy_update = 100

" set windows position, list order, size, and limit results
let g:ctrlp_match_window = 'top,order:ttb,min:15,max:15,results:15'

" enable regexp search
let g:ctrlp_regexp = 1

" include .* files and dirs
let g:ctrlp_show_hidden = 1

" open file in current window
let g:ctrlp_open_new_file = 'r'

" open file in current window
let g:ctrlp_open_multiple_files = '1r'

" limit total files to search; increase for large projects
let g:ctrlp_max_files = 10000

Use <C-Space> to exit Vim CtrlP

" set default key/cmd mapping
let g:ctrlp_map = '<C-o>'
let g:ctrlp_cmd = 'CtrlP'

" set the local working dir
"     r = nearest repo
"     a = shorter of CWD or dir of current file
let g:ctrlp_working_path_mode = 'ra'

" ignore temp and binary files
set wildignore +=*/tmp/*,*.so,*.swp,*.zip,*.class
set wildignore +=*\\tmp\\*,*.zip,*.exe

" ignore gitignore files
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']

" typing delay in miliseconds before update
let g:ctrlp_lazy_update = 100

" set windows position, list order, size, and limit results
let g:ctrlp_match_window = 'top,order:ttb,min:15,max:15,results:15'

" enable regexp search
let g:ctrlp_regexp = 1

" include .* files and dirs
let g:ctrlp_show_hidden = 1

" open file in current window
let g:ctrlp_open_new_file = 'r'

" open file in current window
let g:ctrlp_open_multiple_files = '1r'

" limit total files to search; increase for large projects
let g:ctrlp_max_files = 10000

" update keymapping to match <C-space> as ESC
let g:ctrlp_prompt_mappings = { 'PrtExit()' : ['<bs>', '<c-[>', '<C-Space>'] }


" Bindings for Unite.vim.

nnoremap <leader>b :<C-U>Unite -no-split -buffer-name=buffer
  \ -start-insert buffer<CR>
nnoremap <leader>e :<C-U>Unite -no-split -buffer-name=files
  \ -start-insert file<CR>
nnoremap <leader>f :<C-U>Unite -no-split -buffer-name=files
  \ -start-insert file_rec/async:!<CR>
nnoremap <leader>y :<C-U>Unite -no-split -buffer-name=yank
  \ history/yank<CR>

Add mapping for Unite grep.

" Bindings for Unite.vim.

nnoremap <leader>b :<C-U>Unite -no-split -buffer-name=buffer
  \ -start-insert buffer<CR>
nnoremap <leader>e :<C-U>Unite -no-split -buffer-name=files
  \ -start-insert file<CR>
nnoremap <leader>f :<C-U>Unite -no-split -buffer-name=files
  \ -start-insert file_rec/async:!<CR>
nnoremap <leader>y :<C-U>Unite -no-split -buffer-name=yank
  \ history/yank<CR>
nnoremap <leader>a :<C-U>Unite grep:.<CR>


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

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

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

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

Add command to find the jshintrc

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

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

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

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


let g:deoplete#enable_at_startup = 1

let g:deoplete#sources = {}
let g:deoplete#sources._=['buffer', 'ultisnips', 'file', 'dictionary']
let g:deoplete#sources.clojure=['async_clj', 'file']

command! AsyncCljDebug call deoplete#custom#set('async_clj', 'debug_enabled', 1) | call deoplete#enable_logging("DEBUG", "/tmp/deopletelog")

Add ultisnips and dictionary to deopletion

let g:deoplete#enable_at_startup = 1

let g:deoplete#sources = {}
let g:deoplete#sources._=['buffer', 'ultisnips', 'file', 'dictionary']
let g:deoplete#sources.clojure=['async_clj', 'file', 'ultisnips', 'dictionary']

command! AsyncCljDebug call deoplete#custom#set('async_clj', 'debug_enabled', 1) | call deoplete#enable_logging("DEBUG", "/tmp/deopletelog")


let g:langserver_configuration = {
      \ 'json_rpc_version': "2.0",
      \ }

" Open a text document, and alert the language server
command! LSPOpen call langserver#didOpenTextDocument()

Add some commands and a mapping

let g:langserver_configuration = {
      \ 'json_rpc_version': "2.0",
      \ }

" Start the language server
command! LSPStart call langserver#start({})

" Open a text document, and alert the language server
command! LSPOpen call langserver#didOpenTextDocument()

nnoremap <leader>gd :call langserver#goto#request(langserver#util#get_lsp_id())<CR>


NeoBundleLazy 'moll/vim-node', {
  \   'autoload': {
  \     'filetypes': [
  \       'coffee',
  \       'coffeescript',
  \       'javascript',
  \       'less'
  \     ]
  \   }
  \ }

Fix gf in JavaScript files

NeoBundle 'moll/vim-node'

" For some reason lazily loading this breaks gf
"
" NeoBundleLazy 'moll/vim-node', {
"   \   'autoload': {
"   \     'filetypes': [
"   \       'coffee',
"   \       'coffeescript',
"   \       'javascript',
"   \       'less'
"   \     ]
"   \   }
"   \ }


Plugin 'tpope/vim-sensible'
Plugin 'tpope/vim-fugitive'
Plugin 'ervandew/supertab'
Plugin 'scrooloose/nerdtree'
Plugin 'vim-scripts/gitignore'
Plugin 'vim-scripts/showtrailingwhitespace'
Plugin 'vim-scripts/deletetrailingwhitespace'

Plugin 'altercation/vim-colors-solarized'
Plugin 'tomasr/molokai'

Move vim-fugitive and nerdtree down.

Plugin 'tpope/vim-sensible'
Plugin 'ervandew/supertab'
Plugin 'vim-scripts/gitignore'
Plugin 'vim-scripts/showtrailingwhitespace'
Plugin 'vim-scripts/deletetrailingwhitespace'

Plugin 'scrooloose/nerdtree'
Plugin 'tpope/vim-fugitive'

Plugin 'altercation/vim-colors-solarized'
Plugin 'tomasr/molokai'


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

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

" Ack requires ack command
if executable("ack")
  " use default config
elseif executable("ack-grep")
  let g:ackprg="ack-grep -H --nocolor --nogroup --column"
else
  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

" Tagbar requires ctags
if !executable("ctags")
  call janus#disable_plugin("tagbar", "The ctags 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

Support The Silver Searcher (ag) as ack replacement

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

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

" Ack requires ack command
if executable("ack")
  " use default config
elseif executable("ack-grep")
  let g:ackprg="ack-grep -H --nocolor --nogroup --column"
elseif executable("ag")
  let g:ackprg="ag --nocolor --nogroup --column"
else
  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

" Tagbar requires ctags
if !executable("ctags")
  call janus#disable_plugin("tagbar", "The ctags 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


function! insert#InsertAtLineEnd(text) abort
	call setline('.', getline('.') . a:text)
endfunction

Put cursor in desired location.

function! insert#InsertAtLineEnd(text) abort
	call setline('.', getline('.') . a:text)
	call cursor(getcurpos()[1], 999)
endfunction


" Small default height for CommandT
let g:CommandTMaxHeight=20
let g:CommandTMaxFiles=20000

" Make ESC work in CommandT while in terminal Vim
if &term =~ "xterm" || &term =~ "screen"
  let g:CommandTCancelMap=['<ESC>']
end

Increase files limit (website monorepo!)

" Small default height for CommandT
let g:CommandTMaxHeight=20
let g:CommandTMaxFiles=60000

" Make ESC work in CommandT while in terminal Vim
if &term =~ "xterm" || &term =~ "screen"
  let g:CommandTCancelMap=['<ESC>']
end


runtime! syntax/markdown.vim
unlet! b:current_syntax

" Metadata
syntax region apibMarkdownMetadata start=/\%^.*:.*$/ end=/^$/ contains=apibMarkdownMetadataKey,apibMarkdownMetadataValue fold
syntax match apibMarkdownMetadataKey /^[^:]*\ze:/ contained
syntax match apibMarkdownMetadataValue /:.*/ contained

highlight link apibMarkdownMetadataKey Function

syntax region apibRequestSection start=/^+ Request (.*)$/ end=/$/ oneline
highlight link apibRequestSection Function

syntax region apibResponseSection start=/^+ Response \d\d\d (.*)$/ end=/$/ oneline
highlight link apibResponseSection Function

syntax region apibHeadersSection start=/^+ Headers$/ end=/^\S.*$/ contains=apibHeadersSectionKey,apibHeadersSectionValue
syntax match apibHeadersSectionKey /^[^:]*\ze:/ contained
syntax match apibHeadersSectionValue /:.*/ contained
highlight link apibHeadersSectionKey Function

let b:current_syntax = 'apiblueprint'

Improve matching of Request and Response blocks

runtime! syntax/markdown.vim
unlet! b:current_syntax

" Metadata
syntax region apibMarkdownMetadata start=/\%^.*:.*$/ end=/^$/ contains=apibMarkdownMetadataKey,apibMarkdownMetadataValue fold
syntax match apibMarkdownMetadataKey /^[^:]*\ze:/ contained
syntax match apibMarkdownMetadataValue /:.*/ contained

highlight link apibMarkdownMetadataKey Function

syntax region apibRequestSection start=/^+ Request/ end=/$/ oneline
highlight link apibRequestSection Function

syntax region apibResponseSection start=/^+ Response \d\d\d \(.*\)$/ end=/$/ oneline
highlight link apibResponseSection Function

syntax region apibHeadersSection start=/^+ Headers$/ end=/^\S.*$/ contains=apibHeadersSectionKey,apibHeadersSectionValue
syntax match apibHeadersSectionKey /^[^:]*\ze:/ contained
syntax match apibHeadersSectionValue /:.*/ contained
highlight link apibHeadersSectionKey Function

let b:current_syntax = 'apiblueprint'


filetype off

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

Bundle 'gmarik/Vundle.vim'
Bundle 'tpope/vim-markdown'
Bundle 'Valloric/YouCompleteMe'
Bundle 'Valloric/MatchTagAlways'
Bundle 'groenewege/vim-less'
Bundle 'Lokaltog/vim-powerline'
Bundle 'altercation/vim-colors-solarized'
Bundle 'airblade/vim-gitgutter'
Bundle 'tpope/vim-fugitive'
Bundle 'derekwyatt/vim-scala'
Bundle 'vim-scripts/Vim-R-plugin'
Bundle 'scrooloose/syntastic'
Bundle 'kien/ctrlp.vim'
Bundle 'scrooloose/nerdtree'
Bundle 'jistr/vim-nerdtree-tabs'
Bundle 'majutsushi/tagbar'
Bundle 'techlivezheng/vim-plugin-minibufexpl'

" Restore
filetype on

Update to development version of Vim-R-plugin

filetype off

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

Bundle 'gmarik/Vundle.vim'
Bundle 'tpope/vim-markdown'
Bundle 'Valloric/YouCompleteMe'
Bundle 'Valloric/MatchTagAlways'
Bundle 'groenewege/vim-less'
Bundle 'Lokaltog/vim-powerline'
Bundle 'altercation/vim-colors-solarized'
Bundle 'airblade/vim-gitgutter'
Bundle 'tpope/vim-fugitive'
Bundle 'derekwyatt/vim-scala'
Bundle 'jcfaria/Vim-R-plugin'
Bundle 'scrooloose/syntastic'
Bundle 'kien/ctrlp.vim'
Bundle 'scrooloose/nerdtree'
Bundle 'jistr/vim-nerdtree-tabs'
Bundle 'majutsushi/tagbar'
Bundle 'techlivezheng/vim-plugin-minibufexpl'

" Restore
filetype on


"==============================================================
"          Initial Configuration                            {{{
"==============================================================

if has('unix')
  let $LANG = 'C'
else
  let $LANG = 'en'
endif
execute 'language ' $LANG
execute 'set langmenu='.$LANG
" Encode Settings
set encoding=utf-8
set fileencodings=ucs-bom,utf-8,euc-jp,iso-2022-jp,cp932,sjis
set fileformats=unix,dos,mac
scriptencoding utf-8

let mapleader = "\<Space>"
let maplocalleader = "\\"

" }}}

Fix bug that binary value will change

"==============================================================
"          Initial Configuration                            {{{
"==============================================================

if has('unix')
  let $LANG = 'C'
else
  let $LANG = 'en'
endif
execute 'language ' $LANG
execute 'set langmenu='.$LANG
" Encode Settings
set encoding=utf-8
set fileencodings=ucs-bom,utf-8,euc-jp,iso-2022-jp,cp932,sjis,latin1
set fileformats=unix,dos,mac
scriptencoding utf-8

let mapleader = "\<Space>"
let maplocalleader = "\\"

" }}}


" ----------------------------------------------------------------------------
" Searching
" ----------------------------------------------------------------------------
" Vim only remembers the last 20 commands and search patterns entered. Let's
" boost this up.
set history=50

" Highlight matches
set hlsearch

" Search as characters are entered
set incsearch

" Turn off search highlight
map <silent> <Leader>qs <Esc> :nohlsearch<CR>

" Look for files under current directory
map <C-p> :FZF<CR>

" Use the Silver Searcher
if executable('ag')
  " Use ag over grep.
  " Output the line and column number of each match, so that we can navigate
  " results by jumping to the precise position of each match.
  " Bind K to grep word under cursor
  nnoremap K :grep! "\b<C-R><C-W>\b"<CR>:cw<CR>
  set grepprg=ag\ --nogroup\ --nocolor\ --ignore-case\ --column
  set grepformat=%f:%l:%c:%m,%f:%l:%m

  " Set Ag to search for the provided text and open a 'quickfix' window
  command! -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!

  " Bind \ (backward slash) to grep shortcut
  nnoremap \ :Ag<Space>
endif

Set grep command despite the existence of Ag

" ----------------------------------------------------------------------------
" Searching
" ----------------------------------------------------------------------------
" Vim only remembers the last 20 commands and search patterns entered. Let's
" boost this up.
set history=50

" Highlight matches
set hlsearch

" Search as characters are entered
set incsearch

" Turn off search highlight
map <silent> <Leader>qs <Esc> :nohlsearch<CR>

" Look for files under current directory
map <C-p> :FZF<CR>

" Use the Silver Searcher
if executable('ag')
  " Use ag over grep.
  " Output the line and column number of each match, so that we can navigate
  " results by jumping to the precise position of each match.
  set grepprg=ag\ --nogroup\ --nocolor\ --ignore-case\ --column
  set grepformat=%f:%l:%c:%m,%f:%l:%m

  " Set Ag to search for the provided text and open a 'quickfix' window
  command! -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!

  " Bind \ (backward slash) to grep shortcut
  nnoremap \ :Ag<Space>
endif

" Bind K to grep word under cursor
nnoremap K :grep! "\b<C-R><C-W>\b"<CR>:cw<CR>


" [ ] becomes [x], [x] becomes [ ], nothing gets [ ] at start
function! ToggleTodo()
  s/\[ \]/\[bbb\]/e
  s/\[x\]/\[ \]/e
  s/\[bbb\]/\[x\]/e
	s/^\(\s*\)\([^\[ ]\)/\1[ ] \2/e
endfunction

function! ToggleTodoToday()
  s/\([^ ][^\*]\)$/\1 bbb/e
  s/ \*$//e
  s/bbb$/*/e
endfunction

" CopyMode
function! CopyModeToggle()
  if &number
    set nonumber
    set norelativenumber
  else
    set number
    set relativenumber
  endif
endfunction

" Clear whitespace at end of line
function! ClearExtraWhitespace()
  %s/  *$//gc
endfunction

Make ClearExtraWhitespace run without user input

" [ ] becomes [x], [x] becomes [ ], nothing gets [ ] at start
function! ToggleTodo()
  s/\[ \]/\[bbb\]/e
  s/\[x\]/\[ \]/e
  s/\[bbb\]/\[x\]/e
	s/^\(\s*\)\([^\[ ]\)/\1[ ] \2/e
endfunction

function! ToggleTodoToday()
  s/\([^ ][^\*]\)$/\1 bbb/e
  s/ \*$//e
  s/bbb$/*/e
endfunction

" CopyMode
function! CopyModeToggle()
  if &number
    set nonumber
    set norelativenumber
  else
    set number
    set relativenumber
  endif
endfunction

" Clear whitespace at end of line
function! ClearExtraWhitespace()
  %s/  *$//g
endfunction


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

function! vimtex#kpsewhich#find(file) abort " {{{1
  execute 'lcd' fnameescape(b:vimtex.root)
  let l:output = split(system('kpsewhich "' . a:file . '"'), '\n')
  lcd -

  if empty(l:output) | return '' | endif
  let l:filename = l:output[0]

  " If path is already absolute, return it
  return l:filename[0] ==# '/'
        \ ? l:filename
        \ : simplify(b:vimtex.root . '/' . l:filename)
endfunction

" }}}1
function! vimtex#kpsewhich#run(args) abort " {{{1
  execute 'lcd' fnameescape(b:vimtex.root)
  let l:output = split(system('kpsewhich ' . a:args), '\n')
  lcd -

  return l:output
endfunction

" }}}1

Fix issue with inconsistent CWD

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

function! vimtex#kpsewhich#find(file) abort " {{{1
  let l:output = vimtex#kpsewhich#run(fnameescape(a:file))

  if empty(l:output) | return '' | endif
  let l:filename = l:output[0]

  " If path is already absolute, return it
  return l:filename[0] ==# '/'
        \ ? l:filename
        \ : simplify(b:vimtex.root . '/' . l:filename)
endfunction

" }}}1
function! vimtex#kpsewhich#run(args) abort " {{{1
  " Ensure that we run kpsewhich at the project root directory
  let l:cwd = getcwd()
  let l:change_dir = l:cwd !=# b:vimtex.root
  if l:change_dir
    execute 'lcd' fnameescape(b:vimtex.root)
  endif

  let l:output = split(system('kpsewhich ' . a:args), '\n')

  " Restore local CWD
  if l:change_dir
    execute 'lcd' l:cwd
  endif

  return l:output
endfunction

" }}}1


" after

nnoremap <leader>nn :NERDTreeToggle<CR>
nnoremap \ :NERDTreeToggle<CR>

" Window Splitting
nmap <silent> <leader>hs :split<CR>
nmap <silent> <leader>vs :vsplit<CR>
nmap <silent> <leader>sc :close<CR>
" }}}

map <leader><space> :Vipe <CR>

" Switch between test and production code {{{
nnoremap <leader>. :A<cr>
" }}}

" Common typos {{{
command! W w
command! Q q
command! WQ wq
command! Wq wq
command! Qall qall
" }}}

" If you want to start window resize mode by `Ctrl+W`
let g:winresizer_start_key = '<C-E>'

Remove trailing spaces on save

" after

nnoremap <leader>nn :NERDTreeToggle<CR>
nnoremap \ :NERDTreeToggle<CR>

" Window Splitting
nmap <silent> <leader>hs :split<CR>
nmap <silent> <leader>vs :vsplit<CR>
nmap <silent> <leader>sc :close<CR>
" }}}

map <leader><space> :Vipe <CR>

" Switch between test and production code {{{
nnoremap <leader>. :A<cr>
" }}}

" Common typos {{{
command! W w
command! Q q
command! WQ wq
command! Wq wq
command! Qall qall
" }}}

" If you want to start window resize mode by `Ctrl+W`
let g:winresizer_start_key = '<C-E>'

" Remove trailing spaces on save
autocmd BufWritePre * :%s/\s\+$//e


if ! exists(':ALEInfo')
  finish
endif

let g:ale_set_signs = 0

let g:ale_linters = {
      \ 'python': 'all',
      \ 'java': [],
      \ }

Disable scala linting via ALE

if ! exists(':ALEInfo')
  finish
endif

let g:ale_set_signs = 0

let g:ale_linters = {
      \ 'python': 'all',
      \ 'scala' [],
      \ 'java': [],
      \ }


" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

setlocal shiftwidth=2
setlocal softtabstop=2
setlocal expandtab
setlocal formatoptions=tcqr

" Higlight the 80's line
"setlocal colorcolumn=80

" Operator notation: transforms a.b(c) to a b c
nmap <buffer> <leader>s. f.r<space>f(ds(i <esc>

Add mapping for triple quotes

" Only do this when not done yet for this buffer
if exists("b:did_ftplugin")
  finish
endif
let b:did_ftplugin = 1

setlocal shiftwidth=2
setlocal softtabstop=2
setlocal expandtab
setlocal formatoptions=tcqr

" Higlight the 80's line
"setlocal colorcolumn=80

" Operator notation: transforms a.b(c) to a b c
nmap <buffer> <leader>s. f.r<space>f(ds(i <esc>

" Triple quotes: transforms "abc" to """abc"""
"abc"
nmap <buffer> <leader>s" ysi""lysi""


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

function! tmuxcomplete#complete(findstart, base)
    if a:findstart
        let match = get(g:, 'tmux_complete_match', '\a')
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ match
            let start -= 1
        endwhile
        return start
    endif

    " find words matching with "a:base"
    let capture_args = get(g:, 'tmux_complete_capture_args', '-J')
    for completion in tmuxcomplete#completions(a:base, capture_args)
        call complete_add(completion)
    endfor
    return []
endfun

function! CompleteScript(findstart, base)
    return tmuxcomplete#complete(a:findstart, a:base)
endfun

set completefunc=CompleteScript

let &cpoptions = s:save_cpoptions
unlet s:save_cpoptions

Return matches as list instead of complete_add

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

function! tmuxcomplete#complete(findstart, base)
    if a:findstart
        let match = get(g:, 'tmux_complete_match', '\a')
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ match
            let start -= 1
        endwhile
        return start
    endif

    " find words matching with "a:base"
    let capture_args = get(g:, 'tmux_complete_capture_args', '-J')
    return tmuxcomplete#completions(a:base, capture_args)
endfun

function! CompleteScript(findstart, base)
    return tmuxcomplete#complete(a:findstart, a:base)
endfun

set completefunc=CompleteScript

let &cpoptions = s:save_cpoptions
unlet s:save_cpoptions


let mapleader=" "

inoremap jj <Esc>

" window management
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
nnoremap <C-h> <C-w>h

" buffers
nnoremap <silent> <TAB> :bnext<CR>
nnoremap <silent> <S-TAB> :bprevious<CR>

" tabbing
vnoremap < <gv
vnoremap > >gv

" move selection
vnoremap J :m '>+1<cr>gv=gv
vnoremap K :m '<-2<cr>gv=gv

" open file in external program
nnoremap gO :!open <cfile><CR>

Copy text selected with mouse

let mapleader=" "

inoremap jj <Esc>

" window management
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l
nnoremap <C-h> <C-w>h

" buffers
nnoremap <silent> <TAB> :bnext<CR>
nnoremap <silent> <S-TAB> :bprevious<CR>

" tabbing
vnoremap < <gv
vnoremap > >gv

" move selection
vnoremap J :m '>+1<cr>gv=gv
vnoremap K :m '<-2<cr>gv=gv

" open file in external program
nnoremap gO :!open <cfile><CR>

" copy text selected with mouse
vmap <LeftRelease> "*ygv


" Required for vim-latexsuite to work correctly
" Please install vim-latex from either AUR or manually

set grepprg=grep\ -nH\ $*
set runtimepath=~/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,~/.vim/after
set iskeyword+=:

let g:Tex_ViewRule_pdf = "evince"
let g:Tex_DefaultTargetFormat = 'pdf'
let g:Tex_MultipleCompileFormats='pdf, aux'

Fix issue caused by setting runtimepath

" Required for vim-latexsuite to work correctly
" Please install vim-latex from either AUR or manually

set grepprg=grep\ -nH\ $*
set iskeyword+=:

let g:Tex_ViewRule_pdf = "evince"
let g:Tex_DefaultTargetFormat = 'pdf'
let g:Tex_MultipleCompileFormats='pdf, aux'


colorscheme wal
highlight CursorLine ctermbg=5

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

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

Change cursor line in Neovim

colorscheme wal
highlight CursorLine ctermbg=7

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

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


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

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

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

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

let g:loaded_matchparen = 0

Remove cursor line text style

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

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

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

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

let g:loaded_matchparen = 0


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

let g:go_fmt_command = "goimports"

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

let g:go_template_autocreate = 0

compiler go

Add omnicomplete support in Go files

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

let g:go_fmt_command = "goimports"

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

let g:go_template_autocreate = 0

setlocal omnifunc=go#complete#Complete

inoremap <C-space> <C-x><C-o>

compiler go


" File type specific configurations
"
" Mostly consisting of Auto commands applied when matching files are opened

au BufRead,BufNewFile *.md        set filetype=markdown
au BufRead,BufNewFile *.raml      set filetype=yaml
au BufRead,BufNewFile Vagrantfile set filetype=ruby
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* set filetype=nginx

au BufRead,BufNewFile *.go set noexpandtab

Add syntax highlighting for react templates

" File type specific configurations
"
" Mostly consisting of Auto commands applied when matching files are opened

au BufRead,BufNewFile *.md        set filetype=markdown
au BufRead,BufNewFile *.rt        set filetype=html
au BufRead,BufNewFile *.raml      set filetype=yaml
au BufRead,BufNewFile Vagrantfile set filetype=ruby
au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* set filetype=nginx

au BufRead,BufNewFile *.go set noexpandtab