" ######################################################################################################################
" ### Author : Martin Toma <martin.toma.svk@gmail.com>                                                               ###
" ######################################################################################################################
" ### VIMRC Configuration focused on RAILS development                                                               ###
" ### Date created : Tue Nov 12 14:14:56 CET 2013                                                                    ###
" ######################################################################################################################

" ======================================================================================================================
" 1.0 Plugin manager (Plug) settings
" ======================================================================================================================
"{{{

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

" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" 1.1 Plugin list
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

" ---------------------------------------------------------------------------------------------------------------------
" Language agnostic plugins
" ---------------------------------------------------------------------------------------------------------------------

" Most common languages file types (syntax, indenting, etc.)
Plug 'sheerun/vim-polyglot'
" Needs linters to work properly (see https://github.com/scrooloose/syntastic/wiki/Syntax-Checkers)
Plug 'scrooloose/syntastic', { 'on': 'SyntasticToggleMode' }
" Snippets support
Plug 'SirVer/ultisnips'
" Commenting support (gc)
Plug 'tpope/vim-commentary'

" -----------------------------------------------------
" Ruby/Rails
" -----------------------------------------------------

" (:A, :R, :Rmigration, :Rextract)
Plug 'tpope/vim-rails', { 'for': ['ruby', 'eruby', 'haml', 'slim'] }
" Automatically inserts 'end' wisely
Plug 'tpope/vim-endwise', { 'for': ['ruby', 'eruby'] }
" Change between ruby 1.9 and 1.8 hash syntax
Plug 'ck3g/vim-change-hash-syntax', { 'for': ['ruby', 'eruby'], 'on': 'ChangeHashSyntax' }
" Rails I18 support
Plug 'stefanoverna/vim-i18n', { 'for': ['ruby', 'eruby'], 'on': 'I18nTranslateString'  }
" Ruby best practices checker
Plug 'ngmy/vim-rubocop', { 'for': ['ruby', 'eruby'], 'on': 'RuboCop' }

" -----------------------------------------------------
" HTML/CSS
" -----------------------------------------------------

" CSS color highlighter
Plug 'gorodinskiy/vim-coloresque', { 'for': ['css', 'sass', 'scss', 'less'] }
" Sparkup, emmet alternative (<C-e> to expand expression)
Plug 'rstacruz/sparkup', { 'for': ['html', 'xhtml'] }
" Spacebars syntax
Plug 'Slava/vim-spacebars', { 'for': ['html', 'xhtml'] }

" -----------------------------------------------------
" JavaScript / CoffeeScript
" -----------------------------------------------------

" Tern auto-completion engine (run 'npm install && npm install tern-coffee' after update)
Plug 'marijnh/tern_for_vim', { 'for': ['javascript', 'coffee'] }
" Tern for CoffeeScript
Plug 'othree/tern_for_vim_coffee', { 'for': ['javascript', 'coffee'] }
" JS libs syntax files, ember, angular, etc.
Plug 'othree/javascript-libraries-syntax.vim', { 'for': ['javascript', 'coffee'] }

" -----------------------------------------------------
" Other
" -----------------------------------------------------

" Latex
Plug 'LaTeX-Box-Team/LaTeX-Box', { 'for': ['tex'] }

" ---------------------------------------------------------------------------------------------------------------------
" File, tags, undo, registers browsers
" ---------------------------------------------------------------------------------------------------------------------

" Nerdtree file browser
Plug 'scrooloose/nerdtree', { 'on': ['NERDTreeFind', 'NERDTreeToggle'] }
" Tagbar tag browser
Plug 'majutsushi/tagbar'
" Undo tree
Plug 'mbbill/undotree', { 'on': ['UndotreeToggle'] }
" Peekabo displays what registers contains
Plug 'junegunn/vim-peekaboo'

" ---------------------------------------------------------------------------------------------------------------------
" Projects/Files/code navigation/management plugins
" ---------------------------------------------------------------------------------------------------------------------

" Unite (Files, Buffers, Commands, etc. fuzzy searcher)
Plug 'Shougo/unite.vim'
" Unite tags source
Plug 'Shougo/unite-outline'
" Easy motion
Plug 'Lokaltog/vim-easymotion'
" Extends :e, :new to create new directories in path
Plug 'duggiefresh/vim-easydir'
" RSI movements for vim
Plug 'tpope/vim-rsi'
" Intelligent buffer closing
Plug 'mhinz/vim-sayonara', { 'on': 'Sayonara' }

