" Maintainer:       D. Ben Knoble <ben.knoble@gmail.com>

" Global function for calling terminal with the appropriate interpreter
" b:interpreter controls the program run
function! benknoble#terminal(...)
  let l:interpreter = get(b:, 'interpreter', &shell)
  let l:command = 'term'
  if a:0
    for l:opt in a:000
      let l:command .= printf(' %s', opt)
    endfor
  endif
  let l:command .= printf(' %s', l:interpreter)
  execute l:command
endfunction

" Makes [I nicer to navigate
function! benknoble#findword()
  normal! [I
  call inputsave()
  let l:nr = str2nr(input("Number: "))
  call inputrestore()
  " [I starts with the number 1
  " and a blank string (<CR> or <Esc>) is 0
  if l:nr <=# 0
    return
  else
    exec printf("normal! %d[\t", l:nr)
  endif
endfunction

" Get the directory of a file on the command line
function! benknoble#current_file_directory(keymap) abort
  let l:command_type = getcmdtype()
  if l:command_type isnot# ':'
    return a:keymap
  endif
  let l:dir = expand('%:h')
  if empty(l:dir)
    let l:dir = '.'
  endif
  return l:dir . '/'
endfunction

Convert autoload functions to abort

" Maintainer:       D. Ben Knoble <ben.knoble@gmail.com>

" Global function for calling terminal with the appropriate interpreter
" b:interpreter controls the program run
function! benknoble#terminal(...) abort
  let l:interpreter = get(b:, 'interpreter', &shell)
  let l:command = 'term'
  if a:0
    for l:opt in a:000
      let l:command .= printf(' %s', opt)
    endfor
  endif
  let l:command .= printf(' %s', l:interpreter)
  execute l:command
endfunction

" Makes [I nicer to navigate
function! benknoble#findword() abort
  normal! [I
  call inputsave()
  let l:nr = str2nr(input("Number: "))
  call inputrestore()
  " [I starts with the number 1
  " and a blank string (<CR> or <Esc>) is 0
  if l:nr <=# 0
    return
  else
    exec printf("normal! %d[\t", l:nr)
  endif
endfunction

" Get the directory of a file on the command line
function! benknoble#current_file_directory(keymap) abort
  let l:command_type = getcmdtype()
  if l:command_type isnot# ':'
    return a:keymap
  endif
  let l:dir = expand('%:h')
  if empty(l:dir)
    let l:dir = '.'
  endif
  return l:dir . '/'
endfunction


au BufRead,BufNewFile *.scala set filetype=scala

Add filetype detection for sbt and template files

au BufRead,BufNewFile *.scala set filetype=scala
au BufNewFile,BufRead *.sbt set filetype=scala

" Use haml syntax for scaml
au BufRead,BufNewFile *.scaml set filetype=haml


" Vim filetype plugin
" Language:              Man
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

" Don't show fancy whitespace
setlocal nolist
" No colorcolumn
setlocal colorcolumn=

" Line numbers
setlocal nonumber norelativenumber

let b:undo_ftplugin = ftplugin#undo({
      \ 'opts': [
      \   'list',
      \   'colorcolumn',
      \   'number',
      \   'relativenumber',
      \ ],
      \ })

Make searching for options easy

" Vim filetype plugin
" Language:              Man
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

" Don't show fancy whitespace
setlocal nolist
" No colorcolumn
setlocal colorcolumn=

" Line numbers
setlocal nonumber norelativenumber

" Search for options
" Use very magic to make patterns easy, and case sensitive because -b != -B
nnoremap <buffer> - /\C\v-
nnoremap <buffer> _ /\C\v--

let b:undo_ftplugin = ftplugin#undo({
      \ 'opts': [
      \   'list',
      \   'colorcolumn',
      \   'number',
      \   'relativenumber',
      \ ],
      \ 'maps': [
      \   [ 'n', '-' ],
      \   [ 'n', '_' ],
      \ ],
      \ })


" abbreviations
iab fis for (int i = 0; i < .size(); ++i) {<CR>}<ESC>-f.i
iab ato atoi(.c_str())<ESC>F.i
iab vs vector<string>
iab vi vector<int>
iab vll vector<long long>
iab vb vector<bool>
iab AC accumulate(.begin(), .end(), 0);<ESC>2F.i

" make commands
map <F5> <ESC>:wa!<cr>:make run<cr>
map <F6> <ESC>:wa!<cr>:make test<cr>
map <F7> <ESC>:wa!<cr>:make<cr>
map! <F5> <ESC>:wa!<cr>:make run<cr>
map! <F6> <ESC>:wa!<cr>:make test<cr>
map! <F7> <ESC>:wa!<cr>:make<cr>

Create Vim shortcut for C++11 in Makefile

" abbreviations
iab fis for (int i = 0; i < .size(); ++i) {<CR>}<ESC>-f.i
iab ato atoi(.c_str())<ESC>F.i
iab vs vector<string>
iab vi vector<int>
iab vll vector<long long>
iab vb vector<bool>
iab AC accumulate(.begin(), .end(), 0);<ESC>2F.i

" make commands
map <F5> <ESC>:wa!<cr>:make run<cr>
map <F6> <ESC>:wa!<cr>:make test<cr>
map <F7> <ESC>:wa!<cr>:make<cr>
map <F3> <ESC>:wa!<cr>:vs Makefile<cr>/CXXFLAGS<cr>A -std=c++11<ESC>ZZ
map! <F5> <ESC>:wa!<cr>:make run<cr>
map! <F6> <ESC>:wa!<cr>:make test<cr>
map! <F7> <ESC>:wa!<cr>:make<cr>
map! <F3> <ESC>:wa!<cr>:vs Makefile<cr>/CXXFLAGS<cr>A -std=c++11<ESC>ZZ


" Write and close quickly
nmap <Leader>wq :wq<Cr>

" Set default theme
colorscheme pablo

" Send all yanking/deleting ops to clipboard
clipboard=unnamedplus

Fix typo in vim config

" Write and close quickly
nmap <Leader>wq :wq<Cr>

" Clean up search highlights
nmap <C-l> :noh<Cr>

" Set default theme
colorscheme pablo

" Send all yanking/deleting ops to clipboard
set clipboard=unnamedplus


" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

" Start bundle list -----------------------------

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
Bundle 'altercation/vim-colors-solarized'

" End bundle list -------------------------------

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ

Add syntax highlighting bundles for js, jade, and stylus

" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

" Start bundle list -----------------------------

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
Bundle 'altercation/vim-colors-solarized'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'digitaltoad/vim-jade'
Bundle 'wavded/vim-stylus'

" End bundle list -------------------------------

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ


setl spell
hi SpellBad guibg=None
hi SpellRare guibg=None
hi SpellCap guibg=None

Fix spelling highlight changes in git commits

setl spell
hi SpellBad guibg=NONE
hi SpellRare guibg=NONE
hi SpellCap guibg=NONE


" Vim filetype plugin
" Language:              C
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

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

" Add system tags
setlocal tags+=~/.sys_c_tags

" Find headers *when we want them*!
setlocal path+=/usr/local/include,/usr/include

" Rebuild tags
nnoremap <buffer> <LocalLeader>tr :!ctags --extra=+f -R *<CR><CR>

if !exists("*MyCFtpluginUndo")
  function MyCFtpluginUndo()
    setlocal tags<
    setlocal path<
    silent! nunmap <buffer> <LocalLeader>tr
  endfunction
endif

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

Stop using system tags in C

" Vim filetype plugin
" Language:              C
" Maintainer:            Ben Knoble <ben.knoble@gmail.com>

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

" Find headers *when we want them*!
setlocal path+=/usr/local/include,/usr/include

" Rebuild tags
nnoremap <buffer> <LocalLeader>tr :!ctags --extra=+f -R *<CR><CR>

if !exists("*MyCFtpluginUndo")
  function MyCFtpluginUndo()
    setlocal path<
    silent! nunmap <buffer> <LocalLeader>tr
  endfunction
endif

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


" Formatting
function! FormatOnSave()
    let l:lines = "all"
    pyf /Users/fellipe/dotfiles/clang-format.py
endfunction

map gq :pyf /Users/fellipe/dotfiles/clang-format.py<CR>
autocmd BufWritePre *.h,*.cc,*.cpp call FormatOnSave()

" Folding
setlocal foldmethod=syntax
autocmd Syntax normal zR

Format *.c files upon saving

" Formatting
function! FormatOnSave()
    let l:lines = "all"
    pyf /Users/fellipe/dotfiles/clang-format.py
endfunction

map gq :pyf /Users/fellipe/dotfiles/clang-format.py<CR>
autocmd BufWritePre *.h,*.cc,*.cpp,*.c call FormatOnSave()

" Folding
setlocal foldmethod=syntax
autocmd Syntax normal zR


" Constants: {{{

let s:PUNCTUATIONS = {
      \   'before_space': [
      \     '!',
      \     ')',
      \     ',',
      \     '.',
      \     ':',
      \     ';',
      \     '?'
      \   ],
      \   'after_space': [
      \     '('
      \   ]
      \ }

let s:ISKEYWORD = printf('@,%s-%s', char2nr('0'), char2nr('9'))

" }}} Constants

function! wordword#break(text)
  let t = a:text
  let iskeyword = &l:iskeyword
  execute 'setlocal iskeyword=' . s:ISKEYWORD

  let t = substitute(t, '\>\<', '\0 ', 'g')

  if get(g:, 'wordword_break_on_punctuation')
    let pattern = printf('[%s]\<', join(s:PUNCTUATIONS.before_space, ''))
    let t = substitute(t, pattern, '\0 ', 'g')

    let pattern = printf('\>[%s]', join(s:PUNCTUATIONS.after_space, ''))
    let t = substitute(t, pattern, ' \0', 'g')
  endif

  let &l:iskeyword = iskeyword
  return t
endfunction

Fix substitution on old Vim version (7.3)

" Constants: {{{

let s:PUNCTUATIONS = {
      \   'before_space': [
      \     '!',
      \     ')',
      \     ',',
      \     '.',
      \     ':',
      \     ';',
      \     '?'
      \   ],
      \   'after_space': [
      \     '('
      \   ]
      \ }

let s:ISKEYWORD = printf('@,%s-%s', char2nr('0'), char2nr('9'))

" }}} Constants

function! wordword#break(text)
  let t = a:text
  let iskeyword = &l:iskeyword
  execute 'setlocal iskeyword=' . s:ISKEYWORD

  let t = substitute(t, '\>\<.', ' \0', 'g')

  if get(g:, 'wordword_break_on_punctuation')
    let pattern = printf('[%s]\<', join(s:PUNCTUATIONS.before_space, ''))
    let t = substitute(t, pattern, '\0 ', 'g')

    let pattern = printf('\>[%s]', join(s:PUNCTUATIONS.after_space, ''))
    let t = substitute(t, pattern, ' \0', 'g')
  endif

  let &l:iskeyword = iskeyword
  return t
endfunction


" vim: et sw=2 sts=2

scriptencoding utf-8

" Function: #list_active_buffers {{{1
function! sy#debug#list_active_buffers() abort
  for b in range(0, bufnr('$'))
    if !buflisted(b) || empty(getbufvar(b, 'sy'))
      continue
    endif

    let sy   = copy(getbufvar(b, 'sy'))
    let path = remove(sy, 'path')

    echo "\n". path ."\n". repeat('=', strlen(path))
    for stat in sort(keys(sy))
      echo printf("%20s  =  %s\n", stat, string(sy[stat]))
    endfor
  endfor
endfunction

Use 1-based indexing for buffer ranges

" vim: et sw=2 sts=2

scriptencoding utf-8

" Function: #list_active_buffers {{{1
function! sy#debug#list_active_buffers() abort
  for b in range(1, bufnr('$'))
    if !buflisted(b) || empty(getbufvar(b, 'sy'))
      continue
    endif

    let sy   = copy(getbufvar(b, 'sy'))
    let path = remove(sy, 'path')

    echo "\n". path ."\n". repeat('=', strlen(path))
    for stat in sort(keys(sy))
      echo printf("%20s  =  %s\n", stat, string(sy[stat]))
    endfor
  endfor
endfunction


" Copyright 2010-present Greg Hurrell. All rights reserved.
" Licensed under the terms of the BSD 2-clause license.

if exists('g:command_t_loaded') || &compatible
  finish
endif
let g:command_t_loaded = 1

command! CommandTBuffer call commandt#BufferFinder()
command! CommandTJump call commandt#JumpFinder()
command! CommandTMRU call commandt#MRUFinder()
command! CommandTTag call commandt#TagFinder()
command! -nargs=? -complete=dir CommandT call commandt#FileFinder(<q-args>)
command! CommandTFlush call commandt#Flush()
command! CommandTLoad call commandt#Load()

