set nocompatible

" Manage plugins using vim-plug
filetype off
call plug#begin('~/.vim/bundle')

" functionality
Plug 'scrooloose/syntastic'
Plug 'tpope/vim-fugitive'
Plug 'vim-scripts/closetag.vim'
Plug 'vim-scripts/visSum.vim'
Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
Plug 'tpope/vim-surround'
Plug 'rking/ag.vim', { 'for': 'Ag' }
Plug 'junegunn/goyo.vim', { 'on': 'Goyo' }
Plug 'jamessan/vim-gnupg'
Plug 'groenewege/vim-less'
Plug 'tpope/vim-vinegar'
Plug 'wincent/command-t', { 'do': 'cd ruby/command-t; ruby extconf.rb && make' }
Plug 'a.vim'
Plug 'shime/vim-livedown', { 'on': 'LivedownPreview' }
"Plug 'vimwiki/vimwiki'
"Plug 'ciaranm/detectindent'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }

" syntax
Plug 'kchmck/vim-coffee-script', { 'for': 'coffee' }
Plug 'tpope/vim-markdown', { 'for': 'markdown' }
Plug 'ledger/vim-ledger', { 'for': 'ledger' }
Plug 'PotatoesMaster/i3-vim-syntax', { 'for': 'i3' }
Plug 'tkztmk/vim-vala', { 'for': 'vala' }
Plug 'othree/html5.vim', { 'for': 'html5' }
Plug 'cakebaker/scss-syntax.vim', { 'for': 'scss' }
Plug 'hail2u/vim-css3-syntax', { 'for': 'css' }
"Plug 'jeaye/color_coded', { 'do': './configure && make' }

" color
Plug 'biskark/vim-ultimate-colorscheme-utility'
Plug 'altercation/vim-colors-solarized'
Plug 'noahfrederick/vim-hemisu'
Plug 'junegunn/seoul256.vim'
Plug 'Lokaltog/vim-distinguished'
Plug 'zeis/vim-kolor'
Plug 'nanotech/jellybeans.vim'
Plug 'nice/sweater'
Plug 'tomasr/molokai'
Plug 'fmoralesc/molokayo'

call plug#end()

" enable modeline for all setups
" vim shipped with OSX has it disabled by default
set modeline modelines=5

set mouse=a

" show all possible completions
set wildmenu
set wildmode=list:longest

" search options
set ignorecase " ignore case...
set smartcase " unless it contains uppercase letters
set hlsearch " highlight matches
set incsearch " incremental search

" handling of long lines
"set nowrap
set wrap
set sidescroll=1 " scroll horizontally in 1 character steps
set sidescrolloff=10 " keep some space on the side

" automatically reload files
set autoread

" keep swap files from cluttering directories
" // makes vim to use the full path for the filename
"set directory=~/.vim/swap/

" default indentation
set noexpandtab
set tabstop=4
set softtabstop=4
set shiftwidth=4
set shiftround " round indentation for > and < commands
set autoindent " retain indentation level
set smartindent

" Go
"set runtimepath+=$GOROOT/misc/vim
"au BufRead,BufNewFile *.go set filetype=go
"autocmd BufWritePost *.go :silent Fmt
set runtimepath^=/usr/share/vim/addons
"autocmd FileType go autocmd BufWritePre <buffer> Fmt

" indentation by format
filetype plugin indent on

" behaviour of auto formatting
set formatoptions+=r " insert comment leader after <Enter> in insert mode
set formatoptions+=o " ... and 'o' or 'O' in normal mode
set formatoptions+=n " recognize (numbered) lists
set formatoptions+=l " dont wrap already long lines

" 80 column lines (minus one for split)
set textwidth=79
if exists("&colorcolumn")
  set colorcolumn=+1
endif

" split behaviour
set splitright " create new windows in reading direction
set splitbelow
set equalalways " resize windows when a new one is created
"autocmd VimResized * exe "normal! \<c-w>="

" always display the status line
set laststatus=2

" relative line numbers
"if exists("&relativenumber")
  "set relativenumber
"else
  "set number
"endif

" display position in file
set ruler

" show partial commands
set showcmd

" navigate windows with ctrl+direction
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

" moving a selection
vnoremap <C-j> :m+1<cr>gv
vnoremap <C-k> :m-2<cr>gv

"nmap <Up> 10<c-y>
"nmap <Down> 10<c-e>

" Navigate buffers
nmap <Right> :bn<cr>
nmap <Left> :bp<cr>

"set cpoptions+=<

" Navigate args
nmap [a :N<cr>
nmap ]a :n<cr>

" Buffer navigation
nnoremap <leader>b :buffers<CR>:b<space>

" Use plus/minus for numbers
nmap + <c-a>
nmap - <c-x>

" Set leader to ,
"let mapleader = ","
"let g:mapleader = ","