" ---------------------------------------------------------------------------------------------------------------------
" External tools integration plugins
" ---------------------------------------------------------------------------------------------------------------------

" Git wrapper
Plug 'tpope/vim-fugitive'
" Git changes showed on line numbers
Plug 'airblade/vim-gitgutter'
" Gitk for vim
Plug 'gregsexton/gitv', { 'on':  'Gitv' }
" Git menu for Nerdtree
Plug 'low-ghost/nerdtree-fugitive', { 'on': ['NERDTreeFind', 'NERDTreeToggle'] }

" ---------------------------------------------------------------------------------------------------------------------
" Text insertion/manipulation
" ---------------------------------------------------------------------------------------------------------------------

" Completion with tab
Plug 'ervandew/supertab'
" Multiple cursors
Plug 'terryma/vim-multiple-cursors'
" Safely editing in isolation
Plug 'ferranpm/vim-isolate', { 'on':  'Isolate' }
" Surround (cs"')
Plug 'tpope/vim-surround'
" Easy alignment
Plug 'godlygeek/tabular', { 'on':  'Tabularize' }

" ---------------------------------------------------------------------------------------------------------------------
" Interface improving plugins
" ---------------------------------------------------------------------------------------------------------------------

" Airline (improved status line)
Plug 'bling/vim-airline'
" Highlight long lines
Plug 'whatyouhide/vim-lengthmatters'
" Hybrid
Plug 'w0ng/vim-hybrid'
" Gotham
Plug 'whatyouhide/vim-gotham'
" Molokai
Plug 'tomasr/molokai'
" Badwolf
Plug 'sjl/badwolf'
" Pencil
Plug 'reedes/vim-colors-pencil'

" ---------------------------------------------------------------------------------------------------------------------
" Dependencies
" ---------------------------------------------------------------------------------------------------------------------

" Async processing (for Unite)
Plug 'Shougo/vimproc.vim', { 'do': 'make' }
" Matchit enhances motions
Plug 'edsono/vim-matchit'
" More . repeat functionality
Plug 'tpope/vim-repeat'
" Misc functions
Plug 'xolox/vim-misc'

" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" 1.2 End of plugin declaration
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
call plug#end()
"}}}

" ======================================================================================================================
" 2.0 Basic settings
" ======================================================================================================================
"{{{

set shell=/bin/bash                         " Setting shell to bash
set nocompatible                            " No compatible with vi mode
set encoding=utf8                           " Set UTF-8 as standard encoding and en_US as the standard language
set number                                  " Line numbers
set ignorecase                              " Ignore case by default
set smartcase                               " Make search case sensitive only if it contains uppercase letters
set laststatus=2                            " Always show status line
set showmode                                " Always show mode
set wildmenu                                " Better auto-complete of ex commands
set textwidth=120                           " Text width is 120 chars
set autoread                                " Automatically reload change files on disk
set nocursorline                            " Dont set default cursor line
set cmdheight=1                             " Command line height
set pumheight=10                            " Completion window max size
set iskeyword-=_                            " Set underscore as a word separator
set iskeyword-=-                            " Set dash as a word separator
set timeoutlen=250                          " Setting ESC timeout
set hlsearch                                " Highlight search
set incsearch                               " Incremental search
set hidden                                  " Enables to switch between unsaved buffers and keep undo history
set undolevels=100                          " How many undo commands to remember
set clipboard+=unnamed                      " Use system clipboard
set history=1024                            " Number of things to remember in history
set nohlsearch                              " Don't highlight after search
set mat=2                                   " How many tenths of a second to blink when matching brackets
set lazyredraw                              " Don't redraw while executing macros (better performance)
set magic                                   " For regular expressions turn magic on
set showmatch                               " Show matching brackets when text indicator is over them
set list                                    " Display white chars by default (use <F7>)
set spelllang=en_us                         " Set language to us English
set backspace=indent,eol,start              " Set default behavior of backspace
set spellfile=~/.nvim/dictionary.utf-8.add  " Use this file for spell checking
set nospell                                 " Set spelling off by default
set nostartofline                           " Prevent cursor from moving to beginning of line when switching buffers
set virtualedit=block                       " To be able to select past EOL in visual block mode
set nojoinspaces                            " No extra space when joining a line which ends with . ? !
set startofline                             " When doing thing like gg or G, will move cursor to start of line
set wrapscan                                " Search again from top when reached the bottom
set showcmd                                 " Show incomplete commands
set scrolloff=5                             " Scroll when closing to top or bottom of the screen
set updatetime=1000                         " Update time used to create swap file or other things

