" set nocompatible              " be iMproved, required
filetype off                  " required
set ttyfast

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

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" plugin on GitHub repo
Plugin 'tpope/vim-fugitive'
" Nerdtree and nerdtree-git
Plugin 'scrooloose/nerdtree.git'
Plugin 'Xuyuanp/nerdtree-git-plugin'
"css3-syntax
Plugin 'hail2u/vim-css3-syntax.git'
"scss-syntax
Plugin 'cakebaker/scss-syntax.vim'
"bufexplorer
Plugin 'jlanzarotta/bufexplorer'
"tagbar
Plugin 'majutsushi/tagbar'
"vim-surround
Plugin 'tpope/vim-surround'
"undotree
Plugin 'mbbill/undotree'
" gutentag
"Plugin 'ludovicchabant/vim-gutentags'
" vim-project-tags
"dependancy needed:
"https://github.com/still-dreaming-1/vim-project-tags
Plugin 'still-dreaming-1/vim-elhiv'
Plugin 'still-dreaming-1/vim-project-tags'
" Ctrlp
Plugin 'ctrlpvim/ctrlp.vim'
" Obsession
Plugin 'tpope/vim-obsession'
" vim-css-color
Plugin 'ap/vim-css-color'
" vim-javascript-syntax
" Plugin 'jelera/vim-javascript-syntax'
" vim-javascript
Plugin 'pangloss/vim-javascript'
" vim-mucomplete
" https://github.com/lifepillar/vim-mucomplete
Plugin 'lifepillar/vim-mucomplete'
" ultisnips
" https://github.com/sirver/UltiSnips
Plugin 'SirVer/ultisnips'
" and some snippets
" https://github.com/honza/vim-snippets
Plugin 'honza/vim-snippets'
" ALE
" https://github.com/w0rp/ale
Plugin 'w0rp/ale'
" MatchTag
" https://github.com/gregsexton/MatchTag
Plugin 'gregsexton/MatchTag'
" phpcomplete.vim
" https://github.com/shawncplus/phpcomplete.vim
Plugin 'shawncplus/phpcomplete.vim'
" https://github.com/dsawardekar/wordpress.vim
" For up to date Wordpress Files see:
"   https://github.com/joseluis/wordpress.vim-generator
"Plugin 'dsawardekar/wordpress.vim'
" disabled - doesn't support universal ctags?
" vim-vue
" https://github.com/posva/vim-vue
Plugin 'posva/vim-vue'
" vim-commentary
" https://github.com/tpope/vim-commentary
Plugin 'tpope/vim-commentary'
" vim-repeat
" https://github.com/tpope/vim-repeat
Plugin 'tpope/vim-repeat'
" taboo.vim
" https://github.com/gcmt/taboo.vim
Plugin 'gcmt/taboo.vim'
" https://github.com/mattn/emmet-vim
Plugin 'mattn/emmet-vim'
" vimwiki
" https://github.com/vimwiki/vimwiki
Plugin 'vimwiki/vimwiki'

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

" let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
" let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
" set termguicolors
colorscheme customred256

set backupdir=~/.vimtmp
set directory=~/.vimtmp

" tags file set tags=tags;/

" ignore case when searching
set ignorecase
" unless search contains uppercase
set smartcase

set wildmenu
set wildmode=longest:full,full

" allow hidden buffers
set hidden

set background=dark
" set number
set number relativenumber
set hlsearch " highlight searches

set foldcolumn=1


" key mappings
let g:mapleader = "\<space>"

" jk acts as escape in insert
inoremap jk <esc>

nnoremap <leader>co :!clear; 

" disable arrow keys
"noremap <Up> <nop>
"noremap <Down> <nop>
"noremap <Left> <nop>
"noremap <Right> <nop>

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

" better window resizing
" need to use <Esc>j because urxvt sends the character prefixed with Escape
" instead of setting the eighth bit
" see https://unix.stackexchange.com/a/199705
nnoremap <Esc>j :resize +5<CR>
nnoremap <Esc>k :resize -5<CR>
nnoremap <Esc>l :vertical resize +5<CR>
nnoremap <Esc>h :vertical resize -5<CR>