let g:ulti_color_always_random=2

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

" Save all
command! W :wa

" Sudo save
com! Wsudo :w !sudo tee % >/dev/null

" Fast close buffer
nmap <leader>d :bd<cr>

" Ctrl-L is remapped, so use leader-L
nnoremap <leader>l :redraw!<cr>

" http://vimcasts.org/episodes/show-invisibles/
" Shortcut to rapidly toggle `set list`
nmap <leader>k :set list!<CR>
" Use symbols for tabstops and EOLs
set listchars=tab:▸\ ,eol:¬

" netbeans
noremap <c-s> :nbs<cr>

" Ledger cook
function! LedgerPrint() range
    execute a:firstline.",".a:lastline."!ledger -f - print"
endfunction
noremap <leader>g :call LedgerPrint()<cr>

" Allow unsaved hidden buffers
set hidden

" Use Q for formattting, not ex
map Q gq

" Start Pathogen
silent! call pathogen#infect()

" Set color scheme according to current time of day.
function! HourColor()
  let hr = str2nr(strftime('%H'))
  if hr <= 5
      colo molokai
  elseif hr <= 9
      colo calmar256-dark
  elseif hr <= 14
      colo moria
  elseif hr <= 16
      colo calmar256-light
  else
      colo jellybeans
  endif
  "let nowcolors = 'calmar256-dark mayansmoke moria calmar256-light calmar256-dark'
  "execute 'colorscheme '.split(nowcolors)[i]
  "redraw
  "echo g:colors_name
endfunction

" colors!
syntax on
"colorscheme kolor
"colorscheme solarized
"colorscheme gruvbox
"colorscheme hipster
"colorscheme molokai
"colorscheme tabula
"solarized vividchalk calmar256-dark/light fog bluegreen tango2 torte
"colo zellner
if has('gui_running')
    "set background=light
    "colorscheme hemisu
else
    "set background=dark
    "colorscheme solarized
endif
if !exists("g:colors_name")
    " colo calmar256-dark
    "so ~/.vim/colorscheme.vim
    call HourColor()
endif

" Always edit file with gf
map gf :e <cfile><CR>

" Liberal line endings
set ffs=unix,mac,dos

" Easy executifying
noremap <leader>x :!chmod +x %<cr><cr>
noremap <leader>X :0norm O#!/bin/sh<cr>:w<cr>:!chmod +x %<cr>:e<cr>

" Open vimrc
noremap <leader>; :tabe ~/.vimrc<cr>
" Save and reload vimrc
noremap <leader>. :w<cr>:so ~/.vimrc<cr>

let g:syntastic_java_javac_autoload_maven_classpath = 0
let g:syntastic_java_javac_config_file_enabled = 1
let g:syntastic_always_populate_loc_list=1
"let g:syntastic_c_compiler_options="-Ideps -std=c99"
let g:syntastic_c_config_file = '.syntastic_c_config'
"let g:syntastic_c_include_dirs = ['deps']
"let g:syntastic_javascript_checkers = ['standard']
com! Standard let g:syntastic_javascript_checkers = ['standard']

" Shortcuts for jumping through errors (location list)
map [l :lprev<cr>
map ]l :lnext<cr>

" Shortcuts for jumping through error list
map [e :cprev<cr>
map ]e :cnext<cr>
map [E :cfirst<cr>
map ]E :clast<cr>

" Paste from X Clipboard (hack)
" noremap <leader>v :.!xsel<cr>

" http://sheerun.net/2014/03/21/how-to-boost-your-vim-productivity/
vmap <Leader>y "+y
vmap <Leader>d "+d
nmap <Leader>p "+p
nmap <Leader>P "+P
vmap <Leader>p "+p
vmap <Leader>P "+P

" Present
noremap <leader>p :wa<cr>:!mdp -f %<cr><cr>

augroup celstuff
    au!

" Closetag
au Filetype html,xml,xsl source ~/.vim/bundle/closetag.vim/plugin/closetag.vim

"au BufRead * DetectIndent
au BufReadPost * :DetectIndent

" Dovecot/Sieve
au BufWritePost *.sieve silent !sievec %

" Bind9
au BufWritePost /etc/bind/db.* !/usr/sbin/rndc reload %:t:s?db.??