" -----------------------------------------------------
" 2.1 Intendation settings (2 spaces tabs)
" -----------------------------------------------------
set autoindent
set expandtab
set shiftwidth=2
set softtabstop=2

" -----------------------------------------------------
" 2.2 Split settings (more natural).
" -----------------------------------------------------
set splitbelow
set splitright

" -----------------------------------------------------
" 2.3 Turn backup off, since most stuff is in git
" -----------------------------------------------------
set nobackup
set nowb
set noswapfile

" -----------------------------------------------------
" 2.4 Persistent undo, for non-git projects
" -----------------------------------------------------
if has('persistent_undo')
  " Save undo history to file
  set undofile
  " undo files in folder
  set undodir=~/.nvim/tmp/undo//
  " Maximum number of undos
  set undolevels=100000
  " Save complete files for undo on reload if it has less lines than this
  set undoreload=100000
endif

" -----------------------------------------------------
" 2.5 Highlight whitespaces
" -----------------------------------------------------
set listchars=tab:▸\ ,trail:·,extends:#,nbsp:·

" -----------------------------------------------------
" 2.6 Filetype settings
" -----------------------------------------------------
filetype off
filetype plugin on
filetype indent on

" -----------------------------------------------------
" 2.7 Folding settings, by default is disabled, use 'za'
" -----------------------------------------------------
set foldmethod=marker
set foldlevelstart=2
set fillchars="fold: "

" -----------------------------------------------------
" 2.8 Omni completion settings
" -----------------------------------------------------

" Dont show preview scratch buffers
set completeopt-=preview