if !hasmapto('<Plug>(CommandT)') && maparg('<Leader>t', 'n') ==# ''
  nmap <unique> <Leader>t <Plug>(CommandT)
endif
nnoremap <silent> <Plug>(CommandT) :CommandT<CR>

if !hasmapto('<Plug>(CommandTBuffer)') && maparg('<Leader>b', 'n') ==# ''
  nmap <unique> <Leader>b <Plug>(CommandTBuffer)
endif
nnoremap <silent> <Plug>(CommandTBuffer) :CommandTBuffer<CR>

Add <leader>j mapping for :CommandTJump

" Copyright 2010-present Greg Hurrell. All rights reserved.
" Licensed under the terms of the BSD 2-clause license.

if exists('g:command_t_loaded') || &compatible
  finish
endif
let g:command_t_loaded = 1

command! CommandTBuffer call commandt#BufferFinder()
command! CommandTJump call commandt#JumpFinder()
command! CommandTMRU call commandt#MRUFinder()
command! CommandTTag call commandt#TagFinder()
command! -nargs=? -complete=dir CommandT call commandt#FileFinder(<q-args>)
command! CommandTFlush call commandt#Flush()
command! CommandTLoad call commandt#Load()

if !hasmapto('<Plug>(CommandT)') && maparg('<Leader>t', 'n') ==# ''
  nmap <unique> <Leader>t <Plug>(CommandT)
endif
nnoremap <silent> <Plug>(CommandT) :CommandT<CR>

if !hasmapto('<Plug>(CommandTBuffer)') && maparg('<Leader>b', 'n') ==# ''
  nmap <unique> <Leader>b <Plug>(CommandTBuffer)
endif
nnoremap <silent> <Plug>(CommandTBuffer) :CommandTBuffer<CR>

if has('jumplist')
  if !hasmapto('<Plug>(CommandTJump)') && maparg('<Leader>j', 'n') ==# ''
    nmap <unique> <Leader>j <Plug>(CommandTJump)
  endif
  nnoremap <silent> <Plug>(CommandTJump) :CommandTJump<CR>
endif


runtime colors/jellybeans.vim

let colors_name = 'jellybeans_custom'

hi ColorColumn      guibg=#222222
hi IndentGuidesOdd  guibg=#181818 ctermbg=232
hi IndentGuidesEven guibg=#222222 ctermbg=233
hi VertSplit                      ctermbg=235
hi Cursor           guibg=#AFD700 guifg=black
hi iCursor          guibg=#0087af

Remove indent guides custom colours as jellybeans has support now.

runtime colors/jellybeans.vim

let colors_name = 'jellybeans_custom'

hi ColorColumn      guibg=#222222
hi VertSplit                      ctermbg=235
hi Cursor           guibg=#AFD700 guifg=black
hi iCursor          guibg=#0087af


if has('autocmd')

	au BufRead,BufNewFile {Gemfile,Capfile,Kirkfile,Rakefile,Thorfile,config.ru} set ft=ruby
	au BufRead,BufNewFile *.{md,markdown,mdown,mkd,mkdn,txt} setf markdown
	au BufRead,BufNewFile *.less set filetype=less
	au BufRead,BufNewFile *.json set ft=javascript
	au BufNewFile,BufRead *gitconfig setf gitconfig

	au Filetype html,xml source ~/.vim/scripts/closetag.vim

	au FileType coffee  setl ts=2 sw=2 expandtab
	au FileType ruby    setl ts=2 sw=2 expandtab

	if has('spell')
		au BufNewFile,BufRead COMMIT_EDITMSG setlocal spell
		au BufNewFile,BufRead *.asciidoc setlocal spell
	endif

	au BufNewFile,BufRead COMMIT_EDITMSG call feedkeys('ggi', 't') " Git commits go to top of line and into insert mode

endif

Improve language support and Sencha JS indentation