"location list and quickfix mappings
nnoremap <leader>ll :botright lwindow<CR>
nnoremap <leader>lp :lprev<CR>
nnoremap <leader>ln :lnext<CR>
nnoremap <leader>lc :lclose<CR>
nnoremap <leader>llh :lhistory<CR>
nnoremap <leader>llp :lolder<CR>
nnoremap <leader>lln :lnewer<CR>

nnoremap <leader>qf :botright cwindow<CR>
nnoremap <leader>qp :cprev<CR>
nnoremap <leader>qn :cnext<CR>
nnoremap <leader>qc :cclose<CR>
nnoremap <leader>qfh :chistory<CR>
nnoremap <leader>qfp :colder<CR>
nnoremap <leader>qfn :cnewer<CR>

nnoremap <leader>nh :noh<CR>

" quick grep of visual selection
vnoremap <leader>gr y:grep! -R <C-r>" .

" open quickfix window of TODOs
nnoremap <leader>td :grep! -R '// *TODO' .<CR>:botright cwindow<CR>:echo len(getqflist()) 'TODOs'<CR>

" brace/quotes completion
inoremap {{     {}<left>
inoremap {{{     {<CR>}<esc>O
inoremap {{{;     {<CR>};<esc>O
inoremap }}			{{}}<Left><Left>
inoremap ((			()<Left>
inoremap ((;		();<Left><Left>
inoremap ""			""<Left>
inoremap "";		"";<Left><Left>
inoremap ''			''<Left>
inoremap '';		'';<Left><Left>
inoremap [[			[]<Left>
inoremap [[[			[<CR>]<esc>O

inoremap ;;     ;<esc>

nnoremap <leader>nn :set invrelativenumber<CR>
nnoremap <leader>hl :nohlsearch<CR>

" abbreviations
iabbrev adn and
iabbrev waht what
iabbrev tehn then

set iskeyword+=-
set scrolloff=10  " scroll offset
set showcmd  " show command in bottom bar
set incsearch


" statusline format
set statusline=%#LineNr#
set statusline+=\ \ \ 
set statusline+=%#StatusLineFile#
set statusline+=\ \ %t\ \   " filename
set statusline+=%*
set statusline+=%q     " quickfix/location list flag
set statusline+=%h     " help file flag
set statusline+=%w     " preview window flag
set statusline+=%m     " modified flag
set statusline+=%r     " read only flag
set statusline+=%#StatusLineNC#
set statusline+=\ 
set statusline+=%*
set statusline+=\ %{strlen(&ft)?&ft:'none'},     " filetype
set statusline+=%{strlen(&fenc)?&fenc:&enc},    " encoding
set statusline+=%{&fileformat}\ 
set statusline+=%#StatusLineNC#
set statusline+=\ 
set statusline+=%*
set statusline+=\ %{&spelllang}\ 
set statusline+=%#StatusLineNC#
set statusline+=\ 
set statusline+=%*

set statusline+=%=                              " left/right separator

set statusline+=%#StatusLineNC#
set statusline+=\ 
set statusline+=%*
set statusline+=\ %{v:register}\ 
set statusline+=%#StatusLineNC#
set statusline+=\ 
set statusline+=%*
set statusline+=\ %{ObsessionStatus(fnamemodify(v:this_session,':t'),'---')}\ " session status

set statusline+=%#InterfaceH2#
set statusline+=\ %{LinterStatus()}

set statusline+=%#InterfaceNormalDark#
set statusline+=\ %P\  " percentage through file
set statusline+=%*

set laststatus=2

set foldmethod=manual

set autoindent
set breakindent
set showbreak=↳

syntax on
set mouse=a

set listchars=eol:¬,tab:->,trail:~,extends:>,precedes:<,space:·

" rewrapping set to 80
set textwidth=180
" disable automatic wrapping
set formatoptions=cq
" disable wrapping based on terminal size
set wrapmargin=0

set t_Sf=<Esc>[3%p1%dm  " foreground colour
set t_Sb=<Esc>[4%p1%dm  " background coloru

nnoremap <F2> :set invpaste paste?<CR>
set pastetoggle=<F2>
set showmode

" set custom syntax highlighting
augroup syntaxhighlighting
  autocmd BufNewFile,BufRead *.html set syntax=html_custom
  autocmd BufNewFile,BufRead *.php set syntax=php_custom
  autocmd BufNewFile,BufRead *.vue set syntax=vue_custom
  autocmd BufNewFile,BufRead *.vue syntax sync fromstart
  autocmd BufNewFile,BufRead *.js set syntax=pangloss_javascript_custom
augroup END

" fix higlight problems such as vertical-align etc
augroup VimCSS3Syntax
  autocmd!
  autocmd FileType css setlocal iskeyword+=-
augroup END

" Show trailing whitepace and spaces before a tab:
augroup whitespaceerrors
  autocmd Syntax * syn match ExtraWhitespace /\s\+$\| \+\ze\t/ containedin=ALL 
augroup END 


" autocommands
" automatically reload if color scheme file written
augroup coloreload
  au!
	au BufWritePost customred256.vim so $MYVIMRC
augroup end

augroup linenumbering
  autocmd InsertEnter * :set norelativenumber
  autocmd InsertLeave * :set number relativenumber
  autocmd WinEnter * :set number relativenumber
  autocmd WinLeave * set norelativenumber
augroup END

augroup colorcolumns
  autocmd WinEnter * set colorcolumn=80
  autocmd WinLeave * set colorcolumn=0
augroup END

" Automatically reload .vimrc if chanaged
augroup myvimrc
    au!
    au BufWritePost .vimrc,_vimrc,vimrc,.gvimrc,_gvimrc,gvimrc so $MYVIMRC | if has('gui_running') | so $MYGVIMRC | endif
augroup END


" persisitent undo file
set undodir=/home/ray/.vim/undodir
set undofile

" Use the silver searcher ag command instead of grep
if executable('ag')
  " Use ag over grep
  set grepprg=ag\ --nogroup\ --nocolor

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

  " ag is fast enough that CtrlP doesn't need to cache
  let g:ctrlp_use_caching = 0
endif


" Functions

" get name of syntax item
function! SyntaxItem()
  return synIDattr(synID(line('.'),col('.'),1),'name') . ' -> ' . synIDattr(synIDtrans(synID(line('.'),col('.'),1)), 'name' )
endfunction
nnoremap <leader>p :echom SyntaxItem()<CR>



" plugin stuff

" emmet
let g:user_emmet_leader_key='<c-m>'

" taboo.vim
set sessionoptions+=tabpages,globals
let g:taboo_tab_format = ' %f%m ' 
let g:taboo_renamed_tab_format = ' %l%m '
let g:taboo_modified_tab_flag = '+'

" vue-vim
" disable preprocessor checking for vue files - increases speed
let g:vue_disable_pre_processors=1

" MUcomplete
set omnifunc=syntaxcomplete#Complete
set completeopt+=menuone
let g:mucomplete#enable_auto_at_startup = 1
inoremap <expr> <c-e> mucomplete#popup_exit("\<c-e>")
inoremap <expr> <c-y> mucomplete#popup_exit("\<c-y>")
inoremap <expr>  <cr> mucomplete#popup_exit("\<cr>")
set completeopt+=noselect
set completeopt+=noinsert

set complete-=i
set complete-=t
let g:mucomplete#chains = { 'default' : ['omni', 'tags', 'ulti', 'c-p', 'incl', 'file'] }
" let g:mucomplete#popup_direction = { 'path' : 1, 'c-p': 1, 'tags': 1, 'incl': 1 }
set shortmess+=c   " Shut off completion messages
set belloff+=ctrlg " If Vim beeps during completion
	
" call add(g:mucomplete#chains['default'], 'ulti') 

" ALE
nnoremap <leader>ne :lnext<cr>
nnoremap <leader>pe :lprev<cr>

let g:ale_sign_error = '>>'
let g:ale_sign_warning = '--'
let g:ale_sign_column_always = 1

let g:ale_linters = {'scss': ['stylelint'], 'javascript': ['eslint'], 'php':['php'], 'html':['htmlhint']}
let g:ale_html_htmlhint_options = '-c ~/.htmlhintrc --format=unix'
" let g:ale_javascript_eslint_options = '-c ~/.config/eslint/.eslintrc.js'
let g:ale_fixers = {'javascript': ['eslint']}

" function! ale#handlers#eslint#FindConfig(buffer)
"   return '/home/ray/.config/eslint/.eslintrc.js'
" endfunction



function! LinterStatus() abort
    let l:counts = ale#statusline#Count(bufnr(''))

    let l:all_errors = l:counts.error + l:counts.style_error
    let l:all_non_errors = l:counts.total - l:all_errors

    return l:counts.total == 0 ? 'OK' : printf('%dW %dE', l:all_non_errors, l:all_errors)
endfunction
"nmap <silent> <C-k> <Plug>(ale_previous_wrap)
"nmap <silent> <C-j> <Plug>(ale_next_wrap)

" ultisnips
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsExpandTrigger='<Esc><space>'
let g:UltiSnipsJumpForwardTrigger='<c-b>'
let g:UltiSnipsJumpBackwardTrigger='<c-z>'

" NERDtree
nnoremap <F3> :NERDTreeFocus<CR>
nnoremap <leader>nt :NERDTreeFocus<CR>
" allow closing if only window open is a NERDTree
augroup nerdtreewindow
  autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
augroup END
let NERDTreeQuitOnOpen = 1

" TagBar
nnoremap <leader>tb :TagbarOpen fj<CR>
let g:tagbar_autoclose = 1


" tagbar css/scss thingy
nnoremap <leader>] :tag /[.#@]<c-r>=expand('<cword>')<cr><cr>


" bufexploer
nnoremap <leader>o :BufExplorer<CR>

" undotree
nnoremap <leader>ut :UndotreeToggle<cr>

" vim-project-tags
source ~/.vim/bundle/vim-elhiv/elhiv.vim

" override function so we can have custom tag names for built in languages
" function! project_tags#add_built_in_language_support()
" 	call project_tags#add_language('.jstags', 'js')
" 	call project_tags#add_language('.vimtags', 'vim')
" 	call project_tags#add_language('.phptags', 'php')
" endfunction

" above function causes error (maybe autoloading problem when no
" tags are being used or whatever?)
" see if following three lines work instead
call project_tags#add_language('.jstags', 'js')
call project_tags#add_language('.vimtags', 'vim')
call project_tags#add_language('.phptags', 'php')

call project_tags#add_language('.csstags','css')
call project_tags#add_language('.scsstags','scss')

let g:tagbar_type_css = {
\  'ctagstype' : 'css',
\  'kinds' : [
\    'c:classes',
\    'i:ids',
\    't:tags',
\    'm:medias'
\  ]
\}

let g:tagbar_type_scss = {
\  'ctagstype' : 'scss',
\  'kinds' : [
\    'v:variables',
\    'c:classes',
\    'i:ids',
\    't:tags',
\    'd:medias',
\    'm:mixins',
\    'f:functions'
\  ]
\}

if !exists('*RangerExplorer')
	function RangerExplorer()
			exec 'silent !ranger --choosefile=/tmp/vim_ranger_current_file ' . expand('%:p:h')
			if filereadable('/tmp/vim_ranger_current_file')
					exec 'edit ' . system('cat /tmp/vim_ranger_current_file')
					call system('rm /tmp/vim_ranger_current_file')
			endif
			redraw!
	endfun
	map <Leader>ra :call RangerExplorer()<CR>
endif





" ze end