" -----------------------------------------------------
" 2.9 Completion ignore list
" -----------------------------------------------------
set wildignore=*.o,*.obj,*~
set wildignore+=*vim/backups*
set wildignore+=*sass-cache*
set wildignore+=*DS_Store*
set wildignore+=vendor/rails/**
set wildignore+=vendor/cache/**
set wildignore+=*.gem
set wildignore+=log/**
set wildignore+=tmp/**
set wildignore+=*.png,*.jpg,*.gif
"}}}

" ======================================================================================================================
" 3.0 Mapping settings
" ======================================================================================================================
"{{{

" -----------------------------------------------------
" 3.1 Setting leaders
" -----------------------------------------------------
let g:mapleader="\<space>"

" -----------------------------------------------------
" 3.2 Disabling arrow keys, space key, exmode enter
" with Q key, help with F1, etc.
" -----------------------------------------------------
nnoremap <up> <nop>
nnoremap <down> <nop>
nnoremap <left> <nop>
nnoremap <right> <nop>
nnoremap <bs> <nop>
nnoremap <delete> <nop>
inoremap <up> <nop>
inoremap <down> <nop>
inoremap <left> <nop>
inoremap <right> <nop>
nnoremap <Space> <nop>
inoremap <F1> <nop>
nnoremap <F1> <nop>
nnoremap Q <nop>

" -----------------------------------------------------
" 3.3 Vim defaults overriding
" -----------------------------------------------------

" Intelligent window cycling
nmap <silent> <C-w><C-w> :call utils#intelligentCycling()<CR>

" Visual linewise up and down by default
noremap j gj
noremap k gk

" When jump to next match also center screen
noremap n nzz
noremap N Nzz

" Same when moving up and down
noremap <c-d> <c-d>zz
noremap <c-u> <c-u>zz

" Remap H and L (top, bottom of screen to left and right end of line)
nnoremap H ^
nnoremap L $
vnoremap H ^
vnoremap L g_

" More logical Y (defaul was alias for yy)
nnoremap Y y$

" Quick replay q macro
nnoremap Q @q

" Mark with big M (default to middle of the screen overriden)
" m is used as EasyMotion leader key
nnoremap M m

" Automatically reselect and yank overpasted text in visual mode
xnoremap p pgvy

" -----------------------------------------------------
" 3.4 Common tasks
" -----------------------------------------------------

" Quick save and quit / delete buffers intelligently
nnoremap ,w :w<CR>
nnoremap <silent> ,q :q<CR>
nnoremap <silent> ,d :bd<CR>
nnoremap <silent> ,c :Sayonara!<CR>

" Reformat whole file
nnoremap <silent> ,f mzgg=G`z

" Run current file
nnoremap <silent> ,r :call utils#runCurrentFile()<CR>

" Run terminal shell buffer in right vsplit
nnoremap <silent> <leader>s :call utils#newVertTerm()<CR>

" -----------------------------------------------------
" 3.5 F-key actions
" -----------------------------------------------------

" NERDTree find current file
nnoremap <silent> <F1> :call utils#nerdWrapper()<CR>
" Tagbar panel
nnoremap <silent> <F2> :TagbarToggle<CR>
" Paste mode toggling
nnoremap <silent> <F3> :set paste!<CR> :set paste?<CR>
" Toggle spelling on and off
nnoremap <silent> <F4> :set spell!<CR> :set spell?<CR>
" Source (reload) nvimrc
nnoremap <silent> <F5> :source $MYVIMRC<CR>
" Toggle search highlight
nnoremap <silent> <F6> :set nohlsearch!<CR> :set nohlsearch?<CR>
" Toggle white characters visibility
nnoremap <silent> <F7> :set list!<CR> :set list?<CR>
" Toggle syntax checking
nnoremap <F8> :SyntasticToggleMode<CR>
" Toggle undo tree
nnoremap <silent> <F9> :UndotreeToggle<CR>
" Echo out toggles legend on <F12>
nnoremap <F12> :call utils#showToggles()<CR>

" -----------------------------------------------------
" 3.6 Window / Buffer management
" -----------------------------------------------------

" Windows resizing using arrow keys
nnoremap <silent> <Left> :vertical resize -1<CR>
nnoremap <silent> <Right> :vertical resize +1<CR>
nnoremap <silent> <Up> :resize +1<CR>
nnoremap <silent> <Down> :resize -1<CR>

" Buffers navigation and management
nnoremap <silent> + :bn<CR>
nnoremap <silent> _ :bp<CR>

" -----------------------------------------------------
" 3.7 Command abbrevations and mappings
" -----------------------------------------------------

" Quiting and saving all
cmap ww wqall
cmap qq qall

" Accepting case errors
cab W! w!
cab Q! q!
cab Wq wq
cab Wa wa
cab wQ wq
cab WQ wq
cab W w
cab Q q
"}}}

" ======================================================================================================================
" 4.0 Plugins settings
" ======================================================================================================================
"{{{

" -----------------------------------------------------
" 4.1 My utils settings
" -----------------------------------------------------
let g:utils_autoswitch_kb_layout=0

" -----------------------------------------------------
" 4.2 Airline (status line)
" -----------------------------------------------------
let g:airline_powerline_fonts=1
let g:airline_exclude_preview=1
let g:airline#extensions#branch#empty_message="No VCS"
let g:airline#extensions#whitespace#enabled=0
let g:airline#extensions#syntastic#enabled=1
let g:airline#extensions#tabline#enabled=1
let g:airline#extensions#tabline#tab_nr_type=1
let g:airline#extensions#tabline#fnamecollapse=1
let g:airline#extensions#hunks#non_zero_only=1

" -----------------------------------------------------
" 4.3 Unite
" -----------------------------------------------------

" Matcher settings
call unite#filters#matcher_default#use(['matcher_fuzzy'])
call unite#filters#sorter_default#use(['sorter_rank'])
call unite#custom#source('file_rec/async','sorters','sorter_rank')

" Track yank history
let g:unite_source_history_yank_enable=1

" Use ag if available
if executable('ag')
  let g:unite_source_grep_command='ag'
  let g:unite_source_grep_default_opts='--nocolor --line-numbers --nogroup -S -C0'
  let g:unite_source_grep_recursive_opt=''
  " Ignore vcs files
  let g:unite_source_rec_async_command='ag --nocolor --nogroup --ignore ".hg" --ignore ".svn" --ignore ".git" --ignore
        \ ".bzr" --ignore ".meteor"--hidden -g ""'
  let g:unite_source_file_async_command='ag --nocolor --nogroup --ignore ".hg" --ignore ".svn" --ignore ".git" --ignore
        \ ".bzr" --ignore ".meteor" --hidden -g ""'
endif

" Ignore wildignore files
call unite#custom#source('file_rec', 'ignore_globs', split(&wildignore, ','))

" Custom profile
call unite#custom#profile('default', 'context', {
      \   'prompt': '» ',
      \   'winheight': 15,
      \ })

" Add syntax highlighting
let g:unite_source_line_enable_highlight=1

" -----------------------------------------------------
" 4.4 Syntastic (syntax checker)
" -----------------------------------------------------
" Overriding default linters
let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_ruby_checkers=['mri']

" Disable ugly signs
let g:syntastic_enable_signs=1
" Check on open as well as save
let g:syntastic_check_on_open=1
" Don't care about warnings
let g:syntastic_quiet_messages={ 'level': 'warnings' }
" Passive mode is default
let g:syntastic_mode_map={ 'mode': 'passive', 'active_filetypes': [],'passive_filetypes': [] }

" -----------------------------------------------------
" 4.5 Supertab
" -----------------------------------------------------
let g:SuperTabDefaultCompletionType='context'
autocmd FileType *
      \ if &omnifunc != '' |
      \   call SuperTabChain(&omnifunc, "<c-p>") |
      \ endif

" -----------------------------------------------------
" 4.6 EasyMotion
" -----------------------------------------------------
" Turn on case sensitive feature
let g:EasyMotion_smartcase=1

" -----------------------------------------------------
" 4.7 NERDTree
" -----------------------------------------------------
let NERDTreeMinimalUI=1
let NERDTreeDirArrows=1
let g:NERDTreeWinSize=45

" -----------------------------------------------------
" 4.8 Tagbar settings
" -----------------------------------------------------
let g:tagbar_compact=1

" -----------------------------------------------------
" 4.10 Undotree settings
" -----------------------------------------------------
let g:undotree_WindowLayout=3
"}}}

" ======================================================================================================================
" 5.0 Plugin mappings
" ======================================================================================================================
"{{{
" -----------------------------------------------------
" 5.1 Unite and extensions
" -----------------------------------------------------

" Custom mappings for the unite buffer
autocmd FileType unite call s:unite_settings()
function! s:unite_settings()
  " Play nice with supertab
  let b:SuperTabDisabled=1
  " Enable navigation with control-j and control-k in insert mode
  imap <silent> <buffer> <C-j> <Plug>(unite_select_next_line)
  imap <silent> <buffer> <C-k> <Plug>(unite_select_previous_line)
  " Runs 'splits' action by <C-s> and <C-v>
  imap <silent> <buffer> <expr> <C-s> unite#do_action('split')
  imap <silent> <buffer> <expr> <C-v> unite#do_action('vsplit')
  " Exit with escape
  nmap <silent> <buffer> <ESC> <Plug>(unite_exit)
  " Mark candidates
  vmap <silent> <buffer> m <Plug>(unite_toggle_mark_selected_candidates)
  nmap <silent> <buffer> m <Plug>(unite_toggle_mark_current_candidate)
endfunction

" [U]nite menu
nnoremap <silent> <leader>u :Unite -start-insert source<CR>
" [O]pen files recursively
nnoremap <silent> <leader>o :Unite -no-split -buffer-name=project-files -start-insert file_rec/async:!<CR>
" Search between open files - [b]uffers
nnoremap <silent> <leader>b :Unite -no-split -buffer-name=buffers buffer<CR>
" Search in current file tags
nnoremap <silent> <leader>t :Unite -no-split -buffer-name=tags -start-insert outline<CR>
" Search for term in cwd file ([g]rep)
nnoremap <silent> <leader>g :Unite -silent grep:.<CR>
" Search in edit [h]istory
nnoremap <silent> <leader>h :Unite -buffer-name=edit-history change<CR>
" Search in [l]ines on current buffer
nnoremap <silent> <leader>l :Unite -no-split -buffer-name=line-search -start-insert line<CR>
" Search in [y]ank history
nnoremap <silent> <leader>y :Unite -buffer-name=yank-history history/yank<CR>
" Search in [r]egisters
nnoremap <silent> <leader>r :Unite -buffer-name=registers register<CR>
" Search in opened [w]indow splits
nnoremap <silent> <leader>w :Unite -no-split -buffer-name=splits window<CR>

" -----------------------------------------------------
" 5.3 EasyMotion
" -----------------------------------------------------
" [m]otion prefix
nmap m <Plug>(easymotion-prefix)

" Seek 2 character motion
nmap s <Plug>(easymotion-sl2)

" Improved search
map  / <Plug>(easymotion-sn)
omap / <Plug>(easymotion-tn)

" -----------------------------------------------------
" 5.4 Ultisnips
" -----------------------------------------------------
" Disable built-in cx-ck to be able to go backward
inoremap <c-x><c-k> <nop>
let g:UltiSnipsExpandTrigger='<c-j>'
let g:UltiSnipsListSnippets='<c-l>'
let g:UltiSnipsJumpForwardTrigger='<c-j>'
let g:UltiSnipsJumpBackwardTrigger='<c-k>'
"}}}

" ======================================================================================================================
" 6.0 Color and highlighting settings
" ======================================================================================================================
"{{{
" Syntax highlighting
syntax on

" XTerm 256 colors
if $TERM == 'xterm-256color' || 'screen-256color'
  set t_Co=256
endif

if !has("gui_running")
  " Color scheme based on time
  if strftime("%H") < 15
    let g:rehash256 = 1
    let g:airline_theme='tomorrow'
    colorscheme molokai
  elseif strftime("%H") < 20
    let g:airline_theme='tomorrow'
    colorscheme hybrid
  else
    let g:airline_theme='gotham'
    colorscheme gotham
  endif
endif

" Remove underline in folded lines
hi Folded term=NONE cterm=NONE gui=NONE ctermbg=NONE
"}}}

" ======================================================================================================================
" 7.0 filetype specific settings and autocommands
" ======================================================================================================================
"{{{
autocmd FileType ruby,coffee,sass,scss,haml,slim,vim setlocal tabstop=2 shiftwidth=2 softtabstop=2 textwidth=120
autocmd FileType html,htmldjango,xhtml,css,javascript,snippets setlocal tabstop=4 shiftwidth=4 softtabstop=4 textwidth=120

" Keywordprg settings
autocmd FileType vim setlocal keywordprg=:help

" Omni complete function settings
autocmd FileType html,markdown set omnifunc=htmlcomplete#CompleteTags
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType c set omnifunc=ccomplete#Complete
autocmd FileType java set omnifunc=javacomplete#Complete
autocmd FileType tex set omnifunc=LatexBox_Complete
" No +ruby compiled neovim for now
" autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
" autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading=1
" autocmd FileType ruby,eruby let g:rubycomplete_classes_in_global=1
" autocmd FileType ruby,eruby let g:rubycomplete_rails=1
" autocmd FileType ruby,eruby let g:rubycomplete_load_gemfile=1

" make CSS omni-completion work for SASS and SCSS
autocmd BufNewFile,BufRead *.scss set ft=scss.css
autocmd BufNewFile,BufRead *.sass set ft=sass.css

" use syntax complete if nothing else available
if has("autocmd") && exists("+omnifunc")
  autocmd Filetype *
        \ if &omnifunc == "" |
        \   setlocal omnifunc=syntaxcomplete#Complete |
        \ else |
        \   let g:SuperTabContextDefaultCompletionType='<c-x><c-u>' |
        \ endif
endif

" Close vim if the last open window is nerdtree
autocmd BufEnter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif

" Remove trailing whitespaces automatically before save
autocmd BufWritePre * call utils#stripTrailingWhitespaces()

" Keyboard layout switching
if g:utils_autoswitch_kb_layout == 1
  autocmd InsertEnter * call utils#setSKKBLayout()
  autocmd InsertLeave * call utils#setUSKBLayout()
end
"}}}

" ======================================================================================================================
" 8.0 Other stuff
" ======================================================================================================================
"{{{
" Load other scripts
if filereadable(expand("~/config/dot-files/vim/scripts/utils.vim"))
  source ~/config/dot-files/vim/scripts/utils.vim
else
  echo "Update path to vim scripts!"
endif
"}}}