set encoding=utf-8

" Lider
let mapleader = " "

set backspace=2   " Backspace elimina 
set nobackup
set nowritebackup
set noswapfile    " http://robots.thoughtbot.com/post/18739402579/global-gitignore#comment-458413287
set history=50
set ruler         " mostrar posición del cursor todo el tiempo
set showcmd       " muestra ordenes incompletas
set incsearch     " búsqueda incremental
set laststatus=2  " Muestra siempre bara de estado
set autowrite     " Ejecuta :write antes de ejecutar ordenes
set modelines=0   " Deshabilita modelines como medida de seguridad
set nomodeline

" Habilitar resaltado de sintaxis, cuando la terminal tiene colores
" También resalta último patrón buscado.
if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
  syntax on
endif

if filereadable(expand("~/.vimrc.bundles"))
  source ~/.vimrc.bundles
endif

" Carga matchit.vim, pero sólo si el usuario no ha instalado una 
" versión más reciente
if !exists('g:loaded_matchit') && findfile('plugin/matchit.vim', &rtp) ==# ''
  runtime! macros/matchit.vim
endif

filetype plugin indent on

augroup vimrcEx
  autocmd!

  " Al editar un arcivo, saltar a l aúltima posición del cursor
  " No hacerlo para mensajes de contribuciones (commits) ni
  " dentro de manejadores de eventos (cuando se suelta un archivo en gvim).
  autocmd BufReadPost *
    \ if &ft != 'gitcommit' && line("'\"") > 0 && line("'\"") <= line("$") |
    \   exe "normal g`\"" |
    \ endif

  " Establece resaltado de sintaxis para tipos de archivo específicos
  autocmd BufRead,BufNewFile *.md set filetype=markdown
  autocmd BufRead,BufNewFile .{jscs,jshint,eslint}rc set filetype=json
  autocmd BufRead,BufNewFile aliases.local,zshrc.local,*/zsh/configs/* set filetype=sh
  autocmd BufRead,BufNewFile gitconfig.local set filetype=gitconfig
  autocmd BufRead,BufNewFile tmux.conf.local set filetype=tmux
  autocmd BufRead,BufNewFile vimrc.local set filetype=vim
augroup END

" Cuando el tipo de un archivo de ordenes es /bin/sh, suponer un shell
" compatible con POSIX para el resaltado de sintaxis.
let g:is_posix = 1

" Softtabs, 2 espacios
set tabstop=2
set shiftwidth=2
set shiftround
set expandtab

" Mostrar espacio en blanco extra
set list listchars=tab:»·,trail:·,nbsp:·

" Usar un espacio, no dos, tras puntución.
set nojoinspaces

" Usar Silver Searcher https://github.com/ggreer/the_silver_searcher
if executable('ag')
  " Usar Ag en lugar de Grep
  set grepprg=ag\ --nogroup\ --nocolor

  " Usar ag en fzf para listar arcivos. Rapido y respeta .gitignore
  let $FZF_DEFAULT_COMMAND = 'ag --literal --files-with-matches --nocolor --hidden -g ""'

  if !exists(":Ag")
    command -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!
    nnoremap \ :Ag<SPACE>
  endif
endif

" Hacer obvio dond están los 80 caracteres
set textwidth=80
set colorcolumn=+1

" Números
" set number
" set numberwidth=5

" Completación con tab
" insertará tab al comienzo de la línea
" usara completación si no está al comienzo.
set wildmode=list:longest,list:full
function! InsertTabWrapper()
    let col = col('.') - 1
    if !col || getline('.')[col - 1] !~ '\k'
        return "\<Tab>"
    else
        return "\<C-p>"
    endif
endfunction
inoremap <Tab> <C-r>=InsertTabWrapper()<CR>
inoremap <S-Tab> <C-n>

" Intercambiar entre los dos últimos archivos
nnoremap <Leader><Leader> <C-^>

" Usar teclas rapidas y no flechas
nnoremap <Left> :echoe "Use h"<CR>
nnoremap <Right> :echoe "Use l"<CR>
nnoremap <Up> :echoe "Use k"<CR>
nnoremap <Down> :echoe "Use j"<CR>

" mapeo para vim-test 
nnoremap <silent> <Leader>t :TestFile<CR>
nnoremap <silent> <Leader>s :TestNearest<CR>
nnoremap <silent> <Leader>l :TestLast<CR>
nnoremap <silent> <Leader>a :TestSuite<CR>
nnoremap <silent> <Leader>gt :TestVisit<CR>

" Ejecutar ordenes que requieren un interprete de comandos interactivos
nnoremap <Leader>r :RunInInteractiveShell<Space>

" Tratar etiquetas <li> y <p> como las etiquetas de bloque que son
let g:html_indent_tags = 'li\|p'

" Establece etiquetas para vim-fugitive
set tags^=.git/tags

" Abre nuevos paneles a la derecha y abajo, que es más natural.
set splitbelow
set splitright

" Movimiento de ventanas más rápido
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-h> <C-w>h
nnoremap <C-l> <C-w>l

" Moverse entre errores de linting 
nnoremap ]r :ALENextWrap<CR>
nnoremap [r :ALEPreviousWrap<CR>

" Mapea Ctrl + p para abrir buscar difuso (FZF)
nnoremap <c-p> :Files<cr>

" Correccion ortografica segun
" https://apuntes-snicoper.readthedocs.io/es/latest/editors/vim/spell_vim_es.html
set spell
setlocal spell spelllang=es

" Establece el archivo de ortografía en donde se garantiza que existe,
" puede ser un enlace. 
set spellfile=$HOME/.vim-spell-es.utf-8.add

" Autocompletar con palabras de dicciones cuando se corrige ortografía
set complete+=kspell

" Siempre usar diffs verticales
set diffopt+=vertical

colorscheme default

" Configuración local
if filereadable($HOME . "/.vimrc.local")
  source ~/.vimrc.local
endif
set encoding&       " terminal charset: follows current locale 
set fileencoding&   " auto-sensed charset of current buffer
set encoding&       " terminal charset: follows current locale 
set fileencoding&   " auto-sensed charset of current buffer
