set fileencoding=utf-8 " Set utf-8 encoding on write
scriptencoding utf-8

""""""""""""""""""""""""""""""
" ~ VIMRC ~ for Vim >= 8 && Neovim
" Author: Chris Jones
" Source: http://github.com/ipatch/dotfiles/blob/master/editors/vim/vimrc
" Source: https://git.io/vpEKR
""

""""""""""""""""""""""""""""""
" Notes / gotchas - some good things to know before hacking `~/.vimrc`
" NOTE: this rc file is being linted with `vint`
" NOTE: https://github.com/Kuniwak/vint
" NOTE: To print the value of a setting, ie. return the set value
" `:set autoindent?`
" SEE: `~/.vim/after/ftplugin/vim.vim` for settings related to `.vim`
""

" set this first, the default `leader` key is `\`
let g:mapleader = "\<Space>" " bind 'leader' key to spacebar

" Don't allow vi compatibility mode; don't need it 🤽
" set nocompatible "Enable at own risk, can have undesired effects
" SEE: `:help nocompatible` for more info.
""

"""""""""""""""""""""""""""""
" NOTE: Settings - June 23 2018 moved to `~/.vim/plugin/settings.vim`
""

"""""""""""""""""""""""""""""
" Key mappings / bindings
" NOTE: mappings - June 23 2018 moved to `~/.vim/plugin/mappings.vim`
""

""""""""""""""""""""""""""""""
" check for current OS
" NOTE: `:echo os` to print the variable value in the current buffer
" NOTE: if (n)vim has access to both clipboards it will put copy / paste operations into both clipboards.
""
function! GetRunningOS()
  if has('win32')
    return 'win32'
  elseif has('win32unix')
    return 'win32unix'
  elseif has('macunix')
    if !empty($TMUX)
      " echom 'wtf'
      " let g:clipboard+=tmux
      set clipboard+=unnamed,unnamedplus
    else
      set clipboard+=unnamed,unnamedplus
      " pbcopy for macOS copy/paste
      " vmap <C-x> :!pbcopy<CR>
      " vmap <C-c> :w !pbcopy<CR><CR>
    endif
    set shell=bash
    set runtimepath+=/usr/local/opt/fzf
    return 'macos'
  elseif has ('unix')
    if system('uname')=~?'Linux'
      if !empty($TMUX)
        " TODO: figure out how to set clipboard properly through ssh
        " let g:clipboard+=tmux
        " set clipboard+=xsel
      else
        " set clipboard+=xsel
      endif 
      set shell=bash
      set runtimepath+=/home/linuxbrew/.linuxbrew/bin/fzf
      return 'linux'
    endif
  else
    " catch all 🎣 for everything else
    " No love 💔 for the other guys
  endif
endfunction
let g:os = GetRunningOS()

function! SetupCommandAlias(from, to)
  " NOTE: useful for aliasing `PackUpdate` to `packupdate` etc...
  exec 'cnoreabbrev <expr> '.a:from
        \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
        \ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfunction

""""""""""""""""""""""""""""""
" colorscheme
""
" NOTE: make scope explicit, ie. `let g:[mr-fancy-setting]` NOT `let
" [mr-fancy-setting`
let g:base16colorspace = 256 " Access colors present in 256 colorspace
colorscheme base16-default-dark