if has('autocmd')

	" Get filetype correct
	au BufEnter {Gemfile,Capfile,Kirkfile,Rakefile,Thorfile,config.ru} set filetype=ruby
	au BufEnter *.{md,markdown,mdown,mkd,mkdn,txt} set filetype=markdown
	au BufEnter *.less set filetype=less
	au BufEnter *.json set filetype=json
	au BufEnter *gitconfig setf gitconfig

	" Per-filetype indentation
	au FileType coffee setl ts=2 sw=2 expandtab
	au FileType ruby setl ts=2 sw=2 expandtab

	" Per-project indentation
	au BufEnter */sencha/* setl ts=4 sw=4 expandtab

	" Git commit messages with spelling and automatic insert mode
	if has('spell')
		au BufNewFile,BufRead COMMIT_EDITMSG setlocal spell
	endif
	au BufNewFile,BufRead COMMIT_EDITMSG call feedkeys('ggi', 't')

endif


autocmd BufReadPost,BufNewFile *.apib set syntax=apiblueprint

Set makeprg to lint the blueprint

autocmd BufReadPost,BufNewFile *.apib set filetype=apiblueprint
autocmd FileType apiblueprint set syntax=apiblueprint
autocmd FileType apiblueprint set makeprg=snowcrash\ -l\ %


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! EnterNormalModeHighlight()
    set colorcolumn=
    highlight CursorLineNr ctermfg=Yellow ctermbg=DarkGray
endfunction

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

call EnterNormalModeHighlight()

if &term =~ "xterm" || &term =~ "screen" || &term =~ "putty"
    set t_ZH=
    set t_ZR=
    highlight Comment cterm=Italic
endif

let g:loaded_matchparen = 0

Disable vim italic comments in tmux/screen

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! EnterNormalModeHighlight()
    set colorcolumn=
    highlight CursorLineNr ctermfg=Yellow ctermbg=DarkGray
endfunction

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

call EnterNormalModeHighlight()

if &term =~ "xterm" || &term =~ "putty"
    set t_ZH=
    set t_ZR=
    highlight Comment cterm=Italic
endif

let g:loaded_matchparen = 0


" ----------------------------------------------------------------------------
" 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.
  let &grepprg='ag --nogroup --nocolor --hidden --column'
  set grepformat=%f:%l:%c%m

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

  " 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

Improve format of grep command

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


" Disable bell and visual bell.
set noerrorbells visualbell t_vb=
augroup gui-visualbell
  autocmd!
  autocmd GUIEnter * set visualbell t_vb=
augroup END

" Hide some autocompletion messages.
set shortmess+=c

" Hide buffers instead of closing them.
set hidden

" Show line numbers.
set number

" Set nonzero scrolloff.
set scrolloff=3

" Assume fast connection.
set ttyfast

" Always show status line.
set laststatus=2

" Set indentation preferences.
set smartindent
set tabstop=2
set shiftwidth=2
set expandtab
set ai

" Set search preferences.
set hlsearch
set ignorecase
set smartcase

" Set folding preferences.
set foldmethod=syntax
set nofoldenable

" Open splits below by default.
set splitbelow

Use 4 spaces for php indent

" Disable bell and visual bell.
set noerrorbells visualbell t_vb=
augroup gui-visualbell
  autocmd!
  autocmd GUIEnter * set visualbell t_vb=
augroup END

" Hide some autocompletion messages.
set shortmess+=c

" Hide buffers instead of closing them.
set hidden

" Show line numbers.
set number

" Set nonzero scrolloff.
set scrolloff=3

" Assume fast connection.
set ttyfast

" Always show status line.
set laststatus=2

" Set indentation preferences.
set smartindent
set tabstop=2
set shiftwidth=2
set expandtab
set ai

" Set search preferences.
set hlsearch
set ignorecase
set smartcase

" Set folding preferences.
set foldmethod=syntax
set nofoldenable

" Open splits below by default.
set splitbelow

" Set language specific overrides.
augroup php-indent-size
  autocmd!
  autocmd FileType php setlocal shiftwidth=4 softtabstop=4
augroup END


" Some color remaps
" If statements and def statements should look similar
" so you can see the flow
hi! link rubyDefine rubyControl

" Colors to make LustyJuggler more usable
" the Question color in LustyJuggler is mapped to
" the currently selected buffer.
hi clear Question
hi! Question guifg=yellow

hi! link TagListFileName  Question

Improve visual select color, as well as CommandT

" Some color remaps
" If statements and def statements should look similar
" so you can see the flow
hi! link rubyDefine rubyControl

" This is a bit nicer visual selection, and
" as a side bonus it makes CommandT look better
hi! link Visual DiffChange

" Colors to make LustyJuggler more usable
" the Question color in LustyJuggler is mapped to
" the currently selected buffer.
hi clear Question
hi! Question guifg=yellow

hi! link TagListFileName  Question


" Display the default mode indicator, which is made redundant by the Lightline.
set noshowmode

" Turn on syntax highlighting.
syntax on

" Turn on line numbers.
set number

" Highlight the current selected line.
set cursorline

" The amount of lines around the cursor when scrolling.
set sidescrolloff=3
set scrolloff=3

" Highlight a column to indicate the maximum width of text.
set colorcolumn=81
set textwidth=80

" Turn on invisible characters.
set list

" Set the invisible characters.
set listchars=tab:▸\ ,eol:¬,extends:❯,precedes:❮,trail:·

" Configure ignored files and directories.
set wildignore=.git,vendor,node_modules,bower_components,.DS_Store

" Turn off line wrapping.
set wrapmargin=0
set textwidth=0
set nowrap

" Use soft tabs instead of hard tabs
set softtabstop=4
set shiftwidth=4
set expandtab
set tabstop=4

" Remove the delay when switching between modes.
set ttimeoutlen=50

Make the scrolling smoother in Vim

" Display the default mode indicator, which is made redundant by the Lightline.
set noshowmode

" Turn on syntax highlighting.
syntax on

" Turn on line numbers.
set number

" Highlight the current selected line.
set cursorline

" The amount of lines around the cursor when scrolling.
set sidescrolloff=3
set scrolloff=3

" Highlight a column to indicate the maximum width of text.
set colorcolumn=81
set textwidth=80

" Turn on invisible characters.
set list

" Set the invisible characters.
set listchars=tab:▸\ ,eol:¬,extends:❯,precedes:❮,trail:·

" Configure ignored files and directories.
set wildignore=.git,vendor,node_modules,bower_components,.DS_Store

" Turn off line wrapping.
set wrapmargin=0
set textwidth=0
set nowrap

" Use soft tabs instead of hard tabs
set softtabstop=4
set shiftwidth=4
set expandtab
set tabstop=4

" Remove the delay when switching between modes.
set ttimeoutlen=50

" Make Vim scroll smoother.
set ttyfast
set lazyredraw


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

Remove colorcolumn, annoying on small screen

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


let base16colorspace=256
set cursorline

" Don't try to highlight lines longer than 800 characters.
set synmaxcol=800

" Resize splits when the window is resized
au VimResized * :wincmd =

" Highlight VCS conflict markers
match ErrorMsg '^\(<\|=\|>\)\{7\}\([^=].\+\)\?$'

Make blank lines ~ char disappear

let base16colorspace=256
set cursorline

" Don't try to highlight lines longer than 800 characters.
set synmaxcol=800

" Resize splits when the window is resized
au VimResized * :wincmd =

" Highlight VCS conflict markers
match ErrorMsg '^\(<\|=\|>\)\{7\}\([^=].\+\)\?$'
" Hide ~ for blank lines
hi NonText guifg=bg


let g:gitgutter_highlight_lines = 0
map <leader>gg :GitGutterLineHighlightsToggle<CR>

Add GitGutterFold shortcut - ggf

let g:gitgutter_highlight_lines = 0
map <leader>ggh :GitGutterLineHighlightsToggle<CR>
map <leader>ggf :GitGutterFold<CR>


function! GetCompDB()
    exec CMakeCompDB()
endfunc
let FnCMakeCompDB = function("GetCompDB")
let funccmakecompdb = string(FnCMakeCompDB)
"let RunCMakeCompDB = function('GetCompDB')
"function cmake.run() dict
"   let self.fn = function('GetCompDB')
"endfunction
let g:neomake_cmakecompdb_maker = {
    \ 'exe': 'funccmakecompdb',
    \ 'args': ['']
    \ }
noremap <unique> <Plug>NeomakeCompDB :Neomake! cmakecompdb<CR>
function! CMakeTargets()
    echo "Get CMake Targets"
endfunction

Tweak exe argument for neomake maker.

function! GetCompDB()
    exec CMakeCompDB()
endfunc
"let FnCMakeCompDB = function("GetCompDB")
"let funccmakecompdb = string(FnCMakeCompDB)
"let RunCMakeCompDB = function('GetCompDB')
"function cmake.run() dict
"   let self.fn = function('GetCompDB')
"endfunction
let g:neomake_cmakecompdb_maker = {
    \ 'exe': string(function("GetCompDB")),
    \ 'args': ['']
    \ }
noremap <unique> <Plug>NeomakeCompDB :Neomake! cmakecompdb<CR>
function! CMakeTargets()
    echo "Get CMake Targets"
endfunction


" Author: Bartolomeo Stellato <bartolomeo.stellato@gmail.com>
" Description: A language server for Julia

" Set julia executable variable
call ale#Set('julia_executable', 'julia')

function! ale_linters#julia#languageserver#GetCommand(buffer) abort
    let l:julia_executable = ale#Var(a:buffer, 'julia_executable')
    let l:cmd_string = 'using LanguageServer; using Pkg; import StaticLint; import SymbolServer; server = LanguageServer.LanguageServerInstance(isdefined(Base, :stdin) ? stdin : STDIN, isdefined(Base, :stdout) ? stdout : STDOUT, dirname(Pkg.Types.Context().env.project_file)); server.runlinter = true; run(server);'

    return ale#Escape(l:julia_executable) . '--project=@. --startup-file=no --history-file=no -e ' . ale#Escape(l:cmd_string)
endfunction

call ale#linter#Define('julia', {
\   'name': 'languageserver',
\   'lsp': 'stdio',
\   'executable': {b -> ale#Var(b, 'julia_executable')},
\   'command': function('ale_linters#julia#languageserver#GetCommand'),
\   'language': 'julia',
\   'project_root': function('ale#julia#FindProjectRoot'),
\})

Fix space error in string concat

" Author: Bartolomeo Stellato <bartolomeo.stellato@gmail.com>
" Description: A language server for Julia

" Set julia executable variable
call ale#Set('julia_executable', 'julia')

function! ale_linters#julia#languageserver#GetCommand(buffer) abort
    let l:julia_executable = ale#Var(a:buffer, 'julia_executable')
    let l:cmd_string = 'using LanguageServer; using Pkg; import StaticLint; import SymbolServer; server = LanguageServer.LanguageServerInstance(isdefined(Base, :stdin) ? stdin : STDIN, isdefined(Base, :stdout) ? stdout : STDOUT, dirname(Pkg.Types.Context().env.project_file)); server.runlinter = true; run(server);'

    return ale#Escape(l:julia_executable) . ' --project=@. --startup-file=no --history-file=no -e ' . ale#Escape(l:cmd_string)
endfunction

call ale#linter#Define('julia', {
\   'name': 'languageserver',
\   'lsp': 'stdio',
\   'executable': {b -> ale#Var(b, 'julia_executable')},
\   'command': function('ale_linters#julia#languageserver#GetCommand'),
\   'language': 'julia',
\   'project_root': function('ale#julia#FindProjectRoot'),
\})


set shiftwidth=4
set tabstop=4

set makeprg=ninja\ -C\ build\ -v
set wildignore+=docs/*,install/*,build/*,test/*,*.o,*.a,*.d,*.gnp,*.cdl

set efm=%f:%l:%c:\ %tarning:\ %m,%f:%l:%c:\ %trror:\ %m,%f:%l:%c:\ fatal\ %trror:\ %m,%Dninja:\ Entering\ directory\ `%f',

Make sure Vim shows undefined reference errors too

set shiftwidth=4
set tabstop=4

set makeprg=ninja\ -C\ build\ -v
set wildignore+=docs/*,install/*,build/*,test/*,*.o,*.a,*.d,*.gnp,*.cdl

set efm=%f:%l:%c:\ %tarning:\ %m,%f:%l:%c:\ %trror:\ %m,%f:%l:%c:\ fatal\ %trror:\ %m,%Dninja:\ Entering\ directory\ `%f',/home/ton/development/lightbox/build/.././%f:%l:\ undefined\ reference\ to\ %m


function! s:SetUpLoupeHighlight()
  highlight! clear Search
  execute 'highlight! Search ' . pinnacle#embolden('Underlined')
endfunction

if has('autocmd')
  augroup WincentLoupe
    autocmd!
    autocmd ColorScheme * call s:SetUpLoupeHighlight()
  augroup END
endif

Make QuickFix current line stand out again

function! s:SetUpLoupeHighlight()
  " Only works in Neovim, for now; see: https://github.com/vim/vim/issues/1080
  execute 'highlight! QuickFixLine ' . pinnacle#extract_highlight('Search')

  highlight! clear Search
  execute 'highlight! Search ' . pinnacle#embolden('Underlined')
endfunction

if has('autocmd')
  augroup WincentLoupe
    autocmd!
    autocmd ColorScheme * call s:SetUpLoupeHighlight()
  augroup END
endif


" How to: Type the letters then hit space

" General
iabbrev fsl # frozen_string_literal: true

" debugging
iabbrev bpry binding.pry
iabbrev bpid binding.pry if Rails.env.development?
iabbrev brp binding.remote_pry
iabbrev brpid binding.remote_pry if Rails.env.development?

" RSpec
iabbrev af :aggregate_failures

Add binding abbreviations for vim

" How to: Type the letters then hit space

" General
iabbrev fsl # frozen_string_literal: true

" debugging
iabbrev bpry binding.pry
iabbrev bpid binding.pry if Rails.env.development?
iabbrev bpit binding.pry if Rails.env.test?
iabbrev brp binding.remote_pry
iabbrev brpid binding.remote_pry if Rails.env.development?
iabbrev brpit binding.remote.pry if Rails.env.test?

" RSpec
iabbrev af :aggregate_failures


let s:Vital = vital#of('autocomplete_swift')

let s:String = s:Vital.import('Data.String')

function! omni_swift#complete(first, base)
    if a:first
        let s:context = s:get_context(getline('.'), col('.'))
        return s:context.complete_pos
    else
        let s:context.complete_str = a:base
        return s:complete(s:context)
    endif
endfunction

function! s:get_context(text, column)
    let l:text = a:text[0:a:column - 1]
    let l:complete_pos = autocomplete_swift#decide_completion_position(
    \   l:text,
    \   a:column,
    \)

    let l:context = {
    \   'input_text': l:text,
    \   'complete_pos': l:complete_pos,
    \}

    return l:context
endfunction

function! s:complete(context)
    let l:candidates = []

    for l:c in autocomplete_swift#complete(line('.'), a:context.complete_pos + 1)
        if s:String.starts_with(l:c.word, a:context.complete_str) == 0
            continue
        end
        call add(l:candidates, l:c)
    endfor

    return l:candidates
endfunction

Fix slicing the current line to generate context of completion.

let s:Vital = vital#of('autocomplete_swift')

let s:String = s:Vital.import('Data.String')

function! omni_swift#complete(first, base)
    if a:first
        let s:context = s:get_context(getline('.'), col('.'))
        return s:context.complete_pos
    else
        let s:context.complete_str = a:base
        return s:complete(s:context)
    endif
endfunction

function! s:get_context(text, column)
    let l:text = a:text[0:a:column - 2]
    let l:complete_pos = autocomplete_swift#decide_completion_position(
    \   l:text,
    \   a:column,
    \)

    let l:context = {
    \   'input_text': l:text,
    \   'complete_pos': l:complete_pos,
    \}

    return l:context
endfunction

function! s:complete(context)
    let l:candidates = []

    for l:c in autocomplete_swift#complete(line('.'), a:context.complete_pos + 1)
        if s:String.starts_with(l:c.word, a:context.complete_str) == 0
            continue
        end
        call add(l:candidates, l:c)
    endfor

    return l:candidates
endfunction


" ================ Search Settings  =================

set incsearch       " Find the next match as we type the search
set hlsearch        " Hilight searches by default
set viminfo='100,f1 " Save up to 100 marks, enable capital marks
set ignorecase      " Ignore case when searching...
set smartcase       " ...unless we type a capital
set wrapscan        " Search wrap the file

" Using Perl/Python regex style by default when searching
nnoremap / /\v
vnoremap / /\v

" Keep search matches in the middle of the window.
nnoremap n nzzzv
nnoremap N Nzzzv

" Same when jumping around
nnoremap g; g;zz
nnoremap g, g,zz
nnoremap <c-o> <c-o>zz

Revert "Wrapping search. Perl regex while searching. Center search matches and jumps"


Plug 'Shougo/deoplete.nvim'
Plug 'airblade/vim-gitgutter'
Plug 'ctrlpvim/ctrlp.vim'
Plug 'easymotion/vim-easymotion'
Plug 'jiangmiao/auto-pairs'
Plug 'liuchengxu/vim-better-default'
Plug 'rafi/awesome-vim-colorschemes'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-dadbod'
Plug 'tpope/vim-dispatch'
Plug 'tpope/vim-eunuch'
Plug 'tpope/vim-fireplace'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-sleuth'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-vinegar'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'w0rp/ale'

Add vim-sexp (and tpopes bindings)

Plug 'Shougo/deoplete.nvim'
Plug 'airblade/vim-gitgutter'
Plug 'ctrlpvim/ctrlp.vim'
Plug 'easymotion/vim-easymotion'
Plug 'guns/vim-sexp'
Plug 'jiangmiao/auto-pairs'
Plug 'liuchengxu/vim-better-default'
Plug 'rafi/awesome-vim-colorschemes'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-dadbod'
Plug 'tpope/vim-dispatch'
Plug 'tpope/vim-eunuch'
Plug 'tpope/vim-fireplace'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-sexp-mappings-for-regular-people'
Plug 'tpope/vim-sleuth'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-unimpaired'
Plug 'tpope/vim-vinegar'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'w0rp/ale'


set autoindent
set autoread
set background=dark
set cmdheight=1
set cursorline
set encoding=UTF-8
set expandtab " Convert tabs to spaces
set hidden " TextEdit might fail if hidden is not set
set nobackup
set nocompatible
set noswapfile
set nowrap
set nowritebackup
set number
set ruler
set shortmess+=c " Don't pass messages to |ins-completion-menu|
set smartindent
set smarttab
set termguicolors
set timeoutlen=100
" Use persistent history.
if !isdirectory('~/AppData/Local/nvim/undo')
    call mkdir('~/AppData/Local/nvim/undo', '', 0700)
endif
set undodir=~/AppData/Local/nvim/undo
set undofile " Maintain undo history between sessions
set updatetime=100 " Default is 4000ms
syntax on
syntax enable
filetype plugin indent on

" Automatically install missing plugins on startup
autocmd VimEnter *
  \  if len(filter(values(g:plugs), '!isdirectory(v:val.dir)'))
  \|   PlugInstall --sync | q
  \| endif

Remove undo dir auto create

set autoindent
set autoread
set background=dark
set cmdheight=1
set cursorline
set encoding=UTF-8
set expandtab " Convert tabs to spaces
set hidden " TextEdit might fail if hidden is not set
set nobackup
set nocompatible
set noswapfile
set nowrap
set nowritebackup
set number
set ruler
set shortmess+=c " Don't pass messages to |ins-completion-menu|
set smartindent
set smarttab
set termguicolors
set timeoutlen=100
set undodir=~/AppData/Local/nvim/undo
set undofile " Maintain undo history between sessions
set updatetime=100 " Default is 4000ms
syntax on
syntax enable
filetype plugin indent on

" Automatically install missing plugins on startup
autocmd VimEnter *
  \  if len(filter(values(g:plugs), '!isdirectory(v:val.dir)'))
  \|   PlugInstall --sync | q
  \| endif


let mapleader="\\"

set autoindent
set smartindent
set smarttab
set expandtab
set shiftround
set nojoinspaces
set nofoldenable
set tabstop=4
set softtabstop=4
set shiftwidth=4
set ruler

" Set key shortcuts
set bs=2
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>

" Open the tag definition in a vertical split window, off to the right.
nnoremap <silent> <Leader>] :vsp <CR><C-W>l<CR>:exec("tag ".expand("<cword>"))<CR>
nnoremap <Leader><Left> :tabprev <CR>
nnoremap <Leader>h :tabprev <CR>
nnoremap <Leader>l :tabnext <CR>
nnoremap <Leader><Right> :tabnext <CR>
nnoremap <Leader>n :tabnew <CR>
nnoremap <Leader>q :q <CR>
nnoremap <C-W>t :tabnew <CR>
nnoremap <Leader><Backspace> :undo <CR>
nnoremap <space>y :Unite history/yank<cr>
nnoremap <space>b :Unite buffer<CR>
nnoremap ` :
noremap   <Up>     <NOP>
noremap   <Down>   <NOP>
noremap   <Left>   <NOP>
noremap   <Right>  <NOP>

Switch the unite shortcuts to use the leader rather than space

let mapleader="\\"

set autoindent
set smartindent
set smarttab
set expandtab
set shiftround
set nojoinspaces
set nofoldenable
set tabstop=4
set softtabstop=4
set shiftwidth=4
set ruler

" Set key shortcuts
set bs=2
map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>

" Open the tag definition in a vertical split window, off to the right.
nnoremap <silent> <Leader>] :vsp <CR><C-W>l<CR>:exec("tag ".expand("<cword>"))<CR>
nnoremap <Leader><Left> :tabprev <CR>
nnoremap <Leader>h :tabprev <CR>
nnoremap <Leader>l :tabnext <CR>
nnoremap <Leader><Right> :tabnext <CR>
nnoremap <Leader>n :tabnew <CR>
nnoremap <Leader>q :q <CR>
nnoremap <C-W>t :tabnew <CR>
nnoremap <Leader><Backspace> :undo <CR>
nnoremap <Leader>y :Unite history/yank<cr>
nnoremap <Leader>b :Unite buffer<CR>
nnoremap ` :
noremap   <Up>     <NOP>
noremap   <Down>   <NOP>
noremap   <Left>   <NOP>
noremap   <Right>  <NOP>


" Vim Syntax configuration for ruby-ll grammar files.
"
" Language:   ruby-ll
" Maintainer: Yorick Peterse <yorickpeterse@gmail.com>
"
syntax clear

syn include @rubyTop syntax/ruby.vim

syn match rllKeyword "%[a-zA-Z]\+"
syn match rllComment "#.*$"
syn match rllOperator "?|+|\*"

syn region rllRuby start="{" end="}" contains=@rubyTop

hi link rllKeyword  Keyword
hi link rllComment  Comment
hi link rllOperator Operator

let b:current_syntax = "rll"

Fix Vim highlighting of action blocks

" Vim Syntax configuration for ruby-ll grammar files.
"
" Language:   ruby-ll
" Maintainer: Yorick Peterse <yorickpeterse@gmail.com>
"
syntax clear

syn include @rubyTop syntax/ruby.vim

syn match rllKeyword "%[a-zA-Z]\+"
syn match rllComment "#.*$"
syn match rllOperator "?|+|\*"
syn match rllDelimiter '[=|]'

syn region rllRuby transparent matchgroup=rllDelimiter
                   \ start="{" end="}"
                   \ contains=@rubyTop

hi link rllKeyword  Keyword
hi link rllComment  Comment
hi link rllOperator Operator

let b:current_syntax = "rll"


" Tab width
set shiftwidth=2
set tabstop=2
set softtabstop=2

" Use space indentation
set expandtab

" Use unix line endings by default
set fileformats=unix,dos

Change vim to always use unix formatting


" let s:eslint_path = system('PATH=$(npm bin):$PATH && which eslint')
" let b:syntastic_javascript_eslint_exec = substitute(s:eslint_path, '^\n*\s*\(.\{-}\)\n*\s*$', '\1', '')

Add command to run local installation of ESLint

" let s:eslint_path = system('PATH=$(npm bin):$PATH && which eslint')
" let b:syntastic_javascript_eslint_exec = substitute(s:eslint_path, '^\n*\s*\(.\{-}\)\n*\s*$', '\1', '')

fun! RunESlint(path)
  " Clear terminal
  execute '!clear'

  " Run ESLint
  execute '! ./node_modules/.bin/eslint ' . expand('%')
endfun

command! -nargs=* Lint call RunESlint('src')


" File:        github-issues.vim
" Version:     3.0.0b
" Description: Pulls github issues into Vim
" Maintainer:  Jonathan Warner <jaxbot@gmail.com> <http://github.com/jaxbot>
" Homepage:    http://jaxbot.me/
" Repository:  https://github.com/jaxbot/github-issues.vim
" License:     Copyright (C) 2014 Jonathan Warner
"              Released under the MIT license
"        ======================================================================

" do not load twice
if exists("g:github_issues_loaded") || &cp
  finish
endif
let g:github_issues_loaded = 1

" do not continue if Vim is not compiled with Python2.7 support
if !has("python")
  echo "github-issues.vim requires Python support."
  finish
endif

python <<EOF
from os import path as p
import sys
import vim

# generate path that needs to
base_path = p.abspath(p.join(vim.eval("expand('<sfile>:p:h')"), ".."))
sys.path.append(base_path)

# print lib_path
from lib.issue_list import IssueList
from lib.issue import Issue
EOF

" create issue list
command! -nargs=* Gissues :python IssueList.show_issues(<f-args>)

" create a new issue
command! -nargs=* Gissue :python Issue.open(<f-args>)

Rebuild out plugin front-facing api and include reload ability. Make development a lot easier!!

" File:        github-issues.vim
" Version:     3.0.0b
" Description: Pulls github issues into Vim
" Maintainer:  Jonathan Warner <jaxbot@gmail.com> <http://github.com/jaxbot>
" Homepage:    http://jaxbot.me/
" Repository:  https://github.com/jaxbot/github-issues.vim
" License:     Copyright (C) 2014 Jonathan Warner
"              Released under the MIT license
"        ======================================================================

" do not load twice
if exists("g:github_issues_loaded") || &cp
  finish
endif
let g:github_issues_loaded = 1

" do not continue if Vim is not compiled with Python2.7 support
if !has("python")
  echo "github-issues.vim requires Python support."
  finish
endif

python <<EOF
from os import path as p
import sys
import vim
import imp

# generate path that needs to
base_path = p.abspath(p.join(vim.eval("expand('<sfile>:p:h')"), "../lib"))
sys.path.insert(0, base_path)

import issue
import issue_list

def reload_vimhub():
  imp.reload(issue)
  imp.reload(issue_list)
EOF

" create issue list
command! -nargs=* Gissues :python issue_list.IssueList.show_issues(<f-args>)

" create a new issue
command! -nargs=* Gissue :python issue.Issue.open(<f-args>)

" reload module
command! VimHubReload :python reload_vimhub()


NeoBundle 'scrooloose/syntastic'

" Syntastic Settings
" These are the recommended default settings
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_enable_signs = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

Change from NeoBundle to Vundle


" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.dotfiles/vim/vim.symlink/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" Toggle tagbar {{{
  nmap <Leader>t :TagbarToggle<CR>
" }}}

" neocompcache {{{
  let g:neocomplcache_enable_at_startup = 1
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <Leader>a :AV<CR>
  nmap <C-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'
" }}}

Use Solarized colours with Powerline

" Open Vundle config quickly {{{
  nnoremap <Leader>vu :e ~/.dotfiles/vim/vim.symlink/config/00-vundle.vim<CR>
" }}}

" Run Hammer to preview this buffer {{{
  nmap <Leader>p :Hammer<CR>
" }}}

" Toggle tagbar {{{
  nmap <Leader>t :TagbarToggle<CR>
" }}}

" neocompcache {{{
  let g:neocomplcache_enable_at_startup = 1
" }}}

" NERDTree {{{
  let NERDTreeIgnore=['\.rbc$', '\~$']
  map <Leader>n :NERDTreeToggle<CR>
" }}}

" Rake.vim {{{
  nmap <Leader>a :AV<CR>
  nmap <C-a> :A<CR>
" }}}

" Bufexplorer {{
  nnoremap <C-B> :BufExplorer<cr>
" }}

" PickHEX {{{
  imap <D-C> <c-o>:PickHEX<CR>
  nmap <D-C> :PickHEX<CR>
" }}}

" Syntastic {{{
  " Mark syntax errors with :signs
  let g:syntastic_enable_signs=1
  let g:syntastic_quiet_warnings=1
" }}}

" NERDCommenter {{{
  let NERDSpaceDelims=1
" }}}

" Powerline {{{
  " Use fancy symbols
  let g:Powerline_symbols = 'fancy'

  " Go Solarized
  let g:Powerline_theme = 'skwp'
  let g:Powerline_colorscheme = 'skwp'
" }}}


set nocompatible  " no vi complatibility

" install plugins
call plug#begin()
" Main plugins
Plug 'mileszs/ack.vim'
Plug 'jiangmiao/auto-pairs'
Plug 'kien/ctrlp.vim'
Plug 'Shougo/deoplete.nvim'
Plug 'scrooloose/nerdtree'
Plug 'NLKNguyen/papercolor-theme'
Plug 'ervandew/supertab'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'
Plug 'SirVer/ultisnips'

" Plugin extras
Plug 'zchee/deoplete-jedi'
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'
runtime local.plug.vim
call plug#end()

" source config
runtime core.vim
runtime plugins.vim
runtime functions.vim
runtime remaps.vim

" source local config
runtime local.vim

" source project config
if filereadable(".vimlocal")
	source .vimlocal
endif

Add tab completion for c

set nocompatible  " no vi complatibility

" install plugins
call plug#begin()
" Main plugins
Plug 'mileszs/ack.vim'
Plug 'jiangmiao/auto-pairs'
Plug 'kien/ctrlp.vim'
Plug 'Shougo/deoplete.nvim'
Plug 'scrooloose/nerdtree'
Plug 'NLKNguyen/papercolor-theme'
Plug 'ervandew/supertab'
Plug 'vim-airline/vim-airline'
Plug 'moll/vim-bbye'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-repeat'
Plug 'tpope/vim-surround'
Plug 'SirVer/ultisnips'

" Plugin extras
Plug 'vim-airline/vim-airline-themes'
Plug 'honza/vim-snippets'
Plug 'Shougo/deoplete-clangx'
Plug 'zchee/deoplete-jedi'
runtime local.plug.vim
call plug#end()

" source config
runtime core.vim
runtime plugins.vim
runtime functions.vim
runtime remaps.vim

" source local config
runtime local.vim

" source project config
if filereadable(".vimlocal")
	source .vimlocal
endif


autocmd BufNewFile,BufRead *.cu set cindent

set cinoptions=>s,e0,n0,f0,{0,}0,^0,L-1,:0,=s,l0,b0,g0,hs,N-s,ps,ts,is,+s,c3,C0,/0,(2s,us,U0,w0,W0,k0,m0,j0,J0,)20,*70,#0
nmap <Leader>k :tabe %<CR>g]

Add doxygen highlight for c/c++ files

autocmd BufNewFile,BufRead *.cu set cindent

autocmd BufNewFile,BufRead *.cc,*.cpp,*.cu,*.h,*.hpp,*.c set ft=cpp.doxygen

set cinoptions=>s,e0,n0,f0,{0,}0,^0,L-1,:0,=s,l0,b0,g0,hs,N-s,ps,ts,is,+s,c3,C0,/0,(2s,us,U0,w0,W0,k0,m0,j0,J0,)20,*70,#0
nmap <Leader>k :tabe %<CR>g]


let s:suite = themis#suite('operator_pending_behavior')
let s:assert = themis#helper('assert')

" NOTE: Also see repetition.vim spec
" :h o_v
" :h o_V
" :h o_CTRL-V

" Helper:
function! s:add_line(str)
    put! =a:str
endfunction
function! s:add_lines(lines)
    for line in reverse(a:lines)
        put! =line
    endfor
endfunction
function! s:get_pos_char()
    return getline('.')[col('.')-1]
endfunction

function! s:suite.force_exclusive()
    call s:assert.skip("because it seems vim has no variables to restore o_v, o_V, and o_Ctrl-V information")
    " dv/pattern
    call s:add_line('1pattern 2pattern 3pattern 4pattern 5pattern')
    normal! gg0
    call s:assert.equals(getline('.'), '1pattern 2pattern 3pattern 4pattern 5pattern')
    exec "normal" "dv/\\dpattern\<CR>"
    call s:assert.equals(getline('.'), 'pattern 3pattern 4pattern 5pattern')
endfunction

" TODO:

Add note for skipped test of o_v, o_V, and o_Ctrl-v

let s:suite = themis#suite('operator_pending_behavior')
let s:assert = themis#helper('assert')

" NOTE: Also see repetition.vim spec
" :h o_v
" :h o_V
" :h o_CTRL-V

" Helper:
function! s:add_line(str)
    put! =a:str
endfunction
function! s:add_lines(lines)
    for line in reverse(a:lines)
        put! =line
    endfor
endfunction
function! s:get_pos_char()
    return getline('.')[col('.')-1]
endfunction

function! s:suite.force_exclusive()
    call s:assert.skip("because it seems vim has no variables to restore o_v, o_V, and o_Ctrl-V information")
    " NOTE:
    "   - http://lingr.com/room/vim/archives/2014/09/22#message-20239719
    "   - https://groups.google.com/forum/#!topic/vim_dev/MNtX3jHkNWw
    "   - https://groups.google.com/forum/#!msg/vim_dev/lR5rONDwgs8/iLsVCrxo_WsJ
    call s:add_line('1pattern 2pattern 3pattern 4pattern 5pattern')
    normal! gg0
    call s:assert.equals(getline('.'), '1pattern 2pattern 3pattern 4pattern 5pattern')
    exec "normal" "dv/\\dpattern\<CR>"
    call s:assert.equals(getline('.'), 'pattern 3pattern 4pattern 5pattern')
endfunction

" TODO:


lua << EOF
    -- You dont need to set any of these options. These are the default ones. Only
    -- the loading is important
    local actions = require('telescope.actions')
    require('telescope').setup {
      defaults = {
        mappings = {
          i = {
            ["<C-j>"]   = actions.move_selection_next,
            ["<C-k>"]   = actions.move_selection_previous,
            ["<C-q>"]   = actions.smart_send_to_qflist + actions.open_qflist,
            ["<ESC>"]   = actions.close,
            }
          }
        }
      }

    -- To get fzf loaded and working with telescope, you need to call
    -- load_extension, somewhere after setup function:
    require('telescope').load_extension('fzf')
EOF

" Find files using Telescope command-line sugaras.
nnoremap <C-p> <cmd>lua require('telescope.builtin').find_files()<cr>
nnoremap <C-b> <cmd>lua require('telescope.builtin').buffers()<cr>
nnoremap <C-i> <cmd>lua require('telescope.builtin').lsp_document_symbols()<cr>
nnoremap <leader>r <cmd>lua require('telescope.builtin').lsp_references()<cr>

Change key for document symbols

lua << EOF
    -- You dont need to set any of these options. These are the default ones. Only
    -- the loading is important
    local actions = require('telescope.actions')
    require('telescope').setup {
      defaults = {
        mappings = {
          i = {
            ["<C-j>"]   = actions.move_selection_next,
            ["<C-k>"]   = actions.move_selection_previous,
            ["<C-q>"]   = actions.smart_send_to_qflist + actions.open_qflist,
            ["<ESC>"]   = actions.close,
            }
          }
        }
      }

    -- To get fzf loaded and working with telescope, you need to call
    -- load_extension, somewhere after setup function:
    require('telescope').load_extension('fzf')
EOF

" Find files using Telescope command-line sugaras.
nnoremap <C-p> <cmd>lua require('telescope.builtin').find_files()<cr>
nnoremap <C-b> <cmd>lua require('telescope.builtin').buffers()<cr>
nnoremap <leader>s <cmd>lua require('telescope.builtin').lsp_document_symbols()<cr>
nnoremap <leader>r <cmd>lua require('telescope.builtin').lsp_references()<cr>


" 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'
let g:tex_comment_nospell = 1

let g:syntastic_tex_checkers = ['lacheck']

Add new mapping <F3> to :TTemplate

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

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

nnoremap <F3> :TTemplate<CR>

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

let g:syntastic_tex_checkers = ['lacheck']


" Recognise files with unusual file extensions
au BufRead,BufNewFile *.md set filetype=markdown
au BufNewFile,BufRead *.ejs set filetype=html
au BufNewFile,BufRead *.html set filetype=htmldjango
au BufNewFile,BufRead *.sh.j2 set ft=sh
au BufNewFile,BufRead *.wsgi set ft=python
au BufNewFile,BufRead *.wsgi.j2 set ft=python
au BufNewFile,BufRead *.py.j2 set ft=python
au BufRead,BufNewFile *.tf set filetype=terraform
au BufNewFile,BufRead *.muttrc set ft=muttrc
au BufNewFile,BufRead Jenkinsfile set ft=groovy

Mark .coveragerc as being an INI file

" Recognise files with unusual file extensions
au BufRead,BufNewFile *.md set filetype=markdown
au BufNewFile,BufRead *.ejs set filetype=html
au BufNewFile,BufRead *.html set filetype=htmldjango
au BufNewFile,BufRead *.sh.j2 set ft=sh
au BufNewFile,BufRead *.wsgi set ft=python
au BufNewFile,BufRead *.wsgi.j2 set ft=python
au BufNewFile,BufRead *.py.j2 set ft=python
au BufRead,BufNewFile *.tf set filetype=terraform
au BufNewFile,BufRead *.muttrc set ft=muttrc
au BufNewFile,BufRead Jenkinsfile set ft=groovy
au BufNewFile,BufRead .coveragerc set ft=dosini


"remove right-hand whitespace from all lines on uncomment
let g:tcomment#rstrip_on_uncomment = 2

"use // to comment in vue files
call tcomment#type#Define('vue', '// %s')

Add the correct comment style for the blade filetype

"remove right-hand whitespace from all lines on uncomment
let g:tcomment#rstrip_on_uncomment = 2

"use // to comment in vue files
call tcomment#type#Define('vue', '// %s')
call tcomment#type#Define('blade', '{{-- %s --}}')


" Change the leader key to space
let mapleader = ' '

" TODO: Vs. NERDTreeFind?
nnoremap <Leader>n :NERDTreeToggle<CR>
nnoremap <Leader>s :source $MYVIMRC<CR>

nnoremap <Leader>b :CtrlPBuffer<CR>
nnoremap <Leader>r :CtrlPMRU<CR>
let g:ctrlp_map = '<Leader>t'

" Fast navigation between buffers
nnoremap <C-N> :bnext<CR>
nnoremap <C-P> :bprev<CR>

" TODO: Vs. "w" or "W"?
nmap Q :Bdelete<CR>
nmap QQ :Bdelete!<CR>

" faster navigation between splits
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l

Delete buffers without wait (keypress timeout)

" Change the leader key to space
let mapleader = ' '

" TODO: Vs. NERDTreeFind?
nnoremap <Leader>n :NERDTreeToggle<CR>
nnoremap <Leader>s :source $MYVIMRC<CR>

nnoremap <Leader>b :CtrlPBuffer<CR>
nnoremap <Leader>r :CtrlPMRU<CR>
let g:ctrlp_map = '<Leader>t'

" Fast navigation between buffers
nnoremap <C-N> :bnext<CR>
nnoremap <C-P> :bprev<CR>

nmap <Leader>w :Bdelete<CR>
nmap <Leader>Q :Bdelete!<CR>

" faster navigation between splits
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l


" disable the bell
set vb t_vb=

" enable line numbering
set number

" disable startup message
set shortmess+=I

" statusline
set laststatus=2

" auto reload changed files
set autoread

" mouse compatibility
set mouse=a

" x clipboard access
set clipboard+=unnamedplus

" case-insensitive searching - case-sensitive if uppercase letters are used
set ignorecase
set smartcase

" store all swap files centrally
set directory=$HOME/.config/nvim/tmp/swap/
if !isdirectory(expand(&directory))
  call mkdir(expand(&directory), 'p')
endif

" store all backup files centrally
set backupdir=$HOME/.config/nvim/tmp/backup/
if !isdirectory(expand(&backupdir))
  call mkdir(expand(&backupdir), 'p')
endif

" persistent undo
set undofile
set undodir=$HOME/.config/nvim/tmp/undo/
set undolevels=500
set undoreload=500
if !isdirectory(expand(&undodir))
  call mkdir(expand(&undodir), 'p')
endif

" don't keep commenting on enter or o/O
autocmd BufNewFile,BufRead * setlocal formatoptions-=ro

" always show tab line
set showtabline=2

" don't show mode in command line
set noshowmode

Add checktime option to (hopefully) auto reload

" disable the bell
set vb t_vb=

" enable line numbering
set number

" disable startup message
set shortmess+=I

" statusline
set laststatus=2

" auto reload changed files
set autoread
set checktime

" mouse compatibility
set mouse=a

" x clipboard access
set clipboard+=unnamedplus

" case-insensitive searching - case-sensitive if uppercase letters are used
set ignorecase
set smartcase

" store all swap files centrally
set directory=$HOME/.config/nvim/tmp/swap/
if !isdirectory(expand(&directory))
  call mkdir(expand(&directory), 'p')
endif

" store all backup files centrally
set backupdir=$HOME/.config/nvim/tmp/backup/
if !isdirectory(expand(&backupdir))
  call mkdir(expand(&backupdir), 'p')
endif

" persistent undo
set undofile
set undodir=$HOME/.config/nvim/tmp/undo/
set undolevels=500
set undoreload=500
if !isdirectory(expand(&undodir))
  call mkdir(expand(&undodir), 'p')
endif

" don't keep commenting on enter or o/O
autocmd BufNewFile,BufRead * setlocal formatoptions-=ro

" always show tab line
set showtabline=2

" don't show mode in command line
set noshowmode


" HTML5 ominicomplete & syntax
NeoBundleLazy 'othree/html5.vim', {
            \     'autoload': {'filetypes': ['html', 'htmldjango']}
            \  }
" CSS3 syntax
NeoBundleLazy 'hail2u/vim-css3-syntax', {
            \     'autoload': {'filetypes': ['css']}
            \  }
" Coq syntax
NeoBundleLazy 'jvoorhis/coq.vim', {
            \     'autoload': {'filetypes': ['coq']}
            \  }
" CoffeeScript
if v:version >= 704
    au BufRead,BufNewFile,BufReadPre *.coffee set filetype=coffee
    NeoBundleLazy 'kchmck/vim-coffee-script', {
                \     'autoload': {'filetypes': ['coffee']}
                \  }
endif
" Scala
au BufRead,BufNewFile,BufReadPre *.scala set filetype=scala
NeoBundleLazy 'derekwyatt/vim-scala', {
                \     'autoload': {'filetypes': ['scala']}
                \  }

Add syntax highlighting for JSX

" HTML5 ominicomplete & syntax
NeoBundleLazy 'othree/html5.vim', {
            \     'autoload': {'filetypes': ['html', 'htmldjango']}
            \  }
" CSS3 syntax
NeoBundleLazy 'hail2u/vim-css3-syntax', {
            \     'autoload': {'filetypes': ['css']}
            \  }
" for vim-jsx
NeoBundle 'pangloss/vim-javascript', {
            \     'autoload': {'filetypes': ['javascript']}
            \  }
" React JSX
NeoBundle 'mxw/vim-jsx', {
            \     'autoload': {'filetypes': ['javascript.jsx']}
            \  }
" Coq syntax
NeoBundleLazy 'jvoorhis/coq.vim', {
            \     'autoload': {'filetypes': ['coq']}
            \  }
" Scala
NeoBundleLazy 'derekwyatt/vim-scala', {
            \     'autoload': {'filetypes': ['scala']}
            \  }
" CoffeeScript
if v:version >= 704
    au BufRead,BufNewFile,BufReadPre *.coffee set filetype=coffee
    NeoBundleLazy 'kchmck/vim-coffee-script', {
                \     'autoload': {'filetypes': ['coffee']}
                \  }
endif


" off99555's '.vimrc' configurations
" Extended to the Ultimate .vimrc

"let g:airline_theme='base16_solarized'
"let g:airline#extensions#tabline#enabled = 1
"colorscheme solarized

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" file settings
set number
" Maximize the Vim window under Windows OS
if has('gui_running')
    au GUIEnter * simalt ~x
endif

" Stay in visual mode after indentation
vnoremap < <gv
vnoremap > >gv

" Make big Y behaves like other command
map Y y$

" Improve up/down movement on wrapped lines
nnoremap j gj
nnoremap k gk

" Force saving files that require root permission
cmap w!! %!sudo tee > /dev/null %

" The smash escape
inoremap jk <Esc>
"inoremap kj <Esc>

" Open new split windows to the right/bottom instead of left/top
"set splitright splitbelow

" Allow working with Unicode characters
scriptencoding utf-8
"set listchars=trail:·,precedes:«,extends:»,eol:¬,tab:▸\

Allow full screen on Windows only because the key

" off99555's '.vimrc' configurations
" Extended to the Ultimate .vimrc

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" file settings
set number
" Maximize the Vim window under Windows OS
if has('gui_running') && (has("win16") || has("win32"))
    au GUIEnter * simalt ~x
endif

" Stay in visual mode after indentation
vnoremap < <gv
vnoremap > >gv

" Make big Y behaves like other command
map Y y$

" Improve up/down movement on wrapped lines
nnoremap j gj
nnoremap k gk

" Force saving files that require root permission
cmap w!! %!sudo tee > /dev/null %

" The smash escape
inoremap jk <Esc>
"inoremap kj <Esc>

" Open new split windows to the right/bottom instead of left/top
"set splitright splitbelow

" Allow working with Unicode characters
scriptencoding utf-8
"set listchars=trail:·,precedes:«,extends:»,eol:¬,tab:▸\


au BufWritePost *.rs silent!make ctags > /dev/null 2>&1

Make syntastic plugin work a little better.

au BufWritePost *.rs silent!make ctags > /dev/null 2>&1
let g:syntastic_rust_rustc_fname = "src/lib.rs"


" dockerfile.vim - Syntax highlighting for Dockerfiles
" Maintainer:   Honza Pokorny <https://honza.ca>
" Version:      0.5

if exists("b:current_syntax")
    finish
endif

let b:current_syntax = "dockerfile"

syntax case ignore

syntax match dockerfileKeyword /\v^\s*(ONBUILD\s+)?(ADD|CMD|ENTRYPOINT|ENV|EXPOSE|FROM|MAINTAINER|RUN|USER|LABEL|VOLUME|WORKDIR|COPY|STOPSIGNAL)\s/
highlight link dockerfileKeyword Keyword

syntax region dockerfileString start=/\v"/ skip=/\v\\./ end=/\v"/
highlight link dockerfileString String

syntax match dockerfileComment "\v^\s*#.*$"
highlight link dockerfileComment Comment

set commentstring=#\ %s

" match "RUN", "CMD", and "ENTRYPOINT" lines, and parse them as shell
let s:current_syntax = b:current_syntax
unlet b:current_syntax
syntax include @SH syntax/sh.vim
let b:current_syntax = s:current_syntax
syntax region shLine matchgroup=dockerfileKeyword start=/\v^\s*(RUN|CMD|ENTRYPOINT)\s/ end=/\v$/ contains=@SH
" since @SH will handle "\" as part of the same line automatically, this "just works" for line continuation too, but with the caveat that it will highlight "RUN echo '" followed by a newline as if it were a block because the "'" is shell line continuation...  not sure how to fix that just yet (TODO)

Add `ARG` instruction syntax for vim

" dockerfile.vim - Syntax highlighting for Dockerfiles
" Maintainer:   Honza Pokorny <https://honza.ca>
" Version:      0.5

if exists("b:current_syntax")
    finish
endif

let b:current_syntax = "dockerfile"

syntax case ignore

syntax match dockerfileKeyword /\v^\s*(ONBUILD\s+)?(ADD|CMD|ENTRYPOINT|ENV|EXPOSE|FROM|MAINTAINER|RUN|USER|LABEL|VOLUME|WORKDIR|COPY|STOPSIGNAL|ARG)\s/
highlight link dockerfileKeyword Keyword

syntax region dockerfileString start=/\v"/ skip=/\v\\./ end=/\v"/
highlight link dockerfileString String

syntax match dockerfileComment "\v^\s*#.*$"
highlight link dockerfileComment Comment

set commentstring=#\ %s

" match "RUN", "CMD", and "ENTRYPOINT" lines, and parse them as shell
let s:current_syntax = b:current_syntax
unlet b:current_syntax
syntax include @SH syntax/sh.vim
let b:current_syntax = s:current_syntax
syntax region shLine matchgroup=dockerfileKeyword start=/\v^\s*(RUN|CMD|ENTRYPOINT)\s/ end=/\v$/ contains=@SH
" since @SH will handle "\" as part of the same line automatically, this "just works" for line continuation too, but with the caveat that it will highlight "RUN echo '" followed by a newline as if it were a block because the "'" is shell line continuation...  not sure how to fix that just yet (TODO)


"--------------------------------------
" GUI SETTINGS
"--------------------------------------

set guioptions-=m   " Disable menu bar
set guioptions-=e   " Disable GUI tabs
set guioptions-=T   " Disable toolbar
set guioptions-=r   " Disable right scrollbar
set guioptions-=R   " Disable right scrollbar if vsplit
set guioptions-=l   " Disable left scrollbar
set guioptions-=L   " Disable left scrollbar if vsplit

set cursorline

set colorcolumn=80

colorscheme liquidcarbon

if has("gui_macvim")
    set guifont=Menlo\ Regular:h12
else
    set guifont=Ubuntu\ Mono\ 10
endif

Update font size for linux

"--------------------------------------
" GUI SETTINGS
"--------------------------------------

set guioptions-=m   " Disable menu bar
set guioptions-=e   " Disable GUI tabs
set guioptions-=T   " Disable toolbar
set guioptions-=r   " Disable right scrollbar
set guioptions-=R   " Disable right scrollbar if vsplit
set guioptions-=l   " Disable left scrollbar
set guioptions-=L   " Disable left scrollbar if vsplit

set cursorline

set colorcolumn=80

colorscheme liquidcarbon

if has("gui_macvim")
    set guifont=Menlo\ Regular:h12
else
    set guifont=Ubuntu\ Mono\ 12
endif


" markdown filetype file
au BufRead,BufNewFile *.mkd,*.markdown,*.mdwn   set filetype=mkd

Add md files as markdown files.

" markdown filetype file
au BufRead,BufNewFile *.mkd,*.markdown,*.mdwn,*.md   set filetype=mkd


MP 'pangloss/vim-javascript',  { 'for': ['javascript'] }
MP 'mxw/vim-jsx',              { 'for': ['javascript', 'javascript.jsx'] }
MP 'neoclide/vim-jsx-improve', { 'for': ['javascript', 'javascript.jsx'] }

Remove redundant jsx syntax enhancement plugin

MP 'pangloss/vim-javascript',  { 'for': ['javascript'] }
MP 'neoclide/vim-jsx-improve', { 'for': ['javascript', 'javascript.jsx'] }


" insert a before { } block around a line
nnoremap <silent> \bf ^ibefore { <esc>$a }

" insert a specify { } block around a line
nnoremap <silent> \sp ^ispecify { <esc>$a }

" RSpec.vim mappings
let g:rspec_command = ":!clear; bundle exec rspec -f doc {spec}"

map <Leader>t :call RunCurrentSpecFile()<CR>
map <Leader>s :call RunNearestSpec()<CR>
map <Leader>l :call RunLastSpec()<CR>
map <Leader>a :call RunAllSpecs()<CR>

Prepend spring to speed up test feedback

" insert a before { } block around a line
nnoremap <silent> \bf ^ibefore { <esc>$a }

" insert a specify { } block around a line
nnoremap <silent> \sp ^ispecify { <esc>$a }

" RSpec.vim mappings
let g:rspec_command = ":!clear; bundle exec spring rspec -f doc {spec}"

map <Leader>t :call RunCurrentSpecFile()<CR>
map <Leader>s :call RunNearestSpec()<CR>
map <Leader>l :call RunLastSpec()<CR>
map <Leader>a :call RunAllSpecs()<CR>


autocmd BufReadPost,BufNewFile *.apib set filetype=apiblueprint
autocmd FileType apiblueprint set syntax=apiblueprint
autocmd FileType apiblueprint set makeprg=snowcrash\ -l\ %

fun! s:DetectAPIBlueprint()
  if getline(1) =~ '^FORMAT: 1A$'
    set filetype=apiblueprint
  endif
endfun

autocmd BufNewFile,BufRead * call s:DetectAPIBlueprint()

Use drafter instead of snowcrash

autocmd BufReadPost,BufNewFile *.apib set filetype=apiblueprint
autocmd FileType apiblueprint set syntax=apiblueprint
autocmd FileType apiblueprint set makeprg=draftesnowcrashr\ -l\ %

fun! s:DetectAPIBlueprint()
  if getline(1) =~ '^FORMAT: 1A$'
    set filetype=apiblueprint
  endif
endfun

autocmd BufNewFile,BufRead * call s:DetectAPIBlueprint()


syn match cppNamespacedConstant /::\zs[A-Z]\w*/
syn match cppNamespace /\<\w\+\(::\)\@=/
syn match cppNamespacedType /::\zs[A-Z]\w*\ze[ >]/