" Special File formats
au BufNewFile,BufRead ~/.claws-mail/tmp/tmpmsg.* set ft=mail
au BufNewFile,BufRead ~/.sylpheed-2.0/tmp/tmpmsg-* set ft=mail
au BufNewFile,BufRead ~/Mail/* set ft=mail
au BufNewFile,BufRead dunstrc set ft=dosini

" remove man lookup
"nnoremap K gk
"vnoremap K gk

let b:comment_leader = '// '
au FileType haskell,vhdl,ada let b:comment_leader = '-- '
au FileType vim let b:comment_leader = '" '
au FileType c,cpp,java let b:comment_leader = '// '
au FileType sh,make,perl let b:comment_leader = '# '
au FileType tex let b:comment_leader = '% '

au BufWritePost ~/.vimrc so %
au BufWritePost ~/.files/i3/config silent !i3-msg reload >&-

augroup END

function! CommentOut() range
    if getline('.') =~ '^\s*' . escape(b:comment_leader,'\/')
        execute a:firstline.",".a:lastline." normal ^" .  strlen(b:comment_leader) . "x"
    else
        execute a:firstline.",".a:lastline." normal I" . b:comment_leader
    endif
endfunction

"noremap K :call CommentOut()<cr>
vnoremap # :call CommentOut()<cr>

" Make the wildcard menu work like bash
set wildmenu
set wildmode=longest,list

" make wildcard menu ignore binary files
set wildignore+=*.a,*.o,*.bmp,*.gif,*.ico,*.jpg,*.png,*~,*.swp,*.tmp,*.class

" Status
set laststatus=2
set statusline=%f%m%r\ %l:%c

" wrap on word boundaries
set linebreak

" Toggle line numbers
nmap <leader>n :setlocal number!<cr>

" Enter paste mode
nmap <leader>o :set paste!<cr>
set pastetoggle=<C-g>

" Toggle search highlighting and jumping
nmap <leader>q :set hlsearch!<cr>:set incsearch!<cr>

" Clear highlights
nmap <leader>h :noh<return><esc>

" Search word under cursor with Ag
nmap <leader>a :Ag <cword><cr>

":nmap ; :CtrlPBuffer<CR>

" shift-enter -> escape
:inoremap <S-CR> <Esc>

" Toggle LiteDFM
nnoremap <Leader>z :LiteDFMToggle<CR>i<Esc>`^

" CtrlP
set runtimepath^=~/.vim/bundle/ctrlp.vim
":let g:ctrlp_map = '<leader>p'
let g:ctrlp_match_window_bottom = 0
let g:ctrlp_match_window_reversed = 0
let g:ctrlp_custom_ignore = '\v\~$|\.(o|swp|pyc|wav|mp3|ogg|blend)$|(^|[/\\])\.(hg|git|bzr)($|[/\\])|__init__\.py'
let g:ctrlp_working_path_mode = 0
let g:ctrlp_dotfiles = 0
let g:ctrlp_switch_buffer = 0

" NERDTree
:nmap <leader>e :NERDTreeToggle<CR>

" Color terminal
if $TERM == "xterm-256color" || $TERM == "screen-256color" || $COLORTERM == "gnome-terminal"
  set t_Co=256
endif

" Tab stops
" http://statico.github.com/vim.html
nmap <leader>m8 :set noexpandtab tabstop=8 shiftwidth=8 softtabstop=4<cr>
nmap <leader>M8 :set expandtab tabstop=8 shiftwidth=8 softtabstop=4<cr>
nmap <leader>mn :set noexpandtab tabstop=8 softtabstop=4 shiftwidth=4<cr>
nmap <leader>M4 :set expandtab tabstop=4 shiftwidth=4 softtabstop=4<cr>
nmap <leader>m4 :set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4<cr>
nmap <leader>M2 :set expandtab tabstop=2 shiftwidth=2 softtabstop=2<cr>
nmap <leader>m2 :set noexpandtab tabstop=2 shiftwidth=2 softtabstop=2<cr>

" Toggle line wrap
nmap <leader>r :setlocal wrap!<cr>:setlocal wrap?<cr>

" Disable automatic folding
if v:version
   set nofoldenable
   set foldmethod=indent
   "set foldlevel=20
   "set foldlevelstart=20
endif

nmap <leader>c :CoffeeCompile<cr>

":setlocal makeprg=javac\ %
" Easy make
"noremap <leader>j :w<cr>:make<cr>
nmap <leader>j :wa<cr>:exe "!" . &makeprg<cr>
nmap <leader>J :wa<cr>:!make<cr><cr>
"nmap <leader>j :w<cr>:!cleaver %<cr><cr>
":nmap <leader>j :!tac mint-transactions-2013-12-17.csv \| scripts/mint2ledger > mint.ledger<cr><cr>
"nmap <leader>J :make<cr><cr>
nmap <leader>J :!make 2>&1 >/dev/null &<cr><cr>

" Switch between c/h files
nmap <leader>ec :e %:r.c<cr>
nmap <leader>eh :e %:r.h<cr>
nmap <leader>eC :view %:r.c<cr>
nmap <leader>eH :view %:r.h<cr>

com! MM :au BufWritePost <buffer> silent make |cwindow|redraw!
com! Mpdftex :au BufWritePost <buffer> exe ":!pdftex %:r" |redraw!
com! Mpdflatex :au BufWritePost <buffer> exe ":!pdflatex %:r" |redraw!

function! CloseHiddenBuffers()
    " Tableau pour memoriser la visibilite des buffers
    let visible = {}
    " Pour chaque onglet...
    for t in range(1, tabpagenr('$'))
        " Et pour chacune de ses fenetres...
        for b in tabpagebuflist(t)
            " On indique que le buffer est visible.
            let visible[b] = 1
        endfor
    endfor
    " Pour chaque numero de buffer possible...
    for b in range(1, bufnr('$'))
        " Si b est un numero de buffer valide et qu'il n'est pas visible, on le
        " supprime.
        if bufexists(b) && !has_key(visible, b)
            " On ferme donc tous les buffers qui ne valent pas 1 dans le tableau et qui
            " sont pourtant charges en memoire.
            execute 'bwipeout' b
        endif
    endfor
endfun

command! Bdi :call CloseHiddenBuffers()

" Personal Pastebin
" Based on <http://connermcd.com/blog/2012/09/17/personal-pastebin-system/>
" and http://dubstepdish.com/blog/2013/11/09/personal-pastebin-tool/
com! -range=% HtmlPaste <line1>,<line2>call HtmlPaste()
noremap <silent> gH :HtmlPaste<cr>
fun! HtmlPaste() range
  " *********
  " Settings

  let localPaste = "~/www/paste"
  let remotePublic = "cel:www/paste"
  let remotePasteUrl = "https://celehner.com/paste/"

  " *********

  let hasRN = &relativenumber
  let hasNumber = &number
  let oldBackground = &background
  let oldColorScheme = g:colors_name

  " unset line numbers - makes copy/paste easier for people
  set norelativenumber
  set nonumber

  " set colorscheme
  colors github
  set bg=light

  " convert to html
  exe a:firstline.",".a:lastline."TOhtml"
  " get a random alphanumeric string for the filename
  let pasteName = system("cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 4 | head -n 1 | perl -ne 'chomp and print'")
  " ensure that the local paste directory exists
  exe "silent !mkdir -p " . localPaste
  " save to local paste directory
  exe "w! " . localPaste . "/" . pasteName
  " delete buffer the above command creates
  exe "bwipeout!"
  " sync local/public paste
  " exe "silent !rsync -a --exclude=.*.swp " . localPaste . "/ " . remotePublic
  exe "silent !rsync -a " . localPaste . "/" . pasteName . " " . remotePublic . "/" . pasteName . ".html"
  " copy to clipboard
  exe "silent !echo -n '" . remotePasteUrl . pasteName . ".html' | xsel"

  " restore line numbers
  if hasRN
    set relativenumber
  endif
  if hasNumber
    set number
  endif

  " restore colorscheme
  exe "set bg=" . oldBackground
  exe "colors " . oldColorScheme

  "redraw!
endfun

" Allow toggling background (defined by solarized)
"call togglebg#map("<F5>")

" sort account completion by level of detail/depth instead of alphabetical
let g:ledger_detailed_first = 1

set thesaurus +=~/Downloads/mobythes.aur
set dictionary+=/usr/share/dict/words

let g:GPGDefaultRecipients=['3413F006']
let g:GPGUsePipes=1

" Rename files
function! Rename(new_name)
   if expand("%") != ""
      write
      silent execute "Git mv % " . a:new_name
      silent execute "!mv -f % " . a:new_name
      execute "file " . a:new_name
      write!
      redraw!
   endif
endfunction
command! -nargs=1 Rename :call Rename(<f-args>)

" Map Goyo toggle to <Leader> + spacebar
nnoremap <Leader><Space> :Goyo<CR>

"set printheader=%<%f%h%m%=Page\ %N
set printheader=\
set printexpr=PrintFile(v:fname_in,v:cmdarg)
function! PrintFile(fname_in, cmdarg)
    if a:cmdarg == ""
        call system('ps2pdf ' . a:fname_in . ' ' . a:fname_in . '.pdf && ' .
                    \'( evince ' . a:fname_in . '.pdf && rm ' . a:fname_in . '.pdf ) &')
    else
        call system('ps2pdf ' . a:fname_in . ' ' . a:cmdarg)
    endif
    return v:shell_error
endfunc

" Sort a paragraph
nmap <leader>so Vip:sort<cr>

" Show current color scheem
nmap <leader><leader>c :colo<cr>

set wildignore=*.a,*.o,*.bmp,*.gif,*.ico,*.jpg,*.png,*~,*.swp,*.tmp,*.class,*.d

set mouse=a

" http://vim.1045645.n5.nabble.com/Ellipsis-digraph-td5724588.html
silent! dig -.  8230    "U+2026=…   HORIZONTAL ELLIPSIS 

" au BufWritePost <buffer> wincmd p|%d|exe "r! /tmp/foo; true"|1d|wincmd p