""""""""""""""""""""""""""""""
" fonts
""
highlight Comment gui=italic
highlight Comment cterm=italic
let &t_8f="\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b="\<Esc>[48;2;%lu;%lu;%lum"
set termguicolors " use guifg/guibg instead of ctermfg/ctermbg in terminal

"""""""""""""""""""""""""""""
" conceal levels
" toggle between different conceal levels
" NOTE: `indentLine` will control conceal levels if installed
""
function! ToggleConcealLevel()
  if &conceallevel == 0
    setlocal conceallevel=2
  elseif &conceallevel == 1
    setlocal conceallevel=0
  elseif &conceallevel == 2
    setlocal conceallevel=0
  endif
endfunction

nnoremap <silent> ` :call ToggleConcealLevel()<CR>

" set default conceal level
set conceallevel=0 " DO NOT conceal any text

"""""""""""""""""""""""""""""
" netrw - file explorer
" CREDIT: https://shapeshed.com/vim-netrw/   
""

let g:netrw_liststyle = 3 " tree style
let g:netrw_banner = 0 " Do not display the banner when using Netrw
let g:netrw_browse_split = 1 " TODO: figure out what this variable does ???
let g:netrw_winsize = 25 " set the default width for netrw
" TODO: document what the below variable does to netrw
let g:netrw_altv = 1
" Set atom style macOS key binding to open the project drawer
" CREDIT: https://stackoverflow.com/a/23069285/708807
" NOTE: toggling netrw sucks!
" TODO: get a sane toggle expierence going ...eventually!
nnoremap <M-\> :Lexplore<cr>
inoremap <M-\> :Lexplore<cr>
" OPTIONAL: keep netrw browsing dir the same as current dir
" `let g:netrw-keepdir = 0`

" https://vi.stackexchange.com/a/13012
" Per default, netrw leaves unmodified buffers open. This autocommand
" deletes netrw's buffer once it's hidden (using `:q`, for example)
augroup netrw_delete_hidden_augroup
  autocmd!
  autocmd FileType netrw setl bufhidden=delete
augroup END

"----------------------------
" Autocommands relocated to `~/.vim/plugin/autocmds.vim`
""

"----------------------------
" wildmenu -  completion
"-
if has('wildmenu')
  set wildmenu " display menu when using `tab` completeion
  set wildmode=full " Specifies how the `tab` completion works in wildmenu
  set wildignore=*.o,*.obj,*~ "stuff to ignore when tab completing
  set wildignore+=*/.git/* " ignore the below directories with wild menu
  set wildignore+=*logs*
  set wildignore+=*node_modules/**
  set wildignore+=package-lock.json
  set wildignore+=yarn.lock
  set wildignore+=*DS_Store*
  set wildignore+=*.gem
  set wildignore+=log/**
  set wildignore+=_build/**
  set wildignore+=*.bmp,*.gif,*.ico,*.jpg,*.png,*.pdf,*.psd,session.vim
  set wildignore+=tags
endif

" NOTE: clone minpac first before installing plugins.
set packpath^=~/.vim
" Try to load minpac.
silent! packadd minpac

function! BuildStaticVimMarkdownComposer()
  " if a:info.status != 'unchanged' || a:info.force
    if has('nvim')
      !(cd '/opt/code/dotfiles/editors/vim/vim/pack/minpac/start/vim-markdown-composer'; cargo +nightly build --release)
      " !cargo build --release
    elseif v:version > 8 || v:version == 8 " Check for Vim8 ...sort of
      !(cd '/opt/code/dotfiles/editors/vim/vim/pack/minpac/start_vim8/vim-markdown-composer';cargo build --release --no-default-features --features json-rpc)
      " Explicity set path for Vim8 build of vim-markdown-composer
      set runtimepath+=/opt/code/dotfiles/editors/vim/vim/pack/minpac/start_vim8/vim-markdown-composer
      set runtimepath-=/opt/code/dotfiles/editors/vim/vim/pack/minpac/start/vim-markdown-composer
    endif
endfunction

function! FixupBase16()
  !(sed -i '/Base16hi/\! s/a:\(attr\|guisp\)/l:\1/g' /opt/code/dotfiles/editors/vim/vim/pack/minpac/start/base16-vim/colors/*.vim)
endfunction

let g:ale_completion_enabled = 1

if !exists('*minpac#init')
  " minpac is NOT available
  echo 'Yo!, you need minpac dawg!'
  " Settings for plugin-less, ie. no minpac 😥 environment.
  if empty(glob('~/.vim/pack/minpac/opt/minpac/plugin/minpac.vim'))
    silent !curl -fLo ~/.vim/pack/minpac/opt/minpac/plugin/minpac.vim
          \--create-dirs
          \https://raw.githubusercontent.com/k-takata/minpac/master/plugin/minpac.vim 
   autocmd VimEnter * packadd minpac
   call minpac#init()
   call minpac#add('k-takata/minpac', {'type': 'opt'})
  endif
else
  call minpac#init()
  call minpac#add('k-takata/minpac', {'type': 'opt'})

  "-----------------------------
  " Load additional plugins
  "-
  call minpac#add('machakann/vim-highlightedyank') " name says it all
  call minpac#add('chriskempson/base16-vim') " UX goodness
  call minpac#add('Yggdroot/indentLine') " vert indent lines
  " call minpac#add('MaxMEllon/vim-jsx-pretty') " syntax highlight
  call minpac#add('tpope/vim-commentary') " quickly comment lines
  call minpac#add('sheerun/vim-polyglot') " lazy load syntax hl
  call minpac#add('christoomey/vim-tmux-navigator') " vim&tmux navi
  call minpac#add('w0rp/ale') " Asynchronous Linting Engine
  call minpac#add('tpope/vim-fugitive') " display git branch
  call minpac#add('itchyny/lightline.vim') " lightweight status line.
  call minpac#add('rust-lang/rust.vim')
  call minpac#add('euclio/vim-markdown-composer', {'type': 'opt'})
  " call minpac#add('tpope/vim-obsession') " auto session mgmt

  "-----------------------------
  " minpac - conditional plugins
  "---------------------------------------------------------------
  " neovim only plugins!!!
  "---------------------------------------------------------------
  ""
  if has('nvim')
    call minpac#add('Shougo/denite.nvim')
    " call minpac#add('Shougo/denite.nvim', {'rev': '29bfd4c53271c7a150def2388e059746ae4c1713'})
    " call minpac#add('neoclide/coc.nvim', {'do': function('CocBuildUpdate')}) " code completion
    call minpac#add('neoclide/coc.nvim')
  elseif v:version > 8 || v:version == 8 " Check for Vim8 ...sort of
    call minpac#add('autozimu/LanguageClient-neovim', {'type': 'opt',
          \'branch': 'next', 'do': {-> system('bash install.sh')}})
  endif
  
  "----------------------------
  " minpac - Custom commands
  "-
  command! PackUpdate packadd minpac | source $MYVIMRC | call minpac#update('', {'do': 'call minpac#status()'})
  command! PackClean  packadd minpac | source $MYVIMRC | call minpac#clean()
  command! PackList echo join(minpac#getpackages("minpac", "start"), "\n")
  command! PackStatus packadd minpac | source $MYVIMRC | call minpac#status()

  call SetupCommandAlias("packupdate", "PackUpdate")
  call SetupCommandAlias("packclean", "PackClean")
endif

"----------------------------
" DANGER ZONE > experimental settings
"-

" Setting for rust.vim
let g:autofmt_autosave = 1

"----------------------------
" For Neovim's eyes only 
"-
if has('nvim')
  let g:loaded_sensible=0
  " Keymappings for Neovim
  " Neovim defaults to `<C-\><C-n>` to exit a virtual terminal
  tnoremap <Esc> <C-\><C-n>
  tnoremap <A-[> <Esc>

  if has('nvim-0.1.5')
    set termguicolors " use guifg/guibg instead of ctermfg/ctermbg in terminal
    hi Cursor guifg=green guibg=green
    hi Cursor2 guifg=red guibg=red
    set guicursor=n-v-c:block-Cursor/lCursor,i-ci-ve:ver25-Cursor2/lCursor2,r-cr:hor20,o:hor50
  elseif
    let $NVIM_TUI_ENABLE_TRUE_COLOR = 1   " Legacy way to enable 24bit color.
  endif
endif " END Neovim only settings