hi def link cppNamespace Include
hi def link cppNamespacedConstant Identifier
hi def link cppNamespacedType Type

Tweak to custom syntax highlighting for C++

syn match cppNamespacedConstant /::\zs[A-Z]\w*/
syn match cppNamespace /\<\w\+\(::\)\@=/
syn match cppNamespacedType /::\zs[A-Z]\w*\ze[ >{]/

hi def link cppNamespace Include
hi def link cppNamespacedConstant Identifier
hi def link cppNamespacedType Type


set guifont=Iosevka\ Term:h16

if exists('g:fvim_loaded')
	FVimCursorSmoothBlink v:true
	FVimCursorSmoothMove v:true
	FVimCustomTitleBar v:false
endif

Set font to JetBrains Mono

set guifont=JetBrains\ Mono:h13

if exists('g:fvim_loaded')
	FVimCursorSmoothBlink v:true
	FVimCursorSmoothMove v:true
	FVimCustomTitleBar v:false
endif


setlocal spell spelllang=en_us
set complete+=kspell

highlight htmlItalic cterm=italic
highlight htmlBold cterm=bold

" Highlight words to avoid in tech writing
" http://css-tricks.com/words-avoid-educational-writing/
" https://github.com/pengwynn/dotfiles
highlight TechWordsToAvoid ctermbg=red ctermfg=white
function! MatchTechWordsToAvoid()
  match TechWordsToAvoid /\c\(obviously\|basically\|simply\|of\scourse\|clearly\|just\|everyone\sknows\|however\|so,\|easy\)/
endfunction
call MatchTechWordsToAvoid()
autocmd BufWinEnter *.md call MatchTechWordsToAvoid()
autocmd InsertEnter *.md call MatchTechWordsToAvoid()
autocmd InsertLeave *.md call MatchTechWordsToAvoid()
autocmd BufWinLeave *.md call clearmatches()
command! -nargs=* Wrap set wrap linebreak nolist

" en and em dashes
inoremap <buffer> --<space> –
inoremap <buffer> ---<space> —

Add arrow mappings for Markdown.

setlocal spell spelllang=en_us
set complete+=kspell

highlight htmlItalic cterm=italic
highlight htmlBold cterm=bold

" Highlight words to avoid in tech writing
" http://css-tricks.com/words-avoid-educational-writing/
" https://github.com/pengwynn/dotfiles
highlight TechWordsToAvoid ctermbg=red ctermfg=white
function! MatchTechWordsToAvoid()
  match TechWordsToAvoid /\c\(obviously\|basically\|simply\|of\scourse\|clearly\|just\|everyone\sknows\|however\|so,\|easy\)/
endfunction
call MatchTechWordsToAvoid()
autocmd BufWinEnter *.md call MatchTechWordsToAvoid()
autocmd InsertEnter *.md call MatchTechWordsToAvoid()
autocmd InsertLeave *.md call MatchTechWordsToAvoid()
autocmd BufWinLeave *.md call clearmatches()
command! -nargs=* Wrap set wrap linebreak nolist

" en and em dashes (https://www.w3schools.com/charsets/ref_utf_punctuation.asp)
inoremap <buffer> --<space> –
inoremap <buffer> ---<space> —

" arrows (https://www.w3schools.com/charsets/ref_utf_arrows.asp)
inoremap <buffer> --><space> →
inoremap <buffer> <--<space> ←


" Copy current file path (plus line number, if asked) to system pasteboard.
map <silent> <leader>cp :let @* = expand("%")<CR>:echo "Copied: ".expand("%")<CR>
map <silent> <leader>cP :let @* = expand("%").":".line(".")<CR>:echo "Copied: ".expand("%").":".line(".")<CR>

" Toggle spell check
map <leader>ss :setlocal spell!<cr>

" Gracefully handle holding shift too long after : for common commands
cabbrev Q q
cabbrev Qa qa
cabbrev Tabe tabe
cabbrev Tabn tabn
cabbrev W w
cabbrev Wa wa
cabbrev Wq wq

" Make Y consistent with D and C.
map Y y$

" Indent/unindent visual mode selection with tab/shift+tab
vmap <tab> >gv
vmap <s-tab> <gv

Add Vim mapping to write all files in tab

" Copy current file path (plus line number, if asked) to system pasteboard.
map <silent> <leader>cp :let @* = expand("%")<CR>:echo "Copied: ".expand("%")<CR>
map <silent> <leader>cP :let @* = expand("%").":".line(".")<CR>:echo "Copied: ".expand("%").":".line(".")<CR>

" Toggle spell check
map <leader>ss :setlocal spell!<cr>

" Mapping for writing all files in a tab
cabbrev wt silent windo w

" Gracefully handle holding shift too long after : for common commands
cabbrev Q q
cabbrev Qa qa
cabbrev Tabe tabe
cabbrev Tabn tabn
cabbrev W w
cabbrev Wa wa
cabbrev Wq wq
cabbrev Wt wt

" Make Y consistent with D and C.
map Y y$

" Indent/unindent visual mode selection with tab/shift+tab
vmap <tab> >gv
vmap <s-tab> <gv


" Fast saving
nmap <leader>w :w!<CR>

" Fast saving & exiting
nmap <leader>x :x<CR>

nmap <leader>qa :qall<CR>

" Smart-insert semicolon
inoremap <leader>; <C-o>A;<Esc>:w<CR>
nnoremap <leader>; A;<Esc>:w<CR>

" Make Y consistent with C and D
nnoremap Y y$

Improve fast saving on normal and insert modes

" Fast saving
map  ,, :w<CR>
imap ,, <C-o>:w<CR>

" Fast saving & exiting
nmap <leader>x :x<CR>

nmap <leader>qa :qall<CR>

" Smart-insert semicolon
inoremap <leader>; <C-o>A;<Esc>:w<CR>
nnoremap <leader>; A;<Esc>:w<CR>

" Make Y consistent with C and D
nnoremap Y y$


highlight ColorColumn ctermbg=DarkRed
set cursorline

" Change Color when entering Insert Mode
autocmd InsertEnter * highlight CursorLine ctermbg=DarkGray | set colorcolumn=78,80,117,119,120
"
" Revert Color to default when leaving Insert Mode
autocmd InsertLeave * highlight CursorLine ctermbg=None | set colorcolumn=

Remove cursor line bg color in insert mode

highlight ColorColumn ctermbg=DarkGray
set cursorline

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


" Use eslint linter.
execute('compiler eslint')

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2

Add basic JS include config

" Basic JS from/require include config.
setlocal include=^\\s*[^\/]\\+\\(from\\\|require(['\"]\\)
setlocal suffixesadd=.js

" Use eslint linter.
execute('compiler eslint')

" vim:fdm=marker ft=vim et sts=2 sw=2 ts=2


let g:rails_projections = {
\   "app/javascript/*.js": {
\     "alternate": "spec/javascript/{}.spec.js"
\   },
\   "spec/javascript/*.spec.js": {
\     "alternate": "app/javascript/{}.js"
\   },
\ }

Set up alternate files for JSX specs

let g:rails_projections = {
\   "app/javascript/*.js": {
\     "alternate": "spec/javascript/{}.spec.js"
\   },
\   "app/javascript/*.jsx": {
\     "alternate": "spec/javascript/{}.spec.jsx"
\   },
\   "spec/javascript/*.spec.js": {
\     "alternate": "app/javascript/{}.js"
\   },
\   "spec/javascript/*.spec.jsx": {
\     "alternate": "app/javascript/{}.jsx"
\   },
\ }


" set term=screen-256color-bce

let s:uname = system("uname -s")

let g:solorized_termcolors=256
set t_Co=256
set background=dark
colorscheme solarized

" Added to support visual gitgutter display
highlight clear SignColumn

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
  syntax on
  set hlsearch
endif

Remove unnecessary solarized setting for vim

" set term=screen-256color-bce

let s:uname = system("uname -s")

set t_Co=256
set background=dark
colorscheme solarized

" Added to support visual gitgutter display
highlight clear SignColumn

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
  syntax on
  set hlsearch
endif


" vim-images.vim - Image pasting for vim
" Maintainer:   Blake Taylor <http://blakefrost.com/>
" Version:      0.1

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

if !exists("g:images_root")
  let g:images_root = expand('~/images/')
endif

function! s:warn(msg)
  echohl WarningMsg
  echomsg a:msg
  echohl NONE
endfunction

function! vimages#PasteImage()
  " Paste image from clipboard accroding to date/time
  let date_path = strftime("%Y/%m/%d/")

  let images_path = 'captures/' . date_path
  let images_dir  = g:images_root . images_path
  let file = strftime("%T") . '.png'

  " Make sure the directory exists
  execute 'silent !mkdir -p ' . images_dir
  execute "silent !pngpaste " . images_dir . file

  " Test that the file exists
  if filereadable(images_dir . file)
    execute "normal a \<BS>".'![](/'.images_path.file.')'
    normal! 02l
    startinsert!
  else
    echo "Couldn't paste image. perhaps no image data in clipboard?:"
  endif
  redraw!
endfunction

Fix image linking, needs to be relative under /images

" vim-images.vim - Image pasting for vim
" Maintainer:   Blake Taylor <http://blakefrost.com/>
" Version:      0.1

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

if !exists("g:images_root")
  let g:images_root = expand('~/images/')
endif

function! s:warn(msg)
  echohl WarningMsg
  echomsg a:msg
  echohl NONE
endfunction

function! vimages#PasteImage()
  " Paste image from clipboard accroding to date/time
  let date_path = strftime("%Y/%m/%d/")

  let images_path = 'captures/' . date_path
  let images_dir  = g:images_root . images_path
  let file = strftime("%T") . '.png'

  " Make sure the directory exists
  execute 'silent !mkdir -p ' . images_dir
  execute "silent !pngpaste " . images_dir . file

  " Test that the file exists
  if filereadable(images_dir . file)
    execute "normal a \<BS>".'![](/images/'.images_path.file.')'
    normal! 02l
    startinsert!
  else
    echo "Couldn't paste image. perhaps no image data in clipboard?:"
  endif
  redraw!
endfunction


" plugin/colorscheme.vim
"
" @file Configuration of the color scheme

" Enable true colors if supported by the current environment
if dw#IsSupported('truecolors')
  set termguicolors
endif

" Use Atom One Light color scheme if installed via package manager
if dw#IsInstalled('vim-one')
  if $TERM_PROGRAM ==# 'Apple_Terminal'
    autocmd vimrc ColorScheme one hi Normal guibg=NONE ctermbg=NONE
  endif

  colorscheme one
endif

Improve color scheme for terminal.app

" plugin/colorscheme.vim
"
" @file Configuration of the color scheme

" Enable true colors if supported by the current environment
if dw#IsSupported('truecolors')
  set termguicolors
endif

" Use Atom One Light color scheme if installed via package manager
if dw#IsInstalled('vim-one')
  if $TERM_PROGRAM ==# 'Apple_Terminal'
    autocmd vimrc ColorScheme one
          \ hi Normal guibg=NONE ctermbg=NONE |
          \ hi SignifySignAdd guibg=#fafafa ctermbg=255 |
          \ hi SignifySignChange guibg=#fafafa ctermbg=255 |
          \ hi SignifySignDelete guibg=#fafafa ctermbg=255
  endif

  colorscheme one
endif


" UltiSnips
" UltiSnips is the ultimate solution for snippets in Vim.

let g:UltiSnipsExpandTrigger       ="<c-tab>"
let g:UltiSnipsJumpForwardTrigger  = "<enter>"
let g:UltiSnipsJumpBackwardTrigger = "<s-tab>"

" Enable tabbing through list of results
function! g:UltiSnips_Complete()
    call UltiSnips#ExpandSnippet()
    if g:ulti_expand_res == 0
        if pumvisible()
            return "\<C-n>"
        else
            call UltiSnips#JumpForwards()
            if g:ulti_jump_forwards_res == 0
               return "\<TAB>"
            endif
        endif
    endif
    return ""
endfunction

au InsertEnter * exec "inoremap <silent> " . g:UltiSnipsExpandTrigger . " <C-R>=g:UltiSnips_Complete()<cr>"

" Expand snippet or return
let g:ulti_expand_res = 0
function! Ulti_ExpandOrEnter()
    call UltiSnips#ExpandSnippet()
    if g:ulti_expand_res
        return ''
    else
        return "\<return>"
endfunction

" Set <space> as primary trigger
inoremap <return> <C-R>=Ulti_ExpandOrEnter()<CR>

Use <leader>e to expand snippet

" UltiSnips
" UltiSnips is the ultimate solution for snippets in Vim.

let g:UltiSnipsExpandTrigger       = "<leader>e"
let g:UltiSnipsJumpForwardTrigger  = "<enter>"
let g:UltiSnipsJumpBackwardTrigger = "<s-tab>"

" Enable tabbing through list of results
function! g:UltiSnips_Complete()
    call UltiSnips#ExpandSnippet()
    if g:ulti_expand_res == 0
        if pumvisible()
            return "\<C-n>"
        else
            call UltiSnips#JumpForwards()
            if g:ulti_jump_forwards_res == 0
               return "\<TAB>"
            endif
        endif
    endif
    return ""
endfunction

au InsertEnter * exec "inoremap <silent> " . g:UltiSnipsExpandTrigger . " <C-R>=g:UltiSnips_Complete()<cr>"


call my_plugin#add('sonph/onehalf', {'rtp': 'vim/'})
call my_plugin#add('https://gitlab.com/protesilaos/tempus-themes-vim.git')
call my_plugin#add('NLKNguyen/papercolor-theme')

let s:preferred_color_scheme = get(g:, 'preferred_color_scheme', ['onehalf', 'onehalflight'])

let g:PaperColor_Theme_Options = {
\   'theme': {
\     'default.light': {
\       'override': {
\         'linenumber_fg': ['#111', '000']
\       }
\     }
\   }
\ }

function! s:custom_PaperColor()
endf

function! s:custom_onehalflight()
    hi! link IncSearch PMenuSel
    hi! link ClapCurrentSelection Function
endf

function! ActivatePreferredColorScheme()
  if $TERM !=# 'linux'
    exe 'colorscheme '.s:preferred_color_scheme[1]
    try
      call function('Custom_'.s:preferred_color_scheme[1])()
    catch /E700: Unknown function.*/
    endtry
  endif
endf

execute 'function! Hook_post_source_'.s:preferred_color_scheme[0]."()\n   call ActivatePreferredColorScheme()\n endf"

Fix custom theme override hook

call my_plugin#add('sonph/onehalf', {'rtp': 'vim/'})
call my_plugin#add('https://gitlab.com/protesilaos/tempus-themes-vim.git')
call my_plugin#add('NLKNguyen/papercolor-theme')

let s:preferred_color_scheme = get(g:, 'preferred_color_scheme', ['onehalf', 'onehalflight'])

let g:PaperColor_Theme_Options = {
\   'theme': {
\     'default.light': {
\       'override': {
\         'linenumber_fg': ['#111', '000']
\       }
\     }
\   }
\ }

function! s:custom_PaperColor()
endf

function! s:custom_onehalflight()
    hi! link IncSearch PMenuSel
    hi! link ClapCurrentSelection Function
endf

function! ActivatePreferredColorScheme()
  if $TERM !=# 'linux'
    exe 'colorscheme '.s:preferred_color_scheme[1]
    try
      let F = function('<sid>custom_'.s:preferred_color_scheme[1])
    catch /E700: Unknown function.*/
      return
    endtry
    call F()
  endif
endf

execute 'function! Hook_post_source_'.s:preferred_color_scheme[0]."()\n   call ActivatePreferredColorScheme()\n endf"


set t_Co=256
set background=dark
silent! colorscheme Tomorrow-Night

" Feel free to override the colorscheme by adding a line to ~/.vimrc.local
" such as the following:
"
" colorscheme solarized

Set airline’s theme to tomorrow so it matches

set t_Co=256
set background=dark
silent! colorscheme Tomorrow-Night
silent! let g:airline_theme='tomorrow'

" Feel free to override the colorscheme by adding a line to ~/.vimrc.local
" such as the following:
"
" colorscheme solarized
" let g:airline_theme='solarized'


function! DottedLCD(filename)
	" ignore netrw filenames
	if a:filename =~ '^[a-z]\+:'
		return
	endif
	let dir=substitute(a:filename,'\(.*\)/./.*$','\1','')
	if dir != a:filename
		exe ":lcd ".dir
	endif
endfun

aug DottedLCD
	au BufReadPost * call DottedLCD(expand("<afile>"))
aug END

Rework "dotted directory" changing in Vim

function! DottedLCD(filename)
	" Get the arglist value if present, otherwise the passed-in <afile>
	let i = argidx()
	let name = i < 0 ? a:filename : argv(i)

	" ignore netrw filenames
	if name =~ '^[a-z]\+:'
		return
	endif

	" find the '/./' that relativizes the path
	let dot = stridx(name, '/./')
	if dot < 0
		return
	end

	" take everything up to the relativizer
	let dir = strpart(name, 0, dot)
	exe ":lcd ".dir
endfun

aug DottedLCD
	au BufReadPost * call DottedLCD(expand("<afile>"))
aug END


nnoremap <leader>ff :Files<cr>
nnoremap <leader>fg :Rg<cr>
nnoremap <leader>fb :Buffers<cr>
nnoremap <leader>fc :Commands<cr>
nnoremap <leader>fh :Helptags<cr>
nnoremap <leader>fm :Maps<cr>
nnoremap <leader>f: :History:<cr>
nnoremap <leader>ft :Filetypes<cr>

command! -bang -nargs=* Rg
  \ call fzf#vim#grep(
  \   'rg --hidden -g "!.git/" --column --line-number --no-heading --color=always '.shellescape(<q-args>), 1,
  \   <bang>0 ? fzf#vim#with_preview('up:60%')
  \           : fzf#vim#with_preview('right:50%:hidden', '?'),
  \   <bang>0)

Add a space* binding for search under symbol

nnoremap <leader>ff :Files<cr>
nnoremap <leader>fg :Rg<cr>
nnoremap <leader>fb :Buffers<cr>
nnoremap <leader>fc :Commands<cr>
nnoremap <leader>fh :Helptags<cr>
nnoremap <leader>fm :Maps<cr>
nnoremap <leader>f: :History:<cr>
nnoremap <leader>ft :Filetypes<cr>
nnoremap <leader>* :Rg <c-r><c-w><cr>

command! -bang -nargs=* Rg
  \ call fzf#vim#grep(
  \   'rg --hidden -g "!.git/" --column --line-number --no-heading --color=always '.shellescape(<q-args>), 1,
  \   <bang>0 ? fzf#vim#with_preview('up:60%')
  \           : fzf#vim#with_preview('right:50%:hidden', '?'),
  \   <bang>0)


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

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

" PUBLIC

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

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

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

" PRIVATE

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

Remove wrapping and numbers in Pivo buffer

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

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

" PUBLIC

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

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

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

" PRIVATE

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


" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

" scroll the viewport faster
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

" split horizontally with h
nnoremap <C-w>h <C-w>s

" fly between buffers:
" http://of-vim-and-vigor.blogspot.ro/p/vim-vigor-comic.html
nnoremap <leader>l :ls<CR>:b<space>

Add leader to c/d to copy to null register

" set a map leader for more key combos
let mapleader = ','
let g:mapleader = ','

" scroll the viewport faster
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>

" scroll by visual lines
nnoremap <silent> j gj
nnoremap <silent> k gk

" disable search highlights
nnoremap <silent> <CR> :nohlsearch<CR><CR>

" fold with spacebar
nnoremap <space> za

" use tab for indenting
nnoremap <Tab> >>_
nnoremap <S-Tab> <<_
inoremap <S-Tab> <C-D>
vnoremap <Tab> >gV
vnoremap <S-Tab> <gV

" split horizontally with h
nnoremap <C-w>h <C-w>s

" fly between buffers:
" http://of-vim-and-vigor.blogspot.ro/p/vim-vigor-comic.html
nnoremap <leader>l :ls<CR>:b<space>

" prepend leader to copy to null register
" http://unix.stackexchange.com/a/88755
nnoremap <leader>c "_c
nnoremap <leader>d "_d


" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

au BufRead,BufNewFile,BufReadPre *.coffee set filetype=coffee

augroup fileTypeIndent
    autocmd!
    autocmd BufNewFile,BufRead *.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.coffee setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.rkt setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.py setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.js setlocal tabstop=2 shiftwidth=2 softtabstop=2
augroup END

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~
source $VIMRUNTIME/macros/matchit.vim

" for tex
let g:tex_conceal = ''

Add spell check options to .vimrc

" tab
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab

au BufRead,BufNewFile,BufReadPre *.coffee set filetype=coffee

augroup fileTypeIndent
    autocmd!
    autocmd BufNewFile,BufRead *.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.coffee setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.rkt setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.py setlocal tabstop=2 shiftwidth=2 softtabstop=2
    autocmd BufNewFile,BufRead *.js setlocal tabstop=2 shiftwidth=2 softtabstop=2
augroup END

" appearance
set showmatch
set list
set listchars=tab:>.,trail:_,eol:↲,extends:>,precedes:<,nbsp:%

" control
set backspace=start,eol,indent
set whichwrap=b,s,[,],,~
source $VIMRUNTIME/macros/matchit.vim

" spell check
set spell
set spelllang=en,cjk

" for tex
let g:tex_conceal = ''


" DelimitMate uses:
"     <S-Tab>  to exit current bracket
"     <C-G>g   to exit all brackets
"
" <S-Tab> is already mapped by SuperTab, use an alternate
imap <C-CR> <Plug>delimitMateS-Tab

" enable extra features
" --------------------------
" add matching right-hand space inside of empty pair
let g:delimitMate_expand_space = 1

" <CR> key indents next line and de-dents closing pair on sepeate newline
let g:delimitMate_expand_cr = 1

" correctly jump past closing brace on the next line, instead of duplicating
let g:delimitMate_jump_expansion = 1

" prevent closing pair when right-side match already exists
let g:delimitMate_balance_matchpairs = 1

Fix tripple quotes when ediiting Python code

" DelimitMate uses:
"     <S-Tab>  to exit current bracket
"     <C-G>g   to exit all brackets
"
" <S-Tab> is already mapped by SuperTab, use an alternate
imap <C-CR> <Plug>delimitMateS-Tab

" enable extra features
" --------------------------
" add matching right-hand space inside of empty pair
let g:delimitMate_expand_space = 1

" <CR> key indents next line and de-dents closing pair on sepeate newline
let g:delimitMate_expand_cr = 1

" correctly jump past closing brace on the next line, instead of duplicating
let g:delimitMate_jump_expansion = 1

" prevent closing pair when right-side match already exists
let g:delimitMate_balance_matchpairs = 1

" enable support for tripple quotes in Python
au FileType python let b:delimitMate_nesting_quotes = ['"']


" Inserting Dates and Times
iab Ydate <C-R>=strftime("%d-%b-%Y")<CR>
" Example: 16-Apr-2016

iab Ytime <C-R>=strftime("%H:%M")<CR>
" Example: 22:21

iab YDATE <C-R>=strftime("%a %b %d %T %Z %Y")<CR>
" Example: Sat Apr 16 22:20:24 WEST 2016

" The lower letter alphabet.
iab Yalpha abcdefghijklmnopqrstuvwxyz

" The upper letter alphabet.
iab YALPHA ABCDEFGHIJKLMNOPQRSTUVWXYZ

" The ten digits.
iab Ydigit 1234567890

" The sixteen digits of a hexadecimal system.
iab Yhex 1234567890ABCDEF

Add abbreviation for the current day date

" Inserting Dates and Times
iab Ydate <C-R>=strftime("%d-%b-%Y")<CR>
" Example: 16-Apr-2016

iab Ytoday <C-R>=strftime("%a %b %e")<CR>
" Example: Fri Apr 29

iab Ytime <C-R>=strftime("%H:%M")<CR>
" Example: 22:21

iab YDATE <C-R>=strftime("%a %b %d %T %Z %Y")<CR>
" Example: Sat Apr 16 22:20:24 WEST 2016

" The lower letter alphabet.
iab Yalpha abcdefghijklmnopqrstuvwxyz

" The upper letter alphabet.
iab YALPHA ABCDEFGHIJKLMNOPQRSTUVWXYZ

" The ten digits.
iab Ydigit 1234567890

" The sixteen digits of a hexadecimal system.
iab Yhex 1234567890ABCDEF


" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

" Start bundle list -----------------------------

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
Bundle 'altercation/vim-colors-solarized'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'digitaltoad/vim-jade'
Bundle 'wavded/vim-stylus'
Bundle 'walm/jshint.vim'
Bundle 'eyuelt/vim-whitespace'
Bundle 'elzr/vim-json'

" End bundle list -------------------------------

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ

Use new whitespace stripping plugin

" vundle.vim
" ----------
" Config file for Vundle bundles. This file also sources all
" Vundle-installed plugins. So this file should be sourced
" in the vimrc before attempting to use any of those plugins.
" note: comments after Bundle commands are not allowed.

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

" Start bundle list -----------------------------

" let Vundle manage Vundle (required)
Bundle 'gmarik/vundle'

" My bundles
Bundle 'altercation/vim-colors-solarized'
Bundle 'jelera/vim-javascript-syntax'
Bundle 'digitaltoad/vim-jade'
Bundle 'wavded/vim-stylus'
Bundle 'walm/jshint.vim'
Bundle 'eyuelt/vim-better-whitespace'
Bundle 'elzr/vim-json'

" End bundle list -------------------------------

filetype plugin indent on     " required!

" Brief help
" :BundleList          - list configured bundles
" :BundleInstall(!)    - install (update) bundles
" :BundleSearch(!) foo - search (or refresh cache first) for foo
" :BundleClean(!)      - confirm (or auto-approve) removal of unused bundles
"
" see :h vundle for more details or the Vundle wiki for FAQ


" snipmate          git://github.com/garbas/vim-snipmate.git
let g:snips_author = "Stephen Tudor"
" let g:snips_trigger_key = '<C-Space>'

if !exists('g:snipMate')
  let g:snipMate = {}
  let g:snipMate.scope_aliases = {}
endif
let g:snipMate.scope_aliases['html'] = 'html,css,javascript'
let g:snipMate.scope_aliases['javascript'] = 'javascript,javascript-jquery'
let g:snipMate.scope_aliases['jsp'] = 'jsp,html'
let g:snipMate.scope_aliases['less'] = 'less,css'
let g:snipMate.scope_aliases['scss'] = 'scss,css'

Use html and css snippets only in their respective formats. Allow dust templates to use html snippets.

" snipmate          git://github.com/garbas/vim-snipmate.git
let g:snips_author = "Stephen Tudor"
" let g:snips_trigger_key = '<C-Space>'

if !exists('g:snipMate')
  let g:snipMate = {}
  let g:snipMate.scope_aliases = {}
endif
let g:snipMate.scope_aliases['dust'] = 'html'
let g:snipMate.scope_aliases['javascript'] = 'javascript,javascript-jquery'
let g:snipMate.scope_aliases['jsp'] = 'jsp,html'
let g:snipMate.scope_aliases['less'] = 'less,css'
let g:snipMate.scope_aliases['scss'] = 'scss,css'


" Key mappings
"
" My personal mappings for various commands and key combinations

" Add a way to write a file as sudo
cmap w!! w !sudo tee > /dev/null %

" Remap Ctrl+C to be the same as escape without telling us to use :q to quit
nnoremap <C-c> <silent> <ESC>

" Disable EX mode
map Q <Nop>

""" Buffer Managment
nnoremap <silent>       <Tab>   :bnext<CR>
nnoremap <silent>       <S-Tab> :bprev<CR>
nnoremap <expr><silent> <C-q>   ':confirm '.(NoBuffersOpen() ? 'quit' : 'bdelete').'<CR>'

""" Tabularizatins
nmap <Leader>a= :Tabularize /=<CR>
vmap <Leader>a= :Tabularize /=<CR>
nmap <Leader>a> :Tabularize /=><CR>
vmap <Leader>a> :Tabularize /=><CR>
nmap <Leader>a: :Tabularize /:\zs<CR>
vmap <Leader>a: :Tabularize /:\zs<CR>

" Don't move on *
nnoremap <silent> * :let stay_star_view = winsaveview()<CR>*:call winrestview(stay_star_view)<CR>

Add binding to source line/selection in vim

" Key mappings
"
" My personal mappings for various commands and key combinations

" Add a way to write a file as sudo
cmap w!! w !sudo tee > /dev/null %

" Remap Ctrl+C to be the same as escape without telling us to use :q to quit
nnoremap <C-c> <silent> <ESC>

" Disable EX mode
map Q <Nop>

""" Buffer Managment
nnoremap <silent>       <Tab>   :bnext<CR>
nnoremap <silent>       <S-Tab> :bprev<CR>
nnoremap <expr><silent> <C-q>   ':confirm '.(NoBuffersOpen() ? 'quit' : 'bdelete').'<CR>'

""" Tabularizatins
nmap <Leader>a= :Tabularize /=<CR>
vmap <Leader>a= :Tabularize /=<CR>
nmap <Leader>a> :Tabularize /=><CR>
vmap <Leader>a> :Tabularize /=><CR>
nmap <Leader>a: :Tabularize /:\zs<CR>
vmap <Leader>a: :Tabularize /:\zs<CR>

" Don't move on *
nnoremap <silent> * :let stay_star_view = winsaveview()<CR>*:call winrestview(stay_star_view)<CR>

" Source line and selection in vim
vnoremap <leader>S y:execute @@<CR>:echo 'Sourced selection.'<CR>
nnoremap <leader>S ^vg_y:execute @@<CR>:echo 'Sourced line.'<CR>


" Run `command` in all windows, keeping old open window.
function! lsc#util#winDo(command) abort
  let current_window = winnr()
  execute 'windo ' . a:command
  execute current_window . 'wincmd w'
endfunction

Add keepjumps and noautocmd to WinDo

" Run `command` in all windows, keeping old open window.
function! lsc#util#winDo(command) abort
  let current_window = winnr()
  execute 'keepjumps noautocmd windo '.a:command
  execute 'keepjumps noautocmd '.current_window.'wincmd w'
endfunction


" The Silver Searcher
if executable('ag')
  " Use ag over grep
  set grepprg=ag\ --vimgrep
  " bind \ (backward slash) to grep shortcut
  command -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!
  nnoremap \ :Ag<SPACE>
endif

Use ag with insensitive casing

" The Silver Searcher
if executable('ag')
  " Use ag over grep
  set grepprg=ag\ --vimgrep\ -i
  " bind \ (backward slash) to grep shortcut
  command -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!
  nnoremap \ :Ag<SPACE>
endif